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