blob: 23cb47481f3d219607a06e6dc2c7c10855b5d98c [file] [log] [blame]
Bill Wendling44426052012-12-20 19:22:21 +00001//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
Chris Lattner2eccbc12009-02-17 00:57:29 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner2eccbc12009-02-17 00:57:29 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner31180bb2009-02-17 01:09:29 +00009// This file implements semantic analysis for non-trivial attributes and
10// pragmas.
Chris Lattner2eccbc12009-02-17 00:57:29 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Klecknere43f0fe2013-05-08 13:44:39 +000014#include "clang/AST/ASTConsumer.h"
Alexis Huntdcfba7b2010-08-18 23:23:40 +000015#include "clang/AST/Attr.h"
Chris Lattner2eccbc12009-02-17 00:57:29 +000016#include "clang/AST/Expr.h"
Daniel Dunbarbd606522010-05-27 00:35:16 +000017#include "clang/Basic/TargetInfo.h"
18#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Sema/Lookup.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000020#include "clang/Sema/SemaInternal.h"
Chris Lattner2eccbc12009-02-17 00:57:29 +000021using namespace clang;
22
Chris Lattner31180bb2009-02-17 01:09:29 +000023//===----------------------------------------------------------------------===//
Daniel Dunbar69dac582010-05-27 00:04:40 +000024// Pragma 'pack' and 'options align'
Chris Lattner31180bb2009-02-17 01:09:29 +000025//===----------------------------------------------------------------------===//
26
Denis Zobnin2290dac2016-04-29 11:27:00 +000027Sema::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
40Sema::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}
Chris Lattner31180bb2009-02-17 01:09:29 +000049
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000050void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
Denis Zobnin10c4f452016-04-29 18:17:40 +000051 // If there is no pack value, we don't need any attributes.
52 if (!PackStack.CurrentValue)
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000053 return;
54
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000055 // Otherwise, check to see if we need a max field alignment attribute.
Denis Zobnin10c4f452016-04-29 18:17:40 +000056 if (unsigned Alignment = PackStack.CurrentValue) {
57 if (Alignment == Sema::kMac68kAlignmentSentinel)
Aaron Ballman36a53502014-01-16 13:03:14 +000058 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
Daniel Dunbar6da10982010-05-27 05:45:51 +000059 else
Aaron Ballman36a53502014-01-16 13:03:14 +000060 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
Alexis Huntdcfba7b2010-08-18 23:23:40 +000061 Alignment * 8));
Daniel Dunbar6da10982010-05-27 05:45:51 +000062 }
Alex Lorenz45b40142017-07-28 14:41:21 +000063 if (PackIncludeStack.empty())
64 return;
65 // The #pragma pack affected a record in an included file, so Clang should
66 // warn when that pragma was written in a file that included the included
67 // file.
68 for (auto &PackedInclude : llvm::reverse(PackIncludeStack)) {
69 if (PackedInclude.CurrentPragmaLocation != PackStack.CurrentPragmaLocation)
70 break;
71 if (PackedInclude.HasNonDefaultValue)
72 PackedInclude.ShouldWarnOnInclude = true;
73 }
Chris Lattner31180bb2009-02-17 01:09:29 +000074}
75
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +000076void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +000077 if (MSStructPragmaOn)
David Majnemer8ab003a2015-02-02 19:30:52 +000078 RD->addAttr(MSStructAttr::CreateImplicit(Context));
Reid Klecknerc0dca6d2014-02-12 23:50:26 +000079
80 // FIXME: We should merge AddAlignmentAttributesForRecord with
81 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
82 // all active pragmas and applies them as attributes to class definitions.
Denis Zobnin2290dac2016-04-29 11:27:00 +000083 if (VtorDispStack.CurrentValue != getLangOpts().VtorDispMode)
Reid Klecknerc0dca6d2014-02-12 23:50:26 +000084 RD->addAttr(
Denis Zobnin2290dac2016-04-29 11:27:00 +000085 MSVtorDispAttr::CreateImplicit(Context, VtorDispStack.CurrentValue));
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +000086}
87
Matthias Gehre23092ca2019-08-07 10:45:36 +000088template <typename Attribute>
89static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
90 CXXRecordDecl *Record) {
Matthias Gehref64f4882019-09-06 08:56:30 +000091 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
Matthias Gehre23092ca2019-08-07 10:45:36 +000092 return;
93
Matthias Gehref64f4882019-09-06 08:56:30 +000094 for (Decl *Redecl : Record->redecls())
95 Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
Matthias Gehre23092ca2019-08-07 10:45:36 +000096}
97
98void Sema::inferGslPointerAttribute(NamedDecl *ND,
99 CXXRecordDecl *UnderlyingRecord) {
100 if (!UnderlyingRecord)
101 return;
102
103 const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
104 if (!Parent)
105 return;
106
107 static llvm::StringSet<> Containers{
108 "array",
109 "basic_string",
110 "deque",
111 "forward_list",
112 "vector",
113 "list",
114 "map",
115 "multiset",
116 "multimap",
117 "priority_queue",
118 "queue",
119 "set",
120 "stack",
121 "unordered_set",
122 "unordered_map",
123 "unordered_multiset",
124 "unordered_multimap",
125 };
126
127 static llvm::StringSet<> Iterators{"iterator", "const_iterator",
128 "reverse_iterator",
129 "const_reverse_iterator"};
130
131 if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
132 Containers.count(Parent->getName()))
133 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
134 UnderlyingRecord);
135}
136
137void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
138
139 QualType Canonical = TD->getUnderlyingType().getCanonicalType();
140
141 CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
142 if (!RD) {
143 if (auto *TST =
144 dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
145
146 RD = dyn_cast_or_null<CXXRecordDecl>(
147 TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
148 }
149 }
150
151 inferGslPointerAttribute(TD, RD);
152}
153
154void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
155 static llvm::StringSet<> StdOwners{
156 "any",
157 "array",
158 "basic_regex",
159 "basic_string",
160 "deque",
161 "forward_list",
162 "vector",
163 "list",
164 "map",
165 "multiset",
166 "multimap",
167 "optional",
168 "priority_queue",
169 "queue",
170 "set",
171 "stack",
172 "unique_ptr",
173 "unordered_set",
174 "unordered_map",
175 "unordered_multiset",
176 "unordered_multimap",
177 "variant",
178 };
179 static llvm::StringSet<> StdPointers{
180 "basic_string_view",
181 "reference_wrapper",
182 "regex_iterator",
183 };
184
185 if (!Record->getIdentifier())
186 return;
187
188 // Handle classes that directly appear in std namespace.
189 if (Record->isInStdNamespace()) {
Matthias Gehref64f4882019-09-06 08:56:30 +0000190 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
Matthias Gehre23092ca2019-08-07 10:45:36 +0000191 return;
192
193 if (StdOwners.count(Record->getName()))
194 addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
195 else if (StdPointers.count(Record->getName()))
196 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
197
198 return;
199 }
200
201 // Handle nested classes that could be a gsl::Pointer.
202 inferGslPointerAttribute(Record, Record);
203}
204
Daniel Dunbar69dac582010-05-27 00:04:40 +0000205void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
Eli Friedman68be1642012-10-04 02:36:51 +0000206 SourceLocation PragmaLoc) {
Denis Zobnin10c4f452016-04-29 18:17:40 +0000207 PragmaMsStackAction Action = Sema::PSK_Reset;
Denis Zobnin3f287c22016-04-29 22:50:16 +0000208 unsigned Alignment = 0;
Daniel Dunbar69dac582010-05-27 00:04:40 +0000209 switch (Kind) {
Daniel Dunbar663e8092010-05-27 18:42:09 +0000210 // For all targets we support native and natural are the same.
211 //
212 // FIXME: This is not true on Darwin/PPC.
213 case POAK_Native:
Daniel Dunbar5794c6f2010-05-28 19:43:33 +0000214 case POAK_Power:
Daniel Dunbara6885662010-05-28 20:08:00 +0000215 case POAK_Natural:
Denis Zobnin10c4f452016-04-29 18:17:40 +0000216 Action = Sema::PSK_Push_Set;
217 Alignment = 0;
Daniel Dunbar5794c6f2010-05-28 19:43:33 +0000218 break;
219
Daniel Dunbar9c84d4a2010-05-27 18:42:17 +0000220 // Note that '#pragma options align=packed' is not equivalent to attribute
221 // packed, it has a different precedence relative to attribute aligned.
222 case POAK_Packed:
Denis Zobnin10c4f452016-04-29 18:17:40 +0000223 Action = Sema::PSK_Push_Set;
224 Alignment = 1;
Daniel Dunbar9c84d4a2010-05-27 18:42:17 +0000225 break;
226
Daniel Dunbarbd606522010-05-27 00:35:16 +0000227 case POAK_Mac68k:
228 // Check if the target supports this.
Alp Tokerb6cc5922014-05-03 03:45:55 +0000229 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
Daniel Dunbarbd606522010-05-27 00:35:16 +0000230 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
231 return;
Daniel Dunbarbd606522010-05-27 00:35:16 +0000232 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000233 Action = Sema::PSK_Push_Set;
234 Alignment = Sema::kMac68kAlignmentSentinel;
Daniel Dunbarbd606522010-05-27 00:35:16 +0000235 break;
236
Eli Friedman68be1642012-10-04 02:36:51 +0000237 case POAK_Reset:
238 // Reset just pops the top of the stack, or resets the current alignment to
239 // default.
Denis Zobnin10c4f452016-04-29 18:17:40 +0000240 Action = Sema::PSK_Pop;
241 if (PackStack.Stack.empty()) {
242 if (PackStack.CurrentValue) {
243 Action = Sema::PSK_Reset;
244 } else {
245 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
246 << "stack empty";
247 return;
248 }
Eli Friedman68be1642012-10-04 02:36:51 +0000249 }
Daniel Dunbar69dac582010-05-27 00:04:40 +0000250 break;
251 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000252
253 PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
Daniel Dunbar69dac582010-05-27 00:04:40 +0000254}
255
Javed Absar2a67c9e2017-06-05 10:11:57 +0000256void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action,
257 PragmaClangSectionKind SecKind, StringRef SecName) {
258 PragmaClangSection *CSec;
259 switch (SecKind) {
260 case PragmaClangSectionKind::PCSK_BSS:
261 CSec = &PragmaClangBSSSection;
262 break;
263 case PragmaClangSectionKind::PCSK_Data:
264 CSec = &PragmaClangDataSection;
265 break;
266 case PragmaClangSectionKind::PCSK_Rodata:
267 CSec = &PragmaClangRodataSection;
268 break;
269 case PragmaClangSectionKind::PCSK_Text:
270 CSec = &PragmaClangTextSection;
271 break;
272 default:
273 llvm_unreachable("invalid clang section kind");
274 }
275
276 if (Action == PragmaClangSectionAction::PCSA_Clear) {
277 CSec->Valid = false;
278 return;
279 }
280
281 CSec->Valid = true;
282 CSec->SectionName = SecName;
283 CSec->PragmaLocation = PragmaLoc;
284}
285
Denis Zobnin10c4f452016-04-29 18:17:40 +0000286void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
287 StringRef SlotLabel, Expr *alignment) {
Chris Lattner2eccbc12009-02-17 00:57:29 +0000288 Expr *Alignment = static_cast<Expr *>(alignment);
289
290 // If specified then alignment must be a "small" power of two.
291 unsigned AlignmentVal = 0;
292 if (Alignment) {
293 llvm::APSInt Val;
Mike Stump11289f42009-09-09 15:08:12 +0000294
Daniel Dunbare03c6102009-03-06 20:45:54 +0000295 // pack(0) is like pack(), which just works out since that is what
296 // we use 0 for in PackAttr.
Douglas Gregorbdb604a2010-05-18 23:01:22 +0000297 if (Alignment->isTypeDependent() ||
298 Alignment->isValueDependent() ||
299 !Alignment->isIntegerConstantExpr(Val, Context) ||
Daniel Dunbare03c6102009-03-06 20:45:54 +0000300 !(Val == 0 || Val.isPowerOf2()) ||
Chris Lattner2eccbc12009-02-17 00:57:29 +0000301 Val.getZExtValue() > 16) {
302 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
Chris Lattner2eccbc12009-02-17 00:57:29 +0000303 return; // Ignore
304 }
305
306 AlignmentVal = (unsigned) Val.getZExtValue();
307 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000308 if (Action == Sema::PSK_Show) {
Chris Lattner2eccbc12009-02-17 00:57:29 +0000309 // Show the current alignment, making sure to show the right value
310 // for the default.
Chris Lattner2eccbc12009-02-17 00:57:29 +0000311 // FIXME: This should come from the target.
Denis Zobnin10c4f452016-04-29 18:17:40 +0000312 AlignmentVal = PackStack.CurrentValue;
Chris Lattner2eccbc12009-02-17 00:57:29 +0000313 if (AlignmentVal == 0)
314 AlignmentVal = 8;
Denis Zobnin10c4f452016-04-29 18:17:40 +0000315 if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
Daniel Dunbar6da10982010-05-27 05:45:51 +0000316 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
317 else
318 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Chris Lattner2eccbc12009-02-17 00:57:29 +0000319 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000320 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
321 // "#pragma pack(pop, identifier, n) is undefined"
322 if (Action & Sema::PSK_Pop) {
323 if (Alignment && !SlotLabel.empty())
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000324 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
Denis Zobnin10c4f452016-04-29 18:17:40 +0000325 if (PackStack.Stack.empty())
326 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
327 }
328
329 PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
Chris Lattner2eccbc12009-02-17 00:57:29 +0000330}
331
Alex Lorenz45b40142017-07-28 14:41:21 +0000332void Sema::DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
333 SourceLocation IncludeLoc) {
334 if (Kind == PragmaPackDiagnoseKind::NonDefaultStateAtInclude) {
335 SourceLocation PrevLocation = PackStack.CurrentPragmaLocation;
336 // Warn about non-default alignment at #includes (without redundant
337 // warnings for the same directive in nested includes).
338 // The warning is delayed until the end of the file to avoid warnings
339 // for files that don't have any records that are affected by the modified
340 // alignment.
341 bool HasNonDefaultValue =
342 PackStack.hasValue() &&
343 (PackIncludeStack.empty() ||
344 PackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
345 PackIncludeStack.push_back(
346 {PackStack.CurrentValue,
347 PackStack.hasValue() ? PrevLocation : SourceLocation(),
348 HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
349 return;
350 }
351
352 assert(Kind == PragmaPackDiagnoseKind::ChangedStateAtExit && "invalid kind");
353 PackIncludeState PrevPackState = PackIncludeStack.pop_back_val();
354 if (PrevPackState.ShouldWarnOnInclude) {
355 // Emit the delayed non-default alignment at #include warning.
356 Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
357 Diag(PrevPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
358 }
359 // Warn about modified alignment after #includes.
360 if (PrevPackState.CurrentValue != PackStack.CurrentValue) {
361 Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
362 Diag(PackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
363 }
364}
365
366void Sema::DiagnoseUnterminatedPragmaPack() {
367 if (PackStack.Stack.empty())
368 return;
Alex Lorenza1479d72017-07-31 13:37:50 +0000369 bool IsInnermost = true;
370 for (const auto &StackSlot : llvm::reverse(PackStack.Stack)) {
Alex Lorenz45b40142017-07-28 14:41:21 +0000371 Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
Alex Lorenza1479d72017-07-31 13:37:50 +0000372 // The user might have already reset the alignment, so suggest replacing
373 // the reset with a pop.
374 if (IsInnermost && PackStack.CurrentValue == PackStack.DefaultValue) {
375 DiagnosticBuilder DB = Diag(PackStack.CurrentPragmaLocation,
376 diag::note_pragma_pack_pop_instead_reset);
377 SourceLocation FixItLoc = Lexer::findLocationAfterToken(
378 PackStack.CurrentPragmaLocation, tok::l_paren, SourceMgr, LangOpts,
379 /*SkipTrailing=*/false);
380 if (FixItLoc.isValid())
381 DB << FixItHint::CreateInsertion(FixItLoc, "pop");
382 }
383 IsInnermost = false;
384 }
Alex Lorenz45b40142017-07-28 14:41:21 +0000385}
386
Fangrui Song6907ce22018-07-30 19:24:48 +0000387void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
Fariborz Jahanian743dda42011-04-25 18:49:15 +0000388 MSStructPragmaOn = (Kind == PMSST_ON);
389}
390
Nico Weber66220292016-03-02 17:28:48 +0000391void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
392 PragmaMSCommentKind Kind, StringRef Arg) {
393 auto *PCD = PragmaCommentDecl::Create(
394 Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
395 Context.getTranslationUnitDecl()->addDecl(PCD);
396 Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000397}
398
Nico Webercbbaeb12016-03-02 19:28:54 +0000399void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
400 StringRef Value) {
401 auto *PDMD = PragmaDetectMismatchDecl::Create(
402 Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
403 Context.getTranslationUnitDecl()->addDecl(PDMD);
404 Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
Aaron Ballman5d041be2013-06-04 02:07:14 +0000405}
406
David Majnemer4bb09802014-02-10 19:50:15 +0000407void Sema::ActOnPragmaMSPointersToMembers(
David Majnemer86c318f2014-02-11 21:05:00 +0000408 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
David Majnemer4bb09802014-02-10 19:50:15 +0000409 SourceLocation PragmaLoc) {
410 MSPointerToMemberRepresentationMethod = RepresentationMethod;
411 ImplicitMSInheritanceAttrLoc = PragmaLoc;
412}
413
Denis Zobnin2290dac2016-04-29 11:27:00 +0000414void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000415 SourceLocation PragmaLoc,
416 MSVtorDispAttr::Mode Mode) {
Denis Zobnin2290dac2016-04-29 11:27:00 +0000417 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
418 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
419 << "stack empty";
420 VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000421}
422
Warren Huntc3b18962014-04-08 22:30:47 +0000423template<typename ValueType>
424void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation,
425 PragmaMsStackAction Action,
426 llvm::StringRef StackSlotLabel,
427 ValueType Value) {
428 if (Action == PSK_Reset) {
Denis Zobnin2290dac2016-04-29 11:27:00 +0000429 CurrentValue = DefaultValue;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +0000430 CurrentPragmaLocation = PragmaLocation;
Warren Huntc3b18962014-04-08 22:30:47 +0000431 return;
432 }
433 if (Action & PSK_Push)
Alex Lorenz45b40142017-07-28 14:41:21 +0000434 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
435 PragmaLocation);
Warren Huntc3b18962014-04-08 22:30:47 +0000436 else if (Action & PSK_Pop) {
437 if (!StackSlotLabel.empty()) {
438 // If we've got a label, try to find it and jump there.
David Majnemerf7e36092016-06-23 00:15:04 +0000439 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
440 return x.StackSlotLabel == StackSlotLabel;
441 });
Warren Huntc3b18962014-04-08 22:30:47 +0000442 // If we found the label so pop from there.
443 if (I != Stack.rend()) {
444 CurrentValue = I->Value;
445 CurrentPragmaLocation = I->PragmaLocation;
446 Stack.erase(std::prev(I.base()), Stack.end());
447 }
448 } else if (!Stack.empty()) {
George Burgess IVa75c71d2018-05-26 02:29:14 +0000449 // We do not have a label, just pop the last entry.
Warren Huntc3b18962014-04-08 22:30:47 +0000450 CurrentValue = Stack.back().Value;
451 CurrentPragmaLocation = Stack.back().PragmaLocation;
452 Stack.pop_back();
453 }
454 }
455 if (Action & PSK_Set) {
456 CurrentValue = Value;
457 CurrentPragmaLocation = PragmaLocation;
458 }
459}
460
Craig Topperbf3e3272014-08-30 16:55:52 +0000461bool Sema::UnifySection(StringRef SectionName,
Warren Huntc3b18962014-04-08 22:30:47 +0000462 int SectionFlags,
463 DeclaratorDecl *Decl) {
Hans Wennborg899ded92014-10-16 20:52:46 +0000464 auto Section = Context.SectionInfos.find(SectionName);
465 if (Section == Context.SectionInfos.end()) {
466 Context.SectionInfos[SectionName] =
467 ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags);
Warren Huntc3b18962014-04-08 22:30:47 +0000468 return false;
469 }
470 // A pre-declared section takes precedence w/o diagnostic.
471 if (Section->second.SectionFlags == SectionFlags ||
Hans Wennborg899ded92014-10-16 20:52:46 +0000472 !(Section->second.SectionFlags & ASTContext::PSF_Implicit))
Warren Huntc3b18962014-04-08 22:30:47 +0000473 return false;
474 auto OtherDecl = Section->second.Decl;
475 Diag(Decl->getLocation(), diag::err_section_conflict)
476 << Decl << OtherDecl;
477 Diag(OtherDecl->getLocation(), diag::note_declared_at)
478 << OtherDecl->getName();
479 if (auto A = Decl->getAttr<SectionAttr>())
480 if (A->isImplicit())
481 Diag(A->getLocation(), diag::note_pragma_entered_here);
482 if (auto A = OtherDecl->getAttr<SectionAttr>())
483 if (A->isImplicit())
484 Diag(A->getLocation(), diag::note_pragma_entered_here);
Ehsan Akhgari0b510602014-09-22 19:46:39 +0000485 return true;
Warren Huntc3b18962014-04-08 22:30:47 +0000486}
487
Craig Topperbf3e3272014-08-30 16:55:52 +0000488bool Sema::UnifySection(StringRef SectionName,
Warren Huntc3b18962014-04-08 22:30:47 +0000489 int SectionFlags,
490 SourceLocation PragmaSectionLocation) {
Hans Wennborg899ded92014-10-16 20:52:46 +0000491 auto Section = Context.SectionInfos.find(SectionName);
492 if (Section != Context.SectionInfos.end()) {
Warren Huntc3b18962014-04-08 22:30:47 +0000493 if (Section->second.SectionFlags == SectionFlags)
494 return false;
Hans Wennborg899ded92014-10-16 20:52:46 +0000495 if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) {
Warren Huntc3b18962014-04-08 22:30:47 +0000496 Diag(PragmaSectionLocation, diag::err_section_conflict)
497 << "this" << "a prior #pragma section";
498 Diag(Section->second.PragmaSectionLocation,
499 diag::note_pragma_entered_here);
500 return true;
501 }
502 }
Hans Wennborg899ded92014-10-16 20:52:46 +0000503 Context.SectionInfos[SectionName] =
504 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
Warren Huntc3b18962014-04-08 22:30:47 +0000505 return false;
506}
507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508/// Called on well formed \#pragma bss_seg().
Warren Huntc3b18962014-04-08 22:30:47 +0000509void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
510 PragmaMsStackAction Action,
511 llvm::StringRef StackSlotLabel,
512 StringLiteral *SegmentName,
513 llvm::StringRef PragmaName) {
514 PragmaStack<StringLiteral *> *Stack =
515 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
516 .Case("data_seg", &DataSegStack)
517 .Case("bss_seg", &BSSSegStack)
518 .Case("const_seg", &ConstSegStack)
519 .Case("code_seg", &CodeSegStack);
520 if (Action & PSK_Pop && Stack->Stack.empty())
521 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
522 << "stack empty";
Nico Weber98016212019-07-09 00:02:23 +0000523 if (SegmentName) {
524 if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
525 return;
526
527 if (SegmentName->getString() == ".drectve" &&
528 Context.getTargetInfo().getCXXABI().isMicrosoft())
529 Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
530 }
531
Warren Huntc3b18962014-04-08 22:30:47 +0000532 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
533}
534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000535/// Called on well formed \#pragma bss_seg().
Warren Huntc3b18962014-04-08 22:30:47 +0000536void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
537 int SectionFlags, StringLiteral *SegmentName) {
538 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
539}
540
Reid Kleckner1a711b12014-07-22 00:53:05 +0000541void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
542 StringLiteral *SegmentName) {
543 // There's no stack to maintain, so we just have a current section. When we
544 // see the default section, reset our current section back to null so we stop
545 // tacking on unnecessary attributes.
546 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
547 CurInitSegLoc = PragmaLocation;
548}
549
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000550void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
551 SourceLocation PragmaLoc) {
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000552
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000553 IdentifierInfo *Name = IdTok.getIdentifierInfo();
554 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +0000555 LookupParsedName(Lookup, curScope, nullptr, true);
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000556
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000557 if (Lookup.empty()) {
558 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
559 << Name << SourceRange(IdTok.getLocation());
560 return;
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000561 }
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000562
563 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
Argyrios Kyrtzidisff115a22011-01-27 18:16:48 +0000564 if (!VD) {
565 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000566 << Name << SourceRange(IdTok.getLocation());
567 return;
568 }
569
570 // Warn if this was used before being marked unused.
571 if (VD->isUsed())
572 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
573
Aaron Ballman0bcd6c12016-03-09 16:48:08 +0000574 VD->addAttr(UnusedAttr::CreateImplicit(Context, UnusedAttr::GNU_unused,
575 IdTok.getLocation()));
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000576}
Eli Friedman570024a2010-08-05 06:57:20 +0000577
John McCall32f5fe12011-09-30 05:12:12 +0000578void Sema::AddCFAuditedAttribute(Decl *D) {
579 SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc();
580 if (!Loc.isValid()) return;
581
582 // Don't add a redundant or conflicting attribute.
583 if (D->hasAttr<CFAuditedTransferAttr>() ||
584 D->hasAttr<CFUnknownTransferAttr>())
585 return;
586
Aaron Ballman36a53502014-01-16 13:03:14 +0000587 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Loc));
John McCall32f5fe12011-09-30 05:12:12 +0000588}
589
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000590namespace {
591
592Optional<attr::SubjectMatchRule>
593getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
594 using namespace attr;
595 switch (Rule) {
596 default:
597 return None;
598#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
599#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
600 case Value: \
601 return Parent;
602#include "clang/Basic/AttrSubMatchRulesList.inc"
603 }
604}
605
606bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
607 using namespace attr;
608 switch (Rule) {
609 default:
610 return false;
611#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
612#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
613 case Value: \
614 return IsNegated;
615#include "clang/Basic/AttrSubMatchRulesList.inc"
616 }
617}
618
619CharSourceRange replacementRangeForListElement(const Sema &S,
620 SourceRange Range) {
621 // Make sure that the ',' is removed as well.
622 SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
623 Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
624 /*SkipTrailingWhitespaceAndNewLine=*/false);
625 if (AfterCommaLoc.isValid())
626 return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
627 else
628 return CharSourceRange::getTokenRange(Range);
629}
630
631std::string
632attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
633 std::string Result;
634 llvm::raw_string_ostream OS(Result);
635 for (const auto &I : llvm::enumerate(Rules)) {
636 if (I.index())
637 OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
638 OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
639 }
640 return OS.str();
641}
642
643} // end anonymous namespace
644
Erik Pilkington7d180942018-10-29 17:38:42 +0000645void Sema::ActOnPragmaAttributeAttribute(
646 ParsedAttr &Attribute, SourceLocation PragmaLoc,
647 attr::ParsedSubjectMatchRuleSet Rules) {
Alex Lorenz3cfe9d52019-01-24 19:14:39 +0000648 Attribute.setIsPragmaClangAttribute();
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000649 SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
650 // Gather the subject match rules that are supported by the attribute.
651 SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
652 StrictSubjectMatchRuleSet;
653 Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
654
655 // Figure out which subject matching rules are valid.
656 if (StrictSubjectMatchRuleSet.empty()) {
657 // Check for contradicting match rules. Contradicting match rules are
658 // either:
659 // - a top-level rule and one of its sub-rules. E.g. variable and
660 // variable(is_parameter).
661 // - a sub-rule and a sibling that's negated. E.g.
662 // variable(is_thread_local) and variable(unless(is_parameter))
Alex Lorenz26b47652017-04-18 20:54:23 +0000663 llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000664 RulesToFirstSpecifiedNegatedSubRule;
665 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000666 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000667 Optional<attr::SubjectMatchRule> ParentRule =
Alex Lorenz26b47652017-04-18 20:54:23 +0000668 getParentAttrMatcherRule(MatchRule);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000669 if (!ParentRule)
670 continue;
671 auto It = Rules.find(*ParentRule);
672 if (It != Rules.end()) {
673 // A sub-rule contradicts a parent rule.
674 Diag(Rule.second.getBegin(),
675 diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
Alex Lorenz26b47652017-04-18 20:54:23 +0000676 << attr::getSubjectMatchRuleSpelling(MatchRule)
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000677 << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
678 << FixItHint::CreateRemoval(
679 replacementRangeForListElement(*this, Rule.second));
680 // Keep going without removing this rule as it won't change the set of
681 // declarations that receive the attribute.
682 continue;
683 }
Alex Lorenz26b47652017-04-18 20:54:23 +0000684 if (isNegatedAttrMatcherSubRule(MatchRule))
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000685 RulesToFirstSpecifiedNegatedSubRule.insert(
686 std::make_pair(*ParentRule, Rule));
687 }
688 bool IgnoreNegatedSubRules = false;
689 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000690 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000691 Optional<attr::SubjectMatchRule> ParentRule =
Alex Lorenz26b47652017-04-18 20:54:23 +0000692 getParentAttrMatcherRule(MatchRule);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000693 if (!ParentRule)
694 continue;
695 auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
696 if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
697 It->second != Rule) {
698 // Negated sub-rule contradicts another sub-rule.
699 Diag(
700 It->second.second.getBegin(),
701 diag::
702 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
Alex Lorenz26b47652017-04-18 20:54:23 +0000703 << attr::getSubjectMatchRuleSpelling(
704 attr::SubjectMatchRule(It->second.first))
705 << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000706 << FixItHint::CreateRemoval(
707 replacementRangeForListElement(*this, It->second.second));
708 // Keep going but ignore all of the negated sub-rules.
709 IgnoreNegatedSubRules = true;
710 RulesToFirstSpecifiedNegatedSubRule.erase(It);
711 }
712 }
713
714 if (!IgnoreNegatedSubRules) {
715 for (const auto &Rule : Rules)
Alex Lorenz26b47652017-04-18 20:54:23 +0000716 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000717 } else {
718 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000719 if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
720 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000721 }
722 }
723 Rules.clear();
724 } else {
725 for (const auto &Rule : StrictSubjectMatchRuleSet) {
726 if (Rules.erase(Rule.first)) {
727 // Add the rule to the set of attribute receivers only if it's supported
728 // in the current language mode.
729 if (Rule.second)
730 SubjectMatchRules.push_back(Rule.first);
731 }
732 }
733 }
734
735 if (!Rules.empty()) {
736 auto Diagnostic =
737 Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
738 << Attribute.getName();
739 SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
740 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000741 ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000742 Diagnostic << FixItHint::CreateRemoval(
743 replacementRangeForListElement(*this, Rule.second));
744 }
745 Diagnostic << attrMatcherRuleListToString(ExtraRules);
746 }
747
Erik Pilkington7d180942018-10-29 17:38:42 +0000748 if (PragmaAttributeStack.empty()) {
749 Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
750 return;
751 }
752
753 PragmaAttributeStack.back().Entries.push_back(
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000754 {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
755}
756
Erik Pilkington0876cae2018-12-20 22:32:04 +0000757void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
758 const IdentifierInfo *Namespace) {
Erik Pilkington7d180942018-10-29 17:38:42 +0000759 PragmaAttributeStack.emplace_back();
760 PragmaAttributeStack.back().Loc = PragmaLoc;
Erik Pilkington0876cae2018-12-20 22:32:04 +0000761 PragmaAttributeStack.back().Namespace = Namespace;
Erik Pilkington7d180942018-10-29 17:38:42 +0000762}
763
Erik Pilkington0876cae2018-12-20 22:32:04 +0000764void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
765 const IdentifierInfo *Namespace) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000766 if (PragmaAttributeStack.empty()) {
Erik Pilkington0876cae2018-12-20 22:32:04 +0000767 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000768 return;
769 }
Erik Pilkington7d180942018-10-29 17:38:42 +0000770
Erik Pilkington0876cae2018-12-20 22:32:04 +0000771 // Dig back through the stack trying to find the most recently pushed group
772 // that in Namespace. Note that this works fine if no namespace is present,
773 // think of push/pops without namespaces as having an implicit "nullptr"
774 // namespace.
775 for (size_t Index = PragmaAttributeStack.size(); Index;) {
776 --Index;
777 if (PragmaAttributeStack[Index].Namespace == Namespace) {
778 for (const PragmaAttributeEntry &Entry :
779 PragmaAttributeStack[Index].Entries) {
780 if (!Entry.IsUsed) {
781 assert(Entry.Attribute && "Expected an attribute");
782 Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
783 << *Entry.Attribute;
784 Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
785 }
786 }
787 PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
788 return;
Erik Pilkington7d180942018-10-29 17:38:42 +0000789 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000790 }
Erik Pilkington7d180942018-10-29 17:38:42 +0000791
Erik Pilkington0876cae2018-12-20 22:32:04 +0000792 if (Namespace)
793 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
794 << 0 << Namespace->getName();
795 else
796 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000797}
798
799void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
800 if (PragmaAttributeStack.empty())
801 return;
Erik Pilkington7d180942018-10-29 17:38:42 +0000802 for (auto &Group : PragmaAttributeStack) {
803 for (auto &Entry : Group.Entries) {
804 ParsedAttr *Attribute = Entry.Attribute;
805 assert(Attribute && "Expected an attribute");
Alex Lorenz3cfe9d52019-01-24 19:14:39 +0000806 assert(Attribute->isPragmaClangAttribute() &&
807 "expected #pragma clang attribute");
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000808
Erik Pilkington7d180942018-10-29 17:38:42 +0000809 // Ensure that the attribute can be applied to the given declaration.
810 bool Applies = false;
811 for (const auto &Rule : Entry.MatchRules) {
812 if (Attribute->appliesToDecl(D, Rule)) {
813 Applies = true;
814 break;
815 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000816 }
Erik Pilkington7d180942018-10-29 17:38:42 +0000817 if (!Applies)
818 continue;
819 Entry.IsUsed = true;
820 PragmaAttributeCurrentTargetDecl = D;
821 ParsedAttributesView Attrs;
822 Attrs.addAtEnd(Attribute);
823 ProcessDeclAttributeList(S, D, Attrs);
824 PragmaAttributeCurrentTargetDecl = nullptr;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000825 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000826 }
827}
828
829void Sema::PrintPragmaAttributeInstantiationPoint() {
830 assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000831 Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000832 diag::note_pragma_attribute_applied_decl_here);
833}
834
835void Sema::DiagnoseUnterminatedPragmaAttribute() {
836 if (PragmaAttributeStack.empty())
837 return;
838 Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
839}
840
Dario Domizioli13a0a382014-05-23 12:13:25 +0000841void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
842 if(On)
843 OptimizeOffPragmaLocation = SourceLocation();
844 else
845 OptimizeOffPragmaLocation = PragmaLoc;
846}
847
848void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
849 // In the future, check other pragmas if they're implemented (e.g. pragma
850 // optimize 0 will probably map to this functionality too).
851 if(OptimizeOffPragmaLocation.isValid())
852 AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
853}
854
Fangrui Song6907ce22018-07-30 19:24:48 +0000855void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
Dario Domizioli13a0a382014-05-23 12:13:25 +0000856 SourceLocation Loc) {
857 // Don't add a conflicting attribute. No diagnostic is needed.
858 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
859 return;
860
861 // Add attributes only if required. Optnone requires noinline as well, but if
862 // either is already present then don't bother adding them.
863 if (!FD->hasAttr<OptimizeNoneAttr>())
864 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
865 if (!FD->hasAttr<NoInlineAttr>())
866 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
867}
868
John McCall2faf32c2010-12-10 02:59:44 +0000869typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
Alp Tokerceb95c42014-03-02 03:20:16 +0000870enum : unsigned { NoVisibility = ~0U };
Eli Friedman570024a2010-08-05 06:57:20 +0000871
872void Sema::AddPushedVisibilityAttribute(Decl *D) {
873 if (!VisContext)
874 return;
875
Rafael Espindola54606d52012-12-25 07:31:49 +0000876 NamedDecl *ND = dyn_cast<NamedDecl>(D);
John McCalld041a9b2013-02-20 01:54:26 +0000877 if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
Eli Friedman570024a2010-08-05 06:57:20 +0000878 return;
879
880 VisStack *Stack = static_cast<VisStack*>(VisContext);
John McCall2faf32c2010-12-10 02:59:44 +0000881 unsigned rawType = Stack->back().first;
882 if (rawType == NoVisibility) return;
883
884 VisibilityAttr::VisibilityType type
885 = (VisibilityAttr::VisibilityType) rawType;
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000886 SourceLocation loc = Stack->back().second;
Eli Friedman570024a2010-08-05 06:57:20 +0000887
Aaron Ballman36a53502014-01-16 13:03:14 +0000888 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
Eli Friedman570024a2010-08-05 06:57:20 +0000889}
890
891/// FreeVisContext - Deallocate and null out VisContext.
892void Sema::FreeVisContext() {
893 delete static_cast<VisStack*>(VisContext);
Craig Topperc3ec1492014-05-26 06:22:03 +0000894 VisContext = nullptr;
Eli Friedman570024a2010-08-05 06:57:20 +0000895}
896
John McCall2faf32c2010-12-10 02:59:44 +0000897static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
John McCallb1be5232010-08-26 09:15:37 +0000898 // Put visibility on stack.
899 if (!S.VisContext)
900 S.VisContext = new VisStack;
901
902 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
903 Stack->push_back(std::make_pair(type, loc));
904}
905
Rafael Espindolade15baf2012-01-21 05:43:40 +0000906void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
Eli Friedman570024a2010-08-05 06:57:20 +0000907 SourceLocation PragmaLoc) {
Rafael Espindolade15baf2012-01-21 05:43:40 +0000908 if (VisType) {
Eli Friedman570024a2010-08-05 06:57:20 +0000909 // Compute visibility to use.
Aaron Ballman682ee422013-09-11 19:47:58 +0000910 VisibilityAttr::VisibilityType T;
911 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
912 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
Eli Friedman570024a2010-08-05 06:57:20 +0000913 return;
914 }
Aaron Ballman682ee422013-09-11 19:47:58 +0000915 PushPragmaVisibility(*this, T, PragmaLoc);
Eli Friedman570024a2010-08-05 06:57:20 +0000916 } else {
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000917 PopPragmaVisibility(false, PragmaLoc);
Eli Friedman570024a2010-08-05 06:57:20 +0000918 }
919}
920
Adam Nemet60d32642017-04-04 21:18:36 +0000921void Sema::ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC) {
922 switch (FPC) {
923 case LangOptions::FPC_On:
Adam Nemet049a31d2017-03-29 21:54:24 +0000924 FPFeatures.setAllowFPContractWithinStatement();
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000925 break;
Adam Nemet60d32642017-04-04 21:18:36 +0000926 case LangOptions::FPC_Fast:
927 FPFeatures.setAllowFPContractAcrossStatement();
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000928 break;
Adam Nemet60d32642017-04-04 21:18:36 +0000929 case LangOptions::FPC_Off:
930 FPFeatures.setDisallowFPContract();
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000931 break;
932 }
933}
934
Kevin P. Neal2c0bc8b2018-08-14 17:06:56 +0000935void Sema::ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC) {
936 switch (FPC) {
937 case LangOptions::FEA_On:
938 FPFeatures.setAllowFEnvAccess();
939 break;
940 case LangOptions::FEA_Off:
941 FPFeatures.setDisallowFEnvAccess();
942 break;
943 }
944}
945
946
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000947void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
948 SourceLocation Loc) {
John McCall2faf32c2010-12-10 02:59:44 +0000949 // Visibility calculations will consider the namespace's visibility.
950 // Here we just want to note that we're in a visibility context
951 // which overrides any enclosing #pragma context, but doesn't itself
952 // contribute visibility.
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000953 PushPragmaVisibility(*this, NoVisibility, Loc);
Eli Friedman570024a2010-08-05 06:57:20 +0000954}
955
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000956void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
957 if (!VisContext) {
958 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
959 return;
Eli Friedman570024a2010-08-05 06:57:20 +0000960 }
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000961
962 // Pop visibility from stack
963 VisStack *Stack = static_cast<VisStack*>(VisContext);
964
965 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
966 bool StartsWithPragma = Back->first != NoVisibility;
967 if (StartsWithPragma && IsNamespaceEnd) {
968 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
969 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
970
971 // For better error recovery, eat all pushes inside the namespace.
972 do {
973 Stack->pop_back();
974 Back = &Stack->back();
975 StartsWithPragma = Back->first != NoVisibility;
976 } while (StartsWithPragma);
977 } else if (!StartsWithPragma && !IsNamespaceEnd) {
978 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
979 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
980 return;
981 }
982
983 Stack->pop_back();
984 // To simplify the implementation, never keep around an empty stack.
985 if (Stack->empty())
986 FreeVisContext();
Eli Friedman570024a2010-08-05 06:57:20 +0000987}