• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for non-trivial attributes and
10 // pragmas.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/SemaInternal.h"
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // Pragma 'pack' and 'options align'
25 //===----------------------------------------------------------------------===//
26 
PragmaStackSentinelRAII(Sema & S,StringRef SlotLabel,bool ShouldAct)27 Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
28                                                        StringRef SlotLabel,
29                                                        bool ShouldAct)
30     : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
31   if (ShouldAct) {
32     S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
33     S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
34     S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
35     S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
36     S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
37   }
38 }
39 
~PragmaStackSentinelRAII()40 Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
41   if (ShouldAct) {
42     S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
43     S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
44     S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
45     S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
46     S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
47   }
48 }
49 
AddAlignmentAttributesForRecord(RecordDecl * RD)50 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
51   // If there is no pack value, we don't need any attributes.
52   if (!PackStack.CurrentValue)
53     return;
54 
55   // Otherwise, check to see if we need a max field alignment attribute.
56   if (unsigned Alignment = PackStack.CurrentValue) {
57     if (Alignment == Sema::kMac68kAlignmentSentinel)
58       RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
59     else
60       RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
61                                                         Alignment * 8));
62   }
63   if (PackIncludeStack.empty())
64     return;
65   // The #pragma pack affected a record in an included file,  so Clang should
66   // warn when that pragma was written in a file that included the included
67   // file.
68   for (auto &PackedInclude : llvm::reverse(PackIncludeStack)) {
69     if (PackedInclude.CurrentPragmaLocation != PackStack.CurrentPragmaLocation)
70       break;
71     if (PackedInclude.HasNonDefaultValue)
72       PackedInclude.ShouldWarnOnInclude = true;
73   }
74 }
75 
AddMsStructLayoutForRecord(RecordDecl * RD)76 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
77   if (MSStructPragmaOn)
78     RD->addAttr(MSStructAttr::CreateImplicit(Context));
79 
80   // FIXME: We should merge AddAlignmentAttributesForRecord with
81   // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
82   // all active pragmas and applies them as attributes to class definitions.
83   if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
84     RD->addAttr(MSVtorDispAttr::CreateImplicit(
85         Context, unsigned(VtorDispStack.CurrentValue)));
86 }
87 
88 template <typename Attribute>
addGslOwnerPointerAttributeIfNotExisting(ASTContext & Context,CXXRecordDecl * Record)89 static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
90                                                      CXXRecordDecl *Record) {
91   if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
92     return;
93 
94   for (Decl *Redecl : Record->redecls())
95     Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
96 }
97 
inferGslPointerAttribute(NamedDecl * ND,CXXRecordDecl * UnderlyingRecord)98 void Sema::inferGslPointerAttribute(NamedDecl *ND,
99                                     CXXRecordDecl *UnderlyingRecord) {
100   if (!UnderlyingRecord)
101     return;
102 
103   const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
104   if (!Parent)
105     return;
106 
107   static llvm::StringSet<> Containers{
108       "array",
109       "basic_string",
110       "deque",
111       "forward_list",
112       "vector",
113       "list",
114       "map",
115       "multiset",
116       "multimap",
117       "priority_queue",
118       "queue",
119       "set",
120       "stack",
121       "unordered_set",
122       "unordered_map",
123       "unordered_multiset",
124       "unordered_multimap",
125   };
126 
127   static llvm::StringSet<> Iterators{"iterator", "const_iterator",
128                                      "reverse_iterator",
129                                      "const_reverse_iterator"};
130 
131   if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
132       Containers.count(Parent->getName()))
133     addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
134                                                           UnderlyingRecord);
135 }
136 
inferGslPointerAttribute(TypedefNameDecl * TD)137 void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
138 
139   QualType Canonical = TD->getUnderlyingType().getCanonicalType();
140 
141   CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
142   if (!RD) {
143     if (auto *TST =
144             dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
145 
146       RD = dyn_cast_or_null<CXXRecordDecl>(
147           TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
148     }
149   }
150 
151   inferGslPointerAttribute(TD, RD);
152 }
153 
inferGslOwnerPointerAttribute(CXXRecordDecl * Record)154 void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
155   static llvm::StringSet<> StdOwners{
156       "any",
157       "array",
158       "basic_regex",
159       "basic_string",
160       "deque",
161       "forward_list",
162       "vector",
163       "list",
164       "map",
165       "multiset",
166       "multimap",
167       "optional",
168       "priority_queue",
169       "queue",
170       "set",
171       "stack",
172       "unique_ptr",
173       "unordered_set",
174       "unordered_map",
175       "unordered_multiset",
176       "unordered_multimap",
177       "variant",
178   };
179   static llvm::StringSet<> StdPointers{
180       "basic_string_view",
181       "reference_wrapper",
182       "regex_iterator",
183   };
184 
185   if (!Record->getIdentifier())
186     return;
187 
188   // Handle classes that directly appear in std namespace.
189   if (Record->isInStdNamespace()) {
190     if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
191       return;
192 
193     if (StdOwners.count(Record->getName()))
194       addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
195     else if (StdPointers.count(Record->getName()))
196       addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
197 
198     return;
199   }
200 
201   // Handle nested classes that could be a gsl::Pointer.
202   inferGslPointerAttribute(Record, Record);
203 }
204 
ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,SourceLocation PragmaLoc)205 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
206                                    SourceLocation PragmaLoc) {
207   PragmaMsStackAction Action = Sema::PSK_Reset;
208   unsigned Alignment = 0;
209   switch (Kind) {
210     // For all targets we support native and natural are the same.
211     //
212     // FIXME: This is not true on Darwin/PPC.
213   case POAK_Native:
214   case POAK_Power:
215   case POAK_Natural:
216     Action = Sema::PSK_Push_Set;
217     Alignment = 0;
218     break;
219 
220     // Note that '#pragma options align=packed' is not equivalent to attribute
221     // packed, it has a different precedence relative to attribute aligned.
222   case POAK_Packed:
223     Action = Sema::PSK_Push_Set;
224     Alignment = 1;
225     break;
226 
227   case POAK_Mac68k:
228     // Check if the target supports this.
229     if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
230       Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
231       return;
232     }
233     Action = Sema::PSK_Push_Set;
234     Alignment = Sema::kMac68kAlignmentSentinel;
235     break;
236 
237   case POAK_Reset:
238     // Reset just pops the top of the stack, or resets the current alignment to
239     // default.
240     Action = Sema::PSK_Pop;
241     if (PackStack.Stack.empty()) {
242       if (PackStack.CurrentValue) {
243         Action = Sema::PSK_Reset;
244       } else {
245         Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
246             << "stack empty";
247         return;
248       }
249     }
250     break;
251   }
252 
253   PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
254 }
255 
ActOnPragmaClangSection(SourceLocation PragmaLoc,PragmaClangSectionAction Action,PragmaClangSectionKind SecKind,StringRef SecName)256 void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action,
257                                    PragmaClangSectionKind SecKind, StringRef SecName) {
258   PragmaClangSection *CSec;
259   int SectionFlags = ASTContext::PSF_Read;
260   switch (SecKind) {
261     case PragmaClangSectionKind::PCSK_BSS:
262       CSec = &PragmaClangBSSSection;
263       SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
264       break;
265     case PragmaClangSectionKind::PCSK_Data:
266       CSec = &PragmaClangDataSection;
267       SectionFlags |= ASTContext::PSF_Write;
268       break;
269     case PragmaClangSectionKind::PCSK_Rodata:
270       CSec = &PragmaClangRodataSection;
271       break;
272     case PragmaClangSectionKind::PCSK_Relro:
273       CSec = &PragmaClangRelroSection;
274       break;
275     case PragmaClangSectionKind::PCSK_Text:
276       CSec = &PragmaClangTextSection;
277       SectionFlags |= ASTContext::PSF_Execute;
278       break;
279     default:
280       llvm_unreachable("invalid clang section kind");
281   }
282 
283   if (Action == PragmaClangSectionAction::PCSA_Clear) {
284     CSec->Valid = false;
285     return;
286   }
287 
288   if (UnifySection(SecName, SectionFlags, PragmaLoc))
289     return;
290 
291   CSec->Valid = true;
292   CSec->SectionName = std::string(SecName);
293   CSec->PragmaLocation = PragmaLoc;
294 }
295 
ActOnPragmaPack(SourceLocation PragmaLoc,PragmaMsStackAction Action,StringRef SlotLabel,Expr * alignment)296 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
297                            StringRef SlotLabel, Expr *alignment) {
298   Expr *Alignment = static_cast<Expr *>(alignment);
299 
300   // If specified then alignment must be a "small" power of two.
301   unsigned AlignmentVal = 0;
302   if (Alignment) {
303     Optional<llvm::APSInt> Val;
304 
305     // pack(0) is like pack(), which just works out since that is what
306     // we use 0 for in PackAttr.
307     if (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
308         !(Val = Alignment->getIntegerConstantExpr(Context)) ||
309         !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
310       Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
311       return; // Ignore
312     }
313 
314     AlignmentVal = (unsigned)Val->getZExtValue();
315   }
316   if (Action == Sema::PSK_Show) {
317     // Show the current alignment, making sure to show the right value
318     // for the default.
319     // FIXME: This should come from the target.
320     AlignmentVal = PackStack.CurrentValue;
321     if (AlignmentVal == 0)
322       AlignmentVal = 8;
323     if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
324       Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
325     else
326       Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
327   }
328   // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
329   // "#pragma pack(pop, identifier, n) is undefined"
330   if (Action & Sema::PSK_Pop) {
331     if (Alignment && !SlotLabel.empty())
332       Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
333     if (PackStack.Stack.empty())
334       Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
335   }
336 
337   PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
338 }
339 
DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,SourceLocation IncludeLoc)340 void Sema::DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
341                                         SourceLocation IncludeLoc) {
342   if (Kind == PragmaPackDiagnoseKind::NonDefaultStateAtInclude) {
343     SourceLocation PrevLocation = PackStack.CurrentPragmaLocation;
344     // Warn about non-default alignment at #includes (without redundant
345     // warnings for the same directive in nested includes).
346     // The warning is delayed until the end of the file to avoid warnings
347     // for files that don't have any records that are affected by the modified
348     // alignment.
349     bool HasNonDefaultValue =
350         PackStack.hasValue() &&
351         (PackIncludeStack.empty() ||
352          PackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
353     PackIncludeStack.push_back(
354         {PackStack.CurrentValue,
355          PackStack.hasValue() ? PrevLocation : SourceLocation(),
356          HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
357     return;
358   }
359 
360   assert(Kind == PragmaPackDiagnoseKind::ChangedStateAtExit && "invalid kind");
361   PackIncludeState PrevPackState = PackIncludeStack.pop_back_val();
362   if (PrevPackState.ShouldWarnOnInclude) {
363     // Emit the delayed non-default alignment at #include warning.
364     Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
365     Diag(PrevPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
366   }
367   // Warn about modified alignment after #includes.
368   if (PrevPackState.CurrentValue != PackStack.CurrentValue) {
369     Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
370     Diag(PackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
371   }
372 }
373 
DiagnoseUnterminatedPragmaPack()374 void Sema::DiagnoseUnterminatedPragmaPack() {
375   if (PackStack.Stack.empty())
376     return;
377   bool IsInnermost = true;
378   for (const auto &StackSlot : llvm::reverse(PackStack.Stack)) {
379     Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
380     // The user might have already reset the alignment, so suggest replacing
381     // the reset with a pop.
382     if (IsInnermost && PackStack.CurrentValue == PackStack.DefaultValue) {
383       auto DB = Diag(PackStack.CurrentPragmaLocation,
384                      diag::note_pragma_pack_pop_instead_reset);
385       SourceLocation FixItLoc = Lexer::findLocationAfterToken(
386           PackStack.CurrentPragmaLocation, tok::l_paren, SourceMgr, LangOpts,
387           /*SkipTrailing=*/false);
388       if (FixItLoc.isValid())
389         DB << FixItHint::CreateInsertion(FixItLoc, "pop");
390     }
391     IsInnermost = false;
392   }
393 }
394 
ActOnPragmaMSStruct(PragmaMSStructKind Kind)395 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
396   MSStructPragmaOn = (Kind == PMSST_ON);
397 }
398 
ActOnPragmaMSComment(SourceLocation CommentLoc,PragmaMSCommentKind Kind,StringRef Arg)399 void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
400                                 PragmaMSCommentKind Kind, StringRef Arg) {
401   auto *PCD = PragmaCommentDecl::Create(
402       Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
403   Context.getTranslationUnitDecl()->addDecl(PCD);
404   Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
405 }
406 
ActOnPragmaDetectMismatch(SourceLocation Loc,StringRef Name,StringRef Value)407 void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
408                                      StringRef Value) {
409   auto *PDMD = PragmaDetectMismatchDecl::Create(
410       Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
411   Context.getTranslationUnitDecl()->addDecl(PDMD);
412   Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
413 }
414 
ActOnPragmaFloatControl(SourceLocation Loc,PragmaMsStackAction Action,PragmaFloatControlKind Value)415 void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
416                                    PragmaMsStackAction Action,
417                                    PragmaFloatControlKind Value) {
418   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
419   if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
420       !(CurContext->isTranslationUnit()) && !CurContext->isNamespace()) {
421     // Push and pop can only occur at file or namespace scope.
422     Diag(Loc, diag::err_pragma_fc_pp_scope);
423     return;
424   }
425   switch (Value) {
426   default:
427     llvm_unreachable("invalid pragma float_control kind");
428   case PFC_Precise:
429     NewFPFeatures.setFPPreciseEnabled(true);
430     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
431     break;
432   case PFC_NoPrecise:
433     if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
434       Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
435     else if (CurFPFeatures.getAllowFEnvAccess())
436       Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
437     else
438       NewFPFeatures.setFPPreciseEnabled(false);
439     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
440     break;
441   case PFC_Except:
442     if (!isPreciseFPEnabled())
443       Diag(Loc, diag::err_pragma_fc_except_requires_precise);
444     else
445       NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
446     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
447     break;
448   case PFC_NoExcept:
449     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
450     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
451     break;
452   case PFC_Push:
453     FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
454     break;
455   case PFC_Pop:
456     if (FpPragmaStack.Stack.empty()) {
457       Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
458                                               << "stack empty";
459       return;
460     }
461     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
462     NewFPFeatures = FpPragmaStack.CurrentValue;
463     break;
464   }
465   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
466 }
467 
ActOnPragmaMSPointersToMembers(LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,SourceLocation PragmaLoc)468 void Sema::ActOnPragmaMSPointersToMembers(
469     LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
470     SourceLocation PragmaLoc) {
471   MSPointerToMemberRepresentationMethod = RepresentationMethod;
472   ImplicitMSInheritanceAttrLoc = PragmaLoc;
473 }
474 
ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,SourceLocation PragmaLoc,MSVtorDispMode Mode)475 void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
476                                  SourceLocation PragmaLoc,
477                                  MSVtorDispMode Mode) {
478   if (Action & PSK_Pop && VtorDispStack.Stack.empty())
479     Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
480                                                   << "stack empty";
481   VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
482 }
483 
UnifySection(StringRef SectionName,int SectionFlags,DeclaratorDecl * Decl)484 bool Sema::UnifySection(StringRef SectionName,
485                         int SectionFlags,
486                         DeclaratorDecl *Decl) {
487   SourceLocation PragmaLocation;
488   if (auto A = Decl->getAttr<SectionAttr>())
489     if (A->isImplicit())
490       PragmaLocation = A->getLocation();
491   auto SectionIt = Context.SectionInfos.find(SectionName);
492   if (SectionIt == Context.SectionInfos.end()) {
493     Context.SectionInfos[SectionName] =
494         ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
495     return false;
496   }
497   // A pre-declared section takes precedence w/o diagnostic.
498   const auto &Section = SectionIt->second;
499   if (Section.SectionFlags == SectionFlags ||
500       ((SectionFlags & ASTContext::PSF_Implicit) &&
501        !(Section.SectionFlags & ASTContext::PSF_Implicit)))
502     return false;
503   Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
504   if (Section.Decl)
505     Diag(Section.Decl->getLocation(), diag::note_declared_at)
506         << Section.Decl->getName();
507   if (PragmaLocation.isValid())
508     Diag(PragmaLocation, diag::note_pragma_entered_here);
509   if (Section.PragmaSectionLocation.isValid())
510     Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
511   return true;
512 }
513 
UnifySection(StringRef SectionName,int SectionFlags,SourceLocation PragmaSectionLocation)514 bool Sema::UnifySection(StringRef SectionName,
515                         int SectionFlags,
516                         SourceLocation PragmaSectionLocation) {
517   auto SectionIt = Context.SectionInfos.find(SectionName);
518   if (SectionIt != Context.SectionInfos.end()) {
519     const auto &Section = SectionIt->second;
520     if (Section.SectionFlags == SectionFlags)
521       return false;
522     if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
523       Diag(PragmaSectionLocation, diag::err_section_conflict)
524           << "this" << Section;
525       if (Section.Decl)
526         Diag(Section.Decl->getLocation(), diag::note_declared_at)
527             << Section.Decl->getName();
528       if (Section.PragmaSectionLocation.isValid())
529         Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
530       return true;
531     }
532   }
533   Context.SectionInfos[SectionName] =
534       ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
535   return false;
536 }
537 
538 /// Called on well formed \#pragma bss_seg().
ActOnPragmaMSSeg(SourceLocation PragmaLocation,PragmaMsStackAction Action,llvm::StringRef StackSlotLabel,StringLiteral * SegmentName,llvm::StringRef PragmaName)539 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
540                             PragmaMsStackAction Action,
541                             llvm::StringRef StackSlotLabel,
542                             StringLiteral *SegmentName,
543                             llvm::StringRef PragmaName) {
544   PragmaStack<StringLiteral *> *Stack =
545     llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
546         .Case("data_seg", &DataSegStack)
547         .Case("bss_seg", &BSSSegStack)
548         .Case("const_seg", &ConstSegStack)
549         .Case("code_seg", &CodeSegStack);
550   if (Action & PSK_Pop && Stack->Stack.empty())
551     Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
552         << "stack empty";
553   if (SegmentName) {
554     if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
555       return;
556 
557     if (SegmentName->getString() == ".drectve" &&
558         Context.getTargetInfo().getCXXABI().isMicrosoft())
559       Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
560   }
561 
562   Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
563 }
564 
565 /// Called on well formed \#pragma bss_seg().
ActOnPragmaMSSection(SourceLocation PragmaLocation,int SectionFlags,StringLiteral * SegmentName)566 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
567                                 int SectionFlags, StringLiteral *SegmentName) {
568   UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
569 }
570 
ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,StringLiteral * SegmentName)571 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
572                                 StringLiteral *SegmentName) {
573   // There's no stack to maintain, so we just have a current section.  When we
574   // see the default section, reset our current section back to null so we stop
575   // tacking on unnecessary attributes.
576   CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
577   CurInitSegLoc = PragmaLocation;
578 }
579 
ActOnPragmaUnused(const Token & IdTok,Scope * curScope,SourceLocation PragmaLoc)580 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
581                              SourceLocation PragmaLoc) {
582 
583   IdentifierInfo *Name = IdTok.getIdentifierInfo();
584   LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
585   LookupParsedName(Lookup, curScope, nullptr, true);
586 
587   if (Lookup.empty()) {
588     Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
589       << Name << SourceRange(IdTok.getLocation());
590     return;
591   }
592 
593   VarDecl *VD = Lookup.getAsSingle<VarDecl>();
594   if (!VD) {
595     Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
596       << Name << SourceRange(IdTok.getLocation());
597     return;
598   }
599 
600   // Warn if this was used before being marked unused.
601   if (VD->isUsed())
602     Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
603 
604   VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
605                                          AttributeCommonInfo::AS_Pragma,
606                                          UnusedAttr::GNU_unused));
607 }
608 
AddCFAuditedAttribute(Decl * D)609 void Sema::AddCFAuditedAttribute(Decl *D) {
610   IdentifierInfo *Ident;
611   SourceLocation Loc;
612   std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
613   if (!Loc.isValid()) return;
614 
615   // Don't add a redundant or conflicting attribute.
616   if (D->hasAttr<CFAuditedTransferAttr>() ||
617       D->hasAttr<CFUnknownTransferAttr>())
618     return;
619 
620   AttributeCommonInfo Info(Ident, SourceRange(Loc),
621                            AttributeCommonInfo::AS_Pragma);
622   D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
623 }
624 
625 namespace {
626 
627 Optional<attr::SubjectMatchRule>
getParentAttrMatcherRule(attr::SubjectMatchRule Rule)628 getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
629   using namespace attr;
630   switch (Rule) {
631   default:
632     return None;
633 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
634 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
635   case Value:                                                                  \
636     return Parent;
637 #include "clang/Basic/AttrSubMatchRulesList.inc"
638   }
639 }
640 
isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule)641 bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
642   using namespace attr;
643   switch (Rule) {
644   default:
645     return false;
646 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
647 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
648   case Value:                                                                  \
649     return IsNegated;
650 #include "clang/Basic/AttrSubMatchRulesList.inc"
651   }
652 }
653 
replacementRangeForListElement(const Sema & S,SourceRange Range)654 CharSourceRange replacementRangeForListElement(const Sema &S,
655                                                SourceRange Range) {
656   // Make sure that the ',' is removed as well.
657   SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
658       Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
659       /*SkipTrailingWhitespaceAndNewLine=*/false);
660   if (AfterCommaLoc.isValid())
661     return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
662   else
663     return CharSourceRange::getTokenRange(Range);
664 }
665 
666 std::string
attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules)667 attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
668   std::string Result;
669   llvm::raw_string_ostream OS(Result);
670   for (const auto &I : llvm::enumerate(Rules)) {
671     if (I.index())
672       OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
673     OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
674   }
675   return OS.str();
676 }
677 
678 } // end anonymous namespace
679 
ActOnPragmaAttributeAttribute(ParsedAttr & Attribute,SourceLocation PragmaLoc,attr::ParsedSubjectMatchRuleSet Rules)680 void Sema::ActOnPragmaAttributeAttribute(
681     ParsedAttr &Attribute, SourceLocation PragmaLoc,
682     attr::ParsedSubjectMatchRuleSet Rules) {
683   Attribute.setIsPragmaClangAttribute();
684   SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
685   // Gather the subject match rules that are supported by the attribute.
686   SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
687       StrictSubjectMatchRuleSet;
688   Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
689 
690   // Figure out which subject matching rules are valid.
691   if (StrictSubjectMatchRuleSet.empty()) {
692     // Check for contradicting match rules. Contradicting match rules are
693     // either:
694     //  - a top-level rule and one of its sub-rules. E.g. variable and
695     //    variable(is_parameter).
696     //  - a sub-rule and a sibling that's negated. E.g.
697     //    variable(is_thread_local) and variable(unless(is_parameter))
698     llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
699         RulesToFirstSpecifiedNegatedSubRule;
700     for (const auto &Rule : Rules) {
701       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
702       Optional<attr::SubjectMatchRule> ParentRule =
703           getParentAttrMatcherRule(MatchRule);
704       if (!ParentRule)
705         continue;
706       auto It = Rules.find(*ParentRule);
707       if (It != Rules.end()) {
708         // A sub-rule contradicts a parent rule.
709         Diag(Rule.second.getBegin(),
710              diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
711             << attr::getSubjectMatchRuleSpelling(MatchRule)
712             << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
713             << FixItHint::CreateRemoval(
714                    replacementRangeForListElement(*this, Rule.second));
715         // Keep going without removing this rule as it won't change the set of
716         // declarations that receive the attribute.
717         continue;
718       }
719       if (isNegatedAttrMatcherSubRule(MatchRule))
720         RulesToFirstSpecifiedNegatedSubRule.insert(
721             std::make_pair(*ParentRule, Rule));
722     }
723     bool IgnoreNegatedSubRules = false;
724     for (const auto &Rule : Rules) {
725       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
726       Optional<attr::SubjectMatchRule> ParentRule =
727           getParentAttrMatcherRule(MatchRule);
728       if (!ParentRule)
729         continue;
730       auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
731       if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
732           It->second != Rule) {
733         // Negated sub-rule contradicts another sub-rule.
734         Diag(
735             It->second.second.getBegin(),
736             diag::
737                 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
738             << attr::getSubjectMatchRuleSpelling(
739                    attr::SubjectMatchRule(It->second.first))
740             << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
741             << FixItHint::CreateRemoval(
742                    replacementRangeForListElement(*this, It->second.second));
743         // Keep going but ignore all of the negated sub-rules.
744         IgnoreNegatedSubRules = true;
745         RulesToFirstSpecifiedNegatedSubRule.erase(It);
746       }
747     }
748 
749     if (!IgnoreNegatedSubRules) {
750       for (const auto &Rule : Rules)
751         SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
752     } else {
753       for (const auto &Rule : Rules) {
754         if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
755           SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
756       }
757     }
758     Rules.clear();
759   } else {
760     for (const auto &Rule : StrictSubjectMatchRuleSet) {
761       if (Rules.erase(Rule.first)) {
762         // Add the rule to the set of attribute receivers only if it's supported
763         // in the current language mode.
764         if (Rule.second)
765           SubjectMatchRules.push_back(Rule.first);
766       }
767     }
768   }
769 
770   if (!Rules.empty()) {
771     auto Diagnostic =
772         Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
773         << Attribute;
774     SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
775     for (const auto &Rule : Rules) {
776       ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
777       Diagnostic << FixItHint::CreateRemoval(
778           replacementRangeForListElement(*this, Rule.second));
779     }
780     Diagnostic << attrMatcherRuleListToString(ExtraRules);
781   }
782 
783   if (PragmaAttributeStack.empty()) {
784     Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
785     return;
786   }
787 
788   PragmaAttributeStack.back().Entries.push_back(
789       {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
790 }
791 
ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,const IdentifierInfo * Namespace)792 void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
793                                          const IdentifierInfo *Namespace) {
794   PragmaAttributeStack.emplace_back();
795   PragmaAttributeStack.back().Loc = PragmaLoc;
796   PragmaAttributeStack.back().Namespace = Namespace;
797 }
798 
ActOnPragmaAttributePop(SourceLocation PragmaLoc,const IdentifierInfo * Namespace)799 void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
800                                    const IdentifierInfo *Namespace) {
801   if (PragmaAttributeStack.empty()) {
802     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
803     return;
804   }
805 
806   // Dig back through the stack trying to find the most recently pushed group
807   // that in Namespace. Note that this works fine if no namespace is present,
808   // think of push/pops without namespaces as having an implicit "nullptr"
809   // namespace.
810   for (size_t Index = PragmaAttributeStack.size(); Index;) {
811     --Index;
812     if (PragmaAttributeStack[Index].Namespace == Namespace) {
813       for (const PragmaAttributeEntry &Entry :
814            PragmaAttributeStack[Index].Entries) {
815         if (!Entry.IsUsed) {
816           assert(Entry.Attribute && "Expected an attribute");
817           Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
818               << *Entry.Attribute;
819           Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
820         }
821       }
822       PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
823       return;
824     }
825   }
826 
827   if (Namespace)
828     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
829         << 0 << Namespace->getName();
830   else
831     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
832 }
833 
AddPragmaAttributes(Scope * S,Decl * D)834 void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
835   if (PragmaAttributeStack.empty())
836     return;
837   for (auto &Group : PragmaAttributeStack) {
838     for (auto &Entry : Group.Entries) {
839       ParsedAttr *Attribute = Entry.Attribute;
840       assert(Attribute && "Expected an attribute");
841       assert(Attribute->isPragmaClangAttribute() &&
842              "expected #pragma clang attribute");
843 
844       // Ensure that the attribute can be applied to the given declaration.
845       bool Applies = false;
846       for (const auto &Rule : Entry.MatchRules) {
847         if (Attribute->appliesToDecl(D, Rule)) {
848           Applies = true;
849           break;
850         }
851       }
852       if (!Applies)
853         continue;
854       Entry.IsUsed = true;
855       PragmaAttributeCurrentTargetDecl = D;
856       ParsedAttributesView Attrs;
857       Attrs.addAtEnd(Attribute);
858       ProcessDeclAttributeList(S, D, Attrs);
859       PragmaAttributeCurrentTargetDecl = nullptr;
860     }
861   }
862 }
863 
PrintPragmaAttributeInstantiationPoint()864 void Sema::PrintPragmaAttributeInstantiationPoint() {
865   assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
866   Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
867                diag::note_pragma_attribute_applied_decl_here);
868 }
869 
DiagnoseUnterminatedPragmaAttribute()870 void Sema::DiagnoseUnterminatedPragmaAttribute() {
871   if (PragmaAttributeStack.empty())
872     return;
873   Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
874 }
875 
ActOnPragmaOptimize(bool On,SourceLocation PragmaLoc)876 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
877   if(On)
878     OptimizeOffPragmaLocation = SourceLocation();
879   else
880     OptimizeOffPragmaLocation = PragmaLoc;
881 }
882 
AddRangeBasedOptnone(FunctionDecl * FD)883 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
884   // In the future, check other pragmas if they're implemented (e.g. pragma
885   // optimize 0 will probably map to this functionality too).
886   if(OptimizeOffPragmaLocation.isValid())
887     AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
888 }
889 
AddOptnoneAttributeIfNoConflicts(FunctionDecl * FD,SourceLocation Loc)890 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
891                                             SourceLocation Loc) {
892   // Don't add a conflicting attribute. No diagnostic is needed.
893   if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
894     return;
895 
896   // Add attributes only if required. Optnone requires noinline as well, but if
897   // either is already present then don't bother adding them.
898   if (!FD->hasAttr<OptimizeNoneAttr>())
899     FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
900   if (!FD->hasAttr<NoInlineAttr>())
901     FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
902 }
903 
904 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
905 enum : unsigned { NoVisibility = ~0U };
906 
AddPushedVisibilityAttribute(Decl * D)907 void Sema::AddPushedVisibilityAttribute(Decl *D) {
908   if (!VisContext)
909     return;
910 
911   NamedDecl *ND = dyn_cast<NamedDecl>(D);
912   if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
913     return;
914 
915   VisStack *Stack = static_cast<VisStack*>(VisContext);
916   unsigned rawType = Stack->back().first;
917   if (rawType == NoVisibility) return;
918 
919   VisibilityAttr::VisibilityType type
920     = (VisibilityAttr::VisibilityType) rawType;
921   SourceLocation loc = Stack->back().second;
922 
923   D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
924 }
925 
926 /// FreeVisContext - Deallocate and null out VisContext.
FreeVisContext()927 void Sema::FreeVisContext() {
928   delete static_cast<VisStack*>(VisContext);
929   VisContext = nullptr;
930 }
931 
PushPragmaVisibility(Sema & S,unsigned type,SourceLocation loc)932 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
933   // Put visibility on stack.
934   if (!S.VisContext)
935     S.VisContext = new VisStack;
936 
937   VisStack *Stack = static_cast<VisStack*>(S.VisContext);
938   Stack->push_back(std::make_pair(type, loc));
939 }
940 
ActOnPragmaVisibility(const IdentifierInfo * VisType,SourceLocation PragmaLoc)941 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
942                                  SourceLocation PragmaLoc) {
943   if (VisType) {
944     // Compute visibility to use.
945     VisibilityAttr::VisibilityType T;
946     if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
947       Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
948       return;
949     }
950     PushPragmaVisibility(*this, T, PragmaLoc);
951   } else {
952     PopPragmaVisibility(false, PragmaLoc);
953   }
954 }
955 
ActOnPragmaFPContract(SourceLocation Loc,LangOptions::FPModeKind FPC)956 void Sema::ActOnPragmaFPContract(SourceLocation Loc,
957                                  LangOptions::FPModeKind FPC) {
958   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
959   switch (FPC) {
960   case LangOptions::FPM_On:
961     NewFPFeatures.setAllowFPContractWithinStatement();
962     break;
963   case LangOptions::FPM_Fast:
964     NewFPFeatures.setAllowFPContractAcrossStatement();
965     break;
966   case LangOptions::FPM_Off:
967     NewFPFeatures.setDisallowFPContract();
968     break;
969   case LangOptions::FPM_FastHonorPragmas:
970     llvm_unreachable("Should not happen");
971   }
972   FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
973   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
974 }
975 
ActOnPragmaFPReassociate(SourceLocation Loc,bool IsEnabled)976 void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
977   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
978   NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
979   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
980   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
981 }
982 
setRoundingMode(SourceLocation Loc,llvm::RoundingMode FPR)983 void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
984   // C2x: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
985   // the translator may assume that the default rounding mode is in effect.
986   if (FPR == llvm::RoundingMode::Dynamic &&
987       !CurFPFeatures.getAllowFEnvAccess() &&
988       CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Ignore)
989     FPR = llvm::RoundingMode::NearestTiesToEven;
990 
991   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
992   NewFPFeatures.setRoundingModeOverride(FPR);
993   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
994   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
995 }
996 
setExceptionMode(SourceLocation Loc,LangOptions::FPExceptionModeKind FPE)997 void Sema::setExceptionMode(SourceLocation Loc,
998                             LangOptions::FPExceptionModeKind FPE) {
999   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1000   NewFPFeatures.setFPExceptionModeOverride(FPE);
1001   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1002   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
1003 }
1004 
ActOnPragmaFEnvAccess(SourceLocation Loc,bool IsEnabled)1005 void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
1006   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
1007   auto LO = getLangOpts();
1008   if (IsEnabled) {
1009     // Verify Microsoft restriction:
1010     // You can't enable fenv_access unless precise semantics are enabled.
1011     // Precise semantics can be enabled either by the float_control
1012     // pragma, or by using the /fp:precise or /fp:strict compiler options
1013     if (!isPreciseFPEnabled())
1014       Diag(Loc, diag::err_pragma_fenv_requires_precise);
1015     NewFPFeatures.setAllowFEnvAccessOverride(true);
1016     // Enabling FENV access sets the RoundingMode to Dynamic.
1017     // and ExceptionBehavior to Strict
1018     NewFPFeatures.setRoundingModeOverride(llvm::RoundingMode::Dynamic);
1019     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
1020   } else {
1021     NewFPFeatures.setAllowFEnvAccessOverride(false);
1022   }
1023   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
1024   CurFPFeatures = NewFPFeatures.applyOverrides(LO);
1025 }
1026 
ActOnPragmaFPExceptions(SourceLocation Loc,LangOptions::FPExceptionModeKind FPE)1027 void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
1028                                    LangOptions::FPExceptionModeKind FPE) {
1029   setExceptionMode(Loc, FPE);
1030 }
1031 
PushNamespaceVisibilityAttr(const VisibilityAttr * Attr,SourceLocation Loc)1032 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1033                                        SourceLocation Loc) {
1034   // Visibility calculations will consider the namespace's visibility.
1035   // Here we just want to note that we're in a visibility context
1036   // which overrides any enclosing #pragma context, but doesn't itself
1037   // contribute visibility.
1038   PushPragmaVisibility(*this, NoVisibility, Loc);
1039 }
1040 
PopPragmaVisibility(bool IsNamespaceEnd,SourceLocation EndLoc)1041 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
1042   if (!VisContext) {
1043     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1044     return;
1045   }
1046 
1047   // Pop visibility from stack
1048   VisStack *Stack = static_cast<VisStack*>(VisContext);
1049 
1050   const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
1051   bool StartsWithPragma = Back->first != NoVisibility;
1052   if (StartsWithPragma && IsNamespaceEnd) {
1053     Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
1054     Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
1055 
1056     // For better error recovery, eat all pushes inside the namespace.
1057     do {
1058       Stack->pop_back();
1059       Back = &Stack->back();
1060       StartsWithPragma = Back->first != NoVisibility;
1061     } while (StartsWithPragma);
1062   } else if (!StartsWithPragma && !IsNamespaceEnd) {
1063     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
1064     Diag(Back->second, diag::note_surrounding_namespace_starts_here);
1065     return;
1066   }
1067 
1068   Stack->pop_back();
1069   // To simplify the implementation, never keep around an empty stack.
1070   if (Stack->empty())
1071     FreeVisContext();
1072 }
1073