clang 19.0.0git
SemaStmtAttr.cpp
Go to the documentation of this file.
1//===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===//
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 stmt-related attribute processing.
10//
11//===----------------------------------------------------------------------===//
12
18#include "clang/Sema/Lookup.h"
21#include "llvm/ADT/StringExtras.h"
22#include <optional>
23
24using namespace clang;
25using namespace sema;
26
27static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
28 SourceRange Range) {
29 FallThroughAttr Attr(S.Context, A);
30 if (isa<SwitchCase>(St)) {
31 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
32 << A << St->getBeginLoc();
33 SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
34 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
36 return nullptr;
37 }
38 auto *FnScope = S.getCurFunction();
39 if (FnScope->SwitchStack.empty()) {
40 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
41 return nullptr;
42 }
43
44 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
45 // about using it as an extension.
46 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
47 !A.getScopeName())
48 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
49
50 FnScope->setHasFallthroughStmt();
51 return ::new (S.Context) FallThroughAttr(S.Context, A);
52}
53
54static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
55 SourceRange Range) {
56 if (A.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress &&
57 A.getNumArgs() < 1) {
58 // Suppression attribute with GSL spelling requires at least 1 argument.
59 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
60 return nullptr;
61 }
62
63 std::vector<StringRef> DiagnosticIdentifiers;
64 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
65 StringRef RuleName;
66
67 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
68 return nullptr;
69
70 DiagnosticIdentifiers.push_back(RuleName);
71 }
72
73 return ::new (S.Context) SuppressAttr(
74 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
75}
76
77static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
79 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
80 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
81 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
82 Expr *ValueExpr = A.getArgAsExpr(3);
83
84 StringRef PragmaName =
85 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
86 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
87 PragmaNameLoc->Ident->getName())
88 .Default("clang loop");
89
90 // This could be handled automatically by adding a Subjects definition in
91 // Attr.td, but that would make the diagnostic behavior worse in this case
92 // because the user spells this attribute as a pragma.
93 if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) {
94 std::string Pragma = "#pragma " + std::string(PragmaName);
95 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
96 return nullptr;
97 }
98
99 LoopHintAttr::OptionType Option;
100 LoopHintAttr::LoopHintState State;
101
102 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
103 LoopHintAttr::LoopHintState S) {
104 Option = O;
105 State = S;
106 };
107
108 if (PragmaName == "nounroll") {
109 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
110 } else if (PragmaName == "unroll") {
111 // #pragma unroll N
112 if (ValueExpr)
113 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
114 else
115 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
116 } else if (PragmaName == "nounroll_and_jam") {
117 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
118 } else if (PragmaName == "unroll_and_jam") {
119 // #pragma unroll_and_jam N
120 if (ValueExpr)
121 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
122 else
123 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
124 } else {
125 // #pragma clang loop ...
126 assert(OptionLoc && OptionLoc->Ident &&
127 "Attribute must have valid option info.");
128 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
129 OptionLoc->Ident->getName())
130 .Case("vectorize", LoopHintAttr::Vectorize)
131 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
132 .Case("interleave", LoopHintAttr::Interleave)
133 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
134 .Case("interleave_count", LoopHintAttr::InterleaveCount)
135 .Case("unroll", LoopHintAttr::Unroll)
136 .Case("unroll_count", LoopHintAttr::UnrollCount)
137 .Case("pipeline", LoopHintAttr::PipelineDisabled)
138 .Case("pipeline_initiation_interval",
139 LoopHintAttr::PipelineInitiationInterval)
140 .Case("distribute", LoopHintAttr::Distribute)
141 .Default(LoopHintAttr::Vectorize);
142 if (Option == LoopHintAttr::VectorizeWidth) {
143 assert((ValueExpr || (StateLoc && StateLoc->Ident)) &&
144 "Attribute must have a valid value expression or argument.");
145 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
146 return nullptr;
147 if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("scalable"))
148 State = LoopHintAttr::ScalableWidth;
149 else
150 State = LoopHintAttr::FixedWidth;
151 } else if (Option == LoopHintAttr::InterleaveCount ||
152 Option == LoopHintAttr::UnrollCount ||
153 Option == LoopHintAttr::PipelineInitiationInterval) {
154 assert(ValueExpr && "Attribute must have a valid value expression.");
155 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
156 return nullptr;
157 State = LoopHintAttr::Numeric;
158 } else if (Option == LoopHintAttr::Vectorize ||
159 Option == LoopHintAttr::Interleave ||
160 Option == LoopHintAttr::VectorizePredicate ||
161 Option == LoopHintAttr::Unroll ||
162 Option == LoopHintAttr::Distribute ||
163 Option == LoopHintAttr::PipelineDisabled) {
164 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
165 if (StateLoc->Ident->isStr("disable"))
166 State = LoopHintAttr::Disable;
167 else if (StateLoc->Ident->isStr("assume_safety"))
168 State = LoopHintAttr::AssumeSafety;
169 else if (StateLoc->Ident->isStr("full"))
170 State = LoopHintAttr::Full;
171 else if (StateLoc->Ident->isStr("enable"))
172 State = LoopHintAttr::Enable;
173 else
174 llvm_unreachable("bad loop hint argument");
175 } else
176 llvm_unreachable("bad loop hint");
177 }
178
179 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
180}
181
182namespace {
183class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
184 bool FoundAsmStmt = false;
185 std::vector<const CallExpr *> CallExprs;
186
187public:
189
190 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
191
192 bool foundCallExpr() { return !CallExprs.empty(); }
193 const std::vector<const CallExpr *> &getCallExprs() { return CallExprs; }
194
195 bool foundAsmStmt() { return FoundAsmStmt; }
196
197 void VisitCallExpr(const CallExpr *E) { CallExprs.push_back(E); }
198
199 void VisitAsmStmt(const AsmStmt *S) { FoundAsmStmt = true; }
200
201 void Visit(const Stmt *St) {
202 if (!St)
203 return;
205 }
206};
207} // namespace
208
209static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
210 SourceRange Range) {
211 NoMergeAttr NMA(S.Context, A);
212 CallExprFinder CEF(S, St);
213
214 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
215 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
216 << A;
217 return nullptr;
218 }
219
220 return ::new (S.Context) NoMergeAttr(S.Context, A);
221}
222
223template <typename OtherAttr, int DiagIdx>
224static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt,
225 const Stmt *CurSt,
226 const AttributeCommonInfo &A) {
227 CallExprFinder OrigCEF(SemaRef, OrigSt);
228 CallExprFinder CEF(SemaRef, CurSt);
229
230 // If the call expressions lists are equal in size, we can skip
231 // previously emitted diagnostics. However, if the statement has a pack
232 // expansion, we have no way of telling which CallExpr is the instantiated
233 // version of the other. In this case, we will end up re-diagnosing in the
234 // instantiation.
235 // ie: [[clang::always_inline]] non_dependent(), (other_call<Pack>()...)
236 // will diagnose nondependent again.
237 bool CanSuppressDiag =
238 OrigSt && CEF.getCallExprs().size() == OrigCEF.getCallExprs().size();
239
240 if (!CEF.foundCallExpr()) {
241 return SemaRef.Diag(CurSt->getBeginLoc(),
242 diag::warn_attribute_ignored_no_calls_in_stmt)
243 << A;
244 }
245
246 for (const auto &Tup :
247 llvm::zip_longest(OrigCEF.getCallExprs(), CEF.getCallExprs())) {
248 // If the original call expression already had a callee, we already
249 // diagnosed this, so skip it here. We can't skip if there isn't a 1:1
250 // relationship between the two lists of call expressions.
251 if (!CanSuppressDiag || !(*std::get<0>(Tup))->getCalleeDecl()) {
252 const Decl *Callee = (*std::get<1>(Tup))->getCalleeDecl();
253 if (Callee &&
254 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
255 SemaRef.Diag(CurSt->getBeginLoc(),
256 diag::warn_function_stmt_attribute_precedence)
257 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
258 SemaRef.Diag(Callee->getBeginLoc(), diag::note_conflicting_attribute);
259 }
260 }
261 }
262
263 return false;
264}
265
266bool Sema::CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
267 const AttributeCommonInfo &A) {
268 return CheckStmtInlineAttr<AlwaysInlineAttr, 0>(*this, OrigSt, CurSt, A);
269}
270
271bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
272 const AttributeCommonInfo &A) {
273 return CheckStmtInlineAttr<NoInlineAttr, 2>(*this, OrigSt, CurSt, A);
274}
275
276static Attr *handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
277 SourceRange Range) {
278 NoInlineAttr NIA(S.Context, A);
279 if (!NIA.isClangNoInline()) {
280 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
281 << "[[clang::noinline]]";
282 return nullptr;
283 }
284
285 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, St, A))
286 return nullptr;
287
288 return ::new (S.Context) NoInlineAttr(S.Context, A);
289}
290
292 SourceRange Range) {
293 AlwaysInlineAttr AIA(S.Context, A);
294 if (!AIA.isClangAlwaysInline()) {
295 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
296 << "[[clang::always_inline]]";
297 return nullptr;
298 }
299
300 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, St, A))
301 return nullptr;
302
303 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
304}
305
306static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
307 SourceRange Range) {
308 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
309 if (!Res.isUsable())
310 return nullptr;
311
312 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
313}
314
315static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
316 SourceRange Range) {
317 // Validation is in Sema::ActOnAttributedStmt().
318 return ::new (S.Context) MustTailAttr(S.Context, A);
319}
320
321static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
322 SourceRange Range) {
323
324 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
325 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
326
327 return ::new (S.Context) LikelyAttr(S.Context, A);
328}
329
330static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
331 SourceRange Range) {
332
333 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
334 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
335
336 return ::new (S.Context) UnlikelyAttr(S.Context, A);
337}
338
340 Expr *E) {
341 if (!E->isValueDependent()) {
342 llvm::APSInt ArgVal;
344 if (Res.isInvalid())
345 return nullptr;
346 E = Res.get();
347
348 // This attribute requires an integer argument which is a constant power of
349 // two between 1 and 4096 inclusive.
350 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
351 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
352 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
353 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
354 << CI << CodeAlignAttr::MinimumAlignment
355 << CodeAlignAttr::MaximumAlignment << Value.value();
356 else
357 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
358 << CI << CodeAlignAttr::MinimumAlignment
359 << CodeAlignAttr::MaximumAlignment << E;
360 return nullptr;
361 }
362 }
363 return new (Context) CodeAlignAttr(Context, CI, E);
364}
365
366static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
367
368 Expr *E = A.getArgAsExpr(0);
369 return S.BuildCodeAlignAttr(A, E);
370}
371
372// Diagnose non-identical duplicates as a 'conflicting' loop attributes
373// and suppress duplicate errors in cases where the two match.
374template <typename LoopAttrT>
376 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
377 const auto *FirstItr = std::find_if(Attrs.begin(), Attrs.end(), FindFunc);
378
379 if (FirstItr == Attrs.end()) // no attributes found
380 return;
381
382 const auto *LastFoundItr = FirstItr;
383 std::optional<llvm::APSInt> FirstValue;
384
385 const auto *CAFA =
386 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
387 // Return early if first alignment expression is dependent (since we don't
388 // know what the effective size will be), and skip the loop entirely.
389 if (!CAFA)
390 return;
391
392 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
393 Attrs.end(), FindFunc))) {
394 const auto *CASA =
395 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
396 // If the value is dependent, we can not test anything.
397 if (!CASA)
398 return;
399 // Test the attribute values.
400 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
401 if (!FirstValue)
402 FirstValue = CAFA->getResultAsAPSInt();
403
404 if (FirstValue != SecondValue) {
405 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
406 << *FirstItr;
407 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
408 }
409 }
410 return;
411}
412
414 SourceRange Range) {
416 S.Diag(A.getLoc(), diag::warn_unknown_attribute_ignored)
417 << A << A.getRange();
418 return nullptr;
419 }
420 return ::new (S.Context) MSConstexprAttr(S.Context, A);
421}
422
423#define WANT_STMT_MERGE_LOGIC
424#include "clang/Sema/AttrParsedAttrImpl.inc"
425#undef WANT_STMT_MERGE_LOGIC
426
427static void
429 const SmallVectorImpl<const Attr *> &Attrs) {
430 // The vast majority of attributed statements will only have one attribute
431 // on them, so skip all of the checking in the common case.
432 if (Attrs.size() < 2)
433 return;
434
435 // First, check for the easy cases that are table-generated for us.
436 if (!DiagnoseMutualExclusions(S, Attrs))
437 return;
438
439 enum CategoryType {
440 // For the following categories, they come in two variants: a state form and
441 // a numeric form. The state form may be one of default, enable, and
442 // disable. The numeric form provides an integer hint (for example, unroll
443 // count) to the transformer.
444 Vectorize,
445 Interleave,
446 UnrollAndJam,
447 Pipeline,
448 // For unroll, default indicates full unrolling rather than enabling the
449 // transformation.
450 Unroll,
451 // The loop distribution transformation only has a state form that is
452 // exposed by #pragma clang loop distribute (enable | disable).
453 Distribute,
454 // The vector predication only has a state form that is exposed by
455 // #pragma clang loop vectorize_predicate (enable | disable).
456 VectorizePredicate,
457 // This serves as a indicator to how many category are listed in this enum.
458 NumberOfCategories
459 };
460 // The following array accumulates the hints encountered while iterating
461 // through the attributes to check for compatibility.
462 struct {
463 const LoopHintAttr *StateAttr;
464 const LoopHintAttr *NumericAttr;
465 } HintAttrs[CategoryType::NumberOfCategories] = {};
466
467 for (const auto *I : Attrs) {
468 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
469
470 // Skip non loop hint attributes
471 if (!LH)
472 continue;
473
474 CategoryType Category = CategoryType::NumberOfCategories;
475 LoopHintAttr::OptionType Option = LH->getOption();
476 switch (Option) {
477 case LoopHintAttr::Vectorize:
478 case LoopHintAttr::VectorizeWidth:
479 Category = Vectorize;
480 break;
481 case LoopHintAttr::Interleave:
482 case LoopHintAttr::InterleaveCount:
483 Category = Interleave;
484 break;
485 case LoopHintAttr::Unroll:
486 case LoopHintAttr::UnrollCount:
487 Category = Unroll;
488 break;
489 case LoopHintAttr::UnrollAndJam:
490 case LoopHintAttr::UnrollAndJamCount:
491 Category = UnrollAndJam;
492 break;
493 case LoopHintAttr::Distribute:
494 // Perform the check for duplicated 'distribute' hints.
495 Category = Distribute;
496 break;
497 case LoopHintAttr::PipelineDisabled:
498 case LoopHintAttr::PipelineInitiationInterval:
499 Category = Pipeline;
500 break;
501 case LoopHintAttr::VectorizePredicate:
502 Category = VectorizePredicate;
503 break;
504 };
505
506 assert(Category != NumberOfCategories && "Unhandled loop hint option");
507 auto &CategoryState = HintAttrs[Category];
508 const LoopHintAttr *PrevAttr;
509 if (Option == LoopHintAttr::Vectorize ||
510 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
511 Option == LoopHintAttr::UnrollAndJam ||
512 Option == LoopHintAttr::VectorizePredicate ||
513 Option == LoopHintAttr::PipelineDisabled ||
514 Option == LoopHintAttr::Distribute) {
515 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
516 PrevAttr = CategoryState.StateAttr;
517 CategoryState.StateAttr = LH;
518 } else {
519 // Numeric hint. For example, vectorize_width(8).
520 PrevAttr = CategoryState.NumericAttr;
521 CategoryState.NumericAttr = LH;
522 }
523
525 SourceLocation OptionLoc = LH->getRange().getBegin();
526 if (PrevAttr)
527 // Cannot specify same type of attribute twice.
528 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
529 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
530 << LH->getDiagnosticName(Policy);
531
532 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
533 (Category == Unroll || Category == UnrollAndJam ||
534 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
535 // Disable hints are not compatible with numeric hints of the same
536 // category. As a special case, numeric unroll hints are also not
537 // compatible with enable or full form of the unroll pragma because these
538 // directives indicate full unrolling.
539 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
540 << /*Duplicate=*/false
541 << CategoryState.StateAttr->getDiagnosticName(Policy)
542 << CategoryState.NumericAttr->getDiagnosticName(Policy);
543 }
544 }
545}
546
548 SourceRange Range) {
549 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
550 // useful for OpenCL 1.x too and doesn't require HW support.
551 // opencl_unroll_hint can have 0 arguments (compiler
552 // determines unrolling factor) or 1 argument (the unroll factor provided
553 // by the user).
554 unsigned UnrollFactor = 0;
555 if (A.getNumArgs() == 1) {
556 Expr *E = A.getArgAsExpr(0);
557 std::optional<llvm::APSInt> ArgVal;
558
559 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
560 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
562 return nullptr;
563 }
564
565 int Val = ArgVal->getSExtValue();
566 if (Val <= 0) {
567 S.Diag(A.getRange().getBegin(),
568 diag::err_attribute_requires_positive_integer)
569 << A << /* positive */ 0;
570 return nullptr;
571 }
572 UnrollFactor = static_cast<unsigned>(Val);
573 }
574
575 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
576}
577
578static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
579 SourceRange Range) {
581 return nullptr;
582
583 // Unknown attributes are automatically warned on. Target-specific attributes
584 // which do not apply to the current target architecture are treated as
585 // though they were unknown attributes.
586 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
589 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
590 A.existsInTarget(*Aux)))) {
592 ? (unsigned)diag::err_keyword_not_supported_on_target
594 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
595 : (unsigned)diag::warn_unknown_attribute_ignored)
596 << A << A.getRange();
597 return nullptr;
598 }
599
600 if (S.checkCommonAttributeFeatures(St, A))
601 return nullptr;
602
603 switch (A.getKind()) {
604 case ParsedAttr::AT_AlwaysInline:
605 return handleAlwaysInlineAttr(S, St, A, Range);
606 case ParsedAttr::AT_CXXAssume:
607 return handleCXXAssumeAttr(S, St, A, Range);
608 case ParsedAttr::AT_FallThrough:
609 return handleFallThroughAttr(S, St, A, Range);
610 case ParsedAttr::AT_LoopHint:
611 return handleLoopHintAttr(S, St, A, Range);
612 case ParsedAttr::AT_OpenCLUnrollHint:
613 return handleOpenCLUnrollHint(S, St, A, Range);
614 case ParsedAttr::AT_Suppress:
615 return handleSuppressAttr(S, St, A, Range);
616 case ParsedAttr::AT_NoMerge:
617 return handleNoMergeAttr(S, St, A, Range);
618 case ParsedAttr::AT_NoInline:
619 return handleNoInlineAttr(S, St, A, Range);
620 case ParsedAttr::AT_MustTail:
621 return handleMustTailAttr(S, St, A, Range);
622 case ParsedAttr::AT_Likely:
623 return handleLikely(S, St, A, Range);
624 case ParsedAttr::AT_Unlikely:
625 return handleUnlikely(S, St, A, Range);
626 case ParsedAttr::AT_CodeAlign:
627 return handleCodeAlignAttr(S, St, A);
628 case ParsedAttr::AT_MSConstexpr:
629 return handleMSConstexprAttr(S, St, A, Range);
630 default:
631 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
632 // declaration attribute is not written on a statement, but this code is
633 // needed for attributes in Attr.td that do not list any subjects.
634 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
635 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
636 return nullptr;
637 }
638}
639
642 for (const ParsedAttr &AL : InAttrs) {
643 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
644 OutAttrs.push_back(A);
645 }
646
647 CheckForIncompatibleAttributes(*this, OutAttrs);
648 CheckForDuplicateLoopAttrs<CodeAlignAttr>(*this, OutAttrs);
649}
650
652 CheckForDuplicateLoopAttrs<CodeAlignAttr>(*this, Attrs);
653 return false;
654}
655
657 SourceRange Range) {
658 if (A.getNumArgs() != 1 || !A.getArgAsExpr(0)) {
659 Diag(A.getLoc(), diag::err_assume_attr_args) << A.getAttrName() << Range;
660 return ExprError();
661 }
662
663 auto *Assumption = A.getArgAsExpr(0);
664 if (Assumption->getDependence() == ExprDependence::None) {
665 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
666 if (Res.isInvalid())
667 return ExprError();
668 Assumption = Res.get();
669 }
670
672 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
673
674 return Assumption;
675}
676
678 const IdentifierInfo *AttrName,
679 SourceRange Range) {
680 ExprResult Res = CorrectDelayedTyposInExpr(Assumption);
681 if (Res.isInvalid())
682 return ExprError();
683
684 Res = CheckPlaceholderExpr(Res.get());
685 if (Res.isInvalid())
686 return ExprError();
687
689 if (Res.isInvalid())
690 return ExprError();
691
692 Assumption = Res.get();
693 if (Assumption->HasSideEffects(Context))
694 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
695 << AttrName << Range;
696
697 return Assumption;
698}
Defines the clang::ASTContext interface.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
int Category
Definition: Format.cpp:2975
static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void handleMSConstexprAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void CheckForDuplicateLoopAttrs(Sema &S, ArrayRef< const Attr * > Attrs)
static Attr * handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleLikely(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange)
static void CheckForIncompatibleAttributes(Sema &S, const SmallVectorImpl< const Attr * > &Attrs)
static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
static Attr * handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A)
static Attr * handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
Defines the SourceManager interface.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition: Stmt.h:3105
Attr - This represents one attribute.
Definition: Attr.h:42
unsigned getAttributeSpellingListIndex() const
const IdentifierInfo * getScopeName() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
This represents one expression.
Definition: Expr.h:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3556
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:613
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
bool existsInTarget(const TargetInfo &Target) const
Definition: ParsedAttr.cpp:201
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:402
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:382
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:394
AttributeCommonInfo::Kind getKind() const
Definition: ParsedAttr.h:617
bool isInvalid() const
Definition: ParsedAttr.h:355
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:946
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, SmallVectorImpl< const Attr * > &OutAttrs)
Process the attributes before creating an attributed statement.
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, bool SkipArgCountCheck=false)
Handles semantic checking for features that are common to all attributes, such as checking whether a ...
Definition: SemaAttr.cpp:1470
ExprResult BuildCXXAssumeExpr(Expr *Assumption, const IdentifierInfo *AttrName, SourceRange Range)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17462
ASTContext & Context
Definition: Sema.h:858
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
const LangOptions & getLangOpts() const
Definition: Sema.h:520
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21225
bool CheckRebuiltStmtAttributes(ArrayRef< const Attr * > Attrs)
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3905
ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, SourceRange Range)
CodeAlignAttr * BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition: StmtVisitor.h:44
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Exposes information about the current target.
Definition: TargetInfo.h:213
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus23
Definition: LangStandard.h:60
@ AANT_ArgumentIntegerConstant
Definition: ParsedAttr.h:1066
ExprResult ExprError()
Definition: Ownership.h:264
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:100
IdentifierInfo * Ident
Definition: ParsedAttr.h:102
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57