SemaAttr.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/Attr.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/SemaInternal.h"
  20. #include <optional>
  21. using namespace clang;
  22. //===----------------------------------------------------------------------===//
  23. // Pragma 'pack' and 'options align'
  24. //===----------------------------------------------------------------------===//
  25. Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
  26. StringRef SlotLabel,
  27. bool ShouldAct)
  28. : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
  29. if (ShouldAct) {
  30. S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
  31. S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
  32. S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
  33. S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
  34. S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
  35. S.StrictGuardStackCheckStack.SentinelAction(PSK_Push, SlotLabel);
  36. }
  37. }
  38. Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
  39. if (ShouldAct) {
  40. S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
  41. S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
  42. S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
  43. S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
  44. S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
  45. S.StrictGuardStackCheckStack.SentinelAction(PSK_Pop, SlotLabel);
  46. }
  47. }
  48. void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
  49. AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
  50. AlignPackInfo::Mode M = InfoVal.getAlignMode();
  51. bool IsPackSet = InfoVal.IsPackSet();
  52. bool IsXLPragma = getLangOpts().XLPragmaPack;
  53. // If we are not under mac68k/natural alignment mode and also there is no pack
  54. // value, we don't need any attributes.
  55. if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
  56. return;
  57. if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
  58. RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
  59. } else if (IsPackSet) {
  60. // Check to see if we need a max field alignment attribute.
  61. RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
  62. Context, InfoVal.getPackNumber() * 8));
  63. }
  64. if (IsXLPragma && M == AlignPackInfo::Natural)
  65. RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
  66. if (AlignPackIncludeStack.empty())
  67. return;
  68. // The #pragma align/pack affected a record in an included file, so Clang
  69. // should warn when that pragma was written in a file that included the
  70. // included file.
  71. for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack)) {
  72. if (AlignPackedInclude.CurrentPragmaLocation !=
  73. AlignPackStack.CurrentPragmaLocation)
  74. break;
  75. if (AlignPackedInclude.HasNonDefaultValue)
  76. AlignPackedInclude.ShouldWarnOnInclude = true;
  77. }
  78. }
  79. void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
  80. if (MSStructPragmaOn)
  81. RD->addAttr(MSStructAttr::CreateImplicit(Context));
  82. // FIXME: We should merge AddAlignmentAttributesForRecord with
  83. // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
  84. // all active pragmas and applies them as attributes to class definitions.
  85. if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
  86. RD->addAttr(MSVtorDispAttr::CreateImplicit(
  87. Context, unsigned(VtorDispStack.CurrentValue)));
  88. }
  89. template <typename Attribute>
  90. static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
  91. CXXRecordDecl *Record) {
  92. if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
  93. return;
  94. for (Decl *Redecl : Record->redecls())
  95. Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
  96. }
  97. void Sema::inferGslPointerAttribute(NamedDecl *ND,
  98. CXXRecordDecl *UnderlyingRecord) {
  99. if (!UnderlyingRecord)
  100. return;
  101. const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  102. if (!Parent)
  103. return;
  104. static llvm::StringSet<> Containers{
  105. "array",
  106. "basic_string",
  107. "deque",
  108. "forward_list",
  109. "vector",
  110. "list",
  111. "map",
  112. "multiset",
  113. "multimap",
  114. "priority_queue",
  115. "queue",
  116. "set",
  117. "stack",
  118. "unordered_set",
  119. "unordered_map",
  120. "unordered_multiset",
  121. "unordered_multimap",
  122. };
  123. static llvm::StringSet<> Iterators{"iterator", "const_iterator",
  124. "reverse_iterator",
  125. "const_reverse_iterator"};
  126. if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
  127. Containers.count(Parent->getName()))
  128. addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
  129. UnderlyingRecord);
  130. }
  131. void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
  132. QualType Canonical = TD->getUnderlyingType().getCanonicalType();
  133. CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
  134. if (!RD) {
  135. if (auto *TST =
  136. dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
  137. RD = dyn_cast_or_null<CXXRecordDecl>(
  138. TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
  139. }
  140. }
  141. inferGslPointerAttribute(TD, RD);
  142. }
  143. void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
  144. static llvm::StringSet<> StdOwners{
  145. "any",
  146. "array",
  147. "basic_regex",
  148. "basic_string",
  149. "deque",
  150. "forward_list",
  151. "vector",
  152. "list",
  153. "map",
  154. "multiset",
  155. "multimap",
  156. "optional",
  157. "priority_queue",
  158. "queue",
  159. "set",
  160. "stack",
  161. "unique_ptr",
  162. "unordered_set",
  163. "unordered_map",
  164. "unordered_multiset",
  165. "unordered_multimap",
  166. "variant",
  167. };
  168. static llvm::StringSet<> StdPointers{
  169. "basic_string_view",
  170. "reference_wrapper",
  171. "regex_iterator",
  172. };
  173. if (!Record->getIdentifier())
  174. return;
  175. // Handle classes that directly appear in std namespace.
  176. if (Record->isInStdNamespace()) {
  177. if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
  178. return;
  179. if (StdOwners.count(Record->getName()))
  180. addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
  181. else if (StdPointers.count(Record->getName()))
  182. addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
  183. return;
  184. }
  185. // Handle nested classes that could be a gsl::Pointer.
  186. inferGslPointerAttribute(Record, Record);
  187. }
  188. void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
  189. SourceLocation PragmaLoc) {
  190. PragmaMsStackAction Action = Sema::PSK_Reset;
  191. AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
  192. switch (Kind) {
  193. // For most of the platforms we support, native and natural are the same.
  194. // With XL, native is the same as power, natural means something else.
  195. //
  196. // FIXME: This is not true on Darwin/PPC.
  197. case POAK_Native:
  198. case POAK_Power:
  199. Action = Sema::PSK_Push_Set;
  200. break;
  201. case POAK_Natural:
  202. Action = Sema::PSK_Push_Set;
  203. ModeVal = AlignPackInfo::Natural;
  204. break;
  205. // Note that '#pragma options align=packed' is not equivalent to attribute
  206. // packed, it has a different precedence relative to attribute aligned.
  207. case POAK_Packed:
  208. Action = Sema::PSK_Push_Set;
  209. ModeVal = AlignPackInfo::Packed;
  210. break;
  211. case POAK_Mac68k:
  212. // Check if the target supports this.
  213. if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
  214. Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
  215. return;
  216. }
  217. Action = Sema::PSK_Push_Set;
  218. ModeVal = AlignPackInfo::Mac68k;
  219. break;
  220. case POAK_Reset:
  221. // Reset just pops the top of the stack, or resets the current alignment to
  222. // default.
  223. Action = Sema::PSK_Pop;
  224. if (AlignPackStack.Stack.empty()) {
  225. if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
  226. AlignPackStack.CurrentValue.IsPackAttr()) {
  227. Action = Sema::PSK_Reset;
  228. } else {
  229. Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
  230. << "stack empty";
  231. return;
  232. }
  233. }
  234. break;
  235. }
  236. AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
  237. AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
  238. }
  239. void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
  240. PragmaClangSectionAction Action,
  241. PragmaClangSectionKind SecKind,
  242. StringRef SecName) {
  243. PragmaClangSection *CSec;
  244. int SectionFlags = ASTContext::PSF_Read;
  245. switch (SecKind) {
  246. case PragmaClangSectionKind::PCSK_BSS:
  247. CSec = &PragmaClangBSSSection;
  248. SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
  249. break;
  250. case PragmaClangSectionKind::PCSK_Data:
  251. CSec = &PragmaClangDataSection;
  252. SectionFlags |= ASTContext::PSF_Write;
  253. break;
  254. case PragmaClangSectionKind::PCSK_Rodata:
  255. CSec = &PragmaClangRodataSection;
  256. break;
  257. case PragmaClangSectionKind::PCSK_Relro:
  258. CSec = &PragmaClangRelroSection;
  259. break;
  260. case PragmaClangSectionKind::PCSK_Text:
  261. CSec = &PragmaClangTextSection;
  262. SectionFlags |= ASTContext::PSF_Execute;
  263. break;
  264. default:
  265. llvm_unreachable("invalid clang section kind");
  266. }
  267. if (Action == PragmaClangSectionAction::PCSA_Clear) {
  268. CSec->Valid = false;
  269. return;
  270. }
  271. if (llvm::Error E = isValidSectionSpecifier(SecName)) {
  272. Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
  273. << toString(std::move(E));
  274. CSec->Valid = false;
  275. return;
  276. }
  277. if (UnifySection(SecName, SectionFlags, PragmaLoc))
  278. return;
  279. CSec->Valid = true;
  280. CSec->SectionName = std::string(SecName);
  281. CSec->PragmaLocation = PragmaLoc;
  282. }
  283. void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
  284. StringRef SlotLabel, Expr *alignment) {
  285. bool IsXLPragma = getLangOpts().XLPragmaPack;
  286. // XL pragma pack does not support identifier syntax.
  287. if (IsXLPragma && !SlotLabel.empty()) {
  288. Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
  289. return;
  290. }
  291. const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
  292. Expr *Alignment = static_cast<Expr *>(alignment);
  293. // If specified then alignment must be a "small" power of two.
  294. unsigned AlignmentVal = 0;
  295. AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
  296. if (Alignment) {
  297. std::optional<llvm::APSInt> Val;
  298. Val = Alignment->getIntegerConstantExpr(Context);
  299. // pack(0) is like pack(), which just works out since that is what
  300. // we use 0 for in PackAttr.
  301. if (Alignment->isTypeDependent() || !Val ||
  302. !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
  303. Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
  304. return; // Ignore
  305. }
  306. if (IsXLPragma && *Val == 0) {
  307. // pack(0) does not work out with XL.
  308. Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
  309. return; // Ignore
  310. }
  311. AlignmentVal = (unsigned)Val->getZExtValue();
  312. }
  313. if (Action == Sema::PSK_Show) {
  314. // Show the current alignment, making sure to show the right value
  315. // for the default.
  316. // FIXME: This should come from the target.
  317. AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
  318. if (ModeVal == AlignPackInfo::Mac68k &&
  319. (IsXLPragma || CurVal.IsAlignAttr()))
  320. Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
  321. else
  322. Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
  323. }
  324. // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
  325. // "#pragma pack(pop, identifier, n) is undefined"
  326. if (Action & Sema::PSK_Pop) {
  327. if (Alignment && !SlotLabel.empty())
  328. Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
  329. if (AlignPackStack.Stack.empty()) {
  330. assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
  331. "Empty pack stack can only be at Native alignment mode.");
  332. Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
  333. }
  334. }
  335. AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
  336. AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
  337. }
  338. bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
  339. MutableArrayRef<Expr *> Args) {
  340. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  341. for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
  342. Expr *&E = Args.begin()[Idx];
  343. assert(E && "error are handled before");
  344. if (E->isValueDependent() || E->isTypeDependent())
  345. continue;
  346. // FIXME: Use DefaultFunctionArrayLValueConversion() in place of the logic
  347. // that adds implicit casts here.
  348. if (E->getType()->isArrayType())
  349. E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
  350. clang::CK_ArrayToPointerDecay)
  351. .get();
  352. if (E->getType()->isFunctionType())
  353. E = ImplicitCastExpr::Create(Context,
  354. Context.getPointerType(E->getType()),
  355. clang::CK_FunctionToPointerDecay, E, nullptr,
  356. VK_PRValue, FPOptionsOverride());
  357. if (E->isLValue())
  358. E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
  359. clang::CK_LValueToRValue, E, nullptr,
  360. VK_PRValue, FPOptionsOverride());
  361. Expr::EvalResult Eval;
  362. Notes.clear();
  363. Eval.Diag = &Notes;
  364. bool Result = E->EvaluateAsConstantExpr(Eval, Context);
  365. /// Result means the expression can be folded to a constant.
  366. /// Note.empty() means the expression is a valid constant expression in the
  367. /// current language mode.
  368. if (!Result || !Notes.empty()) {
  369. Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
  370. << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
  371. for (auto &Note : Notes)
  372. Diag(Note.first, Note.second);
  373. return false;
  374. }
  375. assert(Eval.Val.hasValue());
  376. E = ConstantExpr::Create(Context, E, Eval.Val);
  377. }
  378. return true;
  379. }
  380. void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
  381. SourceLocation IncludeLoc) {
  382. if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
  383. SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
  384. // Warn about non-default alignment at #includes (without redundant
  385. // warnings for the same directive in nested includes).
  386. // The warning is delayed until the end of the file to avoid warnings
  387. // for files that don't have any records that are affected by the modified
  388. // alignment.
  389. bool HasNonDefaultValue =
  390. AlignPackStack.hasValue() &&
  391. (AlignPackIncludeStack.empty() ||
  392. AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
  393. AlignPackIncludeStack.push_back(
  394. {AlignPackStack.CurrentValue,
  395. AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
  396. HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
  397. return;
  398. }
  399. assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
  400. "invalid kind");
  401. AlignPackIncludeState PrevAlignPackState =
  402. AlignPackIncludeStack.pop_back_val();
  403. // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
  404. // information, diagnostics below might not be accurate if we have mixed
  405. // pragmas.
  406. if (PrevAlignPackState.ShouldWarnOnInclude) {
  407. // Emit the delayed non-default alignment at #include warning.
  408. Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
  409. Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
  410. }
  411. // Warn about modified alignment after #includes.
  412. if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
  413. Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
  414. Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
  415. }
  416. }
  417. void Sema::DiagnoseUnterminatedPragmaAlignPack() {
  418. if (AlignPackStack.Stack.empty())
  419. return;
  420. bool IsInnermost = true;
  421. // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
  422. // information, diagnostics below might not be accurate if we have mixed
  423. // pragmas.
  424. for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
  425. Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
  426. // The user might have already reset the alignment, so suggest replacing
  427. // the reset with a pop.
  428. if (IsInnermost &&
  429. AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
  430. auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
  431. diag::note_pragma_pack_pop_instead_reset);
  432. SourceLocation FixItLoc =
  433. Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
  434. tok::l_paren, SourceMgr, LangOpts,
  435. /*SkipTrailing=*/false);
  436. if (FixItLoc.isValid())
  437. DB << FixItHint::CreateInsertion(FixItLoc, "pop");
  438. }
  439. IsInnermost = false;
  440. }
  441. }
  442. void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
  443. MSStructPragmaOn = (Kind == PMSST_ON);
  444. }
  445. void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
  446. PragmaMSCommentKind Kind, StringRef Arg) {
  447. auto *PCD = PragmaCommentDecl::Create(
  448. Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
  449. Context.getTranslationUnitDecl()->addDecl(PCD);
  450. Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
  451. }
  452. void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
  453. StringRef Value) {
  454. auto *PDMD = PragmaDetectMismatchDecl::Create(
  455. Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
  456. Context.getTranslationUnitDecl()->addDecl(PDMD);
  457. Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
  458. }
  459. void Sema::ActOnPragmaFPEvalMethod(SourceLocation Loc,
  460. LangOptions::FPEvalMethodKind Value) {
  461. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  462. switch (Value) {
  463. default:
  464. llvm_unreachable("invalid pragma eval_method kind");
  465. case LangOptions::FEM_Source:
  466. NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Source);
  467. break;
  468. case LangOptions::FEM_Double:
  469. NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Double);
  470. break;
  471. case LangOptions::FEM_Extended:
  472. NewFPFeatures.setFPEvalMethodOverride(LangOptions::FEM_Extended);
  473. break;
  474. }
  475. if (getLangOpts().ApproxFunc)
  476. Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 0;
  477. if (getLangOpts().AllowFPReassoc)
  478. Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 1;
  479. if (getLangOpts().AllowRecip)
  480. Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context) << 0 << 2;
  481. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  482. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  483. PP.setCurrentFPEvalMethod(Loc, Value);
  484. }
  485. void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
  486. PragmaMsStackAction Action,
  487. PragmaFloatControlKind Value) {
  488. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  489. if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
  490. !CurContext->getRedeclContext()->isFileContext()) {
  491. // Push and pop can only occur at file or namespace scope, or within a
  492. // language linkage declaration.
  493. Diag(Loc, diag::err_pragma_fc_pp_scope);
  494. return;
  495. }
  496. switch (Value) {
  497. default:
  498. llvm_unreachable("invalid pragma float_control kind");
  499. case PFC_Precise:
  500. NewFPFeatures.setFPPreciseEnabled(true);
  501. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  502. break;
  503. case PFC_NoPrecise:
  504. if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict)
  505. Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
  506. else if (CurFPFeatures.getAllowFEnvAccess())
  507. Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
  508. else
  509. NewFPFeatures.setFPPreciseEnabled(false);
  510. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  511. break;
  512. case PFC_Except:
  513. if (!isPreciseFPEnabled())
  514. Diag(Loc, diag::err_pragma_fc_except_requires_precise);
  515. else
  516. NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Strict);
  517. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  518. break;
  519. case PFC_NoExcept:
  520. NewFPFeatures.setSpecifiedExceptionModeOverride(LangOptions::FPE_Ignore);
  521. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  522. break;
  523. case PFC_Push:
  524. FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
  525. break;
  526. case PFC_Pop:
  527. if (FpPragmaStack.Stack.empty()) {
  528. Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
  529. << "stack empty";
  530. return;
  531. }
  532. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  533. NewFPFeatures = FpPragmaStack.CurrentValue;
  534. break;
  535. }
  536. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  537. }
  538. void Sema::ActOnPragmaMSPointersToMembers(
  539. LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
  540. SourceLocation PragmaLoc) {
  541. MSPointerToMemberRepresentationMethod = RepresentationMethod;
  542. ImplicitMSInheritanceAttrLoc = PragmaLoc;
  543. }
  544. void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
  545. SourceLocation PragmaLoc,
  546. MSVtorDispMode Mode) {
  547. if (Action & PSK_Pop && VtorDispStack.Stack.empty())
  548. Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
  549. << "stack empty";
  550. VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
  551. }
  552. template <>
  553. void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
  554. PragmaMsStackAction Action,
  555. llvm::StringRef StackSlotLabel,
  556. AlignPackInfo Value) {
  557. if (Action == PSK_Reset) {
  558. CurrentValue = DefaultValue;
  559. CurrentPragmaLocation = PragmaLocation;
  560. return;
  561. }
  562. if (Action & PSK_Push)
  563. Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
  564. PragmaLocation));
  565. else if (Action & PSK_Pop) {
  566. if (!StackSlotLabel.empty()) {
  567. // If we've got a label, try to find it and jump there.
  568. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
  569. return x.StackSlotLabel == StackSlotLabel;
  570. });
  571. // We found the label, so pop from there.
  572. if (I != Stack.rend()) {
  573. CurrentValue = I->Value;
  574. CurrentPragmaLocation = I->PragmaLocation;
  575. Stack.erase(std::prev(I.base()), Stack.end());
  576. }
  577. } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
  578. CurrentValue.IsPackAttr()) {
  579. // XL '#pragma align(reset)' would pop the stack until
  580. // a current in effect pragma align is popped.
  581. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
  582. return x.Value.IsAlignAttr();
  583. });
  584. // If we found pragma align so pop from there.
  585. if (I != Stack.rend()) {
  586. Stack.erase(std::prev(I.base()), Stack.end());
  587. if (Stack.empty()) {
  588. CurrentValue = DefaultValue;
  589. CurrentPragmaLocation = PragmaLocation;
  590. } else {
  591. CurrentValue = Stack.back().Value;
  592. CurrentPragmaLocation = Stack.back().PragmaLocation;
  593. Stack.pop_back();
  594. }
  595. }
  596. } else if (!Stack.empty()) {
  597. // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
  598. // over the baseline.
  599. if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
  600. return;
  601. // We don't have a label, just pop the last entry.
  602. CurrentValue = Stack.back().Value;
  603. CurrentPragmaLocation = Stack.back().PragmaLocation;
  604. Stack.pop_back();
  605. }
  606. }
  607. if (Action & PSK_Set) {
  608. CurrentValue = Value;
  609. CurrentPragmaLocation = PragmaLocation;
  610. }
  611. }
  612. bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
  613. NamedDecl *Decl) {
  614. SourceLocation PragmaLocation;
  615. if (auto A = Decl->getAttr<SectionAttr>())
  616. if (A->isImplicit())
  617. PragmaLocation = A->getLocation();
  618. auto SectionIt = Context.SectionInfos.find(SectionName);
  619. if (SectionIt == Context.SectionInfos.end()) {
  620. Context.SectionInfos[SectionName] =
  621. ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
  622. return false;
  623. }
  624. // A pre-declared section takes precedence w/o diagnostic.
  625. const auto &Section = SectionIt->second;
  626. if (Section.SectionFlags == SectionFlags ||
  627. ((SectionFlags & ASTContext::PSF_Implicit) &&
  628. !(Section.SectionFlags & ASTContext::PSF_Implicit)))
  629. return false;
  630. Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
  631. if (Section.Decl)
  632. Diag(Section.Decl->getLocation(), diag::note_declared_at)
  633. << Section.Decl->getName();
  634. if (PragmaLocation.isValid())
  635. Diag(PragmaLocation, diag::note_pragma_entered_here);
  636. if (Section.PragmaSectionLocation.isValid())
  637. Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
  638. return true;
  639. }
  640. bool Sema::UnifySection(StringRef SectionName,
  641. int SectionFlags,
  642. SourceLocation PragmaSectionLocation) {
  643. auto SectionIt = Context.SectionInfos.find(SectionName);
  644. if (SectionIt != Context.SectionInfos.end()) {
  645. const auto &Section = SectionIt->second;
  646. if (Section.SectionFlags == SectionFlags)
  647. return false;
  648. if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
  649. Diag(PragmaSectionLocation, diag::err_section_conflict)
  650. << "this" << Section;
  651. if (Section.Decl)
  652. Diag(Section.Decl->getLocation(), diag::note_declared_at)
  653. << Section.Decl->getName();
  654. if (Section.PragmaSectionLocation.isValid())
  655. Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
  656. return true;
  657. }
  658. }
  659. Context.SectionInfos[SectionName] =
  660. ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
  661. return false;
  662. }
  663. /// Called on well formed \#pragma bss_seg().
  664. void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
  665. PragmaMsStackAction Action,
  666. llvm::StringRef StackSlotLabel,
  667. StringLiteral *SegmentName,
  668. llvm::StringRef PragmaName) {
  669. PragmaStack<StringLiteral *> *Stack =
  670. llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
  671. .Case("data_seg", &DataSegStack)
  672. .Case("bss_seg", &BSSSegStack)
  673. .Case("const_seg", &ConstSegStack)
  674. .Case("code_seg", &CodeSegStack);
  675. if (Action & PSK_Pop && Stack->Stack.empty())
  676. Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
  677. << "stack empty";
  678. if (SegmentName) {
  679. if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
  680. return;
  681. if (SegmentName->getString() == ".drectve" &&
  682. Context.getTargetInfo().getCXXABI().isMicrosoft())
  683. Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
  684. }
  685. Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
  686. }
  687. /// Called on well formed \#pragma strict_gs_check().
  688. void Sema::ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
  689. PragmaMsStackAction Action,
  690. bool Value) {
  691. if (Action & PSK_Pop && StrictGuardStackCheckStack.Stack.empty())
  692. Diag(PragmaLocation, diag::warn_pragma_pop_failed) << "strict_gs_check"
  693. << "stack empty";
  694. StrictGuardStackCheckStack.Act(PragmaLocation, Action, StringRef(), Value);
  695. }
  696. /// Called on well formed \#pragma bss_seg().
  697. void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
  698. int SectionFlags, StringLiteral *SegmentName) {
  699. UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
  700. }
  701. void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
  702. StringLiteral *SegmentName) {
  703. // There's no stack to maintain, so we just have a current section. When we
  704. // see the default section, reset our current section back to null so we stop
  705. // tacking on unnecessary attributes.
  706. CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
  707. CurInitSegLoc = PragmaLocation;
  708. }
  709. void Sema::ActOnPragmaMSAllocText(
  710. SourceLocation PragmaLocation, StringRef Section,
  711. const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
  712. &Functions) {
  713. if (!CurContext->getRedeclContext()->isFileContext()) {
  714. Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
  715. return;
  716. }
  717. for (auto &Function : Functions) {
  718. IdentifierInfo *II;
  719. SourceLocation Loc;
  720. std::tie(II, Loc) = Function;
  721. DeclarationName DN(II);
  722. NamedDecl *ND = LookupSingleName(TUScope, DN, Loc, LookupOrdinaryName);
  723. if (!ND) {
  724. Diag(Loc, diag::err_undeclared_use) << II->getName();
  725. return;
  726. }
  727. auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());
  728. if (!FD) {
  729. Diag(Loc, diag::err_pragma_alloc_text_not_function);
  730. return;
  731. }
  732. if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
  733. Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
  734. return;
  735. }
  736. FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);
  737. }
  738. }
  739. void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
  740. SourceLocation PragmaLoc) {
  741. IdentifierInfo *Name = IdTok.getIdentifierInfo();
  742. LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
  743. LookupParsedName(Lookup, curScope, nullptr, true);
  744. if (Lookup.empty()) {
  745. Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
  746. << Name << SourceRange(IdTok.getLocation());
  747. return;
  748. }
  749. VarDecl *VD = Lookup.getAsSingle<VarDecl>();
  750. if (!VD) {
  751. Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
  752. << Name << SourceRange(IdTok.getLocation());
  753. return;
  754. }
  755. // Warn if this was used before being marked unused.
  756. if (VD->isUsed())
  757. Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
  758. VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
  759. AttributeCommonInfo::AS_Pragma,
  760. UnusedAttr::GNU_unused));
  761. }
  762. void Sema::AddCFAuditedAttribute(Decl *D) {
  763. IdentifierInfo *Ident;
  764. SourceLocation Loc;
  765. std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
  766. if (!Loc.isValid()) return;
  767. // Don't add a redundant or conflicting attribute.
  768. if (D->hasAttr<CFAuditedTransferAttr>() ||
  769. D->hasAttr<CFUnknownTransferAttr>())
  770. return;
  771. AttributeCommonInfo Info(Ident, SourceRange(Loc),
  772. AttributeCommonInfo::AS_Pragma);
  773. D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
  774. }
  775. namespace {
  776. std::optional<attr::SubjectMatchRule>
  777. getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
  778. using namespace attr;
  779. switch (Rule) {
  780. default:
  781. return std::nullopt;
  782. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
  783. #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
  784. case Value: \
  785. return Parent;
  786. #include "clang/Basic/AttrSubMatchRulesList.inc"
  787. }
  788. }
  789. bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
  790. using namespace attr;
  791. switch (Rule) {
  792. default:
  793. return false;
  794. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
  795. #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
  796. case Value: \
  797. return IsNegated;
  798. #include "clang/Basic/AttrSubMatchRulesList.inc"
  799. }
  800. }
  801. CharSourceRange replacementRangeForListElement(const Sema &S,
  802. SourceRange Range) {
  803. // Make sure that the ',' is removed as well.
  804. SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
  805. Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
  806. /*SkipTrailingWhitespaceAndNewLine=*/false);
  807. if (AfterCommaLoc.isValid())
  808. return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
  809. else
  810. return CharSourceRange::getTokenRange(Range);
  811. }
  812. std::string
  813. attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
  814. std::string Result;
  815. llvm::raw_string_ostream OS(Result);
  816. for (const auto &I : llvm::enumerate(Rules)) {
  817. if (I.index())
  818. OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
  819. OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
  820. }
  821. return Result;
  822. }
  823. } // end anonymous namespace
  824. void Sema::ActOnPragmaAttributeAttribute(
  825. ParsedAttr &Attribute, SourceLocation PragmaLoc,
  826. attr::ParsedSubjectMatchRuleSet Rules) {
  827. Attribute.setIsPragmaClangAttribute();
  828. SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
  829. // Gather the subject match rules that are supported by the attribute.
  830. SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
  831. StrictSubjectMatchRuleSet;
  832. Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
  833. // Figure out which subject matching rules are valid.
  834. if (StrictSubjectMatchRuleSet.empty()) {
  835. // Check for contradicting match rules. Contradicting match rules are
  836. // either:
  837. // - a top-level rule and one of its sub-rules. E.g. variable and
  838. // variable(is_parameter).
  839. // - a sub-rule and a sibling that's negated. E.g.
  840. // variable(is_thread_local) and variable(unless(is_parameter))
  841. llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
  842. RulesToFirstSpecifiedNegatedSubRule;
  843. for (const auto &Rule : Rules) {
  844. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  845. std::optional<attr::SubjectMatchRule> ParentRule =
  846. getParentAttrMatcherRule(MatchRule);
  847. if (!ParentRule)
  848. continue;
  849. auto It = Rules.find(*ParentRule);
  850. if (It != Rules.end()) {
  851. // A sub-rule contradicts a parent rule.
  852. Diag(Rule.second.getBegin(),
  853. diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
  854. << attr::getSubjectMatchRuleSpelling(MatchRule)
  855. << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
  856. << FixItHint::CreateRemoval(
  857. replacementRangeForListElement(*this, Rule.second));
  858. // Keep going without removing this rule as it won't change the set of
  859. // declarations that receive the attribute.
  860. continue;
  861. }
  862. if (isNegatedAttrMatcherSubRule(MatchRule))
  863. RulesToFirstSpecifiedNegatedSubRule.insert(
  864. std::make_pair(*ParentRule, Rule));
  865. }
  866. bool IgnoreNegatedSubRules = false;
  867. for (const auto &Rule : Rules) {
  868. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  869. std::optional<attr::SubjectMatchRule> ParentRule =
  870. getParentAttrMatcherRule(MatchRule);
  871. if (!ParentRule)
  872. continue;
  873. auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
  874. if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
  875. It->second != Rule) {
  876. // Negated sub-rule contradicts another sub-rule.
  877. Diag(
  878. It->second.second.getBegin(),
  879. diag::
  880. err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
  881. << attr::getSubjectMatchRuleSpelling(
  882. attr::SubjectMatchRule(It->second.first))
  883. << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
  884. << FixItHint::CreateRemoval(
  885. replacementRangeForListElement(*this, It->second.second));
  886. // Keep going but ignore all of the negated sub-rules.
  887. IgnoreNegatedSubRules = true;
  888. RulesToFirstSpecifiedNegatedSubRule.erase(It);
  889. }
  890. }
  891. if (!IgnoreNegatedSubRules) {
  892. for (const auto &Rule : Rules)
  893. SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
  894. } else {
  895. for (const auto &Rule : Rules) {
  896. if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
  897. SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
  898. }
  899. }
  900. Rules.clear();
  901. } else {
  902. // Each rule in Rules must be a strict subset of the attribute's
  903. // SubjectMatch rules. I.e. we're allowed to use
  904. // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
  905. // but should not allow `apply_to=variables` on an attribute which has
  906. // `SubjectList<[GlobalVar]>`.
  907. for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
  908. // First, check for exact match.
  909. if (Rules.erase(StrictRule.first)) {
  910. // Add the rule to the set of attribute receivers only if it's supported
  911. // in the current language mode.
  912. if (StrictRule.second)
  913. SubjectMatchRules.push_back(StrictRule.first);
  914. }
  915. }
  916. // Check remaining rules for subset matches.
  917. auto RulesToCheck = Rules;
  918. for (const auto &Rule : RulesToCheck) {
  919. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  920. if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
  921. if (llvm::any_of(StrictSubjectMatchRuleSet,
  922. [ParentRule](const auto &StrictRule) {
  923. return StrictRule.first == *ParentRule &&
  924. StrictRule.second; // IsEnabled
  925. })) {
  926. SubjectMatchRules.push_back(MatchRule);
  927. Rules.erase(MatchRule);
  928. }
  929. }
  930. }
  931. }
  932. if (!Rules.empty()) {
  933. auto Diagnostic =
  934. Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
  935. << Attribute;
  936. SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
  937. for (const auto &Rule : Rules) {
  938. ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
  939. Diagnostic << FixItHint::CreateRemoval(
  940. replacementRangeForListElement(*this, Rule.second));
  941. }
  942. Diagnostic << attrMatcherRuleListToString(ExtraRules);
  943. }
  944. if (PragmaAttributeStack.empty()) {
  945. Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
  946. return;
  947. }
  948. PragmaAttributeStack.back().Entries.push_back(
  949. {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
  950. }
  951. void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
  952. const IdentifierInfo *Namespace) {
  953. PragmaAttributeStack.emplace_back();
  954. PragmaAttributeStack.back().Loc = PragmaLoc;
  955. PragmaAttributeStack.back().Namespace = Namespace;
  956. }
  957. void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
  958. const IdentifierInfo *Namespace) {
  959. if (PragmaAttributeStack.empty()) {
  960. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
  961. return;
  962. }
  963. // Dig back through the stack trying to find the most recently pushed group
  964. // that in Namespace. Note that this works fine if no namespace is present,
  965. // think of push/pops without namespaces as having an implicit "nullptr"
  966. // namespace.
  967. for (size_t Index = PragmaAttributeStack.size(); Index;) {
  968. --Index;
  969. if (PragmaAttributeStack[Index].Namespace == Namespace) {
  970. for (const PragmaAttributeEntry &Entry :
  971. PragmaAttributeStack[Index].Entries) {
  972. if (!Entry.IsUsed) {
  973. assert(Entry.Attribute && "Expected an attribute");
  974. Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
  975. << *Entry.Attribute;
  976. Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
  977. }
  978. }
  979. PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
  980. return;
  981. }
  982. }
  983. if (Namespace)
  984. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
  985. << 0 << Namespace->getName();
  986. else
  987. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
  988. }
  989. void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
  990. if (PragmaAttributeStack.empty())
  991. return;
  992. for (auto &Group : PragmaAttributeStack) {
  993. for (auto &Entry : Group.Entries) {
  994. ParsedAttr *Attribute = Entry.Attribute;
  995. assert(Attribute && "Expected an attribute");
  996. assert(Attribute->isPragmaClangAttribute() &&
  997. "expected #pragma clang attribute");
  998. // Ensure that the attribute can be applied to the given declaration.
  999. bool Applies = false;
  1000. for (const auto &Rule : Entry.MatchRules) {
  1001. if (Attribute->appliesToDecl(D, Rule)) {
  1002. Applies = true;
  1003. break;
  1004. }
  1005. }
  1006. if (!Applies)
  1007. continue;
  1008. Entry.IsUsed = true;
  1009. PragmaAttributeCurrentTargetDecl = D;
  1010. ParsedAttributesView Attrs;
  1011. Attrs.addAtEnd(Attribute);
  1012. ProcessDeclAttributeList(S, D, Attrs);
  1013. PragmaAttributeCurrentTargetDecl = nullptr;
  1014. }
  1015. }
  1016. }
  1017. void Sema::PrintPragmaAttributeInstantiationPoint() {
  1018. assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
  1019. Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
  1020. diag::note_pragma_attribute_applied_decl_here);
  1021. }
  1022. void Sema::DiagnoseUnterminatedPragmaAttribute() {
  1023. if (PragmaAttributeStack.empty())
  1024. return;
  1025. Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
  1026. }
  1027. void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
  1028. if(On)
  1029. OptimizeOffPragmaLocation = SourceLocation();
  1030. else
  1031. OptimizeOffPragmaLocation = PragmaLoc;
  1032. }
  1033. void Sema::ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn) {
  1034. if (!CurContext->getRedeclContext()->isFileContext()) {
  1035. Diag(Loc, diag::err_pragma_expected_file_scope) << "optimize";
  1036. return;
  1037. }
  1038. MSPragmaOptimizeIsOn = IsOn;
  1039. }
  1040. void Sema::ActOnPragmaMSFunction(
  1041. SourceLocation Loc, const llvm::SmallVectorImpl<StringRef> &NoBuiltins) {
  1042. if (!CurContext->getRedeclContext()->isFileContext()) {
  1043. Diag(Loc, diag::err_pragma_expected_file_scope) << "function";
  1044. return;
  1045. }
  1046. MSFunctionNoBuiltins.insert(NoBuiltins.begin(), NoBuiltins.end());
  1047. }
  1048. void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
  1049. // In the future, check other pragmas if they're implemented (e.g. pragma
  1050. // optimize 0 will probably map to this functionality too).
  1051. if(OptimizeOffPragmaLocation.isValid())
  1052. AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
  1053. }
  1054. void Sema::AddSectionMSAllocText(FunctionDecl *FD) {
  1055. if (!FD->getIdentifier())
  1056. return;
  1057. StringRef Name = FD->getName();
  1058. auto It = FunctionToSectionMap.find(Name);
  1059. if (It != FunctionToSectionMap.end()) {
  1060. StringRef Section;
  1061. SourceLocation Loc;
  1062. std::tie(Section, Loc) = It->second;
  1063. if (!FD->hasAttr<SectionAttr>())
  1064. FD->addAttr(SectionAttr::CreateImplicit(Context, Section));
  1065. }
  1066. }
  1067. void Sema::ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD) {
  1068. // Don't modify the function attributes if it's "on". "on" resets the
  1069. // optimizations to the ones listed on the command line
  1070. if (!MSPragmaOptimizeIsOn)
  1071. AddOptnoneAttributeIfNoConflicts(FD, FD->getBeginLoc());
  1072. }
  1073. void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
  1074. SourceLocation Loc) {
  1075. // Don't add a conflicting attribute. No diagnostic is needed.
  1076. if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
  1077. return;
  1078. // Add attributes only if required. Optnone requires noinline as well, but if
  1079. // either is already present then don't bother adding them.
  1080. if (!FD->hasAttr<OptimizeNoneAttr>())
  1081. FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
  1082. if (!FD->hasAttr<NoInlineAttr>())
  1083. FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
  1084. }
  1085. void Sema::AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD) {
  1086. SmallVector<StringRef> V(MSFunctionNoBuiltins.begin(),
  1087. MSFunctionNoBuiltins.end());
  1088. if (!MSFunctionNoBuiltins.empty())
  1089. FD->addAttr(NoBuiltinAttr::CreateImplicit(Context, V.data(), V.size()));
  1090. }
  1091. typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
  1092. enum : unsigned { NoVisibility = ~0U };
  1093. void Sema::AddPushedVisibilityAttribute(Decl *D) {
  1094. if (!VisContext)
  1095. return;
  1096. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  1097. if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
  1098. return;
  1099. VisStack *Stack = static_cast<VisStack*>(VisContext);
  1100. unsigned rawType = Stack->back().first;
  1101. if (rawType == NoVisibility) return;
  1102. VisibilityAttr::VisibilityType type
  1103. = (VisibilityAttr::VisibilityType) rawType;
  1104. SourceLocation loc = Stack->back().second;
  1105. D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
  1106. }
  1107. /// FreeVisContext - Deallocate and null out VisContext.
  1108. void Sema::FreeVisContext() {
  1109. delete static_cast<VisStack*>(VisContext);
  1110. VisContext = nullptr;
  1111. }
  1112. static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
  1113. // Put visibility on stack.
  1114. if (!S.VisContext)
  1115. S.VisContext = new VisStack;
  1116. VisStack *Stack = static_cast<VisStack*>(S.VisContext);
  1117. Stack->push_back(std::make_pair(type, loc));
  1118. }
  1119. void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
  1120. SourceLocation PragmaLoc) {
  1121. if (VisType) {
  1122. // Compute visibility to use.
  1123. VisibilityAttr::VisibilityType T;
  1124. if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
  1125. Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
  1126. return;
  1127. }
  1128. PushPragmaVisibility(*this, T, PragmaLoc);
  1129. } else {
  1130. PopPragmaVisibility(false, PragmaLoc);
  1131. }
  1132. }
  1133. void Sema::ActOnPragmaFPContract(SourceLocation Loc,
  1134. LangOptions::FPModeKind FPC) {
  1135. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1136. switch (FPC) {
  1137. case LangOptions::FPM_On:
  1138. NewFPFeatures.setAllowFPContractWithinStatement();
  1139. break;
  1140. case LangOptions::FPM_Fast:
  1141. NewFPFeatures.setAllowFPContractAcrossStatement();
  1142. break;
  1143. case LangOptions::FPM_Off:
  1144. NewFPFeatures.setDisallowFPContract();
  1145. break;
  1146. case LangOptions::FPM_FastHonorPragmas:
  1147. llvm_unreachable("Should not happen");
  1148. }
  1149. FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
  1150. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1151. }
  1152. void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
  1153. if (IsEnabled) {
  1154. // For value unsafe context, combining this pragma with eval method
  1155. // setting is not recommended. See comment in function FixupInvocation#506.
  1156. int Reason = -1;
  1157. if (getLangOpts().getFPEvalMethod() != LangOptions::FEM_UnsetOnCommandLine)
  1158. // Eval method set using the option 'ffp-eval-method'.
  1159. Reason = 1;
  1160. if (PP.getLastFPEvalPragmaLocation().isValid())
  1161. // Eval method set using the '#pragma clang fp eval_method'.
  1162. // We could have both an option and a pragma used to the set the eval
  1163. // method. The pragma overrides the option in the command line. The Reason
  1164. // of the diagnostic is overriden too.
  1165. Reason = 0;
  1166. if (Reason != -1)
  1167. Diag(Loc, diag::err_setting_eval_method_used_in_unsafe_context)
  1168. << Reason << 4;
  1169. }
  1170. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1171. NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
  1172. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1173. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1174. }
  1175. void Sema::ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode FPR) {
  1176. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1177. NewFPFeatures.setConstRoundingModeOverride(FPR);
  1178. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1179. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1180. }
  1181. void Sema::setExceptionMode(SourceLocation Loc,
  1182. LangOptions::FPExceptionModeKind FPE) {
  1183. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1184. NewFPFeatures.setSpecifiedExceptionModeOverride(FPE);
  1185. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1186. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1187. }
  1188. void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
  1189. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1190. if (IsEnabled) {
  1191. // Verify Microsoft restriction:
  1192. // You can't enable fenv_access unless precise semantics are enabled.
  1193. // Precise semantics can be enabled either by the float_control
  1194. // pragma, or by using the /fp:precise or /fp:strict compiler options
  1195. if (!isPreciseFPEnabled())
  1196. Diag(Loc, diag::err_pragma_fenv_requires_precise);
  1197. }
  1198. NewFPFeatures.setAllowFEnvAccessOverride(IsEnabled);
  1199. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1200. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1201. }
  1202. void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
  1203. LangOptions::FPExceptionModeKind FPE) {
  1204. setExceptionMode(Loc, FPE);
  1205. }
  1206. void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
  1207. SourceLocation Loc) {
  1208. // Visibility calculations will consider the namespace's visibility.
  1209. // Here we just want to note that we're in a visibility context
  1210. // which overrides any enclosing #pragma context, but doesn't itself
  1211. // contribute visibility.
  1212. PushPragmaVisibility(*this, NoVisibility, Loc);
  1213. }
  1214. void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
  1215. if (!VisContext) {
  1216. Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
  1217. return;
  1218. }
  1219. // Pop visibility from stack
  1220. VisStack *Stack = static_cast<VisStack*>(VisContext);
  1221. const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
  1222. bool StartsWithPragma = Back->first != NoVisibility;
  1223. if (StartsWithPragma && IsNamespaceEnd) {
  1224. Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
  1225. Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
  1226. // For better error recovery, eat all pushes inside the namespace.
  1227. do {
  1228. Stack->pop_back();
  1229. Back = &Stack->back();
  1230. StartsWithPragma = Back->first != NoVisibility;
  1231. } while (StartsWithPragma);
  1232. } else if (!StartsWithPragma && !IsNamespaceEnd) {
  1233. Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
  1234. Diag(Back->second, diag::note_surrounding_namespace_starts_here);
  1235. return;
  1236. }
  1237. Stack->pop_back();
  1238. // To simplify the implementation, never keep around an empty stack.
  1239. if (Stack->empty())
  1240. FreeVisContext();
  1241. }
  1242. template <typename Ty>
  1243. static bool checkCommonAttributeFeatures(Sema &S, const Ty *Node,
  1244. const ParsedAttr &A,
  1245. bool SkipArgCountCheck) {
  1246. // Several attributes carry different semantics than the parsing requires, so
  1247. // those are opted out of the common argument checks.
  1248. //
  1249. // We also bail on unknown and ignored attributes because those are handled
  1250. // as part of the target-specific handling logic.
  1251. if (A.getKind() == ParsedAttr::UnknownAttribute)
  1252. return false;
  1253. // Check whether the attribute requires specific language extensions to be
  1254. // enabled.
  1255. if (!A.diagnoseLangOpts(S))
  1256. return true;
  1257. // Check whether the attribute appertains to the given subject.
  1258. if (!A.diagnoseAppertainsTo(S, Node))
  1259. return true;
  1260. // Check whether the attribute is mutually exclusive with other attributes
  1261. // that have already been applied to the declaration.
  1262. if (!A.diagnoseMutualExclusion(S, Node))
  1263. return true;
  1264. // Check whether the attribute exists in the target architecture.
  1265. if (S.CheckAttrTarget(A))
  1266. return true;
  1267. if (A.hasCustomParsing())
  1268. return false;
  1269. if (!SkipArgCountCheck) {
  1270. if (A.getMinArgs() == A.getMaxArgs()) {
  1271. // If there are no optional arguments, then checking for the argument
  1272. // count is trivial.
  1273. if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
  1274. return true;
  1275. } else {
  1276. // There are optional arguments, so checking is slightly more involved.
  1277. if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))
  1278. return true;
  1279. else if (!A.hasVariadicArg() && A.getMaxArgs() &&
  1280. !A.checkAtMostNumArgs(S, A.getMaxArgs()))
  1281. return true;
  1282. }
  1283. }
  1284. return false;
  1285. }
  1286. bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
  1287. bool SkipArgCountCheck) {
  1288. return ::checkCommonAttributeFeatures(*this, D, A, SkipArgCountCheck);
  1289. }
  1290. bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
  1291. bool SkipArgCountCheck) {
  1292. return ::checkCommonAttributeFeatures(*this, S, A, SkipArgCountCheck);
  1293. }