1 //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for non-trivial attributes and
13 //===----------------------------------------------------------------------===//
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;
24 //===----------------------------------------------------------------------===//
25 // Pragma 'pack' and 'options align'
26 //===----------------------------------------------------------------------===//
29 struct PackStackEntry {
30 // We just use a sentinel to represent when the stack is set to mac68k
32 static const unsigned kMac68kAlignmentSentinel = ~0U;
38 /// PragmaPackStack - Simple class to wrap the stack used by #pragma
40 class PragmaPackStack {
41 typedef std::vector<PackStackEntry> stack_ty;
43 /// Alignment - The current user specified alignment.
46 /// Stack - Entries in the #pragma pack stack, consisting of saved
47 /// alignments and optional names.
51 PragmaPackStack() : Alignment(0) {}
53 void setAlignment(unsigned A) { Alignment = A; }
54 unsigned getAlignment() { return Alignment; }
56 /// push - Push the current alignment onto the stack, optionally
57 /// using the given \arg Name for the record, if non-zero.
58 void push(IdentifierInfo *Name) {
59 PackStackEntry PSE = { Alignment, Name };
63 /// pop - Pop a record from the stack and restore the current
64 /// alignment to the previous value. If \arg Name is non-zero then
65 /// the first such named record is popped, otherwise the top record
66 /// is popped. Returns true if the pop succeeded.
67 bool pop(IdentifierInfo *Name, bool IsReset);
69 } // end anonymous namespace.
71 bool PragmaPackStack::pop(IdentifierInfo *Name, bool IsReset) {
72 // If name is empty just pop top.
74 // An empty stack is a special case...
76 // If this isn't a reset, it is always an error.
80 // Otherwise, it is an error only if some alignment has been set.
84 // Otherwise, reset to the default alignment.
87 Alignment = Stack.back().Alignment;
94 // Otherwise, find the named record.
95 for (unsigned i = Stack.size(); i != 0; ) {
97 if (Stack[i].Name == Name) {
98 // Found it, pop up to and including this record.
99 Alignment = Stack[i].Alignment;
100 Stack.erase(Stack.begin() + i, Stack.end());
109 /// FreePackedContext - Deallocate and null out PackContext.
110 void Sema::FreePackedContext() {
111 delete static_cast<PragmaPackStack*>(PackContext);
112 PackContext = nullptr;
115 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
116 // If there is no pack context, we don't need any attributes.
120 PragmaPackStack *Stack = static_cast<PragmaPackStack*>(PackContext);
122 // Otherwise, check to see if we need a max field alignment attribute.
123 if (unsigned Alignment = Stack->getAlignment()) {
124 if (Alignment == PackStackEntry::kMac68kAlignmentSentinel)
125 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
127 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
132 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
133 if (MSStructPragmaOn)
134 RD->addAttr(MSStructAttr::CreateImplicit(Context));
136 // FIXME: We should merge AddAlignmentAttributesForRecord with
137 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
138 // all active pragmas and applies them as attributes to class definitions.
139 if (VtorDispModeStack.back() != getLangOpts().VtorDispMode)
141 MSVtorDispAttr::CreateImplicit(Context, VtorDispModeStack.back()));
144 void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
145 SourceLocation PragmaLoc) {
147 PackContext = new PragmaPackStack();
149 PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
152 // For all targets we support native and natural are the same.
154 // FIXME: This is not true on Darwin/PPC.
158 Context->push(nullptr);
159 Context->setAlignment(0);
162 // Note that '#pragma options align=packed' is not equivalent to attribute
163 // packed, it has a different precedence relative to attribute aligned.
165 Context->push(nullptr);
166 Context->setAlignment(1);
170 // Check if the target supports this.
171 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
172 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
175 Context->push(nullptr);
176 Context->setAlignment(PackStackEntry::kMac68kAlignmentSentinel);
180 // Reset just pops the top of the stack, or resets the current alignment to
182 if (!Context->pop(nullptr, /*IsReset=*/true)) {
183 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
190 void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
191 Expr *alignment, SourceLocation PragmaLoc,
192 SourceLocation LParenLoc, SourceLocation RParenLoc) {
193 Expr *Alignment = static_cast<Expr *>(alignment);
195 // If specified then alignment must be a "small" power of two.
196 unsigned AlignmentVal = 0;
200 // pack(0) is like pack(), which just works out since that is what
201 // we use 0 for in PackAttr.
202 if (Alignment->isTypeDependent() ||
203 Alignment->isValueDependent() ||
204 !Alignment->isIntegerConstantExpr(Val, Context) ||
205 !(Val == 0 || Val.isPowerOf2()) ||
206 Val.getZExtValue() > 16) {
207 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
211 AlignmentVal = (unsigned) Val.getZExtValue();
215 PackContext = new PragmaPackStack();
217 PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
220 case Sema::PPK_Default: // pack([n])
221 Context->setAlignment(AlignmentVal);
224 case Sema::PPK_Show: // pack(show)
225 // Show the current alignment, making sure to show the right value
227 AlignmentVal = Context->getAlignment();
228 // FIXME: This should come from the target.
229 if (AlignmentVal == 0)
231 if (AlignmentVal == PackStackEntry::kMac68kAlignmentSentinel)
232 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
234 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
237 case Sema::PPK_Push: // pack(push [, id] [, [n])
239 // Set the new alignment if specified.
241 Context->setAlignment(AlignmentVal);
244 case Sema::PPK_Pop: // pack(pop [, id] [, n])
245 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
246 // "#pragma pack(pop, identifier, n) is undefined"
247 if (Alignment && Name)
248 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
251 if (!Context->pop(Name, /*IsReset=*/false)) {
252 // If a name was specified then failure indicates the name
253 // wasn't found. Otherwise failure indicates the stack was
255 Diag(PragmaLoc, diag::warn_pragma_pop_failed)
256 << "pack" << (Name ? "no record matching name" : "stack empty");
258 // FIXME: Warn about popping named records as MSVC does.
260 // Pop succeeded, set the new alignment if specified.
262 Context->setAlignment(AlignmentVal);
268 void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
269 MSStructPragmaOn = (Kind == PMSST_ON);
272 void Sema::ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg) {
273 // FIXME: Serialize this.
276 llvm_unreachable("unexpected pragma comment kind");
278 Consumer.HandleLinkerOptionPragma(Arg);
281 Consumer.HandleDependentLibrary(Arg);
286 return; // We ignore all of these.
288 llvm_unreachable("invalid pragma comment kind");
291 void Sema::ActOnPragmaDetectMismatch(StringRef Name, StringRef Value) {
292 // FIXME: Serialize this.
293 Consumer.HandleDetectMismatch(Name, Value);
296 void Sema::ActOnPragmaMSPointersToMembers(
297 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
298 SourceLocation PragmaLoc) {
299 MSPointerToMemberRepresentationMethod = RepresentationMethod;
300 ImplicitMSInheritanceAttrLoc = PragmaLoc;
303 void Sema::ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind,
304 SourceLocation PragmaLoc,
305 MSVtorDispAttr::Mode Mode) {
308 VtorDispModeStack.back() = Mode;
311 VtorDispModeStack.push_back(Mode);
314 VtorDispModeStack.clear();
315 VtorDispModeStack.push_back(MSVtorDispAttr::Mode(LangOpts.VtorDispMode));
318 VtorDispModeStack.pop_back();
319 if (VtorDispModeStack.empty()) {
320 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
322 VtorDispModeStack.push_back(MSVtorDispAttr::Mode(LangOpts.VtorDispMode));
328 template<typename ValueType>
329 void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation,
330 PragmaMsStackAction Action,
331 llvm::StringRef StackSlotLabel,
333 if (Action == PSK_Reset) {
334 CurrentValue = nullptr;
337 if (Action & PSK_Push)
338 Stack.push_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation));
339 else if (Action & PSK_Pop) {
340 if (!StackSlotLabel.empty()) {
341 // If we've got a label, try to find it and jump there.
342 auto I = std::find_if(Stack.rbegin(), Stack.rend(),
343 [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; });
344 // If we found the label so pop from there.
345 if (I != Stack.rend()) {
346 CurrentValue = I->Value;
347 CurrentPragmaLocation = I->PragmaLocation;
348 Stack.erase(std::prev(I.base()), Stack.end());
350 } else if (!Stack.empty()) {
351 // We don't have a label, just pop the last entry.
352 CurrentValue = Stack.back().Value;
353 CurrentPragmaLocation = Stack.back().PragmaLocation;
357 if (Action & PSK_Set) {
358 CurrentValue = Value;
359 CurrentPragmaLocation = PragmaLocation;
363 bool Sema::UnifySection(StringRef SectionName,
365 DeclaratorDecl *Decl) {
366 auto Section = Context.SectionInfos.find(SectionName);
367 if (Section == Context.SectionInfos.end()) {
368 Context.SectionInfos[SectionName] =
369 ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags);
372 // A pre-declared section takes precedence w/o diagnostic.
373 if (Section->second.SectionFlags == SectionFlags ||
374 !(Section->second.SectionFlags & ASTContext::PSF_Implicit))
376 auto OtherDecl = Section->second.Decl;
377 Diag(Decl->getLocation(), diag::err_section_conflict)
378 << Decl << OtherDecl;
379 Diag(OtherDecl->getLocation(), diag::note_declared_at)
380 << OtherDecl->getName();
381 if (auto A = Decl->getAttr<SectionAttr>())
383 Diag(A->getLocation(), diag::note_pragma_entered_here);
384 if (auto A = OtherDecl->getAttr<SectionAttr>())
386 Diag(A->getLocation(), diag::note_pragma_entered_here);
390 bool Sema::UnifySection(StringRef SectionName,
392 SourceLocation PragmaSectionLocation) {
393 auto Section = Context.SectionInfos.find(SectionName);
394 if (Section != Context.SectionInfos.end()) {
395 if (Section->second.SectionFlags == SectionFlags)
397 if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) {
398 Diag(PragmaSectionLocation, diag::err_section_conflict)
399 << "this" << "a prior #pragma section";
400 Diag(Section->second.PragmaSectionLocation,
401 diag::note_pragma_entered_here);
405 Context.SectionInfos[SectionName] =
406 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
410 /// \brief Called on well formed \#pragma bss_seg().
411 void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
412 PragmaMsStackAction Action,
413 llvm::StringRef StackSlotLabel,
414 StringLiteral *SegmentName,
415 llvm::StringRef PragmaName) {
416 PragmaStack<StringLiteral *> *Stack =
417 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
418 .Case("data_seg", &DataSegStack)
419 .Case("bss_seg", &BSSSegStack)
420 .Case("const_seg", &ConstSegStack)
421 .Case("code_seg", &CodeSegStack);
422 if (Action & PSK_Pop && Stack->Stack.empty())
423 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
426 !checkSectionName(SegmentName->getLocStart(), SegmentName->getString()))
428 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
431 /// \brief Called on well formed \#pragma bss_seg().
432 void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
433 int SectionFlags, StringLiteral *SegmentName) {
434 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
437 void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
438 StringLiteral *SegmentName) {
439 // There's no stack to maintain, so we just have a current section. When we
440 // see the default section, reset our current section back to null so we stop
441 // tacking on unnecessary attributes.
442 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
443 CurInitSegLoc = PragmaLocation;
446 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
447 SourceLocation PragmaLoc) {
449 IdentifierInfo *Name = IdTok.getIdentifierInfo();
450 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
451 LookupParsedName(Lookup, curScope, nullptr, true);
453 if (Lookup.empty()) {
454 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
455 << Name << SourceRange(IdTok.getLocation());
459 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
461 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
462 << Name << SourceRange(IdTok.getLocation());
466 // Warn if this was used before being marked unused.
468 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
470 VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation()));
473 void Sema::AddCFAuditedAttribute(Decl *D) {
474 SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc();
475 if (!Loc.isValid()) return;
477 // Don't add a redundant or conflicting attribute.
478 if (D->hasAttr<CFAuditedTransferAttr>() ||
479 D->hasAttr<CFUnknownTransferAttr>())
482 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Loc));
485 void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
487 OptimizeOffPragmaLocation = SourceLocation();
489 OptimizeOffPragmaLocation = PragmaLoc;
492 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
493 // In the future, check other pragmas if they're implemented (e.g. pragma
494 // optimize 0 will probably map to this functionality too).
495 if(OptimizeOffPragmaLocation.isValid())
496 AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
499 void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
500 SourceLocation Loc) {
501 // Don't add a conflicting attribute. No diagnostic is needed.
502 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
505 // Add attributes only if required. Optnone requires noinline as well, but if
506 // either is already present then don't bother adding them.
507 if (!FD->hasAttr<OptimizeNoneAttr>())
508 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
509 if (!FD->hasAttr<NoInlineAttr>())
510 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
513 typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
514 enum : unsigned { NoVisibility = ~0U };
516 void Sema::AddPushedVisibilityAttribute(Decl *D) {
520 NamedDecl *ND = dyn_cast<NamedDecl>(D);
521 if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
524 VisStack *Stack = static_cast<VisStack*>(VisContext);
525 unsigned rawType = Stack->back().first;
526 if (rawType == NoVisibility) return;
528 VisibilityAttr::VisibilityType type
529 = (VisibilityAttr::VisibilityType) rawType;
530 SourceLocation loc = Stack->back().second;
532 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
535 /// FreeVisContext - Deallocate and null out VisContext.
536 void Sema::FreeVisContext() {
537 delete static_cast<VisStack*>(VisContext);
538 VisContext = nullptr;
541 static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
542 // Put visibility on stack.
544 S.VisContext = new VisStack;
546 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
547 Stack->push_back(std::make_pair(type, loc));
550 void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
551 SourceLocation PragmaLoc) {
553 // Compute visibility to use.
554 VisibilityAttr::VisibilityType T;
555 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
556 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
559 PushPragmaVisibility(*this, T, PragmaLoc);
561 PopPragmaVisibility(false, PragmaLoc);
565 void Sema::ActOnPragmaFPContract(tok::OnOffSwitch OOS) {
568 FPFeatures.fp_contract = 1;
571 FPFeatures.fp_contract = 0;
573 case tok::OOS_DEFAULT:
574 FPFeatures.fp_contract = getLangOpts().DefaultFPContract;
579 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
580 SourceLocation Loc) {
581 // Visibility calculations will consider the namespace's visibility.
582 // Here we just want to note that we're in a visibility context
583 // which overrides any enclosing #pragma context, but doesn't itself
584 // contribute visibility.
585 PushPragmaVisibility(*this, NoVisibility, Loc);
588 void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
590 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
594 // Pop visibility from stack
595 VisStack *Stack = static_cast<VisStack*>(VisContext);
597 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
598 bool StartsWithPragma = Back->first != NoVisibility;
599 if (StartsWithPragma && IsNamespaceEnd) {
600 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
601 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
603 // For better error recovery, eat all pushes inside the namespace.
606 Back = &Stack->back();
607 StartsWithPragma = Back->first != NoVisibility;
608 } while (StartsWithPragma);
609 } else if (!StartsWithPragma && !IsNamespaceEnd) {
610 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
611 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
616 // To simplify the implementation, never keep around an empty stack.