1 //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for non-trivial attributes and 11 // pragmas. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Sema/SemaInternal.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/Sema/Lookup.h" 22 using namespace clang; 23 24 //===----------------------------------------------------------------------===// 25 // Pragma 'pack' and 'options align' 26 //===----------------------------------------------------------------------===// 27 28 Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S, 29 StringRef SlotLabel, 30 bool ShouldAct) 31 : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) { 32 if (ShouldAct) { 33 S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel); 34 S.DataSegStack.SentinelAction(PSK_Push, SlotLabel); 35 S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel); 36 S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel); 37 S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel); 38 } 39 } 40 41 Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() { 42 if (ShouldAct) { 43 S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel); 44 S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel); 45 S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel); 46 S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel); 47 S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel); 48 } 49 } 50 51 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) { 52 // If there is no pack value, we don't need any attributes. 53 if (!PackStack.CurrentValue) 54 return; 55 56 // Otherwise, check to see if we need a max field alignment attribute. 57 if (unsigned Alignment = PackStack.CurrentValue) { 58 if (Alignment == Sema::kMac68kAlignmentSentinel) 59 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context)); 60 else 61 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context, 62 Alignment * 8)); 63 } 64 } 65 66 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) { 67 if (MSStructPragmaOn) 68 RD->addAttr(MSStructAttr::CreateImplicit(Context)); 69 70 // FIXME: We should merge AddAlignmentAttributesForRecord with 71 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes 72 // all active pragmas and applies them as attributes to class definitions. 73 if (VtorDispStack.CurrentValue != getLangOpts().VtorDispMode) 74 RD->addAttr( 75 MSVtorDispAttr::CreateImplicit(Context, VtorDispStack.CurrentValue)); 76 } 77 78 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 79 SourceLocation PragmaLoc) { 80 PragmaMsStackAction Action = Sema::PSK_Reset; 81 unsigned Alignment = 0; 82 switch (Kind) { 83 // For all targets we support native and natural are the same. 84 // 85 // FIXME: This is not true on Darwin/PPC. 86 case POAK_Native: 87 case POAK_Power: 88 case POAK_Natural: 89 Action = Sema::PSK_Push_Set; 90 Alignment = 0; 91 break; 92 93 // Note that '#pragma options align=packed' is not equivalent to attribute 94 // packed, it has a different precedence relative to attribute aligned. 95 case POAK_Packed: 96 Action = Sema::PSK_Push_Set; 97 Alignment = 1; 98 break; 99 100 case POAK_Mac68k: 101 // Check if the target supports this. 102 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) { 103 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported); 104 return; 105 } 106 Action = Sema::PSK_Push_Set; 107 Alignment = Sema::kMac68kAlignmentSentinel; 108 break; 109 110 case POAK_Reset: 111 // Reset just pops the top of the stack, or resets the current alignment to 112 // default. 113 Action = Sema::PSK_Pop; 114 if (PackStack.Stack.empty()) { 115 if (PackStack.CurrentValue) { 116 Action = Sema::PSK_Reset; 117 } else { 118 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed) 119 << "stack empty"; 120 return; 121 } 122 } 123 break; 124 } 125 126 PackStack.Act(PragmaLoc, Action, StringRef(), Alignment); 127 } 128 129 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 130 StringRef SlotLabel, Expr *alignment) { 131 Expr *Alignment = static_cast<Expr *>(alignment); 132 133 // If specified then alignment must be a "small" power of two. 134 unsigned AlignmentVal = 0; 135 if (Alignment) { 136 llvm::APSInt Val; 137 138 // pack(0) is like pack(), which just works out since that is what 139 // we use 0 for in PackAttr. 140 if (Alignment->isTypeDependent() || 141 Alignment->isValueDependent() || 142 !Alignment->isIntegerConstantExpr(Val, Context) || 143 !(Val == 0 || Val.isPowerOf2()) || 144 Val.getZExtValue() > 16) { 145 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 146 return; // Ignore 147 } 148 149 AlignmentVal = (unsigned) Val.getZExtValue(); 150 } 151 if (Action == Sema::PSK_Show) { 152 // Show the current alignment, making sure to show the right value 153 // for the default. 154 // FIXME: This should come from the target. 155 AlignmentVal = PackStack.CurrentValue; 156 if (AlignmentVal == 0) 157 AlignmentVal = 8; 158 if (AlignmentVal == Sema::kMac68kAlignmentSentinel) 159 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k"; 160 else 161 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal; 162 } 163 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 164 // "#pragma pack(pop, identifier, n) is undefined" 165 if (Action & Sema::PSK_Pop) { 166 if (Alignment && !SlotLabel.empty()) 167 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 168 if (PackStack.Stack.empty()) 169 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty"; 170 } 171 172 PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal); 173 } 174 175 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) { 176 MSStructPragmaOn = (Kind == PMSST_ON); 177 } 178 179 void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc, 180 PragmaMSCommentKind Kind, StringRef Arg) { 181 auto *PCD = PragmaCommentDecl::Create( 182 Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg); 183 Context.getTranslationUnitDecl()->addDecl(PCD); 184 Consumer.HandleTopLevelDecl(DeclGroupRef(PCD)); 185 } 186 187 void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 188 StringRef Value) { 189 auto *PDMD = PragmaDetectMismatchDecl::Create( 190 Context, Context.getTranslationUnitDecl(), Loc, Name, Value); 191 Context.getTranslationUnitDecl()->addDecl(PDMD); 192 Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD)); 193 } 194 195 void Sema::ActOnPragmaMSPointersToMembers( 196 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod, 197 SourceLocation PragmaLoc) { 198 MSPointerToMemberRepresentationMethod = RepresentationMethod; 199 ImplicitMSInheritanceAttrLoc = PragmaLoc; 200 } 201 202 void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 203 SourceLocation PragmaLoc, 204 MSVtorDispAttr::Mode Mode) { 205 if (Action & PSK_Pop && VtorDispStack.Stack.empty()) 206 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp" 207 << "stack empty"; 208 VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode); 209 } 210 211 template<typename ValueType> 212 void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation, 213 PragmaMsStackAction Action, 214 llvm::StringRef StackSlotLabel, 215 ValueType Value) { 216 if (Action == PSK_Reset) { 217 CurrentValue = DefaultValue; 218 return; 219 } 220 if (Action & PSK_Push) 221 Stack.push_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation)); 222 else if (Action & PSK_Pop) { 223 if (!StackSlotLabel.empty()) { 224 // If we've got a label, try to find it and jump there. 225 auto I = std::find_if(Stack.rbegin(), Stack.rend(), 226 [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); 227 // If we found the label so pop from there. 228 if (I != Stack.rend()) { 229 CurrentValue = I->Value; 230 CurrentPragmaLocation = I->PragmaLocation; 231 Stack.erase(std::prev(I.base()), Stack.end()); 232 } 233 } else if (!Stack.empty()) { 234 // We don't have a label, just pop the last entry. 235 CurrentValue = Stack.back().Value; 236 CurrentPragmaLocation = Stack.back().PragmaLocation; 237 Stack.pop_back(); 238 } 239 } 240 if (Action & PSK_Set) { 241 CurrentValue = Value; 242 CurrentPragmaLocation = PragmaLocation; 243 } 244 } 245 246 bool Sema::UnifySection(StringRef SectionName, 247 int SectionFlags, 248 DeclaratorDecl *Decl) { 249 auto Section = Context.SectionInfos.find(SectionName); 250 if (Section == Context.SectionInfos.end()) { 251 Context.SectionInfos[SectionName] = 252 ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags); 253 return false; 254 } 255 // A pre-declared section takes precedence w/o diagnostic. 256 if (Section->second.SectionFlags == SectionFlags || 257 !(Section->second.SectionFlags & ASTContext::PSF_Implicit)) 258 return false; 259 auto OtherDecl = Section->second.Decl; 260 Diag(Decl->getLocation(), diag::err_section_conflict) 261 << Decl << OtherDecl; 262 Diag(OtherDecl->getLocation(), diag::note_declared_at) 263 << OtherDecl->getName(); 264 if (auto A = Decl->getAttr<SectionAttr>()) 265 if (A->isImplicit()) 266 Diag(A->getLocation(), diag::note_pragma_entered_here); 267 if (auto A = OtherDecl->getAttr<SectionAttr>()) 268 if (A->isImplicit()) 269 Diag(A->getLocation(), diag::note_pragma_entered_here); 270 return true; 271 } 272 273 bool Sema::UnifySection(StringRef SectionName, 274 int SectionFlags, 275 SourceLocation PragmaSectionLocation) { 276 auto Section = Context.SectionInfos.find(SectionName); 277 if (Section != Context.SectionInfos.end()) { 278 if (Section->second.SectionFlags == SectionFlags) 279 return false; 280 if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) { 281 Diag(PragmaSectionLocation, diag::err_section_conflict) 282 << "this" << "a prior #pragma section"; 283 Diag(Section->second.PragmaSectionLocation, 284 diag::note_pragma_entered_here); 285 return true; 286 } 287 } 288 Context.SectionInfos[SectionName] = 289 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags); 290 return false; 291 } 292 293 /// \brief Called on well formed \#pragma bss_seg(). 294 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation, 295 PragmaMsStackAction Action, 296 llvm::StringRef StackSlotLabel, 297 StringLiteral *SegmentName, 298 llvm::StringRef PragmaName) { 299 PragmaStack<StringLiteral *> *Stack = 300 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName) 301 .Case("data_seg", &DataSegStack) 302 .Case("bss_seg", &BSSSegStack) 303 .Case("const_seg", &ConstSegStack) 304 .Case("code_seg", &CodeSegStack); 305 if (Action & PSK_Pop && Stack->Stack.empty()) 306 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName 307 << "stack empty"; 308 if (SegmentName && 309 !checkSectionName(SegmentName->getLocStart(), SegmentName->getString())) 310 return; 311 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName); 312 } 313 314 /// \brief Called on well formed \#pragma bss_seg(). 315 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation, 316 int SectionFlags, StringLiteral *SegmentName) { 317 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation); 318 } 319 320 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 321 StringLiteral *SegmentName) { 322 // There's no stack to maintain, so we just have a current section. When we 323 // see the default section, reset our current section back to null so we stop 324 // tacking on unnecessary attributes. 325 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName; 326 CurInitSegLoc = PragmaLocation; 327 } 328 329 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope, 330 SourceLocation PragmaLoc) { 331 332 IdentifierInfo *Name = IdTok.getIdentifierInfo(); 333 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName); 334 LookupParsedName(Lookup, curScope, nullptr, true); 335 336 if (Lookup.empty()) { 337 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var) 338 << Name << SourceRange(IdTok.getLocation()); 339 return; 340 } 341 342 VarDecl *VD = Lookup.getAsSingle<VarDecl>(); 343 if (!VD) { 344 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg) 345 << Name << SourceRange(IdTok.getLocation()); 346 return; 347 } 348 349 // Warn if this was used before being marked unused. 350 if (VD->isUsed()) 351 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name; 352 353 VD->addAttr(UnusedAttr::CreateImplicit(Context, UnusedAttr::GNU_unused, 354 IdTok.getLocation())); 355 } 356 357 void Sema::AddCFAuditedAttribute(Decl *D) { 358 SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc(); 359 if (!Loc.isValid()) return; 360 361 // Don't add a redundant or conflicting attribute. 362 if (D->hasAttr<CFAuditedTransferAttr>() || 363 D->hasAttr<CFUnknownTransferAttr>()) 364 return; 365 366 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Loc)); 367 } 368 369 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) { 370 if(On) 371 OptimizeOffPragmaLocation = SourceLocation(); 372 else 373 OptimizeOffPragmaLocation = PragmaLoc; 374 } 375 376 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) { 377 // In the future, check other pragmas if they're implemented (e.g. pragma 378 // optimize 0 will probably map to this functionality too). 379 if(OptimizeOffPragmaLocation.isValid()) 380 AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation); 381 } 382 383 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, 384 SourceLocation Loc) { 385 // Don't add a conflicting attribute. No diagnostic is needed. 386 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>()) 387 return; 388 389 // Add attributes only if required. Optnone requires noinline as well, but if 390 // either is already present then don't bother adding them. 391 if (!FD->hasAttr<OptimizeNoneAttr>()) 392 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc)); 393 if (!FD->hasAttr<NoInlineAttr>()) 394 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc)); 395 } 396 397 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack; 398 enum : unsigned { NoVisibility = ~0U }; 399 400 void Sema::AddPushedVisibilityAttribute(Decl *D) { 401 if (!VisContext) 402 return; 403 404 NamedDecl *ND = dyn_cast<NamedDecl>(D); 405 if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue)) 406 return; 407 408 VisStack *Stack = static_cast<VisStack*>(VisContext); 409 unsigned rawType = Stack->back().first; 410 if (rawType == NoVisibility) return; 411 412 VisibilityAttr::VisibilityType type 413 = (VisibilityAttr::VisibilityType) rawType; 414 SourceLocation loc = Stack->back().second; 415 416 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc)); 417 } 418 419 /// FreeVisContext - Deallocate and null out VisContext. 420 void Sema::FreeVisContext() { 421 delete static_cast<VisStack*>(VisContext); 422 VisContext = nullptr; 423 } 424 425 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) { 426 // Put visibility on stack. 427 if (!S.VisContext) 428 S.VisContext = new VisStack; 429 430 VisStack *Stack = static_cast<VisStack*>(S.VisContext); 431 Stack->push_back(std::make_pair(type, loc)); 432 } 433 434 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType, 435 SourceLocation PragmaLoc) { 436 if (VisType) { 437 // Compute visibility to use. 438 VisibilityAttr::VisibilityType T; 439 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) { 440 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType; 441 return; 442 } 443 PushPragmaVisibility(*this, T, PragmaLoc); 444 } else { 445 PopPragmaVisibility(false, PragmaLoc); 446 } 447 } 448 449 void Sema::ActOnPragmaFPContract(tok::OnOffSwitch OOS) { 450 switch (OOS) { 451 case tok::OOS_ON: 452 FPFeatures.fp_contract = 1; 453 break; 454 case tok::OOS_OFF: 455 FPFeatures.fp_contract = 0; 456 break; 457 case tok::OOS_DEFAULT: 458 FPFeatures.fp_contract = getLangOpts().DefaultFPContract; 459 break; 460 } 461 } 462 463 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 464 SourceLocation Loc) { 465 // Visibility calculations will consider the namespace's visibility. 466 // Here we just want to note that we're in a visibility context 467 // which overrides any enclosing #pragma context, but doesn't itself 468 // contribute visibility. 469 PushPragmaVisibility(*this, NoVisibility, Loc); 470 } 471 472 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) { 473 if (!VisContext) { 474 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch); 475 return; 476 } 477 478 // Pop visibility from stack 479 VisStack *Stack = static_cast<VisStack*>(VisContext); 480 481 const std::pair<unsigned, SourceLocation> *Back = &Stack->back(); 482 bool StartsWithPragma = Back->first != NoVisibility; 483 if (StartsWithPragma && IsNamespaceEnd) { 484 Diag(Back->second, diag::err_pragma_push_visibility_mismatch); 485 Diag(EndLoc, diag::note_surrounding_namespace_ends_here); 486 487 // For better error recovery, eat all pushes inside the namespace. 488 do { 489 Stack->pop_back(); 490 Back = &Stack->back(); 491 StartsWithPragma = Back->first != NoVisibility; 492 } while (StartsWithPragma); 493 } else if (!StartsWithPragma && !IsNamespaceEnd) { 494 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch); 495 Diag(Back->second, diag::note_surrounding_namespace_starts_here); 496 return; 497 } 498 499 Stack->pop_back(); 500 // To simplify the implementation, never keep around an empty stack. 501 if (Stack->empty()) 502 FreeVisContext(); 503 } 504