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