-
Notifications
You must be signed in to change notification settings - Fork 769
/
Copy pathSemaAttr.cpp
1573 lines (1409 loc) · 57.2 KB
/
SemaAttr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for non-trivial attributes and
// pragmas.
//
//===----------------------------------------------------------------------===//
#include "CheckExprLifetime.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Expr.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include <optional>
using namespace clang;
//===----------------------------------------------------------------------===//
// Pragma 'pack' and 'options align'
//===----------------------------------------------------------------------===//
Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
StringRef SlotLabel,
bool ShouldAct)
: S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
if (ShouldAct) {
S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
S.StrictGuardStackCheckStack.SentinelAction(PSK_Push, SlotLabel);
}
}
Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
if (ShouldAct) {
S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
S.StrictGuardStackCheckStack.SentinelAction(PSK_Pop, SlotLabel);
}
}
void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
AlignPackInfo::Mode M = InfoVal.getAlignMode();
bool IsPackSet = InfoVal.IsPackSet();
bool IsXLPragma = getLangOpts().XLPragmaPack;
// If we are not under mac68k/natural alignment mode and also there is no pack
// value, we don't need any attributes.
if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
return;
if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
} else if (IsPackSet) {
// Check to see if we need a max field alignment attribute.
RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
Context, InfoVal.getPackNumber() * 8));
}
if (IsXLPragma && M == AlignPackInfo::Natural)
RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
if (AlignPackIncludeStack.empty())
return;
// The #pragma align/pack affected a record in an included file, so Clang
// should warn when that pragma was written in a file that included the
// included file.
for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack)) {
if (AlignPackedInclude.CurrentPragmaLocation !=
AlignPackStack.CurrentPragmaLocation)
break;
if (AlignPackedInclude.HasNonDefaultValue)
AlignPackedInclude.ShouldWarnOnInclude = true;
}
}
void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
if (MSStructPragmaOn)
RD->addAttr(MSStructAttr::CreateImplicit(Context));
// FIXME: We should merge AddAlignmentAttributesForRecord with
// AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
// all active pragmas and applies them as attributes to class definitions.
if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
RD->addAttr(MSVtorDispAttr::CreateImplicit(
Context, unsigned(VtorDispStack.CurrentValue)));
}
template <typename Attribute>
static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
CXXRecordDecl *Record) {
if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
return;
for (Decl *Redecl : Record->redecls())
Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
}
void Sema::inferGslPointerAttribute(NamedDecl *ND,
CXXRecordDecl *UnderlyingRecord) {
if (!UnderlyingRecord)
return;
const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
if (!Parent)
return;
static const llvm::StringSet<> Containers{
"array",
"basic_string",
"deque",
"forward_list",
"vector",
"list",
"map",
"multiset",
"multimap",
"priority_queue",
"queue",
"set",
"stack",
"unordered_set",
"unordered_map",
"unordered_multiset",
"unordered_multimap",
};
static const llvm::StringSet<> Iterators{"iterator", "const_iterator",
"reverse_iterator",
"const_reverse_iterator"};
if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
Containers.count(Parent->getName()))
addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
UnderlyingRecord);
}
void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
QualType Canonical = TD->getUnderlyingType().getCanonicalType();
CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
if (!RD) {
if (auto *TST =
dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
RD = dyn_cast_or_null<CXXRecordDecl>(
TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
}
}
inferGslPointerAttribute(TD, RD);
}
void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
static const llvm::StringSet<> StdOwners{
"any",
"array",
"basic_regex",
"basic_string",
"deque",
"forward_list",
"vector",
"list",
"map",
"multiset",
"multimap",
"optional",
"priority_queue",
"queue",
"set",
"stack",
"unique_ptr",
"unordered_set",
"unordered_map",
"unordered_multiset",
"unordered_multimap",
"variant",
};
static const llvm::StringSet<> StdPointers{
"basic_string_view",
"reference_wrapper",
"regex_iterator",
"span",
};
if (!Record->getIdentifier())
return;
// Handle classes that directly appear in std namespace.
if (Record->isInStdNamespace()) {
if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
return;
if (StdOwners.count(Record->getName()))
addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
else if (StdPointers.count(Record->getName()))
addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
return;
}
// Handle nested classes that could be a gsl::Pointer.
inferGslPointerAttribute(Record, Record);
}
void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
if (FD->getNumParams() == 0)
return;
if (unsigned BuiltinID = FD->getBuiltinID()) {
// Add lifetime attribute to std::move, std::fowrard et al.
switch (BuiltinID) {
case Builtin::BIaddressof:
case Builtin::BI__addressof:
case Builtin::BI__builtin_addressof:
case Builtin::BIas_const:
case Builtin::BIforward:
case Builtin::BIforward_like:
case Builtin::BImove:
case Builtin::BImove_if_noexcept:
if (ParmVarDecl *P = FD->getParamDecl(0u);
!P->hasAttr<LifetimeBoundAttr>())
P->addAttr(
LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
break;
default:
break;
}
return;
}
if (auto *CMD = dyn_cast<CXXMethodDecl>(FD)) {
const auto *CRD = CMD->getParent();
if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
return;
if (isa<CXXConstructorDecl>(CMD)) {
auto *Param = CMD->getParamDecl(0);
if (Param->hasAttr<LifetimeBoundAttr>())
return;
if (CRD->getName() == "basic_string_view" &&
Param->getType()->isPointerType()) {
// construct from a char array pointed by a pointer.
// basic_string_view(const CharT* s);
// basic_string_view(const CharT* s, size_type count);
Param->addAttr(
LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
} else if (CRD->getName() == "span") {
// construct from a reference of array.
// span(std::type_identity_t<element_type> (&arr)[N]);
const auto *LRT = Param->getType()->getAs<LValueReferenceType>();
if (LRT && LRT->getPointeeType().IgnoreParens()->isArrayType())
Param->addAttr(
LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
}
}
}
}
void Sema::inferLifetimeCaptureByAttribute(FunctionDecl *FD) {
auto *MD = dyn_cast_if_present<CXXMethodDecl>(FD);
if (!MD || !MD->getParent()->isInStdNamespace())
return;
auto Annotate = [this](const FunctionDecl *MD) {
// Do not infer if any parameter is explicitly annotated.
for (ParmVarDecl *PVD : MD->parameters())
if (PVD->hasAttr<LifetimeCaptureByAttr>())
return;
for (ParmVarDecl *PVD : MD->parameters()) {
// Methods in standard containers that capture values typically accept
// reference-type parameters, e.g., `void push_back(const T& value)`.
// We only apply the lifetime_capture_by attribute to parameters of
// pointer-like reference types (`const T&`, `T&&`).
if (PVD->getType()->isReferenceType() &&
sema::isGLSPointerType(PVD->getType().getNonReferenceType())) {
int CaptureByThis[] = {LifetimeCaptureByAttr::THIS};
PVD->addAttr(
LifetimeCaptureByAttr::CreateImplicit(Context, CaptureByThis, 1));
}
}
};
if (!MD->getIdentifier()) {
static const llvm::StringSet<> MapLikeContainer{
"map",
"multimap",
"unordered_map",
"unordered_multimap",
};
// Infer for the map's operator []:
// std::map<string_view, ...> m;
// m[ReturnString(..)] = ...; // !dangling references in m.
if (MD->getOverloadedOperator() == OO_Subscript &&
MapLikeContainer.contains(MD->getParent()->getName()))
Annotate(MD);
return;
}
static const llvm::StringSet<> CapturingMethods{
"insert", "insert_or_assign", "push", "push_front", "push_back"};
if (!CapturingMethods.contains(MD->getName()))
return;
Annotate(MD);
}
void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
static const llvm::StringSet<> Nullable{
"auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
"coroutine_handle", "function", "move_only_function",
};
if (CRD->isInStdNamespace() && Nullable.count(CRD->getName()) &&
!CRD->hasAttr<TypeNullableAttr>())
for (Decl *Redecl : CRD->redecls())
Redecl->addAttr(TypeNullableAttr::CreateImplicit(Context));
}
void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc) {
PragmaMsStackAction Action = Sema::PSK_Reset;
AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
switch (Kind) {
// For most of the platforms we support, native and natural are the same.
// With XL, native is the same as power, natural means something else.
case POAK_Native:
case POAK_Power:
Action = Sema::PSK_Push_Set;
break;
case POAK_Natural:
Action = Sema::PSK_Push_Set;
ModeVal = AlignPackInfo::Natural;
break;
// Note that '#pragma options align=packed' is not equivalent to attribute
// packed, it has a different precedence relative to attribute aligned.
case POAK_Packed:
Action = Sema::PSK_Push_Set;
ModeVal = AlignPackInfo::Packed;
break;
case POAK_Mac68k:
// Check if the target supports this.
if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
return;
}
Action = Sema::PSK_Push_Set;
ModeVal = AlignPackInfo::Mac68k;
break;
case POAK_Reset:
// Reset just pops the top of the stack, or resets the current alignment to
// default.
Action = Sema::PSK_Pop;
if (AlignPackStack.Stack.empty()) {
if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
AlignPackStack.CurrentValue.IsPackAttr()) {
Action = Sema::PSK_Reset;
} else {
Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
<< "stack empty";
return;
}
}
break;
}
AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
}
void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
PragmaClangSectionAction Action,
PragmaClangSectionKind SecKind,
StringRef SecName) {
PragmaClangSection *CSec;
int SectionFlags = ASTContext::PSF_Read;
switch (SecKind) {
case PragmaClangSectionKind::PCSK_BSS:
CSec = &PragmaClangBSSSection;
SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
break;
case PragmaClangSectionKind::PCSK_Data:
CSec = &PragmaClangDataSection;
SectionFlags |= ASTContext::PSF_Write;
break;
case PragmaClangSectionKind::PCSK_Rodata:
CSec = &PragmaClangRodataSection;
break;
case PragmaClangSectionKind::PCSK_Relro:
CSec = &PragmaClangRelroSection;
break;
case PragmaClangSectionKind::PCSK_Text:
CSec = &PragmaClangTextSection;
SectionFlags |= ASTContext::PSF_Execute;
break;
default:
llvm_unreachable("invalid clang section kind");
}
if (Action == PragmaClangSectionAction::PCSA_Clear) {
CSec->Valid = false;
return;
}
if (llvm::Error E = isValidSectionSpecifier(SecName)) {
Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
<< toString(std::move(E));
CSec->Valid = false;
return;
}
if (UnifySection(SecName, SectionFlags, PragmaLoc))
return;
CSec->Valid = true;
CSec->SectionName = std::string(SecName);
CSec->PragmaLocation = PragmaLoc;
}
void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *alignment) {
bool IsXLPragma = getLangOpts().XLPragmaPack;
// XL pragma pack does not support identifier syntax.
if (IsXLPragma && !SlotLabel.empty()) {
Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
return;
}
const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
Expr *Alignment = static_cast<Expr *>(alignment);
// If specified then alignment must be a "small" power of two.
unsigned AlignmentVal = 0;
AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
if (Alignment) {
std::optional<llvm::APSInt> Val;
Val = Alignment->getIntegerConstantExpr(Context);
// pack(0) is like pack(), which just works out since that is what
// we use 0 for in PackAttr.
if (Alignment->isTypeDependent() || !Val ||
!(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
return; // Ignore
}
if (IsXLPragma && *Val == 0) {
// pack(0) does not work out with XL.
Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
return; // Ignore
}
AlignmentVal = (unsigned)Val->getZExtValue();
}
if (Action == Sema::PSK_Show) {
// Show the current alignment, making sure to show the right value
// for the default.
// FIXME: This should come from the target.
AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
if (ModeVal == AlignPackInfo::Mac68k &&
(IsXLPragma || CurVal.IsAlignAttr()))
Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
else
Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
}
// MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
// "#pragma pack(pop, identifier, n) is undefined"
if (Action & Sema::PSK_Pop) {
if (Alignment && !SlotLabel.empty())
Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
if (AlignPackStack.Stack.empty()) {
assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
"Empty pack stack can only be at Native alignment mode.");
Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
}
}
AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
}
bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
MutableArrayRef<Expr *> Args) {
llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
Expr *&E = Args.begin()[Idx];
assert(E && "error are handled before");
if (E->isValueDependent() || E->isTypeDependent())
continue;
// FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic
// that adds implicit casts here.
if (E->getType()->isArrayType())
E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
clang::CK_ArrayToPointerDecay)
.get();
if (E->getType()->isFunctionType())
E = ImplicitCastExpr::Create(Context,
Context.getPointerType(E->getType()),
clang::CK_FunctionToPointerDecay, E, nullptr,
VK_PRValue, FPOptionsOverride());
if (E->isLValue())
E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
clang::CK_LValueToRValue, E, nullptr,
VK_PRValue, FPOptionsOverride());
Expr::EvalResult Eval;
Notes.clear();
Eval.Diag = &Notes;
bool Result = E->EvaluateAsConstantExpr(Eval, Context);
/// Result means the expression can be folded to a constant.
/// Note.empty() means the expression is a valid constant expression in the
/// current language mode.
if (!Result || !Notes.empty()) {
Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
<< CI << (Idx + 1) << AANT_ArgumentConstantExpr;
for (auto &Note : Notes)
Diag(Note.first, Note.second);
return false;
}
E = ConstantExpr::Create(Context, E, Eval.Val);
}
return true;
}
void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
SourceLocation IncludeLoc) {
if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
// Warn about non-default alignment at #includes (without redundant
// warnings for the same directive in nested includes).
// The warning is delayed until the end of the file to avoid warnings
// for files that don't have any records that are affected by the modified
// alignment.
bool HasNonDefaultValue =
AlignPackStack.hasValue() &&
(AlignPackIncludeStack.empty() ||
AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
AlignPackIncludeStack.push_back(
{AlignPackStack.CurrentValue,
AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
return;
}
assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
"invalid kind");
AlignPackIncludeState PrevAlignPackState =
AlignPackIncludeStack.pop_back_val();
// FIXME: AlignPackStack may contain both #pragma align and #pragma pack
// information, diagnostics below might not be accurate if we have mixed
// pragmas.
if (PrevAlignPackState.ShouldWarnOnInclude) {
// Emit the delayed non-default alignment at #include warning.
Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
}
// Warn about modified alignment after #includes.
if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
}
}
void Sema::DiagnoseUnterminatedPragmaAlignPack() {
if (AlignPackStack.Stack.empty())
return;
bool IsInnermost = true;
// FIXME: AlignPackStack may contain both #pragma align and #pragma pack
// information, diagnostics below might not be accurate if we have mixed
// pragmas.
for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
// The user might have already reset the alignment, so suggest replacing
// the reset with a pop.
if (IsInnermost &&
AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
diag::note_pragma_pack_pop_instead_reset);
SourceLocation FixItLoc =
Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
tok::l_paren, SourceMgr, LangOpts,
/*SkipTrailing=*/false);
if (FixItLoc.isValid())
DB << FixItHint::CreateInsertion(FixItLoc, "pop");
}
IsInnermost = false;
}
}
void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
MSStructPragmaOn = (Kind == PMSST_ON);
}
void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
PragmaMSCommentKind Kind, StringRef Arg) {
auto *PCD = PragmaCommentDecl::Create(
Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
Context.getTranslationUnitDecl()->addDecl(PCD);
Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
}
void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
StringRef Value) {
auto *PDMD = PragmaDetectMismatchDecl::Create(
Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
Context.getTranslationUnitDecl()->addDecl(PDMD);
Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
}
void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,
LangOptions::FPEvalMethodKind Value) {
FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
switch (Value) {
default:
llvm_unreachable("invalid pragma eval_method kind");
case LangOptions::FEM_Source:
NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
break;
case LangOptions::FEM_Double:
NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
break;
case LangOptions::FEM_Extended:
NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
break;
}
if (getLangOpts().ApproxFunc)
Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
if (getLangOpts().AllowFPReassoc)
Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
if (getLangOpts().AllowRecip)
Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
PP.setCurrentFPEvalMethod(Loc, Value);
}
void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
PragmaMsStackAction Action,
PragmaFloatControlKind Value) {
FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
!CurContext->getRedeclContext()->isFileContext()) {
// Push and pop can only occur at file or namespace scope, or within a
// language linkage declaration.
Diag(Loc, diag::err_pragma_fc_pp_scope);
return;
}
switch (Value) {
default:
llvm_unreachable("invalid pragma float_control kind");
case PFC_Precise:
NewFPFeatures.setFPPreciseEnabled(true);
FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
break;
case PFC_NoPrecise:
if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)
Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
else if (CurFPFeatures.getAllowFEnvAccess())
Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
else
NewFPFeatures.setFPPreciseEnabled(false);
FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
break;
case PFC_Except:
if (!isPreciseFPEnabled())
Diag(Loc, diag::err_pragma_fc_except_requires_precise);
else
NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);
FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
break;
case PFC_NoExcept:
NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);
FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
break;
case PFC_Push:
FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
break;
case PFC_Pop:
if (FpPragmaStack.Stack.empty()) {
Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
<< "stack empty";
return;
}
FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
NewFPFeatures = FpPragmaStack.CurrentValue;
break;
}
CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
}
void Sema::ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
SourceLocation PragmaLoc) {
MSPointerToMemberRepresentationMethod = RepresentationMethod;
ImplicitMSInheritanceAttrLoc = PragmaLoc;
}
void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
SourceLocation PragmaLoc,
MSVtorDispMode Mode) {
if (Action & PSK_Pop && VtorDispStack.Stack.empty())
Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
<< "stack empty";
VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
}
template <>
void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
AlignPackInfo Value) {
if (Action == PSK_Reset) {
CurrentValue = DefaultValue;
CurrentPragmaLocation = PragmaLocation;
return;
}
if (Action & PSK_Push)
Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
PragmaLocation));
else if (Action & PSK_Pop) {
if (!StackSlotLabel.empty()) {
// If we've got a label, try to find it and jump there.
auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
return x.StackSlotLabel == StackSlotLabel;
});
// We found the label, so pop from there.
if (I != Stack.rend()) {
CurrentValue = I->Value;
CurrentPragmaLocation = I->PragmaLocation;
Stack.erase(std::prev(I.base()), Stack.end());
}
} else if (Value.IsXLStack() && Value.IsAlignAttr() &&
CurrentValue.IsPackAttr()) {
// XL '#pragma align(reset)' would pop the stack until
// a current in effect pragma align is popped.
auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
return x.Value.IsAlignAttr();
});
// If we found pragma align so pop from there.
if (I != Stack.rend()) {
Stack.erase(std::prev(I.base()), Stack.end());
if (Stack.empty()) {
CurrentValue = DefaultValue;
CurrentPragmaLocation = PragmaLocation;
} else {
CurrentValue = Stack.back().Value;
CurrentPragmaLocation = Stack.back().PragmaLocation;
Stack.pop_back();
}
}
} else if (!Stack.empty()) {
// xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
// over the baseline.
if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
return;
// We don't have a label, just pop the last entry.
CurrentValue = Stack.back().Value;
CurrentPragmaLocation = Stack.back().PragmaLocation;
Stack.pop_back();
}
}
if (Action & PSK_Set) {
CurrentValue = Value;
CurrentPragmaLocation = PragmaLocation;
}
}
bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
NamedDecl *Decl) {
SourceLocation PragmaLocation;
if (auto A = Decl->getAttr<SectionAttr>())
if (A->isImplicit())
PragmaLocation = A->getLocation();
auto [SectionIt, Inserted] = Context.SectionInfos.try_emplace(
SectionName, Decl, PragmaLocation, SectionFlags);
if (Inserted)
return false;
// A pre-declared section takes precedence w/o diagnostic.
const auto &Section = SectionIt->second;
if (Section.SectionFlags == SectionFlags ||
((SectionFlags & ASTContext::PSF_Implicit) &&
!(Section.SectionFlags & ASTContext::PSF_Implicit)))
return false;
Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
if (Section.Decl)
Diag(Section.Decl->getLocation(), diag::note_declared_at)
<< Section.Decl->getName();
if (PragmaLocation.isValid())
Diag(PragmaLocation, diag::note_pragma_entered_here);
if (Section.PragmaSectionLocation.isValid())
Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
return true;
}
bool Sema::UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation) {
auto SectionIt = Context.SectionInfos.find(SectionName);
if (SectionIt != Context.SectionInfos.end()) {
const auto &Section = SectionIt->second;
if (Section.SectionFlags == SectionFlags)
return false;
if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
Diag(PragmaSectionLocation, diag::err_section_conflict)
<< "this" << Section;
if (Section.Decl)
Diag(Section.Decl->getLocation(), diag::note_declared_at)
<< Section.Decl->getName();
if (Section.PragmaSectionLocation.isValid())
Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
return true;
}
}
Context.SectionInfos[SectionName] =
ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
return false;
}
/// Called on well formed \#pragma bss_seg().
void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName) {
PragmaStack<StringLiteral *> *Stack =
llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
.Case("data_seg", &DataSegStack)
.Case("bss_seg", &BSSSegStack)
.Case("const_seg", &ConstSegStack)
.Case("code_seg", &CodeSegStack);
if (Action & PSK_Pop && Stack->Stack.empty())
Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
<< "stack empty";
if (SegmentName) {
if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
return;
if (SegmentName->getString() == ".drectve" &&
Context.getTargetInfo().getCXXABI().isMicrosoft())
Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
}
Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
}
/// Called on well formed \#pragma strict_gs_check().
void Sema::ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
bool Value) {
if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())
Diag(PragmaLocation, diag::warn_pragma_pop_failed) << "strict_gs_check"
<< "stack empty";
StrictGuardStackCheckStack.Act(PragmaLocation, Action, StringRef(), Value);
}
/// Called on well formed \#pragma bss_seg().
void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName) {
UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
}
void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName) {
// There's no stack to maintain, so we just have a current section. When we
// see the default section, reset our current section back to null so we stop
// tacking on unnecessary attributes.
CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
CurInitSegLoc = PragmaLocation;
}
void Sema::ActOnPragmaMSAllocText(
SourceLocation PragmaLocation, StringRef Section,
const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
&Functions) {
if (!CurContext->getRedeclContext()->isFileContext()) {
Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
return;
}
for (auto &Function : Functions) {
IdentifierInfo *II;
SourceLocation Loc;
std::tie(II, Loc) = Function;
DeclarationName DN(II);
NamedDecl *ND = LookupSingleName(TUScope, DN, Loc, LookupOrdinaryName);
if (!ND) {
Diag(Loc, diag::err_undeclared_use) << II->getName();
return;
}
auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());
if (!FD) {
Diag(Loc, diag::err_pragma_alloc_text_not_function);
return;
}
if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
return;
}
FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);
}
}
void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
SourceLocation PragmaLoc) {
IdentifierInfo *Name = IdTok.getIdentifierInfo();
LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
LookupName(Lookup, curScope, /*AllowBuiltinCreation=*/true);
if (Lookup.empty()) {
Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
<< Name << SourceRange(IdTok.getLocation());
return;
}
VarDecl *VD = Lookup.getAsSingle<VarDecl>();
if (!VD) {
Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
<< Name << SourceRange(IdTok.getLocation());
return;
}
// Warn if this was used before being marked unused.
if (VD->isUsed())
Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
UnusedAttr::GNU_unused));
}
namespace {
std::optional<attr::SubjectMatchRule>
getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
using namespace attr;
switch (Rule) {
default:
return std::nullopt;
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
case Value: \
return Parent;
#include "clang/Basic/AttrSubMatchRulesList.inc"
}
}
bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
using namespace attr;
switch (Rule) {
default:
return false;
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
case Value: \
return IsNegated;
#include "clang/Basic/AttrSubMatchRulesList.inc"
}
}
CharSourceRange replacementRangeForListElement(const Sema &S,
SourceRange Range) {
// Make sure that the ',' is removed as well.
SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
/*SkipTrailingWhitespaceAndNewLine=*/false);
if (AfterCommaLoc.isValid())
return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
else
return CharSourceRange::getTokenRange(Range);
}
std::string