1//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for non-trivial attributes and
10// pragmas.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/Attr.h"
16#include "clang/AST/Expr.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/SemaInternal.h"
21#include <optional>
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Pragma 'pack' and 'options align'
26//===----------------------------------------------------------------------===//
27
28Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
29 StringRef SlotLabel,
30 bool ShouldAct)
31 : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
32 if (ShouldAct) {
33 S.VtorDispStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
34 S.DataSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
35 S.BSSSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
36 S.ConstSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
37 S.CodeSegStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
38 S.StrictGuardStackCheckStack.SentinelAction(Action: PSK_Push, Label: SlotLabel);
39 }
40}
41
42Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
43 if (ShouldAct) {
44 S.VtorDispStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
45 S.DataSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
46 S.BSSSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
47 S.ConstSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
48 S.CodeSegStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
49 S.StrictGuardStackCheckStack.SentinelAction(Action: PSK_Pop, Label: SlotLabel);
50 }
51}
52
53void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
54 AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
55 AlignPackInfo::Mode M = InfoVal.getAlignMode();
56 bool IsPackSet = InfoVal.IsPackSet();
57 bool IsXLPragma = getLangOpts().XLPragmaPack;
58
59 // If we are not under mac68k/natural alignment mode and also there is no pack
60 // value, we don't need any attributes.
61 if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
62 return;
63
64 if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
65 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
66 } else if (IsPackSet) {
67 // Check to see if we need a max field alignment attribute.
68 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
69 Context, InfoVal.getPackNumber() * 8));
70 }
71
72 if (IsXLPragma && M == AlignPackInfo::Natural)
73 RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
74
75 if (AlignPackIncludeStack.empty())
76 return;
77 // The #pragma align/pack affected a record in an included file, so Clang
78 // should warn when that pragma was written in a file that included the
79 // included file.
80 for (auto &AlignPackedInclude : llvm::reverse(C&: AlignPackIncludeStack)) {
81 if (AlignPackedInclude.CurrentPragmaLocation !=
82 AlignPackStack.CurrentPragmaLocation)
83 break;
84 if (AlignPackedInclude.HasNonDefaultValue)
85 AlignPackedInclude.ShouldWarnOnInclude = true;
86 }
87}
88
89void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
90 if (MSStructPragmaOn)
91 RD->addAttr(MSStructAttr::CreateImplicit(Context));
92
93 // FIXME: We should merge AddAlignmentAttributesForRecord with
94 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
95 // all active pragmas and applies them as attributes to class definitions.
96 if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
97 RD->addAttr(MSVtorDispAttr::CreateImplicit(
98 Context, unsigned(VtorDispStack.CurrentValue)));
99}
100
101template <typename Attribute>
102static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
103 CXXRecordDecl *Record) {
104 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
105 return;
106
107 for (Decl *Redecl : Record->redecls())
108 Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
109}
110
111void Sema::inferGslPointerAttribute(NamedDecl *ND,
112 CXXRecordDecl *UnderlyingRecord) {
113 if (!UnderlyingRecord)
114 return;
115
116 const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
117 if (!Parent)
118 return;
119
120 static llvm::StringSet<> Containers{
121 "array",
122 "basic_string",
123 "deque",
124 "forward_list",
125 "vector",
126 "list",
127 "map",
128 "multiset",
129 "multimap",
130 "priority_queue",
131 "queue",
132 "set",
133 "stack",
134 "unordered_set",
135 "unordered_map",
136 "unordered_multiset",
137 "unordered_multimap",
138 };
139
140 static llvm::StringSet<> Iterators{"iterator", "const_iterator",
141 "reverse_iterator",
142 "const_reverse_iterator"};
143
144 if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
145 Containers.count(Parent->getName()))
146 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
147 UnderlyingRecord);
148}
149
150void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
151
152 QualType Canonical = TD->getUnderlyingType().getCanonicalType();
153
154 CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
155 if (!RD) {
156 if (auto *TST =
157 dyn_cast<TemplateSpecializationType>(Val: Canonical.getTypePtr())) {
158
159 RD = dyn_cast_or_null<CXXRecordDecl>(
160 Val: TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
161 }
162 }
163
164 inferGslPointerAttribute(TD, RD);
165}
166
167void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
168 static llvm::StringSet<> StdOwners{
169 "any",
170 "array",
171 "basic_regex",
172 "basic_string",
173 "deque",
174 "forward_list",
175 "vector",
176 "list",
177 "map",
178 "multiset",
179 "multimap",
180 "optional",
181 "priority_queue",
182 "queue",
183 "set",
184 "stack",
185 "unique_ptr",
186 "unordered_set",
187 "unordered_map",
188 "unordered_multiset",
189 "unordered_multimap",
190 "variant",
191 };
192 static llvm::StringSet<> StdPointers{
193 "basic_string_view",
194 "reference_wrapper",
195 "regex_iterator",
196 };
197
198 if (!Record->getIdentifier())
199 return;
200
201 // Handle classes that directly appear in std namespace.
202 if (Record->isInStdNamespace()) {
203 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
204 return;
205
206 if (StdOwners.count(Record->getName()))
207 addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
208 else if (StdPointers.count(Record->getName()))
209 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
210
211 return;
212 }
213
214 // Handle nested classes that could be a gsl::Pointer.
215 inferGslPointerAttribute(Record, Record);
216}
217
218void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
219 static llvm::StringSet<> Nullable{
220 "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
221 "coroutine_handle", "function", "move_only_function",
222 };
223
224 if (CRD->isInStdNamespace() && Nullable.count(CRD->getName()) &&
225 !CRD->hasAttr<TypeNullableAttr>())
226 for (Decl *Redecl : CRD->redecls())
227 Redecl->addAttr(TypeNullableAttr::CreateImplicit(Context));
228}
229
230void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
231 SourceLocation PragmaLoc) {
232 PragmaMsStackAction Action = Sema::PSK_Reset;
233 AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
234
235 switch (Kind) {
236 // For most of the platforms we support, native and natural are the same.
237 // With XL, native is the same as power, natural means something else.
238 case POAK_Native:
239 case POAK_Power:
240 Action = Sema::PSK_Push_Set;
241 break;
242 case POAK_Natural:
243 Action = Sema::PSK_Push_Set;
244 ModeVal = AlignPackInfo::Natural;
245 break;
246
247 // Note that '#pragma options align=packed' is not equivalent to attribute
248 // packed, it has a different precedence relative to attribute aligned.
249 case POAK_Packed:
250 Action = Sema::PSK_Push_Set;
251 ModeVal = AlignPackInfo::Packed;
252 break;
253
254 case POAK_Mac68k:
255 // Check if the target supports this.
256 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
257 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
258 return;
259 }
260 Action = Sema::PSK_Push_Set;
261 ModeVal = AlignPackInfo::Mac68k;
262 break;
263 case POAK_Reset:
264 // Reset just pops the top of the stack, or resets the current alignment to
265 // default.
266 Action = Sema::PSK_Pop;
267 if (AlignPackStack.Stack.empty()) {
268 if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
269 AlignPackStack.CurrentValue.IsPackAttr()) {
270 Action = Sema::PSK_Reset;
271 } else {
272 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
273 << "stack empty";
274 return;
275 }
276 }
277 break;
278 }
279
280 AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
281
282 AlignPackStack.Act(PragmaLocation: PragmaLoc, Action, StackSlotLabel: StringRef(), Value: Info);
283}
284
285void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
286 PragmaClangSectionAction Action,
287 PragmaClangSectionKind SecKind,
288 StringRef SecName) {
289 PragmaClangSection *CSec;
290 int SectionFlags = ASTContext::PSF_Read;
291 switch (SecKind) {
292 case PragmaClangSectionKind::PCSK_BSS:
293 CSec = &PragmaClangBSSSection;
294 SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
295 break;
296 case PragmaClangSectionKind::PCSK_Data:
297 CSec = &PragmaClangDataSection;
298 SectionFlags |= ASTContext::PSF_Write;
299 break;
300 case PragmaClangSectionKind::PCSK_Rodata:
301 CSec = &PragmaClangRodataSection;
302 break;
303 case PragmaClangSectionKind::PCSK_Relro:
304 CSec = &PragmaClangRelroSection;
305 break;
306 case PragmaClangSectionKind::PCSK_Text:
307 CSec = &PragmaClangTextSection;
308 SectionFlags |= ASTContext::PSF_Execute;
309 break;
310 default:
311 llvm_unreachable("invalid clang section kind");
312 }
313
314 if (Action == PragmaClangSectionAction::PCSA_Clear) {
315 CSec->Valid = false;
316 return;
317 }
318
319 if (llvm::Error E = isValidSectionSpecifier(Str: SecName)) {
320 Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
321 << toString(std::move(E));
322 CSec->Valid = false;
323 return;
324 }
325
326 if (UnifySection(SectionName: SecName, SectionFlags, PragmaSectionLocation: PragmaLoc))
327 return;
328
329 CSec->Valid = true;
330 CSec->SectionName = std::string(SecName);
331 CSec->PragmaLocation = PragmaLoc;
332}
333
334void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
335 StringRef SlotLabel, Expr *alignment) {
336 bool IsXLPragma = getLangOpts().XLPragmaPack;
337 // XL pragma pack does not support identifier syntax.
338 if (IsXLPragma && !SlotLabel.empty()) {
339 Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
340 return;
341 }
342
343 const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
344 Expr *Alignment = static_cast<Expr *>(alignment);
345
346 // If specified then alignment must be a "small" power of two.
347 unsigned AlignmentVal = 0;
348 AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
349
350 if (Alignment) {
351 std::optional<llvm::APSInt> Val;
352 Val = Alignment->getIntegerConstantExpr(Ctx: Context);
353
354 // pack(0) is like pack(), which just works out since that is what
355 // we use 0 for in PackAttr.
356 if (Alignment->isTypeDependent() || !Val ||
357 !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
358 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
359 return; // Ignore
360 }
361
362 if (IsXLPragma && *Val == 0) {
363 // pack(0) does not work out with XL.
364 Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
365 return; // Ignore
366 }
367
368 AlignmentVal = (unsigned)Val->getZExtValue();
369 }
370
371 if (Action == Sema::PSK_Show) {
372 // Show the current alignment, making sure to show the right value
373 // for the default.
374 // FIXME: This should come from the target.
375 AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
376 if (ModeVal == AlignPackInfo::Mac68k &&
377 (IsXLPragma || CurVal.IsAlignAttr()))
378 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
379 else
380 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
381 }
382
383 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
384 // "#pragma pack(pop, identifier, n) is undefined"
385 if (Action & Sema::PSK_Pop) {
386 if (Alignment && !SlotLabel.empty())
387 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
388 if (AlignPackStack.Stack.empty()) {
389 assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
390 "Empty pack stack can only be at Native alignment mode.");
391 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
392 }
393 }
394
395 AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
396
397 AlignPackStack.Act(PragmaLocation: PragmaLoc, Action, StackSlotLabel: SlotLabel, Value: Info);
398}
399
400bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
401 MutableArrayRef<Expr *> Args) {
402 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
403 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
404 Expr *&E = Args.begin()[Idx];
405 assert(E && "error are handled before");
406 if (E->isValueDependent() || E->isTypeDependent())
407 continue;
408
409 // FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic
410 // that adds implicit casts here.
411 if (E->getType()->isArrayType())
412 E = ImpCastExprToType(E, Type: Context.getPointerType(T: E->getType()),
413 CK: clang::CK_ArrayToPointerDecay)
414 .get();
415 if (E->getType()->isFunctionType())
416 E = ImplicitCastExpr::Create(Context,
417 T: Context.getPointerType(T: E->getType()),
418 Kind: clang::CK_FunctionToPointerDecay, Operand: E, BasePath: nullptr,
419 Cat: VK_PRValue, FPO: FPOptionsOverride());
420 if (E->isLValue())
421 E = ImplicitCastExpr::Create(Context, T: E->getType().getNonReferenceType(),
422 Kind: clang::CK_LValueToRValue, Operand: E, BasePath: nullptr,
423 Cat: VK_PRValue, FPO: FPOptionsOverride());
424
425 Expr::EvalResult Eval;
426 Notes.clear();
427 Eval.Diag = &Notes;
428
429 bool Result = E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context);
430
431 /// Result means the expression can be folded to a constant.
432 /// Note.empty() means the expression is a valid constant expression in the
433 /// current language mode.
434 if (!Result || !Notes.empty()) {
435 Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
436 << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
437 for (auto &Note : Notes)
438 Diag(Note.first, Note.second);
439 return false;
440 }
441 assert(Eval.Val.hasValue());
442 E = ConstantExpr::Create(Context, E, Result: Eval.Val);
443 }
444
445 return true;
446}
447
448void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
449 SourceLocation IncludeLoc) {
450 if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
451 SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
452 // Warn about non-default alignment at #includes (without redundant
453 // warnings for the same directive in nested includes).
454 // The warning is delayed until the end of the file to avoid warnings
455 // for files that don't have any records that are affected by the modified
456 // alignment.
457 bool HasNonDefaultValue =
458 AlignPackStack.hasValue() &&
459 (AlignPackIncludeStack.empty() ||
460 AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
461 AlignPackIncludeStack.push_back(
462 Elt: {.CurrentValue: AlignPackStack.CurrentValue,
463 .CurrentPragmaLocation: AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
464 .HasNonDefaultValue: HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
465 return;
466 }
467
468 assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
469 "invalid kind");
470 AlignPackIncludeState PrevAlignPackState =
471 AlignPackIncludeStack.pop_back_val();
472 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
473 // information, diagnostics below might not be accurate if we have mixed
474 // pragmas.
475 if (PrevAlignPackState.ShouldWarnOnInclude) {
476 // Emit the delayed non-default alignment at #include warning.
477 Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
478 Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
479 }
480 // Warn about modified alignment after #includes.
481 if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
482 Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
483 Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
484 }
485}
486
487void Sema::DiagnoseUnterminatedPragmaAlignPack() {
488 if (AlignPackStack.Stack.empty())
489 return;
490 bool IsInnermost = true;
491
492 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
493 // information, diagnostics below might not be accurate if we have mixed
494 // pragmas.
495 for (const auto &StackSlot : llvm::reverse(C&: AlignPackStack.Stack)) {
496 Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
497 // The user might have already reset the alignment, so suggest replacing
498 // the reset with a pop.
499 if (IsInnermost &&
500 AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
501 auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
502 diag::note_pragma_pack_pop_instead_reset);
503 SourceLocation FixItLoc =
504 Lexer::findLocationAfterToken(loc: AlignPackStack.CurrentPragmaLocation,
505 TKind: tok::l_paren, SM: SourceMgr, LangOpts,
506 /*SkipTrailing=*/SkipTrailingWhitespaceAndNewLine: false);
507 if (FixItLoc.isValid())
508 DB << FixItHint::CreateInsertion(InsertionLoc: FixItLoc, Code: "pop");
509 }
510 IsInnermost = false;
511 }
512}
513
514void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
515 MSStructPragmaOn = (Kind == PMSST_ON);
516}
517
518void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
519 PragmaMSCommentKind Kind, StringRef Arg) {
520 auto *PCD = PragmaCommentDecl::Create(
521 C: Context, DC: Context.getTranslationUnitDecl(), CommentLoc, CommentKind: Kind, Arg);
522 Context.getTranslationUnitDecl()->addDecl(PCD);
523 Consumer.HandleTopLevelDecl(D: DeclGroupRef(PCD));
524}
525
526void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
527 StringRef Value) {
528 auto *PDMD = PragmaDetectMismatchDecl::Create(
529 C: Context, DC: Context.getTranslationUnitDecl(), Loc, Name, Value);
530 Context.getTranslationUnitDecl()->addDecl(PDMD);
531 Consumer.HandleTopLevelDecl(D: DeclGroupRef(PDMD));
532}
533
534void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,
535 LangOptions::FPEvalMethodKind Value) {
536 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
537 switch (Value) {
538 default:
539 llvm_unreachable("invalid pragma eval_method kind");
540 case LangOptions::FEM_Source:
541 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
542 break;
543 case LangOptions::FEM_Double:
544 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
545 break;
546 case LangOptions::FEM_Extended:
547 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
548 break;
549 }
550 if (getLangOpts().ApproxFunc)
551 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
552 if (getLangOpts().AllowFPReassoc)
553 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
554 if (getLangOpts().AllowRecip)
555 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
556 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
557 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
558 PP.setCurrentFPEvalMethod(PragmaLoc: Loc, Val: Value);
559}
560
561void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
562 PragmaMsStackAction Action,
563 PragmaFloatControlKind Value) {
564 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
565 if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
566 !CurContext->getRedeclContext()->isFileContext()) {
567 // Push and pop can only occur at file or namespace scope, or within a
568 // language linkage declaration.
569 Diag(Loc, diag::err_pragma_fc_pp_scope);
570 return;
571 }
572 switch (Value) {
573 default:
574 llvm_unreachable("invalid pragma float_control kind");
575 case PFC_Precise:
576 NewFPFeatures.setFPPreciseEnabled(true);
577 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
578 break;
579 case PFC_NoPrecise:
580 if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)
581 Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
582 else if (CurFPFeatures.getAllowFEnvAccess())
583 Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
584 else
585 NewFPFeatures.setFPPreciseEnabled(false);
586 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
587 break;
588 case PFC_Except:
589 if (!isPreciseFPEnabled())
590 Diag(Loc, diag::err_pragma_fc_except_requires_precise);
591 else
592 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);
593 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
594 break;
595 case PFC_NoExcept:
596 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);
597 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
598 break;
599 case PFC_Push:
600 FpPragmaStack.Act(PragmaLocation: Loc, Action: Sema::PSK_Push_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
601 break;
602 case PFC_Pop:
603 if (FpPragmaStack.Stack.empty()) {
604 Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
605 << "stack empty";
606 return;
607 }
608 FpPragmaStack.Act(PragmaLocation: Loc, Action, StackSlotLabel: StringRef(), Value: NewFPFeatures);
609 NewFPFeatures = FpPragmaStack.CurrentValue;
610 break;
611 }
612 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
613}
614
615void Sema::ActOnPragmaMSPointersToMembers(
616 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
617 SourceLocation PragmaLoc) {
618 MSPointerToMemberRepresentationMethod = RepresentationMethod;
619 ImplicitMSInheritanceAttrLoc = PragmaLoc;
620}
621
622void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
623 SourceLocation PragmaLoc,
624 MSVtorDispMode Mode) {
625 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
626 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
627 << "stack empty";
628 VtorDispStack.Act(PragmaLocation: PragmaLoc, Action, StackSlotLabel: StringRef(), Value: Mode);
629}
630
631template <>
632void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
633 PragmaMsStackAction Action,
634 llvm::StringRef StackSlotLabel,
635 AlignPackInfo Value) {
636 if (Action == PSK_Reset) {
637 CurrentValue = DefaultValue;
638 CurrentPragmaLocation = PragmaLocation;
639 return;
640 }
641 if (Action & PSK_Push)
642 Stack.emplace_back(Args: Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
643 PragmaLocation));
644 else if (Action & PSK_Pop) {
645 if (!StackSlotLabel.empty()) {
646 // If we've got a label, try to find it and jump there.
647 auto I = llvm::find_if(Range: llvm::reverse(C&: Stack), P: [&](const Slot &x) {
648 return x.StackSlotLabel == StackSlotLabel;
649 });
650 // We found the label, so pop from there.
651 if (I != Stack.rend()) {
652 CurrentValue = I->Value;
653 CurrentPragmaLocation = I->PragmaLocation;
654 Stack.erase(CS: std::prev(x: I.base()), CE: Stack.end());
655 }
656 } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
657 CurrentValue.IsPackAttr()) {
658 // XL '#pragma align(reset)' would pop the stack until
659 // a current in effect pragma align is popped.
660 auto I = llvm::find_if(Range: llvm::reverse(C&: Stack), P: [&](const Slot &x) {
661 return x.Value.IsAlignAttr();
662 });
663 // If we found pragma align so pop from there.
664 if (I != Stack.rend()) {
665 Stack.erase(CS: std::prev(x: I.base()), CE: Stack.end());
666 if (Stack.empty()) {
667 CurrentValue = DefaultValue;
668 CurrentPragmaLocation = PragmaLocation;
669 } else {
670 CurrentValue = Stack.back().Value;
671 CurrentPragmaLocation = Stack.back().PragmaLocation;
672 Stack.pop_back();
673 }
674 }
675 } else if (!Stack.empty()) {
676 // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
677 // over the baseline.
678 if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
679 return;
680
681 // We don't have a label, just pop the last entry.
682 CurrentValue = Stack.back().Value;
683 CurrentPragmaLocation = Stack.back().PragmaLocation;
684 Stack.pop_back();
685 }
686 }
687 if (Action & PSK_Set) {
688 CurrentValue = Value;
689 CurrentPragmaLocation = PragmaLocation;
690 }
691}
692
693bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
694 NamedDecl *Decl) {
695 SourceLocation PragmaLocation;
696 if (auto A = Decl->getAttr<SectionAttr>())
697 if (A->isImplicit())
698 PragmaLocation = A->getLocation();
699 auto SectionIt = Context.SectionInfos.find(Key: SectionName);
700 if (SectionIt == Context.SectionInfos.end()) {
701 Context.SectionInfos[SectionName] =
702 ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
703 return false;
704 }
705 // A pre-declared section takes precedence w/o diagnostic.
706 const auto &Section = SectionIt->second;
707 if (Section.SectionFlags == SectionFlags ||
708 ((SectionFlags & ASTContext::PSF_Implicit) &&
709 !(Section.SectionFlags & ASTContext::PSF_Implicit)))
710 return false;
711 Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
712 if (Section.Decl)
713 Diag(Section.Decl->getLocation(), diag::note_declared_at)
714 << Section.Decl->getName();
715 if (PragmaLocation.isValid())
716 Diag(PragmaLocation, diag::note_pragma_entered_here);
717 if (Section.PragmaSectionLocation.isValid())
718 Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
719 return true;
720}
721
722bool Sema::UnifySection(StringRef SectionName,
723 int SectionFlags,
724 SourceLocation PragmaSectionLocation) {
725 auto SectionIt = Context.SectionInfos.find(Key: SectionName);
726 if (SectionIt != Context.SectionInfos.end()) {
727 const auto &Section = SectionIt->second;
728 if (Section.SectionFlags == SectionFlags)
729 return false;
730 if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
731 Diag(PragmaSectionLocation, diag::err_section_conflict)
732 << "this" << Section;
733 if (Section.Decl)
734 Diag(Section.Decl->getLocation(), diag::note_declared_at)
735 << Section.Decl->getName();
736 if (Section.PragmaSectionLocation.isValid())
737 Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
738 return true;
739 }
740 }
741 Context.SectionInfos[SectionName] =
742 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
743 return false;
744}
745
746/// Called on well formed \#pragma bss_seg().
747void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
748 PragmaMsStackAction Action,
749 llvm::StringRef StackSlotLabel,
750 StringLiteral *SegmentName,
751 llvm::StringRef PragmaName) {
752 PragmaStack<StringLiteral *> *Stack =
753 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
754 .Case(S: "data_seg", Value: &DataSegStack)
755 .Case(S: "bss_seg", Value: &BSSSegStack)
756 .Case(S: "const_seg", Value: &ConstSegStack)
757 .Case(S: "code_seg", Value: &CodeSegStack);
758 if (Action & PSK_Pop && Stack->Stack.empty())
759 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
760 << "stack empty";
761 if (SegmentName) {
762 if (!checkSectionName(LiteralLoc: SegmentName->getBeginLoc(), Str: SegmentName->getString()))
763 return;
764
765 if (SegmentName->getString() == ".drectve" &&
766 Context.getTargetInfo().getCXXABI().isMicrosoft())
767 Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
768 }
769
770 Stack->Act(PragmaLocation, Action, StackSlotLabel, Value: SegmentName);
771}
772
773/// Called on well formed \#pragma strict_gs_check().
774void Sema::ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
775 PragmaMsStackAction Action,
776 bool Value) {
777 if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())
778 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << "strict_gs_check"
779 << "stack empty";
780
781 StrictGuardStackCheckStack.Act(PragmaLocation, Action, StackSlotLabel: StringRef(), Value);
782}
783
784/// Called on well formed \#pragma bss_seg().
785void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
786 int SectionFlags, StringLiteral *SegmentName) {
787 UnifySection(SectionName: SegmentName->getString(), SectionFlags, PragmaSectionLocation: PragmaLocation);
788}
789
790void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
791 StringLiteral *SegmentName) {
792 // There's no stack to maintain, so we just have a current section. When we
793 // see the default section, reset our current section back to null so we stop
794 // tacking on unnecessary attributes.
795 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
796 CurInitSegLoc = PragmaLocation;
797}
798
799void Sema::ActOnPragmaMSAllocText(
800 SourceLocation PragmaLocation, StringRef Section,
801 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
802 &Functions) {
803 if (!CurContext->getRedeclContext()->isFileContext()) {
804 Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
805 return;
806 }
807
808 for (auto &Function : Functions) {
809 IdentifierInfo *II;
810 SourceLocation Loc;
811 std::tie(args&: II, args&: Loc) = Function;
812
813 DeclarationName DN(II);
814 NamedDecl *ND = LookupSingleName(S: TUScope, Name: DN, Loc, NameKind: LookupOrdinaryName);
815 if (!ND) {
816 Diag(Loc, diag::err_undeclared_use) << II->getName();
817 return;
818 }
819
820 auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());
821 if (!FD) {
822 Diag(Loc, diag::err_pragma_alloc_text_not_function);
823 return;
824 }
825
826 if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
827 Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
828 return;
829 }
830
831 FunctionToSectionMap[II->getName()] = std::make_tuple(args&: Section, args&: Loc);
832 }
833}
834
835void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
836 SourceLocation PragmaLoc) {
837
838 IdentifierInfo *Name = IdTok.getIdentifierInfo();
839 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
840 LookupParsedName(R&: Lookup, S: curScope, SS: nullptr, AllowBuiltinCreation: true);
841
842 if (Lookup.empty()) {
843 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
844 << Name << SourceRange(IdTok.getLocation());
845 return;
846 }
847
848 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
849 if (!VD) {
850 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
851 << Name << SourceRange(IdTok.getLocation());
852 return;
853 }
854
855 // Warn if this was used before being marked unused.
856 if (VD->isUsed())
857 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
858
859 VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
860 UnusedAttr::GNU_unused));
861}
862
863void Sema::AddCFAuditedAttribute(Decl *D) {
864 IdentifierInfo *Ident;
865 SourceLocation Loc;
866 std::tie(args&: Ident, args&: Loc) = PP.getPragmaARCCFCodeAuditedInfo();
867 if (!Loc.isValid()) return;
868
869 // Don't add a redundant or conflicting attribute.
870 if (D->hasAttr<CFAuditedTransferAttr>() ||
871 D->hasAttr<CFUnknownTransferAttr>())
872 return;
873
874 AttributeCommonInfo Info(Ident, SourceRange(Loc),
875 AttributeCommonInfo::Form::Pragma());
876 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
877}
878
879namespace {
880
881std::optional<attr::SubjectMatchRule>
882getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
883 using namespace attr;
884 switch (Rule) {
885 default:
886 return std::nullopt;
887#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
888#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
889 case Value: \
890 return Parent;
891#include "clang/Basic/AttrSubMatchRulesList.inc"
892 }
893}
894
895bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
896 using namespace attr;
897 switch (Rule) {
898 default:
899 return false;
900#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
901#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
902 case Value: \
903 return IsNegated;
904#include "clang/Basic/AttrSubMatchRulesList.inc"
905 }
906}
907
908CharSourceRange replacementRangeForListElement(const Sema &S,
909 SourceRange Range) {
910 // Make sure that the ',' is removed as well.
911 SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
912 loc: Range.getEnd(), TKind: tok::comma, SM: S.getSourceManager(), LangOpts: S.getLangOpts(),
913 /*SkipTrailingWhitespaceAndNewLine=*/false);
914 if (AfterCommaLoc.isValid())
915 return CharSourceRange::getCharRange(B: Range.getBegin(), E: AfterCommaLoc);
916 else
917 return CharSourceRange::getTokenRange(R: Range);
918}
919
920std::string
921attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
922 std::string Result;
923 llvm::raw_string_ostream OS(Result);
924 for (const auto &I : llvm::enumerate(Rules)) {
925 if (I.index())
926 OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
927 OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
928 }
929 return Result;
930}
931
932} // end anonymous namespace
933
934void Sema::ActOnPragmaAttributeAttribute(
935 ParsedAttr &Attribute, SourceLocation PragmaLoc,
936 attr::ParsedSubjectMatchRuleSet Rules) {
937 Attribute.setIsPragmaClangAttribute();
938 SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
939 // Gather the subject match rules that are supported by the attribute.
940 SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
941 StrictSubjectMatchRuleSet;
942 Attribute.getMatchRules(LangOpts, MatchRules&: StrictSubjectMatchRuleSet);
943
944 // Figure out which subject matching rules are valid.
945 if (StrictSubjectMatchRuleSet.empty()) {
946 // Check for contradicting match rules. Contradicting match rules are
947 // either:
948 // - a top-level rule and one of its sub-rules. E.g. variable and
949 // variable(is_parameter).
950 // - a sub-rule and a sibling that's negated. E.g.
951 // variable(is_thread_local) and variable(unless(is_parameter))
952 llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
953 RulesToFirstSpecifiedNegatedSubRule;
954 for (const auto &Rule : Rules) {
955 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
956 std::optional<attr::SubjectMatchRule> ParentRule =
957 getParentAttrMatcherRule(MatchRule);
958 if (!ParentRule)
959 continue;
960 auto It = Rules.find(*ParentRule);
961 if (It != Rules.end()) {
962 // A sub-rule contradicts a parent rule.
963 Diag(Rule.second.getBegin(),
964 diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
965 << attr::getSubjectMatchRuleSpelling(MatchRule)
966 << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
967 << FixItHint::CreateRemoval(
968 replacementRangeForListElement(*this, Rule.second));
969 // Keep going without removing this rule as it won't change the set of
970 // declarations that receive the attribute.
971 continue;
972 }
973 if (isNegatedAttrMatcherSubRule(MatchRule))
974 RulesToFirstSpecifiedNegatedSubRule.insert(
975 std::make_pair(*ParentRule, Rule));
976 }
977 bool IgnoreNegatedSubRules = false;
978 for (const auto &Rule : Rules) {
979 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
980 std::optional<attr::SubjectMatchRule> ParentRule =
981 getParentAttrMatcherRule(MatchRule);
982 if (!ParentRule)
983 continue;
984 auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
985 if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
986 It->second != Rule) {
987 // Negated sub-rule contradicts another sub-rule.
988 Diag(
989 It->second.second.getBegin(),
990 diag::
991 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
992 << attr::getSubjectMatchRuleSpelling(
993 attr::SubjectMatchRule(It->second.first))
994 << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
995 << FixItHint::CreateRemoval(
996 replacementRangeForListElement(*this, It->second.second));
997 // Keep going but ignore all of the negated sub-rules.
998 IgnoreNegatedSubRules = true;
999 RulesToFirstSpecifiedNegatedSubRule.erase(It);
1000 }
1001 }
1002
1003 if (!IgnoreNegatedSubRules) {
1004 for (const auto &Rule : Rules)
1005 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
1006 } else {
1007 for (const auto &Rule : Rules) {
1008 if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
1009 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
1010 }
1011 }
1012 Rules.clear();
1013 } else {
1014 // Each rule in Rules must be a strict subset of the attribute's
1015 // SubjectMatch rules. I.e. we're allowed to use
1016 // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
1017 // but should not allow `apply_to=variables` on an attribute which has
1018 // `SubjectList<[GlobalVar]>`.
1019 for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
1020 // First, check for exact match.
1021 if (Rules.erase(StrictRule.first)) {
1022 // Add the rule to the set of attribute receivers only if it's supported
1023 // in the current language mode.
1024 if (StrictRule.second)
1025 SubjectMatchRules.push_back(Elt: StrictRule.first);
1026 }
1027 }
1028 // Check remaining rules for subset matches.
1029 auto RulesToCheck = Rules;
1030 for (const auto &Rule : RulesToCheck) {
1031 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1032 if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
1033 if (llvm::any_of(StrictSubjectMatchRuleSet,
1034 [ParentRule](const auto &StrictRule) {
1035 return StrictRule.first == *ParentRule &&
1036 StrictRule.second; // IsEnabled
1037 })) {
1038 SubjectMatchRules.push_back(MatchRule);
1039 Rules.erase(MatchRule);
1040 }
1041 }
1042 }
1043 }
1044
1045 if (!Rules.empty()) {
1046 auto Diagnostic =
1047 Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
1048 << Attribute;
1049 SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
1050 for (const auto &Rule : Rules) {
1051 ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
1052 Diagnostic << FixItHint::CreateRemoval(
1053 replacementRangeForListElement(*this, Rule.second));
1054 }
1055 Diagnostic << attrMatcherRuleListToString(Rules: ExtraRules);
1056 }
1057
1058 if (PragmaAttributeStack.empty()) {
1059 Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
1060 return;
1061 }
1062
1063 PragmaAttributeStack.back().Entries.push_back(
1064 Elt: {.Loc: PragmaLoc, .Attribute: &Attribute, .MatchRules: std::move(SubjectMatchRules), /*IsUsed=*/false});
1065}
1066
1067void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
1068 const IdentifierInfo *Namespace) {
1069 PragmaAttributeStack.emplace_back();
1070 PragmaAttributeStack.back().Loc = PragmaLoc;
1071 PragmaAttributeStack.back().Namespace = Namespace;
1072}
1073
1074void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
1075 const IdentifierInfo *Namespace) {
1076 if (PragmaAttributeStack.empty()) {
1077 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1078 return;
1079 }
1080
1081 // Dig back through the stack trying to find the most recently pushed group
1082 // that in Namespace. Note that this works fine if no namespace is present,
1083 // think of push/pops without namespaces as having an implicit "nullptr"
1084 // namespace.
1085 for (size_t Index = PragmaAttributeStack.size(); Index;) {
1086 --Index;
1087 if (PragmaAttributeStack[Index].Namespace == Namespace) {
1088 for (const PragmaAttributeEntry &Entry :
1089 PragmaAttributeStack[Index].Entries) {
1090 if (!Entry.IsUsed) {
1091 assert(Entry.Attribute && "Expected an attribute");
1092 Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
1093 << *Entry.Attribute;
1094 Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
1095 }
1096 }
1097 PragmaAttributeStack.erase(CI: PragmaAttributeStack.begin() + Index);
1098 return;
1099 }
1100 }
1101
1102 if (Namespace)
1103 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
1104 << 0 << Namespace->getName();
1105 else
1106 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1107}
1108
1109void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
1110 if (PragmaAttributeStack.empty())
1111 return;
1112 for (auto &Group : PragmaAttributeStack) {
1113 for (auto &Entry : Group.Entries) {
1114 ParsedAttr *Attribute = Entry.Attribute;
1115 assert(Attribute && "Expected an attribute");
1116 assert(Attribute->isPragmaClangAttribute() &&
1117 "expected #pragma clang attribute");
1118
1119 // Ensure that the attribute can be applied to the given declaration.
1120 bool Applies = false;
1121 for (const auto &Rule : Entry.MatchRules) {
1122 if (Attribute->appliesToDecl(D, MatchRule: Rule)) {
1123 Applies = true;
1124 break;
1125 }
1126 }
1127 if (!Applies)
1128 continue;
1129 Entry.IsUsed = true;
1130 PragmaAttributeCurrentTargetDecl = D;
1131 ParsedAttributesView Attrs;
1132 Attrs.addAtEnd(newAttr: Attribute);
1133 ProcessDeclAttributeList(S, D, AttrList: Attrs);
1134 PragmaAttributeCurrentTargetDecl = nullptr;
1135 }
1136 }
1137}
1138
1139void Sema::PrintPragmaAttributeInstantiationPoint() {
1140 assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1141 Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1142 diag::note_pragma_attribute_applied_decl_here);
1143}
1144
1145void Sema::DiagnoseUnterminatedPragmaAttribute() {
1146 if (PragmaAttributeStack.empty())
1147 return;
1148 Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
1149}
1150
1151void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
1152 if(On)
1153 OptimizeOffPragmaLocation = SourceLocation();
1154 else
1155 OptimizeOffPragmaLocation = PragmaLoc;
1156}
1157
1158void Sema::ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn) {
1159 if (!CurContext->getRedeclContext()->isFileContext()) {
1160 Diag(Loc, diag::err_pragma_expected_file_scope) << "optimize";
1161 return;
1162 }
1163
1164 MSPragmaOptimizeIsOn = IsOn;
1165}
1166
1167void Sema::ActOnPragmaMSFunction(
1168 SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {
1169 if (!CurContext->getRedeclContext()->isFileContext()) {
1170 Diag(Loc, diag::err_pragma_expected_file_scope) << "function";
1171 return;
1172 }
1173
1174 MSFunctionNoBuiltins.insert(Start: NoBuiltins.begin(), End: NoBuiltins.end());
1175}
1176
1177void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
1178 // In the future, check other pragmas if they're implemented (e.g. pragma
1179 // optimize 0 will probably map to this functionality too).
1180 if(OptimizeOffPragmaLocation.isValid())
1181 AddOptnoneAttributeIfNoConflicts(FD, Loc: OptimizeOffPragmaLocation);
1182}
1183
1184void Sema::AddSectionMSAllocText(FunctionDecl *FD) {
1185 if (!FD->getIdentifier())
1186 return;
1187
1188 StringRef Name = FD->getName();
1189 auto It = FunctionToSectionMap.find(Key: Name);
1190 if (It != FunctionToSectionMap.end()) {
1191 StringRef Section;
1192 SourceLocation Loc;
1193 std::tie(args&: Section, args&: Loc) = It->second;
1194
1195 if (!FD->hasAttr<SectionAttr>())
1196 FD->addAttr(SectionAttr::CreateImplicit(Context, Section));
1197 }
1198}
1199
1200void Sema::ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD) {
1201 // Don't modify the function attributes if it's "on". "on" resets the
1202 // optimizations to the ones listed on the command line
1203 if (!MSPragmaOptimizeIsOn)
1204 AddOptnoneAttributeIfNoConflicts(FD, Loc: FD->getBeginLoc());
1205}
1206
1207void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
1208 SourceLocation Loc) {
1209 // Don't add a conflicting attribute. No diagnostic is needed.
1210 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
1211 return;
1212
1213 // Add attributes only if required. Optnone requires noinline as well, but if
1214 // either is already present then don't bother adding them.
1215 if (!FD->hasAttr<OptimizeNoneAttr>())
1216 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
1217 if (!FD->hasAttr<NoInlineAttr>())
1218 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
1219}
1220
1221void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {
1222 SmallVector<StringRef> V(MSFunctionNoBuiltins.begin(),
1223 MSFunctionNoBuiltins.end());
1224 if (!MSFunctionNoBuiltins.empty())
1225 FD->addAttr(NoBuiltinAttr::CreateImplicit(Context, V.data(), V.size()));
1226}
1227
1228typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1229enum : unsigned { NoVisibility = ~0U };
1230
1231void Sema::AddPushedVisibilityAttribute(Decl *D) {
1232 if (!VisContext)
1233 return;
1234
1235 NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
1236 if (ND && ND->getExplicitVisibility(kind: NamedDecl::VisibilityForValue))
1237 return;
1238
1239 VisStack *Stack = static_cast<VisStack*>(VisContext);
1240 unsigned rawType = Stack->back().first;
1241 if (rawType == NoVisibility) return;
1242
1243 VisibilityAttr::VisibilityType type
1244 = (VisibilityAttr::VisibilityType) rawType;
1245 SourceLocation loc = Stack->back().second;
1246
1247 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
1248}
1249
1250/// FreeVisContext - Deallocate and null out VisContext.
1251void Sema::FreeVisContext() {
1252 delete static_cast<VisStack*>(VisContext);
1253 VisContext = nullptr;
1254}
1255
1256static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1257 // Put visibility on stack.
1258 if (!S.VisContext)
1259 S.VisContext = new VisStack;
1260
1261 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1262 Stack->push_back(x: std::make_pair(x&: type, y&: loc));
1263}
1264
1265void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
1266 SourceLocation PragmaLoc) {
1267 if (VisType) {
1268 // Compute visibility to use.
1269 VisibilityAttr::VisibilityType T;
1270 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
1271 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
1272 return;
1273 }
1274 PushPragmaVisibility(*this, T, PragmaLoc);
1275 } else {
1276 PopPragmaVisibility(IsNamespaceEnd: false, EndLoc: PragmaLoc);
1277 }
1278}
1279
1280void Sema::ActOnPragmaFPContract(SourceLocation Loc,
1281 LangOptions::FPModeKind FPC) {
1282 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1283 switch (FPC) {
1284 case LangOptions::FPM_On:
1285 NewFPFeatures.setAllowFPContractWithinStatement();
1286 break;
1287 case LangOptions::FPM_Fast:
1288 NewFPFeatures.setAllowFPContractAcrossStatement();
1289 break;
1290 case LangOptions::FPM_Off:
1291 NewFPFeatures.setDisallowFPContract();
1292 break;
1293 case LangOptions::FPM_FastHonorPragmas:
1294 llvm_unreachable("Should not happen");
1295 }
1296 FpPragmaStack.Act(PragmaLocation: Loc, Action: Sema::PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1297 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1298}
1299
1300void Sema::ActOnPragmaFPValueChangingOption(SourceLocation Loc,
1301 PragmaFPKind Kind, bool IsEnabled) {
1302 if (IsEnabled) {
1303 // For value unsafe context, combining this pragma with eval method
1304 // setting is not recommended. See comment in function FixupInvocation#506.
1305 int Reason = -1;
1306 if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
1307 // Eval method set using the option 'ffp-eval-method'.
1308 Reason = 1;
1309 if (PP.getLastFPEvalPragmaLocation().isValid())
1310 // Eval method set using the '#pragma clang fp eval_method'.
1311 // We could have both an option and a pragma used to the set the eval
1312 // method. The pragma overrides the option in the command line. The Reason
1313 // of the diagnostic is overriden too.
1314 Reason = 0;
1315 if (Reason != -1)
1316 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)
1317 << Reason << (Kind == PFK_Reassociate ? 4 : 5);
1318 }
1319
1320 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1321 switch (Kind) {
1322 case PFK_Reassociate:
1323 NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1324 break;
1325 case PFK_Reciprocal:
1326 NewFPFeatures.setAllowReciprocalOverride(IsEnabled);
1327 break;
1328 default:
1329 llvm_unreachable("unhandled value changing pragma fp");
1330 }
1331
1332 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1333 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1334}
1335
1336void Sema::ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode FPR) {
1337 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1338 NewFPFeatures.setConstRoundingModeOverride(FPR);
1339 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1340 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1341}
1342
1343void Sema::setExceptionMode(SourceLocation Loc,
1344 LangOptions::FPExceptionModeKind FPE) {
1345 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1346 NewFPFeatures.setSpecifiedExceptionModeOverride(FPE);
1347 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1348 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1349}
1350
1351void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1352 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1353 if (IsEnabled) {
1354 // Verify Microsoft restriction:
1355 // You can't enable fenv_access unless precise semantics are enabled.
1356 // Precise semantics can be enabled either by the float_control
1357 // pragma, or by using the /fp:precise or /fp:strict compiler options
1358 if (!isPreciseFPEnabled())
1359 Diag(Loc, diag::err_pragma_fenv_requires_precise);
1360 }
1361 NewFPFeatures.setAllowFEnvAccessOverride(IsEnabled);
1362 NewFPFeatures.setRoundingMathOverride(IsEnabled);
1363 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1364 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1365}
1366
1367void Sema::ActOnPragmaCXLimitedRange(SourceLocation Loc,
1368 LangOptions::ComplexRangeKind Range) {
1369 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1370 NewFPFeatures.setComplexRangeOverride(Range);
1371 FpPragmaStack.Act(PragmaLocation: Loc, Action: PSK_Set, StackSlotLabel: StringRef(), Value: NewFPFeatures);
1372 CurFPFeatures = NewFPFeatures.applyOverrides(LO: getLangOpts());
1373}
1374
1375void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
1376 LangOptions::FPExceptionModeKind FPE) {
1377 setExceptionMode(Loc, FPE);
1378}
1379
1380void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1381 SourceLocation Loc) {
1382 // Visibility calculations will consider the namespace's visibility.
1383 // Here we just want to note that we're in a visibility context
1384 // which overrides any enclosing #pragma context, but doesn't itself
1385 // contribute visibility.
1386 PushPragmaVisibility(S&: *this, type: NoVisibility, loc: Loc);
1387}
1388
1389void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1390 if (!VisContext) {
1391 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1392 return;
1393 }
1394
1395 // Pop visibility from stack
1396 VisStack *Stack = static_cast<VisStack*>(VisContext);
1397
1398 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1399 bool StartsWithPragma = Back->first != NoVisibility;
1400 if (StartsWithPragma && IsNamespaceEnd) {
1401 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1402 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1403
1404 // For better error recovery, eat all pushes inside the namespace.
1405 do {
1406 Stack->pop_back();
1407 Back = &Stack->back();
1408 StartsWithPragma = Back->first != NoVisibility;
1409 } while (StartsWithPragma);
1410 } else if (!StartsWithPragma && !IsNamespaceEnd) {
1411 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1412 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1413 return;
1414 }
1415
1416 Stack->pop_back();
1417 // To simplify the implementation, never keep around an empty stack.
1418 if (Stack->empty())
1419 FreeVisContext();
1420}
1421
1422template <typename Ty>
1423static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
1424 const ParsedAttr &A,
1425 bool SkipArgCountCheck) {
1426 // Several attributes carry different semantics than the parsing requires, so
1427 // those are opted out of the common argument checks.
1428 //
1429 // We also bail on unknown and ignored attributes because those are handled
1430 // as part of the target-specific handling logic.
1431 if (A.getKind() == ParsedAttr::UnknownAttribute)
1432 return false;
1433 // Check whether the attribute requires specific language extensions to be
1434 // enabled.
1435 if (!A.diagnoseLangOpts(S))
1436 return true;
1437 // Check whether the attribute appertains to the given subject.
1438 if (!A.diagnoseAppertainsTo(S, Node))
1439 return true;
1440 // Check whether the attribute is mutually exclusive with other attributes
1441 // that have already been applied to the declaration.
1442 if (!A.diagnoseMutualExclusion(S, Node))
1443 return true;
1444 // Check whether the attribute exists in the target architecture.
1445 if (S.CheckAttrTarget(CurrAttr: A))
1446 return true;
1447
1448 if (A.hasCustomParsing())
1449 return false;
1450
1451 if (!SkipArgCountCheck) {
1452 if (A.getMinArgs() == A.getMaxArgs()) {
1453 // If there are no optional arguments, then checking for the argument
1454 // count is trivial.
1455 if (!A.checkExactlyNumArgs(S, Num: A.getMinArgs()))
1456 return true;
1457 } else {
1458 // There are optional arguments, so checking is slightly more involved.
1459 if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, Num: A.getMinArgs()))
1460 return true;
1461 else if (!A.hasVariadicArg() && A.getMaxArgs() &&
1462 !A.checkAtMostNumArgs(S, Num: A.getMaxArgs()))
1463 return true;
1464 }
1465 }
1466
1467 return false;
1468}
1469
1470bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
1471 bool SkipArgCountCheck) {
1472 return ::checkCommonAttributeFeatures(S&: *this, Node: D, A, SkipArgCountCheck);
1473}
1474bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
1475 bool SkipArgCountCheck) {
1476 return ::checkCommonAttributeFeatures(S&: *this, Node: S, A, SkipArgCountCheck);
1477}
1478

source code of clang/lib/Sema/SemaAttr.cpp