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