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
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/EvaluatedExprVisitor.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Sema/DelayedDiagnostic.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/SemaInternal.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>(Val: St)) {
31 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
32 << A << St->getBeginLoc();
33 SourceLocation L = S.getLocForEndOfToken(Loc: Range.getEnd());
34 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
35 << FixItHint::CreateInsertion(L, ";");
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(Attr: A, ArgNum: I, Str&: RuleName, ArgLocation: nullptr))
68 return nullptr;
69
70 DiagnosticIdentifiers.push_back(x: 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,
78 SourceRange) {
79 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(Arg: 0);
80 IdentifierLoc *OptionLoc = A.getArgAsIdent(Arg: 1);
81 IdentifierLoc *StateLoc = A.getArgAsIdent(Arg: 2);
82 Expr *ValueExpr = A.getArgAsExpr(Arg: 3);
83
84 StringRef PragmaName =
85 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
86 .Cases(S0: "unroll", S1: "nounroll", S2: "unroll_and_jam", S3: "nounroll_and_jam",
87 Value: PragmaNameLoc->Ident->getName())
88 .Default(Value: "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>(Val: 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 && !ValueExpr->isValueDependent()) {
113 llvm::APSInt ValueAPS;
114 ExprResult R = S.VerifyIntegerConstantExpression(E: ValueExpr, Result: &ValueAPS);
115 assert(!R.isInvalid() && "unroll count value must be a valid value, it's "
116 "should be checked in Sema::CheckLoopHintExpr");
117 (void)R;
118 // The values of 0 and 1 block any unrolling of the loop.
119 if (ValueAPS.isZero() || ValueAPS.isOne())
120 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Disable);
121 else
122 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
123 } else
124 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
125 } else if (PragmaName == "nounroll_and_jam") {
126 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
127 } else if (PragmaName == "unroll_and_jam") {
128 // #pragma unroll_and_jam N
129 if (ValueExpr)
130 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
131 else
132 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
133 } else {
134 // #pragma clang loop ...
135 assert(OptionLoc && OptionLoc->Ident &&
136 "Attribute must have valid option info.");
137 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
138 OptionLoc->Ident->getName())
139 .Case("vectorize", LoopHintAttr::Vectorize)
140 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
141 .Case("interleave", LoopHintAttr::Interleave)
142 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
143 .Case("interleave_count", LoopHintAttr::InterleaveCount)
144 .Case("unroll", LoopHintAttr::Unroll)
145 .Case("unroll_count", LoopHintAttr::UnrollCount)
146 .Case("pipeline", LoopHintAttr::PipelineDisabled)
147 .Case("pipeline_initiation_interval",
148 LoopHintAttr::PipelineInitiationInterval)
149 .Case("distribute", LoopHintAttr::Distribute)
150 .Default(LoopHintAttr::Vectorize);
151 if (Option == LoopHintAttr::VectorizeWidth) {
152 assert((ValueExpr || (StateLoc && StateLoc->Ident)) &&
153 "Attribute must have a valid value expression or argument.");
154 if (ValueExpr && S.CheckLoopHintExpr(E: ValueExpr, Loc: St->getBeginLoc(),
155 /*AllowZero=*/false))
156 return nullptr;
157 if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("scalable"))
158 State = LoopHintAttr::ScalableWidth;
159 else
160 State = LoopHintAttr::FixedWidth;
161 } else if (Option == LoopHintAttr::InterleaveCount ||
162 Option == LoopHintAttr::UnrollCount ||
163 Option == LoopHintAttr::PipelineInitiationInterval) {
164 assert(ValueExpr && "Attribute must have a valid value expression.");
165 if (S.CheckLoopHintExpr(E: ValueExpr, Loc: St->getBeginLoc(),
166 /*AllowZero=*/false))
167 return nullptr;
168 State = LoopHintAttr::Numeric;
169 } else if (Option == LoopHintAttr::Vectorize ||
170 Option == LoopHintAttr::Interleave ||
171 Option == LoopHintAttr::VectorizePredicate ||
172 Option == LoopHintAttr::Unroll ||
173 Option == LoopHintAttr::Distribute ||
174 Option == LoopHintAttr::PipelineDisabled) {
175 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
176 if (StateLoc->Ident->isStr(Str: "disable"))
177 State = LoopHintAttr::Disable;
178 else if (StateLoc->Ident->isStr(Str: "assume_safety"))
179 State = LoopHintAttr::AssumeSafety;
180 else if (StateLoc->Ident->isStr(Str: "full"))
181 State = LoopHintAttr::Full;
182 else if (StateLoc->Ident->isStr(Str: "enable"))
183 State = LoopHintAttr::Enable;
184 else
185 llvm_unreachable("bad loop hint argument");
186 } else
187 llvm_unreachable("bad loop hint");
188 }
189
190 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
191}
192
193namespace {
194class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
195 bool FoundAsmStmt = false;
196 std::vector<const CallExpr *> CallExprs;
197
198public:
199 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited;
200
201 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
202
203 bool foundCallExpr() { return !CallExprs.empty(); }
204 const std::vector<const CallExpr *> &getCallExprs() { return CallExprs; }
205
206 bool foundAsmStmt() { return FoundAsmStmt; }
207
208 void VisitCallExpr(const CallExpr *E) { CallExprs.push_back(x: E); }
209
210 void VisitAsmStmt(const AsmStmt *S) { FoundAsmStmt = true; }
211
212 void Visit(const Stmt *St) {
213 if (!St)
214 return;
215 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(S: St);
216 }
217};
218} // namespace
219
220static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
221 SourceRange Range) {
222 NoMergeAttr NMA(S.Context, A);
223 CallExprFinder CEF(S, St);
224
225 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
226 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
227 << A;
228 return nullptr;
229 }
230
231 return ::new (S.Context) NoMergeAttr(S.Context, A);
232}
233
234template <typename OtherAttr, int DiagIdx>
235static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt,
236 const Stmt *CurSt,
237 const AttributeCommonInfo &A) {
238 CallExprFinder OrigCEF(SemaRef, OrigSt);
239 CallExprFinder CEF(SemaRef, CurSt);
240
241 // If the call expressions lists are equal in size, we can skip
242 // previously emitted diagnostics. However, if the statement has a pack
243 // expansion, we have no way of telling which CallExpr is the instantiated
244 // version of the other. In this case, we will end up re-diagnosing in the
245 // instantiation.
246 // ie: [[clang::always_inline]] non_dependent(), (other_call<Pack>()...)
247 // will diagnose nondependent again.
248 bool CanSuppressDiag =
249 OrigSt && CEF.getCallExprs().size() == OrigCEF.getCallExprs().size();
250
251 if (!CEF.foundCallExpr()) {
252 return SemaRef.Diag(CurSt->getBeginLoc(),
253 diag::warn_attribute_ignored_no_calls_in_stmt)
254 << A;
255 }
256
257 for (const auto &Tup :
258 llvm::zip_longest(t: OrigCEF.getCallExprs(), u: CEF.getCallExprs())) {
259 // If the original call expression already had a callee, we already
260 // diagnosed this, so skip it here. We can't skip if there isn't a 1:1
261 // relationship between the two lists of call expressions.
262 if (!CanSuppressDiag || !(*std::get<0>(t: Tup))->getCalleeDecl()) {
263 const Decl *Callee = (*std::get<1>(t: Tup))->getCalleeDecl();
264 if (Callee &&
265 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
266 SemaRef.Diag(CurSt->getBeginLoc(),
267 diag::warn_function_stmt_attribute_precedence)
268 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
269 SemaRef.Diag(Callee->getBeginLoc(), diag::note_conflicting_attribute);
270 }
271 }
272 }
273
274 return false;
275}
276
277bool Sema::CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
278 const AttributeCommonInfo &A) {
279 return CheckStmtInlineAttr<AlwaysInlineAttr, 0>(*this, OrigSt, CurSt, A);
280}
281
282bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
283 const AttributeCommonInfo &A) {
284 return CheckStmtInlineAttr<NoInlineAttr, 2>(*this, OrigSt, CurSt, A);
285}
286
287static Attr *handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
288 SourceRange Range) {
289 NoInlineAttr NIA(S.Context, A);
290 if (!NIA.isClangNoInline()) {
291 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
292 << "[[clang::noinline]]";
293 return nullptr;
294 }
295
296 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, CurSt: St, A))
297 return nullptr;
298
299 return ::new (S.Context) NoInlineAttr(S.Context, A);
300}
301
302static Attr *handleAlwaysInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
303 SourceRange Range) {
304 AlwaysInlineAttr AIA(S.Context, A);
305 if (!AIA.isClangAlwaysInline()) {
306 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
307 << "[[clang::always_inline]]";
308 return nullptr;
309 }
310
311 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, CurSt: St, A))
312 return nullptr;
313
314 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
315}
316
317static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
318 SourceRange Range) {
319 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
320 if (!Res.isUsable())
321 return nullptr;
322
323 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
324}
325
326static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
327 SourceRange Range) {
328 // Validation is in Sema::ActOnAttributedStmt().
329 return ::new (S.Context) MustTailAttr(S.Context, A);
330}
331
332static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
333 SourceRange Range) {
334
335 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
336 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
337
338 return ::new (S.Context) LikelyAttr(S.Context, A);
339}
340
341static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
342 SourceRange Range) {
343
344 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
345 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
346
347 return ::new (S.Context) UnlikelyAttr(S.Context, A);
348}
349
350CodeAlignAttr *Sema::BuildCodeAlignAttr(const AttributeCommonInfo &CI,
351 Expr *E) {
352 if (!E->isValueDependent()) {
353 llvm::APSInt ArgVal;
354 ExprResult Res = VerifyIntegerConstantExpression(E, Result: &ArgVal);
355 if (Res.isInvalid())
356 return nullptr;
357 E = Res.get();
358
359 // This attribute requires an integer argument which is a constant power of
360 // two between 1 and 4096 inclusive.
361 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
362 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
363 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
364 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
365 << CI << CodeAlignAttr::MinimumAlignment
366 << CodeAlignAttr::MaximumAlignment << Value.value();
367 else
368 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
369 << CI << CodeAlignAttr::MinimumAlignment
370 << CodeAlignAttr::MaximumAlignment << E;
371 return nullptr;
372 }
373 }
374 return new (Context) CodeAlignAttr(Context, CI, E);
375}
376
377static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
378
379 Expr *E = A.getArgAsExpr(Arg: 0);
380 return S.BuildCodeAlignAttr(A, E);
381}
382
383// Diagnose non-identical duplicates as a 'conflicting' loop attributes
384// and suppress duplicate errors in cases where the two match.
385template <typename LoopAttrT>
386static void CheckForDuplicateLoopAttrs(Sema &S, ArrayRef<const Attr *> Attrs) {
387 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
388 const auto *FirstItr = std::find_if(Attrs.begin(), Attrs.end(), FindFunc);
389
390 if (FirstItr == Attrs.end()) // no attributes found
391 return;
392
393 const auto *LastFoundItr = FirstItr;
394 std::optional<llvm::APSInt> FirstValue;
395
396 const auto *CAFA =
397 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
398 // Return early if first alignment expression is dependent (since we don't
399 // know what the effective size will be), and skip the loop entirely.
400 if (!CAFA)
401 return;
402
403 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
404 Attrs.end(), FindFunc))) {
405 const auto *CASA =
406 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
407 // If the value is dependent, we can not test anything.
408 if (!CASA)
409 return;
410 // Test the attribute values.
411 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
412 if (!FirstValue)
413 FirstValue = CAFA->getResultAsAPSInt();
414
415 if (FirstValue != SecondValue) {
416 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
417 << *FirstItr;
418 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
419 }
420 }
421 return;
422}
423
424static Attr *handleMSConstexprAttr(Sema &S, Stmt *St, const ParsedAttr &A,
425 SourceRange Range) {
426 if (!S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2022_3)) {
427 S.Diag(A.getLoc(), diag::warn_unknown_attribute_ignored)
428 << A << A.getRange();
429 return nullptr;
430 }
431 return ::new (S.Context) MSConstexprAttr(S.Context, A);
432}
433
434#define WANT_STMT_MERGE_LOGIC
435#include "clang/Sema/AttrParsedAttrImpl.inc"
436#undef WANT_STMT_MERGE_LOGIC
437
438static void
439CheckForIncompatibleAttributes(Sema &S,
440 const SmallVectorImpl<const Attr *> &Attrs) {
441 // The vast majority of attributed statements will only have one attribute
442 // on them, so skip all of the checking in the common case.
443 if (Attrs.size() < 2)
444 return;
445
446 // First, check for the easy cases that are table-generated for us.
447 if (!DiagnoseMutualExclusions(S, Attrs))
448 return;
449
450 enum CategoryType {
451 // For the following categories, they come in two variants: a state form and
452 // a numeric form. The state form may be one of default, enable, and
453 // disable. The numeric form provides an integer hint (for example, unroll
454 // count) to the transformer.
455 Vectorize,
456 Interleave,
457 UnrollAndJam,
458 Pipeline,
459 // For unroll, default indicates full unrolling rather than enabling the
460 // transformation.
461 Unroll,
462 // The loop distribution transformation only has a state form that is
463 // exposed by #pragma clang loop distribute (enable | disable).
464 Distribute,
465 // The vector predication only has a state form that is exposed by
466 // #pragma clang loop vectorize_predicate (enable | disable).
467 VectorizePredicate,
468 // This serves as a indicator to how many category are listed in this enum.
469 NumberOfCategories
470 };
471 // The following array accumulates the hints encountered while iterating
472 // through the attributes to check for compatibility.
473 struct {
474 const LoopHintAttr *StateAttr;
475 const LoopHintAttr *NumericAttr;
476 } HintAttrs[CategoryType::NumberOfCategories] = {};
477
478 for (const auto *I : Attrs) {
479 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
480
481 // Skip non loop hint attributes
482 if (!LH)
483 continue;
484
485 CategoryType Category = CategoryType::NumberOfCategories;
486 LoopHintAttr::OptionType Option = LH->getOption();
487 switch (Option) {
488 case LoopHintAttr::Vectorize:
489 case LoopHintAttr::VectorizeWidth:
490 Category = Vectorize;
491 break;
492 case LoopHintAttr::Interleave:
493 case LoopHintAttr::InterleaveCount:
494 Category = Interleave;
495 break;
496 case LoopHintAttr::Unroll:
497 case LoopHintAttr::UnrollCount:
498 Category = Unroll;
499 break;
500 case LoopHintAttr::UnrollAndJam:
501 case LoopHintAttr::UnrollAndJamCount:
502 Category = UnrollAndJam;
503 break;
504 case LoopHintAttr::Distribute:
505 // Perform the check for duplicated 'distribute' hints.
506 Category = Distribute;
507 break;
508 case LoopHintAttr::PipelineDisabled:
509 case LoopHintAttr::PipelineInitiationInterval:
510 Category = Pipeline;
511 break;
512 case LoopHintAttr::VectorizePredicate:
513 Category = VectorizePredicate;
514 break;
515 };
516
517 assert(Category != NumberOfCategories && "Unhandled loop hint option");
518 auto &CategoryState = HintAttrs[Category];
519 const LoopHintAttr *PrevAttr;
520 if (Option == LoopHintAttr::Vectorize ||
521 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
522 Option == LoopHintAttr::UnrollAndJam ||
523 Option == LoopHintAttr::VectorizePredicate ||
524 Option == LoopHintAttr::PipelineDisabled ||
525 Option == LoopHintAttr::Distribute) {
526 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
527 PrevAttr = CategoryState.StateAttr;
528 CategoryState.StateAttr = LH;
529 } else {
530 // Numeric hint. For example, vectorize_width(8).
531 PrevAttr = CategoryState.NumericAttr;
532 CategoryState.NumericAttr = LH;
533 }
534
535 PrintingPolicy Policy(S.Context.getLangOpts());
536 SourceLocation OptionLoc = LH->getRange().getBegin();
537 if (PrevAttr)
538 // Cannot specify same type of attribute twice.
539 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
540 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
541 << LH->getDiagnosticName(Policy);
542
543 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
544 (Category == Unroll || Category == UnrollAndJam ||
545 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
546 // Disable hints are not compatible with numeric hints of the same
547 // category. As a special case, numeric unroll hints are also not
548 // compatible with enable or full form of the unroll pragma because these
549 // directives indicate full unrolling.
550 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
551 << /*Duplicate=*/false
552 << CategoryState.StateAttr->getDiagnosticName(Policy)
553 << CategoryState.NumericAttr->getDiagnosticName(Policy);
554 }
555 }
556}
557
558static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
559 SourceRange Range) {
560 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
561 // useful for OpenCL 1.x too and doesn't require HW support.
562 // opencl_unroll_hint can have 0 arguments (compiler
563 // determines unrolling factor) or 1 argument (the unroll factor provided
564 // by the user).
565 unsigned UnrollFactor = 0;
566 if (A.getNumArgs() == 1) {
567 Expr *E = A.getArgAsExpr(Arg: 0);
568 std::optional<llvm::APSInt> ArgVal;
569
570 if (!(ArgVal = E->getIntegerConstantExpr(Ctx: S.Context))) {
571 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
572 << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
573 return nullptr;
574 }
575
576 int Val = ArgVal->getSExtValue();
577 if (Val <= 0) {
578 S.Diag(A.getRange().getBegin(),
579 diag::err_attribute_requires_positive_integer)
580 << A << /* positive */ 0;
581 return nullptr;
582 }
583 UnrollFactor = static_cast<unsigned>(Val);
584 }
585
586 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
587}
588
589static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
590 SourceRange Range) {
591 if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute)
592 return nullptr;
593
594 // Unknown attributes are automatically warned on. Target-specific attributes
595 // which do not apply to the current target architecture are treated as
596 // though they were unknown attributes.
597 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
598 if (A.getKind() == ParsedAttr::UnknownAttribute ||
599 !(A.existsInTarget(Target: S.Context.getTargetInfo()) ||
600 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
601 A.existsInTarget(Target: *Aux)))) {
602 S.Diag(A.getLoc(), A.isRegularKeywordAttribute()
603 ? (unsigned)diag::err_keyword_not_supported_on_target
604 : A.isDeclspecAttribute()
605 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
606 : (unsigned)diag::warn_unknown_attribute_ignored)
607 << A << A.getRange();
608 return nullptr;
609 }
610
611 if (S.checkCommonAttributeFeatures(S: St, A))
612 return nullptr;
613
614 switch (A.getKind()) {
615 case ParsedAttr::AT_AlwaysInline:
616 return handleAlwaysInlineAttr(S, St, A, Range);
617 case ParsedAttr::AT_CXXAssume:
618 return handleCXXAssumeAttr(S, St, A, Range);
619 case ParsedAttr::AT_FallThrough:
620 return handleFallThroughAttr(S, St, A, Range);
621 case ParsedAttr::AT_LoopHint:
622 return handleLoopHintAttr(S, St, A, Range);
623 case ParsedAttr::AT_OpenCLUnrollHint:
624 return handleOpenCLUnrollHint(S, St, A, Range);
625 case ParsedAttr::AT_Suppress:
626 return handleSuppressAttr(S, St, A, Range);
627 case ParsedAttr::AT_NoMerge:
628 return handleNoMergeAttr(S, St, A, Range);
629 case ParsedAttr::AT_NoInline:
630 return handleNoInlineAttr(S, St, A, Range);
631 case ParsedAttr::AT_MustTail:
632 return handleMustTailAttr(S, St, A, Range);
633 case ParsedAttr::AT_Likely:
634 return handleLikely(S, St, A, Range);
635 case ParsedAttr::AT_Unlikely:
636 return handleUnlikely(S, St, A, Range);
637 case ParsedAttr::AT_CodeAlign:
638 return handleCodeAlignAttr(S, St, A);
639 case ParsedAttr::AT_MSConstexpr:
640 return handleMSConstexprAttr(S, St, A, Range);
641 default:
642 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
643 // declaration attribute is not written on a statement, but this code is
644 // needed for attributes in Attr.td that do not list any subjects.
645 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
646 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
647 return nullptr;
648 }
649}
650
651void Sema::ProcessStmtAttributes(Stmt *S, const ParsedAttributes &InAttrs,
652 SmallVectorImpl<const Attr *> &OutAttrs) {
653 for (const ParsedAttr &AL : InAttrs) {
654 if (const Attr *A = ProcessStmtAttribute(S&: *this, St: S, A: AL, Range: InAttrs.Range))
655 OutAttrs.push_back(Elt: A);
656 }
657
658 CheckForIncompatibleAttributes(S&: *this, Attrs: OutAttrs);
659 CheckForDuplicateLoopAttrs<CodeAlignAttr>(*this, OutAttrs);
660}
661
662bool Sema::CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs) {
663 CheckForDuplicateLoopAttrs<CodeAlignAttr>(*this, Attrs);
664 return false;
665}
666
667ExprResult Sema::ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
668 SourceRange Range) {
669 if (A.getNumArgs() != 1 || !A.getArgAsExpr(Arg: 0)) {
670 Diag(A.getLoc(), diag::err_assume_attr_args) << A.getAttrName() << Range;
671 return ExprError();
672 }
673
674 auto *Assumption = A.getArgAsExpr(Arg: 0);
675 if (Assumption->getDependence() == ExprDependence::None) {
676 ExprResult Res = BuildCXXAssumeExpr(Assumption, AttrName: A.getAttrName(), Range);
677 if (Res.isInvalid())
678 return ExprError();
679 Assumption = Res.get();
680 }
681
682 if (!getLangOpts().CPlusPlus23)
683 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
684
685 return Assumption;
686}
687
688ExprResult Sema::BuildCXXAssumeExpr(Expr *Assumption,
689 const IdentifierInfo *AttrName,
690 SourceRange Range) {
691 ExprResult Res = CorrectDelayedTyposInExpr(E: Assumption);
692 if (Res.isInvalid())
693 return ExprError();
694
695 Res = CheckPlaceholderExpr(E: Res.get());
696 if (Res.isInvalid())
697 return ExprError();
698
699 Res = PerformContextuallyConvertToBool(From: Res.get());
700 if (Res.isInvalid())
701 return ExprError();
702
703 Assumption = Res.get();
704 if (Assumption->HasSideEffects(Context))
705 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
706 << AttrName << Range;
707
708 return Assumption;
709}
710

source code of clang/lib/Sema/SemaStmtAttr.cpp