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 if (MD->getName() == "insert" && MD->getParent()->getName() == "basic_string")
324 return;
325 Annotate(MD);
326}
327
329 static const llvm::StringSet<> Nullable{
330 "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",
331 "coroutine_handle", "function", "move_only_function",
332 };
333
334 if (CRD->isInStdNamespace() && Nullable.count(CRD->getName()) &&
335 !CRD->hasAttr<TypeNullableAttr>())
336 for (Decl *Redecl : CRD->redecls())
337 Redecl->addAttr(TypeNullableAttr::CreateImplicit(Context));
338}
339
341 SourceLocation PragmaLoc) {
344
345 switch (Kind) {
346 // For most of the platforms we support, native and natural are the same.
347 // With XL, native is the same as power, natural means something else.
350 Action = Sema::PSK_Push_Set;
351 break;
353 Action = Sema::PSK_Push_Set;
354 ModeVal = AlignPackInfo::Natural;
355 break;
356
357 // Note that '#pragma options align=packed' is not equivalent to attribute
358 // packed, it has a different precedence relative to attribute aligned.
360 Action = Sema::PSK_Push_Set;
361 ModeVal = AlignPackInfo::Packed;
362 break;
363
365 // Check if the target supports this.
366 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
367 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
368 return;
369 }
370 Action = Sema::PSK_Push_Set;
371 ModeVal = AlignPackInfo::Mac68k;
372 break;
374 // Reset just pops the top of the stack, or resets the current alignment to
375 // default.
376 Action = Sema::PSK_Pop;
377 if (AlignPackStack.Stack.empty()) {
378 if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
379 AlignPackStack.CurrentValue.IsPackAttr()) {
380 Action = Sema::PSK_Reset;
381 } else {
382 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
383 << "stack empty";
384 return;
385 }
386 }
387 break;
388 }
389
390 AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
391
392 AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
393}
394
398 StringRef SecName) {
399 PragmaClangSection *CSec;
400 int SectionFlags = ASTContext::PSF_Read;
401 switch (SecKind) {
403 CSec = &PragmaClangBSSSection;
405 break;
408 SectionFlags |= ASTContext::PSF_Write;
409 break;
412 break;
415 break;
418 SectionFlags |= ASTContext::PSF_Execute;
419 break;
420 default:
421 llvm_unreachable("invalid clang section kind");
422 }
423
424 if (Action == PragmaClangSectionAction::Clear) {
425 CSec->Valid = false;
426 return;
427 }
428
429 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
430 Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
431 << toString(std::move(E));
432 CSec->Valid = false;
433 return;
434 }
435
436 if (UnifySection(SecName, SectionFlags, PragmaLoc))
437 return;
438
439 CSec->Valid = true;
440 CSec->SectionName = std::string(SecName);
441 CSec->PragmaLocation = PragmaLoc;
442}
443
445 StringRef SlotLabel, Expr *Alignment) {
446 bool IsXLPragma = getLangOpts().XLPragmaPack;
447 // XL pragma pack does not support identifier syntax.
448 if (IsXLPragma && !SlotLabel.empty()) {
449 Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
450 return;
451 }
452
453 const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
454
455 // If specified then alignment must be a "small" power of two.
456 unsigned AlignmentVal = 0;
457 AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
458
459 if (Alignment) {
460 std::optional<llvm::APSInt> Val;
461 Val = Alignment->getIntegerConstantExpr(Context);
462
463 // pack(0) is like pack(), which just works out since that is what
464 // we use 0 for in PackAttr.
465 if (Alignment->isTypeDependent() || !Val ||
466 !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
467 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
468 return; // Ignore
469 }
470
471 if (IsXLPragma && *Val == 0) {
472 // pack(0) does not work out with XL.
473 Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
474 return; // Ignore
475 }
476
477 AlignmentVal = (unsigned)Val->getZExtValue();
478 }
479
480 if (Action == Sema::PSK_Show) {
481 // Show the current alignment, making sure to show the right value
482 // for the default.
483 // FIXME: This should come from the target.
484 AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
485 if (ModeVal == AlignPackInfo::Mac68k &&
486 (IsXLPragma || CurVal.IsAlignAttr()))
487 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
488 else
489 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
490 }
491
492 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
493 // "#pragma pack(pop, identifier, n) is undefined"
494 if (Action & Sema::PSK_Pop) {
495 if (Alignment && !SlotLabel.empty())
496 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
497 if (AlignPackStack.Stack.empty()) {
498 assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
499 "Empty pack stack can only be at Native alignment mode.");
500 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
501 }
502 }
503
504 AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
505
506 AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
507}
508
512 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
513 Expr *&E = Args.begin()[Idx];
514 assert(E && "error are handled before");
515 if (E->isValueDependent() || E->isTypeDependent())
516 continue;
517
518 // FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic
519 // that adds implicit casts here.
520 if (E->getType()->isArrayType())
521 E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
522 clang::CK_ArrayToPointerDecay)
523 .get();
524 if (E->getType()->isFunctionType())
526 Context.getPointerType(E->getType()),
527 clang::CK_FunctionToPointerDecay, E, nullptr,
529 if (E->isLValue())
531 clang::CK_LValueToRValue, E, nullptr,
533
534 Expr::EvalResult Eval;
535 Notes.clear();
536 Eval.Diag = &Notes;
537
538 bool Result = E->EvaluateAsConstantExpr(Eval, Context);
539
540 /// Result means the expression can be folded to a constant.
541 /// Note.empty() means the expression is a valid constant expression in the
542 /// current language mode.
543 if (!Result || !Notes.empty()) {
544 Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
545 << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
546 for (auto &Note : Notes)
547 Diag(Note.first, Note.second);
548 return false;
549 }
550 E = ConstantExpr::Create(Context, E, Eval.Val);
551 }
552
553 return true;
554}
555
557 SourceLocation IncludeLoc) {
559 SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
560 // Warn about non-default alignment at #includes (without redundant
561 // warnings for the same directive in nested includes).
562 // The warning is delayed until the end of the file to avoid warnings
563 // for files that don't have any records that are affected by the modified
564 // alignment.
565 bool HasNonDefaultValue =
566 AlignPackStack.hasValue() &&
567 (AlignPackIncludeStack.empty() ||
568 AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
569 AlignPackIncludeStack.push_back(
570 {AlignPackStack.CurrentValue,
571 AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
572 HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
573 return;
574 }
575
577 "invalid kind");
578 AlignPackIncludeState PrevAlignPackState =
579 AlignPackIncludeStack.pop_back_val();
580 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
581 // information, diagnostics below might not be accurate if we have mixed
582 // pragmas.
583 if (PrevAlignPackState.ShouldWarnOnInclude) {
584 // Emit the delayed non-default alignment at #include warning.
585 Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
586 Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
587 }
588 // Warn about modified alignment after #includes.
589 if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
590 Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
591 Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
592 }
593}
594
596 if (AlignPackStack.Stack.empty())
597 return;
598 bool IsInnermost = true;
599
600 // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
601 // information, diagnostics below might not be accurate if we have mixed
602 // pragmas.
603 for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
604 Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
605 // The user might have already reset the alignment, so suggest replacing
606 // the reset with a pop.
607 if (IsInnermost &&
608 AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
609 auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
610 diag::note_pragma_pack_pop_instead_reset);
611 SourceLocation FixItLoc =
612 Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
613 tok::l_paren, SourceMgr, LangOpts,
614 /*SkipTrailing=*/false);
615 if (FixItLoc.isValid())
616 DB << FixItHint::CreateInsertion(FixItLoc, "pop");
617 }
618 IsInnermost = false;
619 }
620}
621
625
627 PragmaMSCommentKind Kind, StringRef Arg) {
628 auto *PCD = PragmaCommentDecl::Create(
629 Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
630 Context.getTranslationUnitDecl()->addDecl(PCD);
631 Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
632}
633
635 StringRef Value) {
637 Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
638 Context.getTranslationUnitDecl()->addDecl(PDMD);
639 Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
640}
641
645 switch (Value) {
646 default:
647 llvm_unreachable("invalid pragma eval_method kind");
649 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
650 break;
652 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
653 break;
655 NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
656 break;
657 }
658 if (getLangOpts().ApproxFunc)
659 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
660 if (getLangOpts().AllowFPReassoc)
661 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
662 if (getLangOpts().AllowRecip)
663 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
664 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
665 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
666 PP.setCurrentFPEvalMethod(Loc, Value);
667}
668
670 PragmaMsStackAction Action,
673 if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
674 !CurContext->getRedeclContext()->isFileContext()) {
675 // Push and pop can only occur at file or namespace scope, or within a
676 // language linkage declaration.
677 Diag(Loc, diag::err_pragma_fc_pp_scope);
678 return;
679 }
680 switch (Value) {
681 default:
682 llvm_unreachable("invalid pragma float_control kind");
683 case PFC_Precise:
684 NewFPFeatures.setFPPreciseEnabled(true);
685 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
686 break;
687 case PFC_NoPrecise:
688 if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)
689 Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
690 else if (CurFPFeatures.getAllowFEnvAccess())
691 Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
692 else
693 NewFPFeatures.setFPPreciseEnabled(false);
694 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
695 break;
696 case PFC_Except:
697 if (!isPreciseFPEnabled())
698 Diag(Loc, diag::err_pragma_fc_except_requires_precise);
699 else
700 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);
701 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
702 break;
703 case PFC_NoExcept:
704 NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);
705 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
706 break;
707 case PFC_Push:
708 FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
709 break;
710 case PFC_Pop:
711 if (FpPragmaStack.Stack.empty()) {
712 Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
713 << "stack empty";
714 return;
715 }
716 FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
717 NewFPFeatures = FpPragmaStack.CurrentValue;
718 break;
719 }
720 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
721}
722
729
731 SourceLocation PragmaLoc,
732 MSVtorDispMode Mode) {
733 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
734 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
735 << "stack empty";
736 VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
737}
738
739template <>
741 PragmaMsStackAction Action,
742 llvm::StringRef StackSlotLabel,
743 AlignPackInfo Value) {
744 if (Action == PSK_Reset) {
745 CurrentValue = DefaultValue;
746 CurrentPragmaLocation = PragmaLocation;
747 return;
748 }
749 if (Action & PSK_Push)
750 Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
751 PragmaLocation));
752 else if (Action & PSK_Pop) {
753 if (!StackSlotLabel.empty()) {
754 // If we've got a label, try to find it and jump there.
755 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
756 return x.StackSlotLabel == StackSlotLabel;
757 });
758 // We found the label, so pop from there.
759 if (I != Stack.rend()) {
760 CurrentValue = I->Value;
761 CurrentPragmaLocation = I->PragmaLocation;
762 Stack.erase(std::prev(I.base()), Stack.end());
763 }
764 } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
765 CurrentValue.IsPackAttr()) {
766 // XL '#pragma align(reset)' would pop the stack until
767 // a current in effect pragma align is popped.
768 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
769 return x.Value.IsAlignAttr();
770 });
771 // If we found pragma align so pop from there.
772 if (I != Stack.rend()) {
773 Stack.erase(std::prev(I.base()), Stack.end());
774 if (Stack.empty()) {
775 CurrentValue = DefaultValue;
776 CurrentPragmaLocation = PragmaLocation;
777 } else {
778 CurrentValue = Stack.back().Value;
779 CurrentPragmaLocation = Stack.back().PragmaLocation;
780 Stack.pop_back();
781 }
782 }
783 } else if (!Stack.empty()) {
784 // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
785 // over the baseline.
786 if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
787 return;
788
789 // We don't have a label, just pop the last entry.
790 CurrentValue = Stack.back().Value;
791 CurrentPragmaLocation = Stack.back().PragmaLocation;
792 Stack.pop_back();
793 }
794 }
795 if (Action & PSK_Set) {
796 CurrentValue = Value;
797 CurrentPragmaLocation = PragmaLocation;
798 }
799}
800
801bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
802 NamedDecl *Decl) {
803 SourceLocation PragmaLocation;
804 if (auto A = Decl->getAttr<SectionAttr>())
805 if (A->isImplicit())
806 PragmaLocation = A->getLocation();
807 auto [SectionIt, Inserted] = Context.SectionInfos.try_emplace(
808 SectionName, Decl, PragmaLocation, SectionFlags);
809 if (Inserted)
810 return false;
811 // A pre-declared section takes precedence w/o diagnostic.
812 const auto &Section = SectionIt->second;
813 if (Section.SectionFlags == SectionFlags ||
814 ((SectionFlags & ASTContext::PSF_Implicit) &&
815 !(Section.SectionFlags & ASTContext::PSF_Implicit)))
816 return false;
817 Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
818 if (Section.Decl)
819 Diag(Section.Decl->getLocation(), diag::note_declared_at)
820 << Section.Decl->getName();
821 if (PragmaLocation.isValid())
822 Diag(PragmaLocation, diag::note_pragma_entered_here);
823 if (Section.PragmaSectionLocation.isValid())
824 Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
825 return true;
826}
827
828bool Sema::UnifySection(StringRef SectionName,
829 int SectionFlags,
830 SourceLocation PragmaSectionLocation) {
831 auto SectionIt = Context.SectionInfos.find(SectionName);
832 if (SectionIt != Context.SectionInfos.end()) {
833 const auto &Section = SectionIt->second;
834 if (Section.SectionFlags == SectionFlags)
835 return false;
836 if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
837 Diag(PragmaSectionLocation, diag::err_section_conflict)
838 << "this" << Section;
839 if (Section.Decl)
840 Diag(Section.Decl->getLocation(), diag::note_declared_at)
841 << Section.Decl->getName();
842 if (Section.PragmaSectionLocation.isValid())
843 Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
844 return true;
845 }
846 }
847 Context.SectionInfos[SectionName] =
848 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
849 return false;
850}
851
852/// Called on well formed \#pragma bss_seg().
854 PragmaMsStackAction Action,
855 llvm::StringRef StackSlotLabel,
856 StringLiteral *SegmentName,
857 llvm::StringRef PragmaName) {
859 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
860 .Case("data_seg", &DataSegStack)
861 .Case("bss_seg", &BSSSegStack)
862 .Case("const_seg", &ConstSegStack)
863 .Case("code_seg", &CodeSegStack);
864 if (Action & PSK_Pop && Stack->Stack.empty())
865 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
866 << "stack empty";
867 if (SegmentName) {
868 if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
869 return;
870
871 if (SegmentName->getString() == ".drectve" &&
872 Context.getTargetInfo().getCXXABI().isMicrosoft())
873 Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
874 }
875
876 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
877}
878
879/// Called on well formed \#pragma strict_gs_check().
881 PragmaMsStackAction Action,
882 bool Value) {
883 if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())
884 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << "strict_gs_check"
885 << "stack empty";
886
887 StrictGuardStackCheckStack.Act(PragmaLocation, Action, StringRef(), Value);
888}
889
890/// Called on well formed \#pragma bss_seg().
892 int SectionFlags, StringLiteral *SegmentName) {
893 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
894}
895
897 StringLiteral *SegmentName) {
898 // There's no stack to maintain, so we just have a current section. When we
899 // see the default section, reset our current section back to null so we stop
900 // tacking on unnecessary attributes.
901 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
902 CurInitSegLoc = PragmaLocation;
903}
904
906 SourceLocation PragmaLocation, StringRef Section,
907 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
908 &Functions) {
909 if (!CurContext->getRedeclContext()->isFileContext()) {
910 Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
911 return;
912 }
913
914 for (auto &Function : Functions) {
915 IdentifierInfo *II;
916 SourceLocation Loc;
917 std::tie(II, Loc) = Function;
918
919 DeclarationName DN(II);
921 if (!ND) {
922 Diag(Loc, diag::err_undeclared_use) << II->getName();
923 return;
924 }
925
926 auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());
927 if (!FD) {
928 Diag(Loc, diag::err_pragma_alloc_text_not_function);
929 return;
930 }
931
932 if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
933 Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
934 return;
935 }
936
937 FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);
938 }
939}
940
941void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
942 SourceLocation PragmaLoc) {
943
944 IdentifierInfo *Name = IdTok.getIdentifierInfo();
945 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
946 LookupName(Lookup, curScope, /*AllowBuiltinCreation=*/true);
947
948 if (Lookup.empty()) {
949 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
950 << Name << SourceRange(IdTok.getLocation());
951 return;
952 }
953
954 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
955 if (!VD) {
956 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
957 << Name << SourceRange(IdTok.getLocation());
958 return;
959 }
960
961 // Warn if this was used before being marked unused.
962 if (VD->isUsed())
963 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
964
965 VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
966 UnusedAttr::GNU_unused));
967}
968
969namespace {
970
971std::optional<attr::SubjectMatchRule>
972getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
973 using namespace attr;
974 switch (Rule) {
975 default:
976 return std::nullopt;
977#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
978#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
979 case Value: \
980 return Parent;
981#include "clang/Basic/AttrSubMatchRulesList.inc"
982 }
983}
984
985bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
986 using namespace attr;
987 switch (Rule) {
988 default:
989 return false;
990#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
991#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
992 case Value: \
993 return IsNegated;
994#include "clang/Basic/AttrSubMatchRulesList.inc"
995 }
996}
997
998CharSourceRange replacementRangeForListElement(const Sema &S,
999 SourceRange Range) {
1000 // Make sure that the ',' is removed as well.
1001 SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
1002 Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
1003 /*SkipTrailingWhitespaceAndNewLine=*/false);
1004 if (AfterCommaLoc.isValid())
1005 return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
1006 else
1007 return CharSourceRange::getTokenRange(Range);
1008}
1009
1010std::string
1011attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
1012 std::string Result;
1013 llvm::raw_string_ostream OS(Result);
1014 for (const auto &I : llvm::enumerate(Rules)) {
1015 if (I.index())
1016 OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
1017 OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
1018 }
1019 return Result;
1020}
1021
1022} // end anonymous namespace
1023
1025 ParsedAttr &Attribute, SourceLocation PragmaLoc,
1027 Attribute.setIsPragmaClangAttribute();
1029 // Gather the subject match rules that are supported by the attribute.
1031 StrictSubjectMatchRuleSet;
1032 Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
1033
1034 // Figure out which subject matching rules are valid.
1035 if (StrictSubjectMatchRuleSet.empty()) {
1036 // Check for contradicting match rules. Contradicting match rules are
1037 // either:
1038 // - a top-level rule and one of its sub-rules. E.g. variable and
1039 // variable(is_parameter).
1040 // - a sub-rule and a sibling that's negated. E.g.
1041 // variable(is_thread_local) and variable(unless(is_parameter))
1042 llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
1043 RulesToFirstSpecifiedNegatedSubRule;
1044 for (const auto &Rule : Rules) {
1045 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1046 std::optional<attr::SubjectMatchRule> ParentRule =
1047 getParentAttrMatcherRule(MatchRule);
1048 if (!ParentRule)
1049 continue;
1050 auto It = Rules.find(*ParentRule);
1051 if (It != Rules.end()) {
1052 // A sub-rule contradicts a parent rule.
1053 Diag(Rule.second.getBegin(),
1054 diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
1056 << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
1058 replacementRangeForListElement(*this, Rule.second));
1059 // Keep going without removing this rule as it won't change the set of
1060 // declarations that receive the attribute.
1061 continue;
1062 }
1063 if (isNegatedAttrMatcherSubRule(MatchRule))
1064 RulesToFirstSpecifiedNegatedSubRule.insert(
1065 std::make_pair(*ParentRule, Rule));
1066 }
1067 bool IgnoreNegatedSubRules = false;
1068 for (const auto &Rule : Rules) {
1069 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1070 std::optional<attr::SubjectMatchRule> ParentRule =
1071 getParentAttrMatcherRule(MatchRule);
1072 if (!ParentRule)
1073 continue;
1074 auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
1075 if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
1076 It->second != Rule) {
1077 // Negated sub-rule contradicts another sub-rule.
1078 Diag(
1079 It->second.second.getBegin(),
1080 diag::
1081 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
1083 attr::SubjectMatchRule(It->second.first))
1084 << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
1086 replacementRangeForListElement(*this, It->second.second));
1087 // Keep going but ignore all of the negated sub-rules.
1088 IgnoreNegatedSubRules = true;
1089 RulesToFirstSpecifiedNegatedSubRule.erase(It);
1090 }
1091 }
1092
1093 if (!IgnoreNegatedSubRules) {
1094 for (const auto &Rule : Rules)
1095 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
1096 } else {
1097 for (const auto &Rule : Rules) {
1098 if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
1099 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
1100 }
1101 }
1102 Rules.clear();
1103 } else {
1104 // Each rule in Rules must be a strict subset of the attribute's
1105 // SubjectMatch rules. I.e. we're allowed to use
1106 // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
1107 // but should not allow `apply_to=variables` on an attribute which has
1108 // `SubjectList<[GlobalVar]>`.
1109 for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
1110 // First, check for exact match.
1111 if (Rules.erase(StrictRule.first)) {
1112 // Add the rule to the set of attribute receivers only if it's supported
1113 // in the current language mode.
1114 if (StrictRule.second)
1115 SubjectMatchRules.push_back(StrictRule.first);
1116 }
1117 }
1118 // Check remaining rules for subset matches.
1119 auto RulesToCheck = Rules;
1120 for (const auto &Rule : RulesToCheck) {
1121 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
1122 if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
1123 if (llvm::any_of(StrictSubjectMatchRuleSet,
1124 [ParentRule](const auto &StrictRule) {
1125 return StrictRule.first == *ParentRule &&
1126 StrictRule.second; // IsEnabled
1127 })) {
1128 SubjectMatchRules.push_back(MatchRule);
1129 Rules.erase(MatchRule);
1130 }
1131 }
1132 }
1133 }
1134
1135 if (!Rules.empty()) {
1136 auto Diagnostic =
1137 Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
1138 << Attribute;
1140 for (const auto &Rule : Rules) {
1141 ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
1143 replacementRangeForListElement(*this, Rule.second));
1144 }
1145 Diagnostic << attrMatcherRuleListToString(ExtraRules);
1146 }
1147
1148 if (PragmaAttributeStack.empty()) {
1149 Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
1150 return;
1151 }
1152
1153 PragmaAttributeStack.back().Entries.push_back(
1154 {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
1155}
1156
1158 const IdentifierInfo *Namespace) {
1159 PragmaAttributeStack.emplace_back();
1160 PragmaAttributeStack.back().Loc = PragmaLoc;
1161 PragmaAttributeStack.back().Namespace = Namespace;
1162}
1163
1165 const IdentifierInfo *Namespace) {
1166 if (PragmaAttributeStack.empty()) {
1167 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1168 return;
1169 }
1170
1171 // Dig back through the stack trying to find the most recently pushed group
1172 // that in Namespace. Note that this works fine if no namespace is present,
1173 // think of push/pops without namespaces as having an implicit "nullptr"
1174 // namespace.
1175 for (size_t Index = PragmaAttributeStack.size(); Index;) {
1176 --Index;
1177 if (PragmaAttributeStack[Index].Namespace == Namespace) {
1178 for (const PragmaAttributeEntry &Entry :
1179 PragmaAttributeStack[Index].Entries) {
1180 if (!Entry.IsUsed) {
1181 assert(Entry.Attribute && "Expected an attribute");
1182 Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
1183 << *Entry.Attribute;
1184 Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
1185 }
1186 }
1187 PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
1188 return;
1189 }
1190 }
1191
1192 if (Namespace)
1193 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
1194 << 0 << Namespace->getName();
1195 else
1196 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
1197}
1198
1200 if (PragmaAttributeStack.empty())
1201 return;
1202
1203 if (const auto *P = dyn_cast<ParmVarDecl>(D))
1204 if (P->getType()->isVoidType())
1205 return;
1206
1207 for (auto &Group : PragmaAttributeStack) {
1208 for (auto &Entry : Group.Entries) {
1209 ParsedAttr *Attribute = Entry.Attribute;
1210 assert(Attribute && "Expected an attribute");
1211 assert(Attribute->isPragmaClangAttribute() &&
1212 "expected #pragma clang attribute");
1213
1214 // Ensure that the attribute can be applied to the given declaration.
1215 bool Applies = false;
1216 for (const auto &Rule : Entry.MatchRules) {
1217 if (Attribute->appliesToDecl(D, Rule)) {
1218 Applies = true;
1219 break;
1220 }
1221 }
1222 if (!Applies)
1223 continue;
1224 Entry.IsUsed = true;
1227 Attrs.addAtEnd(Attribute);
1228 ProcessDeclAttributeList(S, D, Attrs);
1230 }
1231 }
1232}
1233
1236 assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
1237 DiagFunc(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
1238 PDiag(diag::note_pragma_attribute_applied_decl_here));
1239}
1240
1242 for (auto &[Type, Num] : ExcessPrecisionNotSatisfied) {
1243 assert(LocationOfExcessPrecisionNotSatisfied.isValid() &&
1244 "expected a valid source location");
1246 diag::warn_excess_precision_not_supported)
1247 << static_cast<bool>(Num);
1248 }
1249}
1250
1252 if (PragmaAttributeStack.empty())
1253 return;
1254 Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
1255}
1256
1258 if(On)
1260 else
1261 OptimizeOffPragmaLocation = PragmaLoc;
1262}
1263
1265 if (!CurContext->getRedeclContext()->isFileContext()) {
1266 Diag(Loc, diag::err_pragma_expected_file_scope) << "optimize";
1267 return;
1268 }
1269
1270 MSPragmaOptimizeIsOn = IsOn;
1271}
1272
1274 SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {
1275 if (!CurContext->getRedeclContext()->isFileContext()) {
1276 Diag(Loc, diag::err_pragma_expected_file_scope) << "function";
1277 return;
1278 }
1279
1280 MSFunctionNoBuiltins.insert_range(NoBuiltins);
1281}
1282
1284 // In the future, check other pragmas if they're implemented (e.g. pragma
1285 // optimize 0 will probably map to this functionality too).
1286 if(OptimizeOffPragmaLocation.isValid())
1288}
1289
1291 if (!FD->getIdentifier())
1292 return;
1293
1294 StringRef Name = FD->getName();
1295 auto It = FunctionToSectionMap.find(Name);
1296 if (It != FunctionToSectionMap.end()) {
1297 StringRef Section;
1298 SourceLocation Loc;
1299 std::tie(Section, Loc) = It->second;
1300
1301 if (!FD->hasAttr<SectionAttr>())
1302 FD->addAttr(SectionAttr::CreateImplicit(Context, Section));
1303 }
1304}
1305
1307 // Don't modify the function attributes if it's "on". "on" resets the
1308 // optimizations to the ones listed on the command line
1311}
1312
1314 SourceLocation Loc) {
1315 // Don't add a conflicting attribute. No diagnostic is needed.
1316 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
1317 return;
1318
1319 // Add attributes only if required. Optnone requires noinline as well, but if
1320 // either is already present then don't bother adding them.
1321 if (!FD->hasAttr<OptimizeNoneAttr>())
1322 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
1323 if (!FD->hasAttr<NoInlineAttr>())
1324 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
1325}
1326
1328 if (FD->isDeleted() || FD->isDefaulted())
1329 return;
1331 MSFunctionNoBuiltins.end());
1332 if (!MSFunctionNoBuiltins.empty())
1333 FD->addAttr(NoBuiltinAttr::CreateImplicit(Context, V.data(), V.size()));
1334}
1335
1337 SourceLocation NameLoc,
1338 Scope *curScope) {
1339 LookupResult Result(*this, IdentId, NameLoc, LookupOrdinaryName);
1340 LookupName(Result, curScope);
1341 if (!getLangOpts().CPlusPlus)
1342 return Result.getAsSingle<NamedDecl>();
1343 for (NamedDecl *D : Result) {
1344 if (auto *FD = dyn_cast<FunctionDecl>(D))
1345 if (FD->isExternC())
1346 return D;
1347 if (isa<VarDecl>(D))
1348 return D;
1349 }
1350 return nullptr;
1351}
1352
1354 Scope *curScope) {
1355 if (!CurContext->getRedeclContext()->isFileContext()) {
1356 Diag(NameLoc, diag::err_pragma_expected_file_scope) << "export";
1357 return;
1358 }
1359
1360 PendingPragmaInfo Info;
1361 Info.NameLoc = NameLoc;
1362 Info.Used = false;
1363
1364 NamedDecl *PrevDecl =
1365 lookupExternCFunctionOrVariable(IdentId, NameLoc, curScope);
1366 if (!PrevDecl) {
1367 PendingExportedNames[IdentId] = Info;
1368 return;
1369 }
1370
1371 if (auto *FD = dyn_cast<FunctionDecl>(PrevDecl->getCanonicalDecl())) {
1372 if (!FD->hasExternalFormalLinkage()) {
1373 Diag(NameLoc, diag::warn_pragma_not_applied) << "export" << PrevDecl;
1374 return;
1375 }
1376 if (FD->hasBody()) {
1377 Diag(NameLoc, diag::warn_pragma_not_applied_to_defined_symbol)
1378 << "export";
1379 return;
1380 }
1381 } else if (auto *VD = dyn_cast<VarDecl>(PrevDecl->getCanonicalDecl())) {
1382 if (!VD->hasExternalFormalLinkage()) {
1383 Diag(NameLoc, diag::warn_pragma_not_applied) << "export" << PrevDecl;
1384 return;
1385 }
1386 if (VD->hasDefinition() == VarDecl::Definition) {
1387 Diag(NameLoc, diag::warn_pragma_not_applied_to_defined_symbol)
1388 << "export";
1389 return;
1390 }
1391 }
1392 mergeVisibilityType(PrevDecl->getCanonicalDecl(), NameLoc,
1393 VisibilityAttr::Default);
1394}
1395
1396typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
1397enum : unsigned { NoVisibility = ~0U };
1398
1400 if (!VisContext)
1401 return;
1402
1403 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1405 return;
1406
1407 VisStack *Stack = static_cast<VisStack*>(VisContext);
1408 unsigned rawType = Stack->back().first;
1409 if (rawType == NoVisibility) return;
1410
1411 VisibilityAttr::VisibilityType type
1412 = (VisibilityAttr::VisibilityType) rawType;
1413 SourceLocation loc = Stack->back().second;
1414
1415 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
1416}
1417
1419 delete static_cast<VisStack*>(VisContext);
1420 VisContext = nullptr;
1421}
1422
1423static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
1424 // Put visibility on stack.
1425 if (!S.VisContext)
1426 S.VisContext = new VisStack;
1427
1428 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
1429 Stack->push_back(std::make_pair(type, loc));
1430}
1431
1433 SourceLocation PragmaLoc) {
1434 if (VisType) {
1435 // Compute visibility to use.
1436 VisibilityAttr::VisibilityType T;
1437 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
1438 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
1439 return;
1440 }
1441 PushPragmaVisibility(*this, T, PragmaLoc);
1442 } else {
1443 PopPragmaVisibility(false, PragmaLoc);
1444 }
1445}
1446
1449 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1450 switch (FPC) {
1452 NewFPFeatures.setAllowFPContractWithinStatement();
1453 break;
1456 NewFPFeatures.setAllowFPContractAcrossStatement();
1457 break;
1459 NewFPFeatures.setDisallowFPContract();
1460 break;
1461 }
1462 FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
1463 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1464}
1465
1467 PragmaFPKind Kind, bool IsEnabled) {
1468 if (IsEnabled) {
1469 // For value unsafe context, combining this pragma with eval method
1470 // setting is not recommended. See comment in function FixupInvocation#506.
1471 int Reason = -1;
1472 if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
1473 // Eval method set using the option 'ffp-eval-method'.
1474 Reason = 1;
1475 if (PP.getLastFPEvalPragmaLocation().isValid())
1476 // Eval method set using the '#pragma clang fp eval_method'.
1477 // We could have both an option and a pragma used to the set the eval
1478 // method. The pragma overrides the option in the command line. The Reason
1479 // of the diagnostic is overriden too.
1480 Reason = 0;
1481 if (Reason != -1)
1482 Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)
1483 << Reason << (Kind == PFK_Reassociate ? 4 : 5);
1484 }
1485
1486 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1487 switch (Kind) {
1488 case PFK_Reassociate:
1489 NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
1490 break;
1491 case PFK_Reciprocal:
1492 NewFPFeatures.setAllowReciprocalOverride(IsEnabled);
1493 break;
1494 default:
1495 llvm_unreachable("unhandled value changing pragma fp");
1496 }
1497
1498 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1499 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1500}
1501
1502void Sema::ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode FPR) {
1503 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1504 NewFPFeatures.setConstRoundingModeOverride(FPR);
1505 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1506 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1507}
1508
1511 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1512 NewFPFeatures.setSpecifiedExceptionModeOverride(FPE);
1513 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1514 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1515}
1516
1518 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1519 if (IsEnabled) {
1520 // Verify Microsoft restriction:
1521 // You can't enable fenv_access unless precise semantics are enabled.
1522 // Precise semantics can be enabled either by the float_control
1523 // pragma, or by using the /fp:precise or /fp:strict compiler options
1524 if (!isPreciseFPEnabled())
1525 Diag(Loc, diag::err_pragma_fenv_requires_precise);
1526 }
1527 NewFPFeatures.setAllowFEnvAccessOverride(IsEnabled);
1528 NewFPFeatures.setRoundingMathOverride(IsEnabled);
1529 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1530 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1531}
1532
1535 FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1536 NewFPFeatures.setComplexRangeOverride(Range);
1537 FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1538 CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1539}
1540
1545
1546void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1547 SourceLocation Loc) {
1548 // Visibility calculations will consider the namespace's visibility.
1549 // Here we just want to note that we're in a visibility context
1550 // which overrides any enclosing #pragma context, but doesn't itself
1551 // contribute visibility.
1553}
1554
1555void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1556 if (!VisContext) {
1557 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1558 return;
1559 }
1560
1561 // Pop visibility from stack
1562 VisStack *Stack = static_cast<VisStack*>(VisContext);
1563
1564 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1565 bool StartsWithPragma = Back->first != NoVisibility;
1566 if (StartsWithPragma && IsNamespaceEnd) {
1567 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1568 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1569
1570 // For better error recovery, eat all pushes inside the namespace.
1571 do {
1572 Stack->pop_back();
1573 Back = &Stack->back();
1574 StartsWithPragma = Back->first != NoVisibility;
1575 } while (StartsWithPragma);
1576 } else if (!StartsWithPragma && !IsNamespaceEnd) {
1577 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1578 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1579 return;
1580 }
1581
1582 Stack->pop_back();
1583 // To simplify the implementation, never keep around an empty stack.
1584 if (Stack->empty())
1586}
1587
1588template <typename Ty>
1589static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
1590 const ParsedAttr &A,
1591 bool SkipArgCountCheck) {
1592 // Several attributes carry different semantics than the parsing requires, so
1593 // those are opted out of the common argument checks.
1594 //
1595 // We also bail on unknown and ignored attributes because those are handled
1596 // as part of the target-specific handling logic.
1598 return false;
1599 // Check whether the attribute requires specific language extensions to be
1600 // enabled.
1601 if (!A.diagnoseLangOpts(S))
1602 return true;
1603 // Check whether the attribute appertains to the given subject.
1604 if (!A.diagnoseAppertainsTo(S, Node))
1605 return true;
1606 // Check whether the attribute is mutually exclusive with other attributes
1607 // that have already been applied to the declaration.
1608 if (!A.diagnoseMutualExclusion(S, Node))
1609 return true;
1610 // Check whether the attribute exists in the target architecture.
1611 if (S.CheckAttrTarget(A))
1612 return true;
1613
1614 if (A.hasCustomParsing())
1615 return false;
1616
1617 if (!SkipArgCountCheck) {
1618 if (A.getMinArgs() == A.getMaxArgs()) {
1619 // If there are no optional arguments, then checking for the argument
1620 // count is trivial.
1621 if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
1622 return true;
1623 } else {
1624 // There are optional arguments, so checking is slightly more involved.
1625 if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))
1626 return true;
1627 else if (!A.hasVariadicArg() && A.getMaxArgs() &&
1628 !A.checkAtMostNumArgs(S, A.getMaxArgs()))
1629 return true;
1630 }
1631 }
1632
1633 return false;
1634}
1635
1637 bool SkipArgCountCheck) {
1638 return ::checkCommonAttributeFeatures(*this, D, A, SkipArgCountCheck);
1639}
1641 bool SkipArgCountCheck) {
1642 return ::checkCommonAttributeFeatures(*this, S, A, SkipArgCountCheck);
1643}
#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:2015
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
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:2860
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2555
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2400
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:3667
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:1395
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:1805
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:8431
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:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
Represents a struct/union/class.
Definition Decl.h:4342
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:1919
bool IsPackSet() const
Definition Sema.h:1921
bool IsAlignAttr() const
Definition Sema.h:1915
Mode getAlignMode() const
Definition Sema.h:1917
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:509
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:9402
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:634
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
Definition Sema.h:2137
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2312
void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode)
Called to set constant rounding mode for floating point operations.
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1841
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:8402
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:281
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2072
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2066
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:626
SmallVector< AlignPackIncludeState, 8 > AlignPackIncludeStack
Definition Sema.h:2061
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2073
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:853
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:669
void ActOnPragmaMSPointersToMembers(LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc)
ActOnPragmaMSPointersToMembers - called on well formed #pragma pointers_to_members(representation met...
Definition SemaAttr.cpp:723
void DiagnosePrecisionLossInComplexDivision()
ASTContext & Context
Definition Sema.h:1304
void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc)
ActOnPragmaUnused - Called on well-formed '#pragma unused'.
Definition SemaAttr.cpp:941
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2354
void ActOnPragmaMSAllocText(SourceLocation PragmaLocation, StringRef Section, const SmallVector< std::tuple< IdentifierInfo *, SourceLocation > > &Functions)
Called on well-formed #pragma alloc_text().
Definition SemaAttr.cpp:905
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2069
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules)
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2065
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:757
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc)
ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
Definition SemaAttr.cpp:340
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:642
void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName)
ActOnPragmaClangSection - Called on well formed #pragma clang section.
Definition SemaAttr.cpp:395
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:801
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:273
const LangOptions & getLangOpts() const
Definition Sema.h:932
SourceLocation CurInitSegLoc
Definition Sema.h:2108
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value)
Called on well formed #pragma vtordisp().
Definition SemaAttr.cpp:730
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:224
Preprocessor & PP
Definition Sema.h:1303
bool MSPragmaOptimizeIsOn
The "on" or "off" argument passed by #pragma optimize, that denotes whether the optimizations in the ...
Definition Sema.h:2155
SmallVector< PragmaAttributeGroup, 2 > PragmaAttributeStack
Definition Sema.h:2133
const LangOptions & LangOpts
Definition Sema.h:1302
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1842
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1831
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:2054
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2064
llvm::StringMap< std::tuple< StringRef, SourceLocation > > FunctionToSectionMap
Sections used with pragma alloc_text.
Definition Sema.h:2111
llvm::SmallSetVector< StringRef, 4 > MSFunctionNoBuiltins
Set of no-builtin functions listed by #pragma function.
Definition Sema.h:2158
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:2107
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1442
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:622
bool isPreciseFPEnabled()
Are precise floating point semantics currently enabled?
Definition Sema.h:2238
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName)
Called on well-formed #pragma init_seg().
Definition SemaAttr.cpp:896
bool MSStructPragmaOn
Definition Sema.h:1828
SourceManager & getSourceManager() const
Definition Sema.h:937
void PrintPragmaAttributeInstantiationPoint()
Definition Sema.h:2326
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition SemaAttr.cpp:556
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1843
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:8401
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1840
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:2053
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:2114
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
ASTConsumer & Consumer
Definition Sema.h:1305
PragmaAlignPackDiagnoseKind
Definition Sema.h:2216
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1263
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:1307
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment)
ActOnPragmaPack - Called on well formed #pragma pack(...).
Definition SemaAttr.cpp:444
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:595
FPOptions CurFPFeatures
Definition Sema.h:1300
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2063
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:2142
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1826
void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, PragmaMsStackAction Action, bool Value)
ActOnPragmaMSStrictGuardStackCheck - Called on well formed #pragma strict_gs_check.
Definition SemaAttr.cpp:880
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1839
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:891
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:328
PragmaMsStackAction
Definition Sema.h:1845
@ PSK_Push_Set
Definition Sema.h:1851
@ PSK_Reset
Definition Sema.h:1846
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:1866
bool isVoidType() const
Definition TypeBase.h:9034
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:8767
bool isFunctionType() const
Definition TypeBase.h:8664
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
QualType getUnderlyingType() const
Definition Decl.h:3632
Represents a variable declaration or definition.
Definition Decl.h:926
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1316
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:2058
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2349
This an attribute introduced by #pragma clang attribute.
Definition Sema.h:2117
SourceLocation PragmaLocation
Definition Sema.h:1836
SmallVector< Slot, 2 > Stack
Definition Sema.h:2037
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value)
Definition Sema.h:1976