clang 23.0.0git
SemaAttr.cpp
Go to the documentation of this file.
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
15#include "clang/AST/Attr.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/Expr.h"
21#include "clang/Sema/Lookup.h"
22#include <optional>
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// Pragma 'pack' and 'options align'
27//===----------------------------------------------------------------------===//
28
30 StringRef SlotLabel,
31 bool ShouldAct)
32 : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
33 if (ShouldAct) {
34 S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
35 S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
36 S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
37 S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
38 S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
39 S.StrictGuardStackCheckStack.SentinelAction(PSK_Push, SlotLabel);
40 }
41}
42
44 if (ShouldAct) {
45 S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
46 S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
47 S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
48 S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
49 S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
50 S.StrictGuardStackCheckStack.SentinelAction(PSK_Pop, SlotLabel);
51 }
52}
53
55 AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
57 bool IsPackSet = InfoVal.IsPackSet();
58 bool IsXLPragma = getLangOpts().XLPragmaPack;
59
60 // If we are not under mac68k/natural alignment mode and also there is no pack
61 // value, we don't need any attributes.
62 if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
63 return;
64
65 if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
66 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
67 } else if (IsPackSet) {
68 // Check to see if we need a max field alignment attribute.
69 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
70 Context, InfoVal.getPackNumber() * 8));
71 }
72
73 if (IsXLPragma && M == AlignPackInfo::Natural)
74 RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
75
76 if (AlignPackIncludeStack.empty())
77 return;
78 // The #pragma align/pack affected a record in an included file, so Clang
79 // should warn when that pragma was written in a file that included the
80 // included file.
81 for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack)) {
82 if (AlignPackedInclude.CurrentPragmaLocation !=
83 AlignPackStack.CurrentPragmaLocation)
84 break;
85 if (AlignPackedInclude.HasNonDefaultValue)
86 AlignPackedInclude.ShouldWarnOnInclude = true;
87 }
88}
89
92 RD->addAttr(MSStructAttr::CreateImplicit(Context));
93
94 // FIXME: We should merge AddAlignmentAttributesForRecord with
95 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
96 // all active pragmas and applies them as attributes to class definitions.
97 if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
98 RD->addAttr(MSVtorDispAttr::CreateImplicit(
99 Context, unsigned(VtorDispStack.CurrentValue)));
100}
101
102template <typename Attribute>
105 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
106 return;
107
108 for (Decl *Redecl : Record->redecls())
109 Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
110}
111
113 CXXRecordDecl *UnderlyingRecord) {
114 if (!UnderlyingRecord)
115 return;
116
117 const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
118 if (!Parent)
119 return;
120
121 static const llvm::StringSet<> Containers{
122 "array",
123 "basic_string",
124 "deque",
125 "forward_list",
126 "vector",
127 "list",
128 "map",
129 "multiset",
130 "multimap",
131 "priority_queue",
132 "queue",
133 "set",
134 "stack",
135 "unordered_set",
136 "unordered_map",
137 "unordered_multiset",
138 "unordered_multimap",
139 "flat_map",
140 "flat_set",
141 };
142
143 static const llvm::StringSet<> Iterators{"iterator", "const_iterator",
144 "reverse_iterator",
145 "const_reverse_iterator"};
146
147 if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
148 Containers.count(Parent->getName()))
150 UnderlyingRecord);
151}
152
154
155 QualType Canonical = TD->getUnderlyingType().getCanonicalType();
156
157 CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
158 if (!RD) {
159 if (auto *TST =
160 dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
161
162 if (const auto *TD = TST->getTemplateName().getAsTemplateDecl())
163 RD = dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
164 }
165 }
166
168}
169
171 static const llvm::StringSet<> StdOwners{
172 "any",
173 "array",
174 "basic_regex",
175 "basic_string",
176 "deque",
177 "forward_list",
178 "vector",
179 "list",
180 "map",
181 "multiset",
182 "multimap",
183 "optional",
184 "priority_queue",
185 "queue",
186 "set",
187 "stack",
188 "unique_ptr",
189 "unordered_set",
190 "unordered_map",
191 "unordered_multiset",
192 "unordered_multimap",
193 "variant",
194 "flat_map",
195 "flat_set",
196 };
197 static const llvm::StringSet<> StdPointers{
198 "basic_string_view",
199 "reference_wrapper",
200 "regex_iterator",
201 "span",
202 };
203
204 if (!Record->getIdentifier())
205 return;
206
207 // Handle classes that directly appear in std namespace.
208 if (Record->isInStdNamespace()) {
209 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
210 return;
211
212 if (StdOwners.count(Record->getName()))
214 else if (StdPointers.count(Record->getName()))
216
217 return;
218 }
219
220 // Handle nested classes that could be a gsl::Pointer.
222}
223
225 if (FD->getNumParams() == 0)
226 return;
227 // Skip void returning functions (except constructors). This can occur in
228 // cases like 'as_const'.
230 return;
231
232 if (unsigned BuiltinID = FD->getBuiltinID()) {
233 // Add lifetime attribute to std::move, std::fowrard et al.
234 switch (BuiltinID) {
235 case Builtin::BIaddressof:
236 case Builtin::BI__addressof:
237 case Builtin::BI__builtin_addressof:
238 case Builtin::BIas_const:
239 case Builtin::BIforward:
240 case Builtin::BIforward_like:
241 case Builtin::BImove:
242 case Builtin::BImove_if_noexcept:
243 if (ParmVarDecl *P = FD->getParamDecl(0u);
244 !P->hasAttr<LifetimeBoundAttr>())
245 P->addAttr(
246 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
247 break;
248 default:
249 break;
250 }
251 return;
252 }
253 if (auto *CMD = dyn_cast<CXXMethodDecl>(FD)) {
254 const auto *CRD = CMD->getParent();
255 if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
256 return;
257
258 if (isa<CXXConstructorDecl>(CMD)) {
259 auto *Param = CMD->getParamDecl(0);
260 if (Param->hasAttr<LifetimeBoundAttr>())
261 return;
262 if (CRD->getName() == "basic_string_view" &&
263 Param->getType()->isPointerType()) {
264 // construct from a char array pointed by a pointer.
265 // basic_string_view(const CharT* s);
266 // basic_string_view(const CharT* s, size_type count);
267 Param->addAttr(
268 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
269 } else if (CRD->getName() == "span") {
270 // construct from a reference of array.
271 // span(std::type_identity_t<element_type> (&arr)[N]);
272 const auto *LRT = Param->getType()->getAs<LValueReferenceType>();
273 if (LRT && LRT->getPointeeType().IgnoreParens()->isArrayType())
274 Param->addAttr(
275 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
276 }
277 }
278 }
279}
280
282 auto *MD = dyn_cast_if_present<CXXMethodDecl>(FD);
283 if (!MD || !MD->getParent()->isInStdNamespace())
284 return;
285 auto Annotate = [this](const FunctionDecl *MD) {
286 // Do not infer if any parameter is explicitly annotated.
287 for (ParmVarDecl *PVD : MD->parameters())
288 if (PVD->hasAttr<LifetimeCaptureByAttr>())
289 return;
290 for (ParmVarDecl *PVD : MD->parameters()) {
291 // Methods in standard containers that capture values typically accept
292 // reference-type parameters, e.g., `void push_back(const T& value)`.
293 // We only apply the lifetime_capture_by attribute to parameters of
294 // pointer-like reference types (`const T&`, `T&&`).
295 if (PVD->getType()->isReferenceType() &&
296 lifetimes::isGslPointerType(PVD->getType().getNonReferenceType())) {
297 int CaptureByThis[] = {LifetimeCaptureByAttr::This};
298 PVD->addAttr(
299 LifetimeCaptureByAttr::CreateImplicit(Context, CaptureByThis, 1));
300 }
301 }
302 };
303
304 if (!MD->getIdentifier()) {
305 static const llvm::StringSet<> MapLikeContainer{
306 "map",
307 "multimap",
308 "unordered_map",
309 "unordered_multimap",
310 };
311 // Infer for the map's operator []:
312 // std::map<string_view, ...> m;
313 // m[ReturnString(..)] = ...; // !dangling references in m.
314 if (MD->getOverloadedOperator() == OO_Subscript &&
315 MapLikeContainer.contains(MD->getParent()->getName()))
316 Annotate(MD);
317 return;
318 }
319 static const llvm::StringSet<> CapturingMethods{
320 "insert", "insert_or_assign", "push", "push_front", "push_back"};
321 if (!CapturingMethods.contains(MD->getName()))
322 return;
323 Annotate(MD);
324}
325
327 static const llvm::StringSet<> Nullable{
328 "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
329 "coroutine_handle", "function", "move_only_function",
330 };
331
332 if (CRD->isInStdNamespace() && Nullable.count(CRD->getName()) &&
333 !CRD->hasAttr<TypeNullableAttr>())
334 for (Decl *Redecl : CRD->redecls())
335 Redecl->addAttr(TypeNullableAttr::CreateImplicit(Context));
336}
337
339 SourceLocation PragmaLoc) {
342
343 switch (Kind) {
344 // For most of the platforms we support, native and natural are the same.
345 // With XL, native is the same as power, natural means something else.
348 Action = Sema::PSK_Push_Set;
349 break;
351 Action = Sema::PSK_Push_Set;
352 ModeVal = AlignPackInfo::Natural;
353 break;
354
355 // Note that '#pragma options align=packed' is not equivalent to attribute
356 // packed, it has a different precedence relative to attribute aligned.
358 Action = Sema::PSK_Push_Set;
359 ModeVal = AlignPackInfo::Packed;
360 break;
361
363 // Check if the target supports this.
364 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
365 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
366 return;
367 }
368 Action = Sema::PSK_Push_Set;
369 ModeVal = AlignPackInfo::Mac68k;
370 break;
372 // Reset just pops the top of the stack, or resets the current alignment to
373 // default.
374 Action = Sema::PSK_Pop;
375 if (AlignPackStack.Stack.empty()) {
376 if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
377 AlignPackStack.CurrentValue.IsPackAttr()) {
378 Action = Sema::PSK_Reset;
379 } else {
380 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
381 << "stack empty";
382 return;
383 }
384 }
385 break;
386 }
387
388 AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
389
390 AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
391}
392
396 StringRef SecName) {
397 PragmaClangSection *CSec;
398 int SectionFlags = ASTContext::PSF_Read;
399 switch (SecKind) {
401 CSec = &PragmaClangBSSSection;
403 break;
406 SectionFlags |= ASTContext::PSF_Write;
407 break;
410 break;
413 break;
416 SectionFlags |= ASTContext::PSF_Execute;
417 break;
418 default:
419 llvm_unreachable("invalid clang section kind");
420 }
421
422 if (Action == PragmaClangSectionAction::Clear) {
423 CSec->Valid = false;
424 return;
425 }
426
427 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
428 Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
429 << toString(std::move(E));
430 CSec->Valid = false;
431 return;
432 }
433
434 if (UnifySection(SecName, SectionFlags, PragmaLoc))
435 return;
436
437 CSec->Valid = true;
438 CSec->SectionName = std::string(SecName);
439 CSec->PragmaLocation = PragmaLoc;
440}
441
443 StringRef SlotLabel, Expr *Alignment) {
444 bool IsXLPragma = getLangOpts().XLPragmaPack;
445 // XL pragma pack does not support identifier syntax.
446 if (IsXLPragma && !SlotLabel.empty()) {
447 Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
448 return;
449 }
450
451 const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
452
453 // If specified then alignment must be a "small" power of two.
454 unsigned AlignmentVal = 0;
455 AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
456
457 if (Alignment) {
458 std::optional<llvm::APSInt> Val;
459 Val = Alignment->getIntegerConstantExpr(Context);
460
461 // pack(0) is like pack(), which just works out since that is what
462 // we use 0 for in PackAttr.
463 if (Alignment->isTypeDependent() || !Val ||
464 !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
465 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
466 return; // Ignore
467 }
468
469 if (IsXLPragma && *Val == 0) {
470 // pack(0) does not work out with XL.
471 Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
472 return; // Ignore
473 }
474
475 AlignmentVal = (unsigned)Val->getZExtValue();
476 }
477
478 if (Action == Sema::PSK_Show) {
479 // Show the current alignment, making sure to show the right value
480 // for the default.
481 // FIXME: This should come from the target.
482 AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
483 if (ModeVal == AlignPackInfo::Mac68k &&
484 (IsXLPragma || CurVal.IsAlignAttr()))
485 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
486 else
487 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
488 }
489
490 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
491 // "#pragma pack(pop, identifier, n) is undefined"
492 if (Action & Sema::PSK_Pop) {
493 if (Alignment && !SlotLabel.empty())
494 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
495 if (AlignPackStack.Stack.empty()) {
496 assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
497 "Empty pack stack can only be at Native alignment mode.");
498 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
499 }
500 }
501
502 AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
503
504 AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
505}
506
510 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
511 Expr *&E = Args.begin()[Idx];
512 assert(E && "error are handled before");
513 if (E->isValueDependent() || E->isTypeDependent())
514 continue;
515
516 // FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic
517 // that adds implicit casts here.
518 if (E->getType()->isArrayType())
519 E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
520 clang::CK_ArrayToPointerDecay)
521 .get();
522 if (E->getType()->isFunctionType())
524 Context.getPointerType(E->getType()),
525 clang::CK_FunctionToPointerDecay, E, nullptr,
527 if (E->isLValue())
529 clang::CK_LValueToRValue, E, nullptr,
531
532 Expr::EvalResult Eval;
533 Notes.clear();
534 Eval.Diag = &Notes;
535
536 bool Result = E->EvaluateAsConstantExpr(Eval, Context);
537
538 /// Result means the expression can be folded to a constant.
539 /// Note.empty() means the expression is a valid constant expression in the
540 /// current language mode.
541 if (!Result || !Notes.empty()) {
542 Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
543 << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
544 for (auto &Note : Notes)
545 Diag(Note.first, Note.second);
546 return false;
547 }
548 E = ConstantExpr::Create(Context, E, Eval.Val);
549 }
550
551 return true;
552}
553
555 SourceLocation IncludeLoc) {
557 SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
558 // Warn about non-default alignment at #includes (without redundant
559 // warnings for the same directive in nested includes).
560 // The warning is delayed until the end of the file to avoid warnings
561 // for files that don't have any records that are affected by the modified
562 // alignment.
563 bool HasNonDefaultValue =
564 AlignPackStack.hasValue() &&
565 (AlignPackIncludeStack.empty() ||
566 AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
567 AlignPackIncludeStack.push_back(
568 {AlignPackStack.CurrentValue,
569 AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
570 HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
571 return;
572 }
573
575 "invalid kind");
576 AlignPackIncludeState PrevAlignPackState =
577 AlignPackIncludeStack.pop_back_val();
578 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
579 // information, diagnostics below might not be accurate if we have mixed
580 // pragmas.
581 if (PrevAlignPackState.ShouldWarnOnInclude) {
582 // Emit the delayed non-default alignment at #include warning.
583 Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
584 Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
585 }
586 // Warn about modified alignment after #includes.
587 if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
588 Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
589 Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
590 }
591}
592
594 if (AlignPackStack.Stack.empty())
595 return;
596 bool IsInnermost = true;
597
598 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
599 // information, diagnostics below might not be accurate if we have mixed
600 // pragmas.
601 for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
602 Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
603 // The user might have already reset the alignment, so suggest replacing
604 // the reset with a pop.
605 if (IsInnermost &&
606 AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
607 auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
608 diag::note_pragma_pack_pop_instead_reset);
609 SourceLocation FixItLoc =
610 Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
611 tok::l_paren, SourceMgr, LangOpts,
612 /*SkipTrailing=*/false);
613 if (FixItLoc.isValid())
614 DB << FixItHint::CreateInsertion(FixItLoc, "pop");
615 }
616 IsInnermost = false;
617 }
618}
619
623
625 PragmaMSCommentKind Kind, StringRef Arg) {
626 auto *PCD = PragmaCommentDecl::Create(
627 Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
628 Context.getTranslationUnitDecl()->addDecl(PCD);
629 Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
630}
631
633 StringRef Value) {
635 Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
636 Context.getTranslationUnitDecl()->addDecl(PDMD);
637 Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
638}
639
643 switch (Value) {
644 default:
645 llvm_unreachable("invalid pragma eval_method kind");
647 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
648 break;
650 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
651 break;
653 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
654 break;
655 }
656 if (getLangOpts().ApproxFunc)
657 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
658 if (getLangOpts().AllowFPReassoc)
659 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
660 if (getLangOpts().AllowRecip)
661 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
662 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
663 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
664 PP.setCurrentFPEvalMethod(Loc, Value);
665}
666
668 PragmaMsStackAction Action,
671 if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
672 !CurContext->getRedeclContext()->isFileContext()) {
673 // Push and pop can only occur at file or namespace scope, or within a
674 // language linkage declaration.
675 Diag(Loc, diag::err_pragma_fc_pp_scope);
676 return;
677 }
678 switch (Value) {
679 default:
680 llvm_unreachable("invalid pragma float_control kind");
681 case PFC_Precise:
682 NewFPFeatures.setFPPreciseEnabled(true);
683 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
684 break;
685 case PFC_NoPrecise:
686 if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)
687 Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
688 else if (CurFPFeatures.getAllowFEnvAccess())
689 Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
690 else
691 NewFPFeatures.setFPPreciseEnabled(false);
692 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
693 break;
694 case PFC_Except:
695 if (!isPreciseFPEnabled())
696 Diag(Loc, diag::err_pragma_fc_except_requires_precise);
697 else
698 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);
699 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
700 break;
701 case PFC_NoExcept:
702 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);
703 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
704 break;
705 case PFC_Push:
706 FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
707 break;
708 case PFC_Pop:
709 if (FpPragmaStack.Stack.empty()) {
710 Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
711 << "stack empty";
712 return;
713 }
714 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
715 NewFPFeatures = FpPragmaStack.CurrentValue;
716 break;
717 }
718 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
719}
720
727
729 SourceLocation PragmaLoc,
730 MSVtorDispMode Mode) {
731 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
732 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
733 << "stack empty";
734 VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
735}
736
737template <>
739 PragmaMsStackAction Action,
740 llvm::StringRef StackSlotLabel,
741 AlignPackInfo Value) {
742 if (Action == PSK_Reset) {
743 CurrentValue = DefaultValue;
744 CurrentPragmaLocation = PragmaLocation;
745 return;
746 }
747 if (Action & PSK_Push)
748 Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
749 PragmaLocation));
750 else if (Action & PSK_Pop) {
751 if (!StackSlotLabel.empty()) {
752 // If we've got a label, try to find it and jump there.
753 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
754 return x.StackSlotLabel == StackSlotLabel;
755 });
756 // We found the label, so pop from there.
757 if (I != Stack.rend()) {
758 CurrentValue = I->Value;
759 CurrentPragmaLocation = I->PragmaLocation;
760 Stack.erase(std::prev(I.base()), Stack.end());
761 }
762 } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
763 CurrentValue.IsPackAttr()) {
764 // XL '#pragma align(reset)' would pop the stack until
765 // a current in effect pragma align is popped.
766 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
767 return x.Value.IsAlignAttr();
768 });
769 // If we found pragma align so pop from there.
770 if (I != Stack.rend()) {
771 Stack.erase(std::prev(I.base()), Stack.end());
772 if (Stack.empty()) {
773 CurrentValue = DefaultValue;
774 CurrentPragmaLocation = PragmaLocation;
775 } else {
776 CurrentValue = Stack.back().Value;
777 CurrentPragmaLocation = Stack.back().PragmaLocation;
778 Stack.pop_back();
779 }
780 }
781 } else if (!Stack.empty()) {
782 // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
783 // over the baseline.
784 if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
785 return;
786
787 // We don't have a label, just pop the last entry.
788 CurrentValue = Stack.back().Value;
789 CurrentPragmaLocation = Stack.back().PragmaLocation;
790 Stack.pop_back();
791 }
792 }
793 if (Action & PSK_Set) {
794 CurrentValue = Value;
795 CurrentPragmaLocation = PragmaLocation;
796 }
797}
798
799bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
800 NamedDecl *Decl) {
801 SourceLocation PragmaLocation;
802 if (auto A = Decl->getAttr<SectionAttr>())
803 if (A->isImplicit())
804 PragmaLocation = A->getLocation();
805 auto [SectionIt, Inserted] = Context.SectionInfos.try_emplace(
806 SectionName, Decl, PragmaLocation, SectionFlags);
807 if (Inserted)
808 return false;
809 // A pre-declared section takes precedence w/o diagnostic.
810 const auto &Section = SectionIt->second;
811 if (Section.SectionFlags == SectionFlags ||
812 ((SectionFlags & ASTContext::PSF_Implicit) &&
813 !(Section.SectionFlags & ASTContext::PSF_Implicit)))
814 return false;
815 Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
816 if (Section.Decl)
817 Diag(Section.Decl->getLocation(), diag::note_declared_at)
818 << Section.Decl->getName();
819 if (PragmaLocation.isValid())
820 Diag(PragmaLocation, diag::note_pragma_entered_here);
821 if (Section.PragmaSectionLocation.isValid())
822 Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
823 return true;
824}
825
826bool Sema::UnifySection(StringRef SectionName,
827 int SectionFlags,
828 SourceLocation PragmaSectionLocation) {
829 auto SectionIt = Context.SectionInfos.find(SectionName);
830 if (SectionIt != Context.SectionInfos.end()) {
831 const auto &Section = SectionIt->second;
832 if (Section.SectionFlags == SectionFlags)
833 return false;
834 if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
835 Diag(PragmaSectionLocation, diag::err_section_conflict)
836 << "this" << Section;
837 if (Section.Decl)
838 Diag(Section.Decl->getLocation(), diag::note_declared_at)
839 << Section.Decl->getName();
840 if (Section.PragmaSectionLocation.isValid())
841 Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
842 return true;
843 }
844 }
845 Context.SectionInfos[SectionName] =
846 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
847 return false;
848}
849
850/// Called on well formed \#pragma bss_seg().
852 PragmaMsStackAction Action,
853 llvm::StringRef StackSlotLabel,
854 StringLiteral *SegmentName,
855 llvm::StringRef PragmaName) {
857 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
858 .Case("data_seg", &DataSegStack)
859 .Case("bss_seg", &BSSSegStack)
860 .Case("const_seg", &ConstSegStack)
861 .Case("code_seg", &CodeSegStack);
862 if (Action & PSK_Pop && Stack->Stack.empty())
863 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
864 << "stack empty";
865 if (SegmentName) {
866 if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
867 return;
868
869 if (SegmentName->getString() == ".drectve" &&
870 Context.getTargetInfo().getCXXABI().isMicrosoft())
871 Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
872 }
873
874 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
875}
876
877/// Called on well formed \#pragma strict_gs_check().
879 PragmaMsStackAction Action,
880 bool Value) {
881 if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())
882 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << "strict_gs_check"
883 << "stack empty";
884
885 StrictGuardStackCheckStack.Act(PragmaLocation, Action, StringRef(), Value);
886}
887
888/// Called on well formed \#pragma bss_seg().
890 int SectionFlags, StringLiteral *SegmentName) {
891 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
892}
893
895 StringLiteral *SegmentName) {
896 // There's no stack to maintain, so we just have a current section. When we
897 // see the default section, reset our current section back to null so we stop
898 // tacking on unnecessary attributes.
899 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
900 CurInitSegLoc = PragmaLocation;
901}
902
904 SourceLocation PragmaLocation, StringRef Section,
905 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
906 &Functions) {
907 if (!CurContext->getRedeclContext()->isFileContext()) {
908 Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
909 return;
910 }
911
912 for (auto &Function : Functions) {
913 IdentifierInfo *II;
914 SourceLocation Loc;
915 std::tie(II, Loc) = Function;
916
917 DeclarationName DN(II);
919 if (!ND) {
920 Diag(Loc, diag::err_undeclared_use) << II->getName();
921 return;
922 }
923
924 auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());
925 if (!FD) {
926 Diag(Loc, diag::err_pragma_alloc_text_not_function);
927 return;
928 }
929
930 if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
931 Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
932 return;
933 }
934
935 FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);
936 }
937}
938
939void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
940 SourceLocation PragmaLoc) {
941
942 IdentifierInfo *Name = IdTok.getIdentifierInfo();
943 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
944 LookupName(Lookup, curScope, /*AllowBuiltinCreation=*/true);
945
946 if (Lookup.empty()) {
947 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
948 << Name << SourceRange(IdTok.getLocation());
949 return;
950 }
951
952 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
953 if (!VD) {
954 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
955 << Name << SourceRange(IdTok.getLocation());
956 return;
957 }
958
959 // Warn if this was used before being marked unused.
960 if (VD->isUsed())
961 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
962
963 VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
964 UnusedAttr::GNU_unused));
965}
966
967namespace {
968
969std::optional<attr::SubjectMatchRule>
970getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
971 using namespace attr;
972 switch (Rule) {
973 default:
974 return std::nullopt;
975#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
976#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
977 case Value: \
978 return Parent;
979#include "clang/Basic/AttrSubMatchRulesList.inc"
980 }
981}
982
983bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
984 using namespace attr;
985 switch (Rule) {
986 default:
987 return false;
988#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
989#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
990 case Value: \
991 return IsNegated;
992#include "clang/Basic/AttrSubMatchRulesList.inc"
993 }
994}
995
996CharSourceRange replacementRangeForListElement(const Sema &S,
997 SourceRange Range) {
998 // Make sure that the ',' is removed as well.
999 SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
1000 Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
1001 /*SkipTrailingWhitespaceAndNewLine=*/false);
1002 if (AfterCommaLoc.isValid())
1003 return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
1004 else
1005 return CharSourceRange::getTokenRange(Range);
1006}
1007
1008std::string
1009attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
1010 std::string Result;
1011 llvm::raw_string_ostream OS(Result);
1012 for (const auto &I : llvm::enumerate(Rules)) {
1013 if (I.index())
1014 OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
1015 OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
1016 }
1017 return Result;
1018}
1019
1020} // end anonymous namespace
1021
1023 ParsedAttr &Attribute, SourceLocation PragmaLoc,
1025 Attribute.setIsPragmaClangAttribute();
1027 // Gather the subject match rules that are supported by the attribute.
1029 StrictSubjectMatchRuleSet;
1030 Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
1031
1032 // Figure out which subject matching rules are valid.
1033 if (StrictSubjectMatchRuleSet.empty()) {
1034 // Check for contradicting match rules. Contradicting match rules are
1035 // either:
1036 // - a top-level rule and one of its sub-rules. E.g. variable and
1037 // variable(is_parameter).
1038 // - a sub-rule and a sibling that's negated. E.g.
1039 // variable(is_thread_local) and variable(unless(is_parameter))
1040 llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
1041 RulesToFirstSpecifiedNegatedSubRule;
1042 for (const auto &Rule : Rules) {
1043 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1044 std::optional<attr::SubjectMatchRule> ParentRule =
1045 getParentAttrMatcherRule(MatchRule);
1046 if (!ParentRule)
1047 continue;
1048 auto It = Rules.find(*ParentRule);
1049 if (It != Rules.end()) {
1050 // A sub-rule contradicts a parent rule.
1051 Diag(Rule.second.getBegin(),
1052 diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
1054 << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
1056 replacementRangeForListElement(*this, Rule.second));
1057 // Keep going without removing this rule as it won't change the set of
1058 // declarations that receive the attribute.
1059 continue;
1060 }
1061 if (isNegatedAttrMatcherSubRule(MatchRule))
1062 RulesToFirstSpecifiedNegatedSubRule.insert(
1063 std::make_pair(*ParentRule, Rule));
1064 }
1065 bool IgnoreNegatedSubRules = false;
1066 for (const auto &Rule : Rules) {
1067 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1068 std::optional<attr::SubjectMatchRule> ParentRule =
1069 getParentAttrMatcherRule(MatchRule);
1070 if (!ParentRule)
1071 continue;
1072 auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
1073 if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
1074 It->second != Rule) {
1075 // Negated sub-rule contradicts another sub-rule.
1076 Diag(
1077 It->second.second.getBegin(),
1078 diag::
1079 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
1081 attr::SubjectMatchRule(It->second.first))
1082 << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
1084 replacementRangeForListElement(*this, It->second.second));
1085 // Keep going but ignore all of the negated sub-rules.
1086 IgnoreNegatedSubRules = true;
1087 RulesToFirstSpecifiedNegatedSubRule.erase(It);
1088 }
1089 }
1090
1091 if (!IgnoreNegatedSubRules) {
1092 for (const auto &Rule : Rules)
1093 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
1094 } else {
1095 for (const auto &Rule : Rules) {
1096 if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
1097 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
1098 }
1099 }
1100 Rules.clear();
1101 } else {
1102 // Each rule in Rules must be a strict subset of the attribute's
1103 // SubjectMatch rules. I.e. we're allowed to use
1104 // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
1105 // but should not allow `apply_to=variables` on an attribute which has
1106 // `SubjectList<[GlobalVar]>`.
1107 for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
1108 // First, check for exact match.
1109 if (Rules.erase(StrictRule.first)) {
1110 // Add the rule to the set of attribute receivers only if it's supported
1111 // in the current language mode.
1112 if (StrictRule.second)
1113 SubjectMatchRules.push_back(StrictRule.first);
1114 }
1115 }
1116 // Check remaining rules for subset matches.
1117 auto RulesToCheck = Rules;
1118 for (const auto &Rule : RulesToCheck) {
1119 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1120 if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
1121 if (llvm::any_of(StrictSubjectMatchRuleSet,
1122 [ParentRule](const auto &StrictRule) {
1123 return StrictRule.first == *ParentRule &&
1124 StrictRule.second; // IsEnabled
1125 })) {
1126 SubjectMatchRules.push_back(MatchRule);
1127 Rules.erase(MatchRule);
1128 }
1129 }
1130 }
1131 }
1132
1133 if (!Rules.empty()) {
1134 auto Diagnostic =
1135 Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
1136 << Attribute;
1138 for (const auto &Rule : Rules) {
1139 ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
1141 replacementRangeForListElement(*this, Rule.second));
1142 }
1143 Diagnostic << attrMatcherRuleListToString(ExtraRules);
1144 }
1145
1146 if (PragmaAttributeStack.empty()) {
1147 Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
1148 return;
1149 }
1150
1151 PragmaAttributeStack.back().Entries.push_back(
1152 {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
1153}
1154
1156 const IdentifierInfo *Namespace) {
1157 PragmaAttributeStack.emplace_back();
1158 PragmaAttributeStack.back().Loc = PragmaLoc;
1159 PragmaAttributeStack.back().Namespace = Namespace;
1160}
1161
1163 const IdentifierInfo *Namespace) {
1164 if (PragmaAttributeStack.empty()) {
1165 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1166 return;
1167 }
1168
1169 // Dig back through the stack trying to find the most recently pushed group
1170 // that in Namespace. Note that this works fine if no namespace is present,
1171 // think of push/pops without namespaces as having an implicit "nullptr"
1172 // namespace.
1173 for (size_t Index = PragmaAttributeStack.size(); Index;) {
1174 --Index;
1175 if (PragmaAttributeStack[Index].Namespace == Namespace) {
1176 for (const PragmaAttributeEntry &Entry :
1177 PragmaAttributeStack[Index].Entries) {
1178 if (!Entry.IsUsed) {
1179 assert(Entry.Attribute && "Expected an attribute");
1180 Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
1181 << *Entry.Attribute;
1182 Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
1183 }
1184 }
1185 PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
1186 return;
1187 }
1188 }
1189
1190 if (Namespace)
1191 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
1192 << 0 << Namespace->getName();
1193 else
1194 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1195}
1196
1198 if (PragmaAttributeStack.empty())
1199 return;
1200
1201 if (const auto *P = dyn_cast<ParmVarDecl>(D))
1202 if (P->getType()->isVoidType())
1203 return;
1204
1205 for (auto &Group : PragmaAttributeStack) {
1206 for (auto &Entry : Group.Entries) {
1207 ParsedAttr *Attribute = Entry.Attribute;
1208 assert(Attribute && "Expected an attribute");
1209 assert(Attribute->isPragmaClangAttribute() &&
1210 "expected #pragma clang attribute");
1211
1212 // Ensure that the attribute can be applied to the given declaration.
1213 bool Applies = false;
1214 for (const auto &Rule : Entry.MatchRules) {
1215 if (Attribute->appliesToDecl(D, Rule)) {
1216 Applies = true;
1217 break;
1218 }
1219 }
1220 if (!Applies)
1221 continue;
1222 Entry.IsUsed = true;
1225 Attrs.addAtEnd(Attribute);
1226 ProcessDeclAttributeList(S, D, Attrs);
1228 }
1229 }
1230}
1231
1234 assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1235 DiagFunc(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1236 PDiag(diag::note_pragma_attribute_applied_decl_here));
1237}
1238
1240 for (auto &[Type, Num] : ExcessPrecisionNotSatisfied) {
1241 assert(LocationOfExcessPrecisionNotSatisfied.isValid() &&
1242 "expected a valid source location");
1244 diag::warn_excess_precision_not_supported)
1245 << static_cast<bool>(Num);
1246 }
1247}
1248
1250 if (PragmaAttributeStack.empty())
1251 return;
1252 Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
1253}
1254
1256 if(On)
1258 else
1259 OptimizeOffPragmaLocation = PragmaLoc;
1260}
1261
1263 if (!CurContext->getRedeclContext()->isFileContext()) {
1264 Diag(Loc, diag::err_pragma_expected_file_scope) << "optimize";
1265 return;
1266 }
1267
1268 MSPragmaOptimizeIsOn = IsOn;
1269}
1270
1272 SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {
1273 if (!CurContext->getRedeclContext()->isFileContext()) {
1274 Diag(Loc, diag::err_pragma_expected_file_scope) << "function";
1275 return;
1276 }
1277
1278 MSFunctionNoBuiltins.insert_range(NoBuiltins);
1279}
1280
1282 // In the future, check other pragmas if they're implemented (e.g. pragma
1283 // optimize 0 will probably map to this functionality too).
1284 if(OptimizeOffPragmaLocation.isValid())
1286}
1287
1289 if (!FD->getIdentifier())
1290 return;
1291
1292 StringRef Name = FD->getName();
1293 auto It = FunctionToSectionMap.find(Name);
1294 if (It != FunctionToSectionMap.end()) {
1295 StringRef Section;
1296 SourceLocation Loc;
1297 std::tie(Section, Loc) = It->second;
1298
1299 if (!FD->hasAttr<SectionAttr>())
1300 FD->addAttr(SectionAttr::CreateImplicit(Context, Section));
1301 }
1302}
1303
1305 // Don't modify the function attributes if it's "on". "on" resets the
1306 // optimizations to the ones listed on the command line
1309}
1310
1312 SourceLocation Loc) {
1313 // Don't add a conflicting attribute. No diagnostic is needed.
1314 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
1315 return;
1316
1317 // Add attributes only if required. Optnone requires noinline as well, but if
1318 // either is already present then don't bother adding them.
1319 if (!FD->hasAttr<OptimizeNoneAttr>())
1320 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
1321 if (!FD->hasAttr<NoInlineAttr>())
1322 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
1323}
1324
1326 if (FD->isDeleted() || FD->isDefaulted())
1327 return;
1329 MSFunctionNoBuiltins.end());
1330 if (!MSFunctionNoBuiltins.empty())
1331 FD->addAttr(NoBuiltinAttr::CreateImplicit(Context, V.data(), V.size()));
1332}
1333
1335 SourceLocation NameLoc,
1336 Scope *curScope) {
1337 LookupResult Result(*this, IdentId, NameLoc, LookupOrdinaryName);
1338 LookupName(Result, curScope);
1339 if (!getLangOpts().CPlusPlus)
1340 return Result.getAsSingle<NamedDecl>();
1341 for (NamedDecl *D : Result) {
1342 if (auto *FD = dyn_cast<FunctionDecl>(D))
1343 if (FD->isExternC())
1344 return D;
1345 if (isa<VarDecl>(D))
1346 return D;
1347 }
1348 return nullptr;
1349}
1350
1352 Scope *curScope) {
1353 if (!CurContext->getRedeclContext()->isFileContext()) {
1354 Diag(NameLoc, diag::err_pragma_expected_file_scope) << "export";
1355 return;
1356 }
1357
1358 PendingPragmaInfo Info;
1359 Info.NameLoc = NameLoc;
1360 Info.Used = false;
1361
1362 NamedDecl *PrevDecl =
1363 lookupExternCFunctionOrVariable(IdentId, NameLoc, curScope);
1364 if (!PrevDecl) {
1365 PendingExportedNames[IdentId] = Info;
1366 return;
1367 }
1368
1369 if (auto *FD = dyn_cast<FunctionDecl>(PrevDecl->getCanonicalDecl())) {
1370 if (!FD->hasExternalFormalLinkage()) {
1371 Diag(NameLoc, diag::warn_pragma_not_applied) << "export" << PrevDecl;
1372 return;
1373 }
1374 if (FD->hasBody()) {
1375 Diag(NameLoc, diag::warn_pragma_not_applied_to_defined_symbol)
1376 << "export";
1377 return;
1378 }
1379 } else if (auto *VD = dyn_cast<VarDecl>(PrevDecl->getCanonicalDecl())) {
1380 if (!VD->hasExternalFormalLinkage()) {
1381 Diag(NameLoc, diag::warn_pragma_not_applied) << "export" << PrevDecl;
1382 return;
1383 }
1384 if (VD->hasDefinition() == VarDecl::Definition) {
1385 Diag(NameLoc, diag::warn_pragma_not_applied_to_defined_symbol)
1386 << "export";
1387 return;
1388 }
1389 }
1390 mergeVisibilityType(PrevDecl->getCanonicalDecl(), NameLoc,
1391 VisibilityAttr::Default);
1392}
1393
1394typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1395enum : unsigned { NoVisibility = ~0U };
1396
1398 if (!VisContext)
1399 return;
1400
1401 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1403 return;
1404
1405 VisStack *Stack = static_cast<VisStack*>(VisContext);
1406 unsigned rawType = Stack->back().first;
1407 if (rawType == NoVisibility) return;
1408
1409 VisibilityAttr::VisibilityType type
1410 = (VisibilityAttr::VisibilityType) rawType;
1411 SourceLocation loc = Stack->back().second;
1412
1413 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
1414}
1415
1417 delete static_cast<VisStack*>(VisContext);
1418 VisContext = nullptr;
1419}
1420
1421static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1422 // Put visibility on stack.
1423 if (!S.VisContext)
1424 S.VisContext = new VisStack;
1425
1426 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1427 Stack->push_back(std::make_pair(type, loc));
1428}
1429
1431 SourceLocation PragmaLoc) {
1432 if (VisType) {
1433 // Compute visibility to use.
1434 VisibilityAttr::VisibilityType T;
1435 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
1436 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
1437 return;
1438 }
1439 PushPragmaVisibility(*this, T, PragmaLoc);
1440 } else {
1441 PopPragmaVisibility(false, PragmaLoc);
1442 }
1443}
1444
1447 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1448 switch (FPC) {
1450 NewFPFeatures.setAllowFPContractWithinStatement();
1451 break;
1454 NewFPFeatures.setAllowFPContractAcrossStatement();
1455 break;
1457 NewFPFeatures.setDisallowFPContract();
1458 break;
1459 }
1460 FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
1461 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1462}
1463
1465 PragmaFPKind Kind, bool IsEnabled) {
1466 if (IsEnabled) {
1467 // For value unsafe context, combining this pragma with eval method
1468 // setting is not recommended. See comment in function FixupInvocation#506.
1469 int Reason = -1;
1470 if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
1471 // Eval method set using the option 'ffp-eval-method'.
1472 Reason = 1;
1473 if (PP.getLastFPEvalPragmaLocation().isValid())
1474 // Eval method set using the '#pragma clang fp eval_method'.
1475 // We could have both an option and a pragma used to the set the eval
1476 // method. The pragma overrides the option in the command line. The Reason
1477 // of the diagnostic is overriden too.
1478 Reason = 0;
1479 if (Reason != -1)
1480 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)
1481 << Reason << (Kind == PFK_Reassociate ? 4 : 5);
1482 }
1483
1484 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1485 switch (Kind) {
1486 case PFK_Reassociate:
1487 NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1488 break;
1489 case PFK_Reciprocal:
1490 NewFPFeatures.setAllowReciprocalOverride(IsEnabled);
1491 break;
1492 default:
1493 llvm_unreachable("unhandled value changing pragma fp");
1494 }
1495
1496 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1497 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1498}
1499
1500void Sema::ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode FPR) {
1501 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1502 NewFPFeatures.setConstRoundingModeOverride(FPR);
1503 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1504 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1505}
1506
1509 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1510 NewFPFeatures.setSpecifiedExceptionModeOverride(FPE);
1511 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1512 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1513}
1514
1516 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1517 if (IsEnabled) {
1518 // Verify Microsoft restriction:
1519 // You can't enable fenv_access unless precise semantics are enabled.
1520 // Precise semantics can be enabled either by the float_control
1521 // pragma, or by using the /fp:precise or /fp:strict compiler options
1522 if (!isPreciseFPEnabled())
1523 Diag(Loc, diag::err_pragma_fenv_requires_precise);
1524 }
1525 NewFPFeatures.setAllowFEnvAccessOverride(IsEnabled);
1526 NewFPFeatures.setRoundingMathOverride(IsEnabled);
1527 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1528 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1529}
1530
1533 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1534 NewFPFeatures.setComplexRangeOverride(Range);
1535 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1536 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1537}
1538
1543
1544void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1545 SourceLocation Loc) {
1546 // Visibility calculations will consider the namespace's visibility.
1547 // Here we just want to note that we're in a visibility context
1548 // which overrides any enclosing #pragma context, but doesn't itself
1549 // contribute visibility.
1551}
1552
1553void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1554 if (!VisContext) {
1555 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1556 return;
1557 }
1558
1559 // Pop visibility from stack
1560 VisStack *Stack = static_cast<VisStack*>(VisContext);
1561
1562 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1563 bool StartsWithPragma = Back->first != NoVisibility;
1564 if (StartsWithPragma && IsNamespaceEnd) {
1565 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1566 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1567
1568 // For better error recovery, eat all pushes inside the namespace.
1569 do {
1570 Stack->pop_back();
1571 Back = &Stack->back();
1572 StartsWithPragma = Back->first != NoVisibility;
1573 } while (StartsWithPragma);
1574 } else if (!StartsWithPragma && !IsNamespaceEnd) {
1575 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1576 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1577 return;
1578 }
1579
1580 Stack->pop_back();
1581 // To simplify the implementation, never keep around an empty stack.
1582 if (Stack->empty())
1584}
1585
1586template <typename Ty>
1587static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
1588 const ParsedAttr &A,
1589 bool SkipArgCountCheck) {
1590 // Several attributes carry different semantics than the parsing requires, so
1591 // those are opted out of the common argument checks.
1592 //
1593 // We also bail on unknown and ignored attributes because those are handled
1594 // as part of the target-specific handling logic.
1596 return false;
1597 // Check whether the attribute requires specific language extensions to be
1598 // enabled.
1599 if (!A.diagnoseLangOpts(S))
1600 return true;
1601 // Check whether the attribute appertains to the given subject.
1602 if (!A.diagnoseAppertainsTo(S, Node))
1603 return true;
1604 // Check whether the attribute is mutually exclusive with other attributes
1605 // that have already been applied to the declaration.
1606 if (!A.diagnoseMutualExclusion(S, Node))
1607 return true;
1608 // Check whether the attribute exists in the target architecture.
1609 if (S.CheckAttrTarget(A))
1610 return true;
1611
1612 if (A.hasCustomParsing())
1613 return false;
1614
1615 if (!SkipArgCountCheck) {
1616 if (A.getMinArgs() == A.getMaxArgs()) {
1617 // If there are no optional arguments, then checking for the argument
1618 // count is trivial.
1619 if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1620 return true;
1621 } else {
1622 // There are optional arguments, so checking is slightly more involved.
1623 if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))
1624 return true;
1625 else if (!A.hasVariadicArg() && A.getMaxArgs() &&
1626 !A.checkAtMostNumArgs(S, A.getMaxArgs()))
1627 return true;
1628 }
1629 }
1630
1631 return false;
1632}
1633
1635 bool SkipArgCountCheck) {
1636 return ::checkCommonAttributeFeatures(*this, D, A, SkipArgCountCheck);
1637}
1639 bool SkipArgCountCheck) {
1640 return ::checkCommonAttributeFeatures(*this, S, A, SkipArgCountCheck);
1641}
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
std::vector< std::pair< unsigned, SourceLocation > > VisStack
static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc)
@ NoVisibility
static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context, CXXRecordDecl *Record)
Definition SemaAttr.cpp:103
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
PtrTy get() const
Definition Ownership.h:171
Attr - This represents one attribute.
Definition Attr.h:46
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl()=delete
bool isInStdNamespace() const
Definition DeclBase.cpp:449
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
void setFPPreciseEnabled(bool Value)
FPOptions applyOverrides(FPOptions Base)
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
QualType getReturnType() const
Definition Decl.h:2845
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3625
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
ComplexRangeKind
Controls the various implementations for complex multiplication and.
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1387
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
This represents a decl that may have a name.
Definition Decl.h:274
@ VisibilityForValue
Do an LV computation for, ultimately, a non-type declaration.
Definition Decl.h:461
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
std::optional< Visibility > getExplicitVisibility(ExplicitVisibilityKind kind) const
If visibility was explicitly specified for this declaration, return that visibility.
Definition Decl.cpp:1313
Represents a parameter to a function.
Definition Decl.h:1790
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
bool hasCustomParsing() const
unsigned getMinArgs() const
bool checkExactlyNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has exactly as many args as Num.
bool hasVariadicArg() const
bool diagnoseMutualExclusion(class Sema &S, const Decl *D) const
bool diagnoseAppertainsTo(class Sema &S, const Decl *D) const
bool checkAtLeastNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at least as many args as Num.
unsigned getMaxArgs() const
AttributeCommonInfo::Kind getKind() const
Definition ParsedAttr.h:610
bool diagnoseLangOpts(class Sema &S) const
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
void addAtEnd(ParsedAttr *newAttr)
Definition ParsedAttr.h:827
static PragmaCommentDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation CommentLoc, PragmaMSCommentKind CommentKind, StringRef Arg)
Definition Decl.cpp:5503
static PragmaDetectMismatchDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation Loc, StringRef Name, StringRef Value)
Definition Decl.cpp:5526
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8388
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8573
QualType getCanonicalType() const
Definition TypeBase.h:8440
Represents a struct/union/class.
Definition Decl.h:4327
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
unsigned getPackNumber() const
Definition Sema.h:1915
bool IsPackSet() const
Definition Sema.h:1917
bool IsAlignAttr() const
Definition Sema.h:1911
Mode getAlignMode() const
Definition Sema.h:1913
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct)
Definition SemaAttr.cpp:29
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn)
pragma optimize("[optimization-list]", on | off).
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:507
void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc, Scope *curScope)
ActonPragmaExport - called on well-formed '#pragma export'.
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9382
void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace)
Called on well-formed '#pragma clang attribute pop'.
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value)
ActOnPragmaDetectMismatch - Call on well-formed #pragma detect_mismatch.
Definition SemaAttr.cpp:632
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
Definition Sema.h:2133
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2308
void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode)
Called to set constant rounding mode for floating point operations.
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1837
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str)
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, bool SkipArgCountCheck=false)
Handles semantic checking for features that are common to all attributes, such as checking whether a ...
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc)
Adds the 'optnone' attribute to the function declaration if there are no conflicts; Loc represents th...
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8382
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:281
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2068
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2062
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg)
ActOnPragmaMSComment - Called on well formed #pragma comment(kind, "arg").
Definition SemaAttr.cpp:624
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2057
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2069
void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName)
Called on well formed #pragma bss_seg/data_seg/const_seg/code_seg.
Definition SemaAttr.cpp:851
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value)
ActOnPragmaFloatControl - Call on well-formed #pragma float_control.
Definition SemaAttr.cpp:667
void ActOnPragmaMSPointersToMembers(LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc)
ActOnPragmaMSPointersToMembers - called on well formed #pragma pointers_to_members(representation met...
Definition SemaAttr.cpp:721
void DiagnosePrecisionLossInComplexDivision()
ASTContext & Context
Definition Sema.h:1300
void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc)
ActOnPragmaUnused - Called on well-formed '#pragma unused'.
Definition SemaAttr.cpp:939
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2350
void ActOnPragmaMSAllocText(SourceLocation PragmaLocation, StringRef Section, const SmallVector< std::tuple< IdentifierInfo *, SourceLocation > > &Functions)
Called on well-formed #pragma alloc_text().
Definition SemaAttr.cpp:903
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2065
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules)
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2061
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc)
ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
Definition SemaAttr.cpp:338
void ActOnPragmaCXLimitedRange(SourceLocation Loc, LangOptions::ComplexRangeKind Range)
ActOnPragmaCXLimitedRange - Called on well formed #pragma STDC CX_LIMITED_RANGE.
void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind)
Called on well formed '#pragma clang fp' that has option 'exceptions'.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
void ActOnPragmaFPEvalMethod(SourceLocation Loc, LangOptions::FPEvalMethodKind Value)
Definition SemaAttr.cpp:640
void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName)
ActOnPragmaClangSection - Called on well formed #pragma clang section.
Definition SemaAttr.cpp:393
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:799
void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind)
Called to set exception behavior for floating point operations.
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
const LangOptions & getLangOpts() const
Definition Sema.h:932
SourceLocation CurInitSegLoc
Definition Sema.h:2104
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value)
Called on well formed #pragma vtordisp().
Definition SemaAttr.cpp:728
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:224
Preprocessor & PP
Definition Sema.h:1299
bool MSPragmaOptimizeIsOn
The "on" or "off" argument passed by #pragma optimize, that denotes whether the optimizations in the ...
Definition Sema.h:2151
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2129
const LangOptions & LangOpts
Definition Sema.h:1298
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1838
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1827
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2050
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2060
llvm::StringMap< std::tuple< StringRef, SourceLocation > > FunctionToSectionMap
Sections used with pragma alloc_text.
Definition Sema.h:2107
llvm::SmallSetVector< StringRef, 4 > MSFunctionNoBuiltins
Set of no-builtin functions listed by #pragma function.
Definition Sema.h:2154
NamedDecl * lookupExternCFunctionOrVariable(IdentifierInfo *IdentId, SourceLocation NameLoc, Scope *curScope)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2103
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
void ActOnPragmaMSFunction(SourceLocation Loc, const llvm::SmallVectorImpl< StringRef > &NoBuiltins)
Call on well formed #pragma function.
void ActOnPragmaMSStruct(PragmaMSStructKind Kind)
ActOnPragmaMSStruct - Called on well formed #pragma ms_struct [on|off].
Definition SemaAttr.cpp:620
bool isPreciseFPEnabled()
Are precise floating point semantics currently enabled?
Definition Sema.h:2234
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName)
Called on well-formed #pragma init_seg().
Definition SemaAttr.cpp:894
bool MSStructPragmaOn
Definition Sema.h:1824
SourceManager & getSourceManager() const
Definition Sema.h:937
void PrintPragmaAttributeInstantiationPoint()
Definition Sema.h:2322
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition SemaAttr.cpp:554
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1839
void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind, bool IsEnabled)
Called on well formed #pragma clang fp reassociate or #pragma clang fp reciprocal.
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8381
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1836
llvm::Error isValidSectionSpecifier(StringRef Str)
Used to implement to perform semantic checking on attribute((section("foo"))) specifiers.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
PragmaStack< MSVtorDispMode > VtorDispStack
Whether to insert vtordisps prior to virtual bases in the Microsoft C++ ABI.
Definition Sema.h:2049
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2110
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
ASTConsumer & Consumer
Definition Sema.h:1301
PragmaAlignPackDiagnoseKind
Definition Sema.h:2212
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1259
void DiagnoseUnterminatedPragmaAttribute()
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
SourceManager & SourceMgr
Definition Sema.h:1303
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment)
ActOnPragmaPack - Called on well formed #pragma pack(...).
Definition SemaAttr.cpp:442
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:593
FPOptions CurFPFeatures
Definition Sema.h:1296
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2059
void ActOnPragmaVisibility(const IdentifierInfo *VisType, SourceLocation PragmaLoc)
ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
SourceLocation OptimizeOffPragmaLocation
This represents the last location of a "#pragma clang optimize off" directive if such a directive has...
Definition Sema.h:2138
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1822
void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, PragmaMsStackAction Action, bool Value)
ActOnPragmaMSStrictGuardStackCheck - Called on well formed #pragma strict_gs_check.
Definition SemaAttr.cpp:878
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1835
void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC)
ActOnPragmaFPContract - Called on well formed #pragma {STDC,OPENCL} FP_CONTRACT and #pragma clang fp ...
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc)
Called on well formed #pragma clang optimize.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled)
ActOnPragmaFenvAccess - Called on well formed #pragma STDC FENV_ACCESS.
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName)
Called on well formed #pragma section().
Definition SemaAttr.cpp:889
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:326
PragmaMsStackAction
Definition Sema.h:1841
@ PSK_Push_Set
Definition Sema.h:1847
@ PSK_Reset
Definition Sema.h:1842
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1976
StringRef getString() const
Definition Expr.h:1870
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isVoidType() const
Definition TypeBase.h:8991
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8724
bool isFunctionType() const
Definition TypeBase.h:8621
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
QualType getUnderlyingType() const
Definition Decl.h:3617
Represents a variable declaration or definition.
Definition Decl.h:926
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1301
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
SubjectMatchRule
A list of all the recognized kinds of attributes.
const char * getSubjectMatchRuleSpelling(SubjectMatchRule Rule)
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
bool isGslPointerType(QualType QT)
The JSON file list parser is used to communicate input to InstallAPI.
PragmaClangSectionAction
Definition Sema.h:476
@ PFK_Reassociate
Definition PragmaKinds.h:40
@ PFK_Reciprocal
Definition PragmaKinds.h:41
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
PragmaMSCommentKind
Definition PragmaKinds.h:14
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ AANT_ArgumentConstantExpr
PragmaOptionsAlignKind
Definition Sema.h:478
@ Result
The result type of a method or function.
Definition TypeBase.h:905
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition LangOptions.h:38
PragmaClangSectionKind
pragma clang section kind
Definition Sema.h:467
PragmaMSStructKind
Definition PragmaKinds.h:23
@ PMSST_ON
Definition PragmaKinds.h:25
PragmaFloatControlKind
Definition PragmaKinds.h:28
@ PFC_NoExcept
Definition PragmaKinds.h:33
@ PFC_NoPrecise
Definition PragmaKinds.h:31
@ PFC_Pop
Definition PragmaKinds.h:35
@ PFC_Precise
Definition PragmaKinds.h:30
@ PFC_Except
Definition PragmaKinds.h:32
@ PFC_Push
Definition PragmaKinds.h:34
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
SourceLocation CurrentPragmaLocation
Definition Sema.h:2054
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2345
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2113
SourceLocation PragmaLocation
Definition Sema.h:1832
SmallVector< Slot, 2 > Stack
Definition Sema.h:2033
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:1972