Home | History | Annotate | Line # | Download | only in Sema
      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->isTranslationUnit()) && !CurContext->isNamespace()) {
    479     // Push and pop can only occur at file or namespace scope.
    480     Diag(Loc, diag::err_pragma_fc_pp_scope);
    481     return;
    482   }
    483   switch (Value) {
    484   default:
    485     llvm_unreachable("invalid pragma float_control kind");
    486   case PFC_Precise:
    487     NewFPFeatures.setFPPreciseEnabled(true);
    488     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
    489     break;
    490   case PFC_NoPrecise:
    491     if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
    492       Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
    493     else if (CurFPFeatures.getAllowFEnvAccess())
    494       Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
    495     else
    496       NewFPFeatures.setFPPreciseEnabled(false);
    497     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
    498     break;
    499   case PFC_Except:
    500     if (!isPreciseFPEnabled())
    501       Diag(Loc, diag::err_pragma_fc_except_requires_precise);
    502     else
    503       NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
    504     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
    505     break;
    506   case PFC_NoExcept:
    507     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
    508     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
    509     break;
    510   case PFC_Push:
    511     FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
    512     break;
    513   case PFC_Pop:
    514     if (FpPragmaStack.Stack.empty()) {
    515       Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
    516                                               << "stack empty";
    517       return;
    518     }
    519     FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
    520     NewFPFeatures = FpPragmaStack.CurrentValue;
    521     break;
    522   }
    523   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
    524 }
    525 
    526 void Sema::ActOnPragmaMSPointersToMembers(
    527     LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
    528     SourceLocation PragmaLoc) {
    529   MSPointerToMemberRepresentationMethod = RepresentationMethod;
    530   ImplicitMSInheritanceAttrLoc = PragmaLoc;
    531 }
    532 
    533 void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
    534                                  SourceLocation PragmaLoc,
    535                                  MSVtorDispMode Mode) {
    536   if (Action & PSK_Pop && VtorDispStack.Stack.empty())
    537     Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
    538                                                   << "stack empty";
    539   VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
    540 }
    541 
    542 template <>
    543 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
    544                                                  PragmaMsStackAction Action,
    545                                                  llvm::StringRef StackSlotLabel,
    546                                                  AlignPackInfo Value) {
    547   if (Action == PSK_Reset) {
    548     CurrentValue = DefaultValue;
    549     CurrentPragmaLocation = PragmaLocation;
    550     return;
    551   }
    552   if (Action & PSK_Push)
    553     Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
    554                             PragmaLocation));
    555   else if (Action & PSK_Pop) {
    556     if (!StackSlotLabel.empty()) {
    557       // If we've got a label, try to find it and jump there.
    558       auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
    559         return x.StackSlotLabel == StackSlotLabel;
    560       });
    561       // We found the label, so pop from there.
    562       if (I != Stack.rend()) {
    563         CurrentValue = I->Value;
    564         CurrentPragmaLocation = I->PragmaLocation;
    565         Stack.erase(std::prev(I.base()), Stack.end());
    566       }
    567     } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
    568                CurrentValue.IsPackAttr()) {
    569       // XL '#pragma align(reset)' would pop the stack until
    570       // a current in effect pragma align is popped.
    571       auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
    572         return x.Value.IsAlignAttr();
    573       });
    574       // If we found pragma align so pop from there.
    575       if (I != Stack.rend()) {
    576         Stack.erase(std::prev(I.base()), Stack.end());
    577         if (Stack.empty()) {
    578           CurrentValue = DefaultValue;
    579           CurrentPragmaLocation = PragmaLocation;
    580         } else {
    581           CurrentValue = Stack.back().Value;
    582           CurrentPragmaLocation = Stack.back().PragmaLocation;
    583           Stack.pop_back();
    584         }
    585       }
    586     } else if (!Stack.empty()) {
    587       // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
    588       // over the baseline.
    589       if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
    590         return;
    591 
    592       // We don't have a label, just pop the last entry.
    593       CurrentValue = Stack.back().Value;
    594       CurrentPragmaLocation = Stack.back().PragmaLocation;
    595       Stack.pop_back();
    596     }
    597   }
    598   if (Action & PSK_Set) {
    599     CurrentValue = Value;
    600     CurrentPragmaLocation = PragmaLocation;
    601   }
    602 }
    603 
    604 bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
    605                         NamedDecl *Decl) {
    606   SourceLocation PragmaLocation;
    607   if (auto A = Decl->getAttr<SectionAttr>())
    608     if (A->isImplicit())
    609       PragmaLocation = A->getLocation();
    610   auto SectionIt = Context.SectionInfos.find(SectionName);
    611   if (SectionIt == Context.SectionInfos.end()) {
    612     Context.SectionInfos[SectionName] =
    613         ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
    614     return false;
    615   }
    616   // A pre-declared section takes precedence w/o diagnostic.
    617   const auto &Section = SectionIt->second;
    618   if (Section.SectionFlags == SectionFlags ||
    619       ((SectionFlags & ASTContext::PSF_Implicit) &&
    620        !(Section.SectionFlags & ASTContext::PSF_Implicit)))
    621     return false;
    622   Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
    623   if (Section.Decl)
    624     Diag(Section.Decl->getLocation(), diag::note_declared_at)
    625         << Section.Decl->getName();
    626   if (PragmaLocation.isValid())
    627     Diag(PragmaLocation, diag::note_pragma_entered_here);
    628   if (Section.PragmaSectionLocation.isValid())
    629     Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
    630   return true;
    631 }
    632 
    633 bool Sema::UnifySection(StringRef SectionName,
    634                         int SectionFlags,
    635                         SourceLocation PragmaSectionLocation) {
    636   auto SectionIt = Context.SectionInfos.find(SectionName);
    637   if (SectionIt != Context.SectionInfos.end()) {
    638     const auto &Section = SectionIt->second;
    639     if (Section.SectionFlags == SectionFlags)
    640       return false;
    641     if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
    642       Diag(PragmaSectionLocation, diag::err_section_conflict)
    643           << "this" << Section;
    644       if (Section.Decl)
    645         Diag(Section.Decl->getLocation(), diag::note_declared_at)
    646             << Section.Decl->getName();
    647       if (Section.PragmaSectionLocation.isValid())
    648         Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
    649       return true;
    650     }
    651   }
    652   Context.SectionInfos[SectionName] =
    653       ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
    654   return false;
    655 }
    656 
    657 /// Called on well formed \#pragma bss_seg().
    658 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
    659                             PragmaMsStackAction Action,
    660                             llvm::StringRef StackSlotLabel,
    661                             StringLiteral *SegmentName,
    662                             llvm::StringRef PragmaName) {
    663   PragmaStack<StringLiteral *> *Stack =
    664     llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
    665         .Case("data_seg", &DataSegStack)
    666         .Case("bss_seg", &BSSSegStack)
    667         .Case("const_seg", &ConstSegStack)
    668         .Case("code_seg", &CodeSegStack);
    669   if (Action & PSK_Pop && Stack->Stack.empty())
    670     Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
    671         << "stack empty";
    672   if (SegmentName) {
    673     if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
    674       return;
    675 
    676     if (SegmentName->getString() == ".drectve" &&
    677         Context.getTargetInfo().getCXXABI().isMicrosoft())
    678       Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
    679   }
    680 
    681   Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
    682 }
    683 
    684 /// Called on well formed \#pragma bss_seg().
    685 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
    686                                 int SectionFlags, StringLiteral *SegmentName) {
    687   UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
    688 }
    689 
    690 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
    691                                 StringLiteral *SegmentName) {
    692   // There's no stack to maintain, so we just have a current section.  When we
    693   // see the default section, reset our current section back to null so we stop
    694   // tacking on unnecessary attributes.
    695   CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
    696   CurInitSegLoc = PragmaLocation;
    697 }
    698 
    699 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
    700                              SourceLocation PragmaLoc) {
    701 
    702   IdentifierInfo *Name = IdTok.getIdentifierInfo();
    703   LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
    704   LookupParsedName(Lookup, curScope, nullptr, true);
    705 
    706   if (Lookup.empty()) {
    707     Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
    708       << Name << SourceRange(IdTok.getLocation());
    709     return;
    710   }
    711 
    712   VarDecl *VD = Lookup.getAsSingle<VarDecl>();
    713   if (!VD) {
    714     Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
    715       << Name << SourceRange(IdTok.getLocation());
    716     return;
    717   }
    718 
    719   // Warn if this was used before being marked unused.
    720   if (VD->isUsed())
    721     Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
    722 
    723   VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
    724                                          AttributeCommonInfo::AS_Pragma,
    725                                          UnusedAttr::GNU_unused));
    726 }
    727 
    728 void Sema::AddCFAuditedAttribute(Decl *D) {
    729   IdentifierInfo *Ident;
    730   SourceLocation Loc;
    731   std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
    732   if (!Loc.isValid()) return;
    733 
    734   // Don't add a redundant or conflicting attribute.
    735   if (D->hasAttr<CFAuditedTransferAttr>() ||
    736       D->hasAttr<CFUnknownTransferAttr>())
    737     return;
    738 
    739   AttributeCommonInfo Info(Ident, SourceRange(Loc),
    740                            AttributeCommonInfo::AS_Pragma);
    741   D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
    742 }
    743 
    744 namespace {
    745 
    746 Optional<attr::SubjectMatchRule>
    747 getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
    748   using namespace attr;
    749   switch (Rule) {
    750   default:
    751     return None;
    752 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
    753 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
    754   case Value:                                                                  \
    755     return Parent;
    756 #include "clang/Basic/AttrSubMatchRulesList.inc"
    757   }
    758 }
    759 
    760 bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
    761   using namespace attr;
    762   switch (Rule) {
    763   default:
    764     return false;
    765 #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
    766 #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated)    \
    767   case Value:                                                                  \
    768     return IsNegated;
    769 #include "clang/Basic/AttrSubMatchRulesList.inc"
    770   }
    771 }
    772 
    773 CharSourceRange replacementRangeForListElement(const Sema &S,
    774                                                SourceRange Range) {
    775   // Make sure that the ',' is removed as well.
    776   SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
    777       Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
    778       /*SkipTrailingWhitespaceAndNewLine=*/false);
    779   if (AfterCommaLoc.isValid())
    780     return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
    781   else
    782     return CharSourceRange::getTokenRange(Range);
    783 }
    784 
    785 std::string
    786 attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
    787   std::string Result;
    788   llvm::raw_string_ostream OS(Result);
    789   for (const auto &I : llvm::enumerate(Rules)) {
    790     if (I.index())
    791       OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
    792     OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
    793   }
    794   return OS.str();
    795 }
    796 
    797 } // end anonymous namespace
    798 
    799 void Sema::ActOnPragmaAttributeAttribute(
    800     ParsedAttr &Attribute, SourceLocation PragmaLoc,
    801     attr::ParsedSubjectMatchRuleSet Rules) {
    802   Attribute.setIsPragmaClangAttribute();
    803   SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
    804   // Gather the subject match rules that are supported by the attribute.
    805   SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
    806       StrictSubjectMatchRuleSet;
    807   Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
    808 
    809   // Figure out which subject matching rules are valid.
    810   if (StrictSubjectMatchRuleSet.empty()) {
    811     // Check for contradicting match rules. Contradicting match rules are
    812     // either:
    813     //  - a top-level rule and one of its sub-rules. E.g. variable and
    814     //    variable(is_parameter).
    815     //  - a sub-rule and a sibling that's negated. E.g.
    816     //    variable(is_thread_local) and variable(unless(is_parameter))
    817     llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
    818         RulesToFirstSpecifiedNegatedSubRule;
    819     for (const auto &Rule : Rules) {
    820       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
    821       Optional<attr::SubjectMatchRule> ParentRule =
    822           getParentAttrMatcherRule(MatchRule);
    823       if (!ParentRule)
    824         continue;
    825       auto It = Rules.find(*ParentRule);
    826       if (It != Rules.end()) {
    827         // A sub-rule contradicts a parent rule.
    828         Diag(Rule.second.getBegin(),
    829              diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
    830             << attr::getSubjectMatchRuleSpelling(MatchRule)
    831             << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
    832             << FixItHint::CreateRemoval(
    833                    replacementRangeForListElement(*this, Rule.second));
    834         // Keep going without removing this rule as it won't change the set of
    835         // declarations that receive the attribute.
    836         continue;
    837       }
    838       if (isNegatedAttrMatcherSubRule(MatchRule))
    839         RulesToFirstSpecifiedNegatedSubRule.insert(
    840             std::make_pair(*ParentRule, Rule));
    841     }
    842     bool IgnoreNegatedSubRules = false;
    843     for (const auto &Rule : Rules) {
    844       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
    845       Optional<attr::SubjectMatchRule> ParentRule =
    846           getParentAttrMatcherRule(MatchRule);
    847       if (!ParentRule)
    848         continue;
    849       auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
    850       if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
    851           It->second != Rule) {
    852         // Negated sub-rule contradicts another sub-rule.
    853         Diag(
    854             It->second.second.getBegin(),
    855             diag::
    856                 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
    857             << attr::getSubjectMatchRuleSpelling(
    858                    attr::SubjectMatchRule(It->second.first))
    859             << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
    860             << FixItHint::CreateRemoval(
    861                    replacementRangeForListElement(*this, It->second.second));
    862         // Keep going but ignore all of the negated sub-rules.
    863         IgnoreNegatedSubRules = true;
    864         RulesToFirstSpecifiedNegatedSubRule.erase(It);
    865       }
    866     }
    867 
    868     if (!IgnoreNegatedSubRules) {
    869       for (const auto &Rule : Rules)
    870         SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
    871     } else {
    872       for (const auto &Rule : Rules) {
    873         if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
    874           SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
    875       }
    876     }
    877     Rules.clear();
    878   } else {
    879     // Each rule in Rules must be a strict subset of the attribute's
    880     // SubjectMatch rules.  I.e. we're allowed to use
    881     // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
    882     // but should not allow `apply_to=variables` on an attribute which has
    883     // `SubjectList<[GlobalVar]>`.
    884     for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
    885       // First, check for exact match.
    886       if (Rules.erase(StrictRule.first)) {
    887         // Add the rule to the set of attribute receivers only if it's supported
    888         // in the current language mode.
    889         if (StrictRule.second)
    890           SubjectMatchRules.push_back(StrictRule.first);
    891       }
    892     }
    893     // Check remaining rules for subset matches.
    894     auto RulesToCheck = Rules;
    895     for (const auto &Rule : RulesToCheck) {
    896       attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
    897       if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
    898         if (llvm::any_of(StrictSubjectMatchRuleSet,
    899                          [ParentRule](const auto &StrictRule) {
    900                            return StrictRule.first == *ParentRule &&
    901                                   StrictRule.second; // IsEnabled
    902                          })) {
    903           SubjectMatchRules.push_back(MatchRule);
    904           Rules.erase(MatchRule);
    905         }
    906       }
    907     }
    908   }
    909 
    910   if (!Rules.empty()) {
    911     auto Diagnostic =
    912         Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
    913         << Attribute;
    914     SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
    915     for (const auto &Rule : Rules) {
    916       ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
    917       Diagnostic << FixItHint::CreateRemoval(
    918           replacementRangeForListElement(*this, Rule.second));
    919     }
    920     Diagnostic << attrMatcherRuleListToString(ExtraRules);
    921   }
    922 
    923   if (PragmaAttributeStack.empty()) {
    924     Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
    925     return;
    926   }
    927 
    928   PragmaAttributeStack.back().Entries.push_back(
    929       {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
    930 }
    931 
    932 void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
    933                                          const IdentifierInfo *Namespace) {
    934   PragmaAttributeStack.emplace_back();
    935   PragmaAttributeStack.back().Loc = PragmaLoc;
    936   PragmaAttributeStack.back().Namespace = Namespace;
    937 }
    938 
    939 void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
    940                                    const IdentifierInfo *Namespace) {
    941   if (PragmaAttributeStack.empty()) {
    942     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
    943     return;
    944   }
    945 
    946   // Dig back through the stack trying to find the most recently pushed group
    947   // that in Namespace. Note that this works fine if no namespace is present,
    948   // think of push/pops without namespaces as having an implicit "nullptr"
    949   // namespace.
    950   for (size_t Index = PragmaAttributeStack.size(); Index;) {
    951     --Index;
    952     if (PragmaAttributeStack[Index].Namespace == Namespace) {
    953       for (const PragmaAttributeEntry &Entry :
    954            PragmaAttributeStack[Index].Entries) {
    955         if (!Entry.IsUsed) {
    956           assert(Entry.Attribute && "Expected an attribute");
    957           Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
    958               << *Entry.Attribute;
    959           Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
    960         }
    961       }
    962       PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
    963       return;
    964     }
    965   }
    966 
    967   if (Namespace)
    968     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
    969         << 0 << Namespace->getName();
    970   else
    971     Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
    972 }
    973 
    974 void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
    975   if (PragmaAttributeStack.empty())
    976     return;
    977   for (auto &Group : PragmaAttributeStack) {
    978     for (auto &Entry : Group.Entries) {
    979       ParsedAttr *Attribute = Entry.Attribute;
    980       assert(Attribute && "Expected an attribute");
    981       assert(Attribute->isPragmaClangAttribute() &&
    982              "expected #pragma clang attribute");
    983 
    984       // Ensure that the attribute can be applied to the given declaration.
    985       bool Applies = false;
    986       for (const auto &Rule : Entry.MatchRules) {
    987         if (Attribute->appliesToDecl(D, Rule)) {
    988           Applies = true;
    989           break;
    990         }
    991       }
    992       if (!Applies)
    993         continue;
    994       Entry.IsUsed = true;
    995       PragmaAttributeCurrentTargetDecl = D;
    996       ParsedAttributesView Attrs;
    997       Attrs.addAtEnd(Attribute);
    998       ProcessDeclAttributeList(S, D, Attrs);
    999       PragmaAttributeCurrentTargetDecl = nullptr;
   1000     }
   1001   }
   1002 }
   1003 
   1004 void Sema::PrintPragmaAttributeInstantiationPoint() {
   1005   assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
   1006   Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
   1007                diag::note_pragma_attribute_applied_decl_here);
   1008 }
   1009 
   1010 void Sema::DiagnoseUnterminatedPragmaAttribute() {
   1011   if (PragmaAttributeStack.empty())
   1012     return;
   1013   Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
   1014 }
   1015 
   1016 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
   1017   if(On)
   1018     OptimizeOffPragmaLocation = SourceLocation();
   1019   else
   1020     OptimizeOffPragmaLocation = PragmaLoc;
   1021 }
   1022 
   1023 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
   1024   // In the future, check other pragmas if they're implemented (e.g. pragma
   1025   // optimize 0 will probably map to this functionality too).
   1026   if(OptimizeOffPragmaLocation.isValid())
   1027     AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
   1028 }
   1029 
   1030 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
   1031                                             SourceLocation Loc) {
   1032   // Don't add a conflicting attribute. No diagnostic is needed.
   1033   if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
   1034     return;
   1035 
   1036   // Add attributes only if required. Optnone requires noinline as well, but if
   1037   // either is already present then don't bother adding them.
   1038   if (!FD->hasAttr<OptimizeNoneAttr>())
   1039     FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
   1040   if (!FD->hasAttr<NoInlineAttr>())
   1041     FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
   1042 }
   1043 
   1044 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
   1045 enum : unsigned { NoVisibility = ~0U };
   1046 
   1047 void Sema::AddPushedVisibilityAttribute(Decl *D) {
   1048   if (!VisContext)
   1049     return;
   1050 
   1051   NamedDecl *ND = dyn_cast<NamedDecl>(D);
   1052   if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
   1053     return;
   1054 
   1055   VisStack *Stack = static_cast<VisStack*>(VisContext);
   1056   unsigned rawType = Stack->back().first;
   1057   if (rawType == NoVisibility) return;
   1058 
   1059   VisibilityAttr::VisibilityType type
   1060     = (VisibilityAttr::VisibilityType) rawType;
   1061   SourceLocation loc = Stack->back().second;
   1062 
   1063   D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
   1064 }
   1065 
   1066 /// FreeVisContext - Deallocate and null out VisContext.
   1067 void Sema::FreeVisContext() {
   1068   delete static_cast<VisStack*>(VisContext);
   1069   VisContext = nullptr;
   1070 }
   1071 
   1072 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
   1073   // Put visibility on stack.
   1074   if (!S.VisContext)
   1075     S.VisContext = new VisStack;
   1076 
   1077   VisStack *Stack = static_cast<VisStack*>(S.VisContext);
   1078   Stack->push_back(std::make_pair(type, loc));
   1079 }
   1080 
   1081 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
   1082                                  SourceLocation PragmaLoc) {
   1083   if (VisType) {
   1084     // Compute visibility to use.
   1085     VisibilityAttr::VisibilityType T;
   1086     if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
   1087       Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
   1088       return;
   1089     }
   1090     PushPragmaVisibility(*this, T, PragmaLoc);
   1091   } else {
   1092     PopPragmaVisibility(false, PragmaLoc);
   1093   }
   1094 }
   1095 
   1096 void Sema::ActOnPragmaFPContract(SourceLocation Loc,
   1097                                  LangOptions::FPModeKind FPC) {
   1098   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
   1099   switch (FPC) {
   1100   case LangOptions::FPM_On:
   1101     NewFPFeatures.setAllowFPContractWithinStatement();
   1102     break;
   1103   case LangOptions::FPM_Fast:
   1104     NewFPFeatures.setAllowFPContractAcrossStatement();
   1105     break;
   1106   case LangOptions::FPM_Off:
   1107     NewFPFeatures.setDisallowFPContract();
   1108     break;
   1109   case LangOptions::FPM_FastHonorPragmas:
   1110     llvm_unreachable("Should not happen");
   1111   }
   1112   FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
   1113   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
   1114 }
   1115 
   1116 void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
   1117   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
   1118   NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
   1119   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
   1120   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
   1121 }
   1122 
   1123 void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
   1124   // C2x: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
   1125   // the translator may assume that the default rounding mode is in effect.
   1126   if (FPR == llvm::RoundingMode::Dynamic &&
   1127       !CurFPFeatures.getAllowFEnvAccess() &&
   1128       CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Ignore)
   1129     FPR = llvm::RoundingMode::NearestTiesToEven;
   1130 
   1131   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
   1132   NewFPFeatures.setRoundingModeOverride(FPR);
   1133   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
   1134   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
   1135 }
   1136 
   1137 void Sema::setExceptionMode(SourceLocation Loc,
   1138                             LangOptions::FPExceptionModeKind FPE) {
   1139   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
   1140   NewFPFeatures.setFPExceptionModeOverride(FPE);
   1141   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
   1142   CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
   1143 }
   1144 
   1145 void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
   1146   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
   1147   auto LO = getLangOpts();
   1148   if (IsEnabled) {
   1149     // Verify Microsoft restriction:
   1150     // You can't enable fenv_access unless precise semantics are enabled.
   1151     // Precise semantics can be enabled either by the float_control
   1152     // pragma, or by using the /fp:precise or /fp:strict compiler options
   1153     if (!isPreciseFPEnabled())
   1154       Diag(Loc, diag::err_pragma_fenv_requires_precise);
   1155     NewFPFeatures.setAllowFEnvAccessOverride(true);
   1156     // Enabling FENV access sets the RoundingMode to Dynamic.
   1157     // and ExceptionBehavior to Strict
   1158     NewFPFeatures.setRoundingModeOverride(llvm::RoundingMode::Dynamic);
   1159     NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
   1160   } else {
   1161     NewFPFeatures.setAllowFEnvAccessOverride(false);
   1162   }
   1163   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
   1164   CurFPFeatures = NewFPFeatures.applyOverrides(LO);
   1165 }
   1166 
   1167 void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
   1168                                    LangOptions::FPExceptionModeKind FPE) {
   1169   setExceptionMode(Loc, FPE);
   1170 }
   1171 
   1172 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
   1173                                        SourceLocation Loc) {
   1174   // Visibility calculations will consider the namespace's visibility.
   1175   // Here we just want to note that we're in a visibility context
   1176   // which overrides any enclosing #pragma context, but doesn't itself
   1177   // contribute visibility.
   1178   PushPragmaVisibility(*this, NoVisibility, Loc);
   1179 }
   1180 
   1181 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
   1182   if (!VisContext) {
   1183     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
   1184     return;
   1185   }
   1186 
   1187   // Pop visibility from stack
   1188   VisStack *Stack = static_cast<VisStack*>(VisContext);
   1189 
   1190   const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
   1191   bool StartsWithPragma = Back->first != NoVisibility;
   1192   if (StartsWithPragma && IsNamespaceEnd) {
   1193     Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
   1194     Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
   1195 
   1196     // For better error recovery, eat all pushes inside the namespace.
   1197     do {
   1198       Stack->pop_back();
   1199       Back = &Stack->back();
   1200       StartsWithPragma = Back->first != NoVisibility;
   1201     } while (StartsWithPragma);
   1202   } else if (!StartsWithPragma && !IsNamespaceEnd) {
   1203     Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
   1204     Diag(Back->second, diag::note_surrounding_namespace_starts_here);
   1205     return;
   1206   }
   1207 
   1208   Stack->pop_back();
   1209   // To simplify the implementation, never keep around an empty stack.
   1210   if (Stack->empty())
   1211     FreeVisContext();
   1212 }
   1213 
   1214 template <typename Ty>
   1215 static bool checkCommonAttributeFeatures(Sema& S, const Ty *Node,
   1216                                          const ParsedAttr& A) {
   1217   // Several attributes carry different semantics than the parsing requires, so
   1218   // those are opted out of the common argument checks.
   1219   //
   1220   // We also bail on unknown and ignored attributes because those are handled
   1221   // as part of the target-specific handling logic.
   1222   if (A.getKind() == ParsedAttr::UnknownAttribute)
   1223     return false;
   1224   // Check whether the attribute requires specific language extensions to be
   1225   // enabled.
   1226   if (!A.diagnoseLangOpts(S))
   1227     return true;
   1228   // Check whether the attribute appertains to the given subject.
   1229   if (!A.diagnoseAppertainsTo(S, Node))
   1230     return true;
   1231   // Check whether the attribute is mutually exclusive with other attributes
   1232   // that have already been applied to the declaration.
   1233   if (!A.diagnoseMutualExclusion(S, Node))
   1234     return true;
   1235   // Check whether the attribute exists in the target architecture.
   1236   if (S.CheckAttrTarget(A))
   1237     return true;
   1238 
   1239   if (A.hasCustomParsing())
   1240     return false;
   1241 
   1242   if (A.getMinArgs() == A.getMaxArgs()) {
   1243     // If there are no optional arguments, then checking for the argument count
   1244     // is trivial.
   1245     if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
   1246       return true;
   1247   } else {
   1248     // There are optional arguments, so checking is slightly more involved.
   1249     if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))
   1250       return true;
   1251     else if (!A.hasVariadicArg() && A.getMaxArgs() &&
   1252              !A.checkAtMostNumArgs(S, A.getMaxArgs()))
   1253       return true;
   1254   }
   1255 
   1256   return false;
   1257 }
   1258 
   1259 bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A) {
   1260   return ::checkCommonAttributeFeatures(*this, D, A);
   1261 }
   1262 bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A) {
   1263   return ::checkCommonAttributeFeatures(*this, S, A);
   1264 }
   1265