clang 24.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
19#include <optional>
20
21using namespace clang;
22using namespace sema;
23
24static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
25 SourceRange Range) {
26 FallThroughAttr Attr(S.Context, A);
27 if (isa<SwitchCase>(St)) {
28 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
29 << A << St->getBeginLoc();
30 SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
31 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
33 return nullptr;
34 }
35 auto *FnScope = S.getCurFunction();
36 if (FnScope->SwitchStack.empty()) {
37 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
38 return nullptr;
39 }
40
41 // CWG 3045: The innermost enclosing switch statement of a fallthrough
42 // statement S shall be contained in the innermost enclosing expansion
43 // statement (8.7 [stmt.expand]) of S, if any.
44 for (Scope *Sc = S.getCurScope();
45 Sc && !Sc->isFunctionScope() && !Sc->isSwitchScope();
46 Sc = Sc->getParent()) {
47 if (Sc->isExpansionStmtScope()) {
48 S.Diag(A.getLoc(), diag::err_fallthrough_attr_invalid_placement);
49 return nullptr;
50 }
51 }
52
53 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
54 // about using it as an extension.
55 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
56 !A.getScopeName())
57 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
58
59 FnScope->setHasFallthroughStmt();
60 return ::new (S.Context) FallThroughAttr(S.Context, A);
61}
62
63static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
64 SourceRange Range) {
65 if (A.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress &&
66 A.getNumArgs() < 1) {
67 // Suppression attribute with GSL spelling requires at least 1 argument.
68 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
69 return nullptr;
70 }
71
72 std::vector<StringRef> DiagnosticIdentifiers;
73 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
74 StringRef RuleName;
75
76 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
77 return nullptr;
78
79 DiagnosticIdentifiers.push_back(RuleName);
80 }
81
82 return ::new (S.Context) SuppressAttr(
83 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
84}
85
86static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
88 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
89 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
90 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
91 Expr *ValueExpr = A.getArgAsExpr(3);
92
93 StringRef PragmaName =
94 llvm::StringSwitch<StringRef>(
95 PragmaNameLoc->getIdentifierInfo()->getName())
96 .Cases({"unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam"},
97 PragmaNameLoc->getIdentifierInfo()->getName())
98 .Default("clang loop");
99
100 // This could be handled automatically by adding a Subjects definition in
101 // Attr.td, but that would make the diagnostic behavior worse in this case
102 // because the user spells this attribute as a pragma.
104 std::string Pragma = "#pragma " + std::string(PragmaName);
105 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
106 return nullptr;
107 }
108
109 LoopHintAttr::OptionType Option;
110 LoopHintAttr::LoopHintState State;
111
112 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
113 LoopHintAttr::LoopHintState S) {
114 Option = O;
115 State = S;
116 };
117
118 if (PragmaName == "nounroll") {
119 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
120 } else if (PragmaName == "unroll") {
121 // #pragma unroll N
122 if (ValueExpr) {
123 if (!ValueExpr->isValueDependent()) {
124 auto Value = ValueExpr->EvaluateKnownConstInt(S.getASTContext());
125 if (Value.isZero() || Value.isOne())
126 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
127 else
128 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
129 } else
130 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
131 } else
132 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
133 } else if (PragmaName == "nounroll_and_jam") {
134 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
135 } else if (PragmaName == "unroll_and_jam") {
136 // #pragma unroll_and_jam N
137 if (ValueExpr)
138 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
139 else
140 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
141 } else {
142 // #pragma clang loop ...
143 assert(OptionLoc && OptionLoc->getIdentifierInfo() &&
144 "Attribute must have valid option info.");
145 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
146 OptionLoc->getIdentifierInfo()->getName())
147 .Case("vectorize", LoopHintAttr::Vectorize)
148 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
149 .Case("interleave", LoopHintAttr::Interleave)
150 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
151 .Case("interleave_count", LoopHintAttr::InterleaveCount)
152 .Case("unroll", LoopHintAttr::Unroll)
153 .Case("unroll_count", LoopHintAttr::UnrollCount)
154 .Case("pipeline", LoopHintAttr::PipelineDisabled)
155 .Case("pipeline_initiation_interval",
156 LoopHintAttr::PipelineInitiationInterval)
157 .Case("distribute", LoopHintAttr::Distribute)
158 .Case("licm", LoopHintAttr::LICMDisabled)
159 .Default(LoopHintAttr::Vectorize);
160 if (Option == LoopHintAttr::VectorizeWidth) {
161 assert((ValueExpr || (StateLoc && StateLoc->getIdentifierInfo())) &&
162 "Attribute must have a valid value expression or argument.");
163 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc(),
164 /*AllowZero=*/false))
165 return nullptr;
166 if (StateLoc && StateLoc->getIdentifierInfo() &&
167 StateLoc->getIdentifierInfo()->isStr("scalable"))
168 State = LoopHintAttr::ScalableWidth;
169 else
170 State = LoopHintAttr::FixedWidth;
171 } else if (Option == LoopHintAttr::InterleaveCount ||
172 Option == LoopHintAttr::UnrollCount ||
173 Option == LoopHintAttr::PipelineInitiationInterval) {
174 assert(ValueExpr && "Attribute must have a valid value expression.");
175 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc(),
176 /*AllowZero=*/false))
177 return nullptr;
178 State = LoopHintAttr::Numeric;
179 } else if (Option == LoopHintAttr::Vectorize ||
180 Option == LoopHintAttr::Interleave ||
181 Option == LoopHintAttr::VectorizePredicate ||
182 Option == LoopHintAttr::Unroll ||
183 Option == LoopHintAttr::Distribute ||
184 Option == LoopHintAttr::PipelineDisabled ||
185 Option == LoopHintAttr::LICMDisabled) {
186 assert(StateLoc && StateLoc->getIdentifierInfo() &&
187 "Loop hint must have an argument");
188 if (StateLoc->getIdentifierInfo()->isStr("disable"))
189 State = LoopHintAttr::Disable;
190 else if (StateLoc->getIdentifierInfo()->isStr("assume_safety"))
191 State = LoopHintAttr::AssumeSafety;
192 else if (StateLoc->getIdentifierInfo()->isStr("full"))
193 State = LoopHintAttr::Full;
194 else if (StateLoc->getIdentifierInfo()->isStr("enable"))
195 State = LoopHintAttr::Enable;
196 else
197 llvm_unreachable("bad loop hint argument");
198 } else
199 llvm_unreachable("bad loop hint");
200 }
201
202 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
203}
204
205namespace {
206class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
207 bool FoundAsmStmt = false;
208 std::vector<const CallExpr *> CallExprs;
209
210public:
211 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited;
212
213 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
214
215 bool foundCallExpr() { return !CallExprs.empty(); }
216 const std::vector<const CallExpr *> &getCallExprs() { return CallExprs; }
217
218 bool foundAsmStmt() { return FoundAsmStmt; }
219
220 void VisitCallExpr(const CallExpr *E) { CallExprs.push_back(E); }
221
222 void VisitAsmStmt(const AsmStmt *S) { FoundAsmStmt = true; }
223
224 void Visit(const Stmt *St) {
225 if (!St)
226 return;
227 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St);
228 }
229};
230} // namespace
231
232static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
233 SourceRange Range) {
234 CallExprFinder CEF(S, St);
235
236 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
237 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
238 << A;
239 return nullptr;
240 }
241
242 return ::new (S.Context) NoMergeAttr(S.Context, A);
243}
244
246 SourceRange Range) {
247 CallExprFinder CEF(S, St);
248
249 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
250 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
251 << A;
252 return nullptr;
253 }
254
255 return ::new (S.Context) NoConvergentAttr(S.Context, A);
256}
257
258template <typename OtherAttr, int DiagIdx>
259static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt,
260 const Stmt *CurSt,
261 const AttributeCommonInfo &A) {
262 CallExprFinder OrigCEF(SemaRef, OrigSt);
263 CallExprFinder CEF(SemaRef, CurSt);
264
265 // If the call expressions lists are equal in size, we can skip
266 // previously emitted diagnostics. However, if the statement has a pack
267 // expansion, we have no way of telling which CallExpr is the instantiated
268 // version of the other. In this case, we will end up re-diagnosing in the
269 // instantiation.
270 // ie: [[clang::always_inline]] non_dependent(), (other_call<Pack>()...)
271 // will diagnose nondependent again.
272 bool CanSuppressDiag =
273 OrigSt && CEF.getCallExprs().size() == OrigCEF.getCallExprs().size();
274
275 if (!CEF.foundCallExpr()) {
276 return SemaRef.Diag(CurSt->getBeginLoc(),
277 diag::warn_attribute_ignored_no_calls_in_stmt)
278 << A;
279 }
280
281 for (const auto &Tup :
282 llvm::zip_longest(OrigCEF.getCallExprs(), CEF.getCallExprs())) {
283 // If the original call expression already had a callee, we already
284 // diagnosed this, so skip it here. We can't skip if there isn't a 1:1
285 // relationship between the two lists of call expressions.
286 if (!CanSuppressDiag || !(*std::get<0>(Tup))->getCalleeDecl()) {
287 const Decl *Callee = (*std::get<1>(Tup))->getCalleeDecl();
288 if (Callee &&
289 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
290 SemaRef.Diag(CurSt->getBeginLoc(),
291 diag::warn_function_stmt_attribute_precedence)
292 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
293 SemaRef.Diag(Callee->getBeginLoc(), diag::note_conflicting_attribute);
294 }
295 }
296 }
297
298 return false;
299}
300
301bool Sema::CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
302 const AttributeCommonInfo &A) {
303 return CheckStmtInlineAttr<AlwaysInlineAttr, 0>(*this, OrigSt, CurSt, A);
304}
305
306bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
307 const AttributeCommonInfo &A) {
308 return CheckStmtInlineAttr<NoInlineAttr, 2>(*this, OrigSt, CurSt, A);
309}
310
311static Attr *handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
312 SourceRange Range) {
313 NoInlineAttr NIA(S.Context, A);
314 if (!NIA.isStmtNoInline()) {
315 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
316 << "[[clang::noinline]]";
317 return nullptr;
318 }
319
320 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, St, A))
321 return nullptr;
322
323 return ::new (S.Context) NoInlineAttr(S.Context, A);
324}
325
327 SourceRange Range) {
328 AlwaysInlineAttr AIA(S.Context, A);
329 if (!S.getLangOpts().MicrosoftExt &&
330 (AIA.isMSVCForceInline() || AIA.isMSVCForceInlineCalls())) {
331 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored) << A;
332 return nullptr;
333 }
334 if (AIA.isMSVCForceInline()) {
335 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
336 << "[[msvc::forceinline_calls]]";
337 return nullptr;
338 }
339 if (!AIA.isClangAlwaysInline() && !AIA.isMSVCForceInlineCalls()) {
340 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
341 << "[[clang::always_inline]]";
342 return nullptr;
343 }
344
345 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, St, A))
346 return nullptr;
347
348 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
349}
350
351static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
352 SourceRange Range) {
353 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
354 if (!Res.isUsable())
355 return nullptr;
356
357 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
358}
359
360static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
361 SourceRange Range) {
362 // Validation is in Sema::ActOnAttributedStmt().
363 return ::new (S.Context) MustTailAttr(S.Context, A);
364}
365
366/// Return true if E is an atomic expression or a fence.
367static bool isAtomicExprOrFence(const Expr *E) {
368 E = E->IgnoreParenCasts();
369
370 if (isa<AtomicExpr>(E))
371 return true;
372
373 // _Atomic type qualifier operations: assignments and compound assignments
374 // to atomic lvalues, and loads from atomic lvalues.
375 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
376 if (BO->getLHS()->getType()->isAtomicType())
377 return true;
378 } else if (E->getType()->isAtomicType()) {
379 return true;
380 }
381
382 // Target-independent fence builtins.
383 if (const auto *CE = dyn_cast<CallExpr>(E)) {
384 switch (CE->getBuiltinCallee()) {
385 case Builtin::BI__c11_atomic_thread_fence:
386 case Builtin::BI__c11_atomic_signal_fence:
387 case Builtin::BI__atomic_thread_fence:
388 case Builtin::BI__atomic_signal_fence:
389 case Builtin::BI__scoped_atomic_thread_fence:
390 return true;
391 default:
392 break;
393 }
394 }
395
396 return false;
397}
398
400 const ParsedAttr &A,
401 SourceRange Range) {
402 StringRef Mode;
403 if (!S.checkStringLiteralArgumentAttr(A, 0, Mode))
404 return nullptr;
405
406 if (Mode != "none") {
407 S.Diag(A.getLoc(), diag::warn_attribute_type_not_supported) << A << Mode;
408 return nullptr;
409 }
410
411 if (const auto *E = dyn_cast<Expr>(St)) {
412 if (!isAtomicExprOrFence(E)) {
413 S.Diag(A.getLoc(), diag::warn_amdgpu_av_requires_atomic) << A;
414 return nullptr;
415 }
416 } else {
417 S.Diag(A.getLoc(), diag::warn_amdgpu_av_requires_expr) << A;
418 return nullptr;
419 }
420
421 return ::new (S.Context) AMDGPUAvailableVisibleAttr(S.Context, A, Mode);
422}
423
424static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
425 SourceRange Range) {
426
427 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
428 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
429
430 return ::new (S.Context) LikelyAttr(S.Context, A);
431}
432
433static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
434 SourceRange Range) {
435
436 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
437 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
438
439 return ::new (S.Context) UnlikelyAttr(S.Context, A);
440}
441
443 Expr *E) {
444 if (!E->isValueDependent()) {
445 llvm::APSInt ArgVal;
447 if (Res.isInvalid())
448 return nullptr;
449 E = Res.get();
450
451 // This attribute requires an integer argument which is a constant power of
452 // two between 1 and 4096 inclusive.
453 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
454 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
455 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
456 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
457 << CI << CodeAlignAttr::MinimumAlignment
458 << CodeAlignAttr::MaximumAlignment << Value.value();
459 else
460 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
461 << CI << CodeAlignAttr::MinimumAlignment
462 << CodeAlignAttr::MaximumAlignment << E;
463 return nullptr;
464 }
465 }
466 return new (Context) CodeAlignAttr(Context, CI, E);
467}
468
469static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
470
471 Expr *E = A.getArgAsExpr(0);
472 return S.BuildCodeAlignAttr(A, E);
473}
474
475// Diagnose non-identical duplicates as a 'conflicting' loop attributes
476// and suppress duplicate errors in cases where the two match.
477template <typename LoopAttrT>
479 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
480 const auto *FirstItr = llvm::find_if(Attrs, FindFunc);
481
482 if (FirstItr == Attrs.end()) // no attributes found
483 return;
484
485 const auto *LastFoundItr = FirstItr;
486 std::optional<llvm::APSInt> FirstValue;
487
488 const auto *CAFA =
489 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
490 // Return early if first alignment expression is dependent (since we don't
491 // know what the effective size will be), and skip the loop entirely.
492 if (!CAFA)
493 return;
494
495 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
496 Attrs.end(), FindFunc))) {
497 const auto *CASA =
498 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
499 // If the value is dependent, we can not test anything.
500 if (!CASA)
501 return;
502 // Test the attribute values.
503 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
504 if (!FirstValue)
505 FirstValue = CAFA->getResultAsAPSInt();
506
507 if (llvm::APSInt::isSameValue(*FirstValue, SecondValue))
508 continue;
509
510 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
511 << *FirstItr;
512 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
513 }
514}
515
517 SourceRange Range) {
519 S.Diag(A.getLoc(), diag::warn_unknown_attribute_ignored)
520 << A << A.getRange();
521 return nullptr;
522 }
523 return ::new (S.Context) MSConstexprAttr(S.Context, A);
524}
525
526#define WANT_STMT_MERGE_LOGIC
527#include "clang/Sema/AttrParsedAttrImpl.inc"
528#undef WANT_STMT_MERGE_LOGIC
529
530static void
532 const SmallVectorImpl<const Attr *> &Attrs) {
533 // The vast majority of attributed statements will only have one attribute
534 // on them, so skip all of the checking in the common case.
535 if (Attrs.size() < 2)
536 return;
537
538 // First, check for the easy cases that are table-generated for us.
539 if (!DiagnoseMutualExclusions(S, Attrs))
540 return;
541
542 enum CategoryType {
543 // For the following categories, they come in two variants: a state form and
544 // a numeric form. The state form may be one of default, enable, and
545 // disable. The numeric form provides an integer hint (for example, unroll
546 // count) to the transformer.
547 Vectorize,
548 Interleave,
549 UnrollAndJam,
550 Pipeline,
551 // For unroll, default indicates full unrolling rather than enabling the
552 // transformation.
553 Unroll,
554 // The loop distribution transformation only has a state form that is
555 // exposed by #pragma clang loop distribute (enable | disable).
556 Distribute,
557 // The vector predication only has a state form that is exposed by
558 // #pragma clang loop vectorize_predicate (enable | disable).
559 VectorizePredicate,
560 // The LICM transformation only has a disable state form that is
561 // exposed by #pragma clang loop licm(disable).
562 LICM,
563 // This serves as a indicator to how many category are listed in this enum.
564 NumberOfCategories
565 };
566 // The following array accumulates the hints encountered while iterating
567 // through the attributes to check for compatibility.
568 struct {
569 const LoopHintAttr *StateAttr;
570 const LoopHintAttr *NumericAttr;
571 } HintAttrs[CategoryType::NumberOfCategories] = {};
572
573 for (const auto *I : Attrs) {
574 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
575
576 // Skip non loop hint attributes
577 if (!LH)
578 continue;
579
580 CategoryType Category = CategoryType::NumberOfCategories;
581 LoopHintAttr::OptionType Option = LH->getOption();
582 switch (Option) {
583 case LoopHintAttr::Vectorize:
584 case LoopHintAttr::VectorizeWidth:
585 Category = Vectorize;
586 break;
587 case LoopHintAttr::Interleave:
588 case LoopHintAttr::InterleaveCount:
589 Category = Interleave;
590 break;
591 case LoopHintAttr::Unroll:
592 case LoopHintAttr::UnrollCount:
593 Category = Unroll;
594 break;
595 case LoopHintAttr::UnrollAndJam:
596 case LoopHintAttr::UnrollAndJamCount:
597 Category = UnrollAndJam;
598 break;
599 case LoopHintAttr::Distribute:
600 // Perform the check for duplicated 'distribute' hints.
601 Category = Distribute;
602 break;
603 case LoopHintAttr::PipelineDisabled:
604 case LoopHintAttr::PipelineInitiationInterval:
605 Category = Pipeline;
606 break;
607 case LoopHintAttr::VectorizePredicate:
608 Category = VectorizePredicate;
609 break;
610 case LoopHintAttr::LICMDisabled:
611 Category = LICM;
612 break;
613 };
614
615 assert(Category != NumberOfCategories && "Unhandled loop hint option");
616 auto &CategoryState = HintAttrs[Category];
617 const LoopHintAttr *PrevAttr;
618 if (Option == LoopHintAttr::Vectorize ||
619 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
620 Option == LoopHintAttr::UnrollAndJam ||
621 Option == LoopHintAttr::VectorizePredicate ||
622 Option == LoopHintAttr::PipelineDisabled ||
623 Option == LoopHintAttr::LICMDisabled ||
624 Option == LoopHintAttr::Distribute) {
625 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
626 PrevAttr = CategoryState.StateAttr;
627 CategoryState.StateAttr = LH;
628 } else {
629 // Numeric hint. For example, vectorize_width(8).
630 PrevAttr = CategoryState.NumericAttr;
631 CategoryState.NumericAttr = LH;
632 }
633
635 SourceLocation OptionLoc = LH->getRange().getBegin();
636 if (PrevAttr)
637 // Cannot specify same type of attribute twice.
638 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
639 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
640 << LH->getDiagnosticName(Policy);
641
642 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
643 (Category == Unroll || Category == UnrollAndJam ||
644 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
645 // Disable hints are not compatible with numeric hints of the same
646 // category. As a special case, numeric unroll hints are also not
647 // compatible with enable or full form of the unroll pragma because these
648 // directives indicate full unrolling.
649 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
650 << /*Duplicate=*/false
651 << CategoryState.StateAttr->getDiagnosticName(Policy)
652 << CategoryState.NumericAttr->getDiagnosticName(Policy);
653 }
654 }
655}
656
658 SourceRange Range) {
659 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
660 // useful for OpenCL 1.x too and doesn't require HW support.
661 // opencl_unroll_hint can have 0 arguments (compiler
662 // determines unrolling factor) or 1 argument (the unroll factor provided
663 // by the user).
664 unsigned UnrollFactor = 0;
665 if (A.getNumArgs() == 1) {
666 Expr *E = A.getArgAsExpr(0);
667 std::optional<llvm::APSInt> ArgVal;
668
669 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
670 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
672 return nullptr;
673 }
674
675 int Val = ArgVal->getSExtValue();
676 if (Val <= 0) {
677 S.Diag(A.getRange().getBegin(),
678 diag::err_attribute_requires_positive_integer)
679 << A << /* positive */ 0;
680 return nullptr;
681 }
682 UnrollFactor = static_cast<unsigned>(Val);
683 }
684
685 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
686}
687
689 SourceRange Range) {
690
691 if (A.getSemanticSpelling() == HLSLLoopHintAttr::Spelling::Microsoft_loop &&
692 !A.checkAtMostNumArgs(S, 0))
693 return nullptr;
694
695 unsigned UnrollFactor = 0;
696 if (A.getNumArgs() == 1) {
697 Expr *E = A.getArgAsExpr(0);
698
699 if (S.CheckLoopHintExpr(E, St->getBeginLoc(),
700 /*AllowZero=*/false))
701 return nullptr;
702
703 std::optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(S.Context);
704 // CheckLoopHintExpr handles non int const cases
705 assert(ArgVal != std::nullopt && "ArgVal should be an integer constant.");
706 int Val = ArgVal->getSExtValue();
707 // CheckLoopHintExpr handles negative and zero cases
708 assert(Val > 0 && "Val should be a positive integer greater than zero.");
709 UnrollFactor = static_cast<unsigned>(Val);
710 }
711 return ::new (S.Context) HLSLLoopHintAttr(S.Context, A, UnrollFactor);
712}
713
715 SourceRange Range) {
716
717 return ::new (S.Context) HLSLControlFlowHintAttr(S.Context, A);
718}
719
720static Attr *handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL,
721 SourceRange Range) {
722 if (!AL.checkAtLeastNumArgs(S, 1))
723 return nullptr;
724
726 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
727 AtomicAttr::ConsumedOption Option;
728 StringRef OptionString;
729 SourceLocation Loc;
730
731 if (!AL.isArgIdent(ArgIndex)) {
732 S.Diag(AL.getArgAsExpr(ArgIndex)->getBeginLoc(),
733 diag::err_attribute_argument_type)
735 return nullptr;
736 }
737
738 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
739 OptionString = Ident->getIdentifierInfo()->getName();
740 Loc = Ident->getLoc();
741 if (!AtomicAttr::ConvertStrToConsumedOption(OptionString, Option)) {
742 S.Diag(Loc, diag::err_attribute_invalid_atomic_argument) << OptionString;
743 return nullptr;
744 }
745 Options.push_back(Option);
746 }
747
748 return ::new (S.Context)
749 AtomicAttr(S.Context, AL, Options.data(), Options.size());
750}
751
752static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
753 SourceRange Range) {
755 return nullptr;
756
757 // Unknown attributes are automatically warned on. Target-specific attributes
758 // which do not apply to the current target architecture are treated as
759 // though they were unknown attributes.
760 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
763 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
764 A.existsInTarget(*Aux)))) {
766 S.Diag(A.getLoc(), diag::err_keyword_not_supported_on_target)
767 << A << A.getRange();
768 } else if (A.isDeclspecAttribute()) {
769 S.Diag(A.getLoc(), diag::warn_unhandled_ms_attribute_ignored)
770 << A << A.getRange();
771 } else {
773 }
774 return nullptr;
775 }
776
777 if (S.checkCommonAttributeFeatures(St, A))
778 return nullptr;
779
780 switch (A.getKind()) {
781 case ParsedAttr::AT_AlwaysInline:
782 return handleAlwaysInlineAttr(S, St, A, Range);
783 case ParsedAttr::AT_CXXAssume:
784 return handleCXXAssumeAttr(S, St, A, Range);
785 case ParsedAttr::AT_FallThrough:
786 return handleFallThroughAttr(S, St, A, Range);
787 case ParsedAttr::AT_LoopHint:
788 return handleLoopHintAttr(S, St, A, Range);
789 case ParsedAttr::AT_HLSLLoopHint:
790 return handleHLSLLoopHintAttr(S, St, A, Range);
791 case ParsedAttr::AT_HLSLControlFlowHint:
792 return handleHLSLControlFlowHint(S, St, A, Range);
793 case ParsedAttr::AT_OpenCLUnrollHint:
794 return handleOpenCLUnrollHint(S, St, A, Range);
795 case ParsedAttr::AT_Suppress:
796 return handleSuppressAttr(S, St, A, Range);
797 case ParsedAttr::AT_NoMerge:
798 return handleNoMergeAttr(S, St, A, Range);
799 case ParsedAttr::AT_NoInline:
800 return handleNoInlineAttr(S, St, A, Range);
801 case ParsedAttr::AT_MustTail:
802 return handleMustTailAttr(S, St, A, Range);
803 case ParsedAttr::AT_AMDGPUAvailableVisible:
804 return handleAMDGPUAvailableVisibleAttr(S, St, A, Range);
805 case ParsedAttr::AT_Likely:
806 return handleLikely(S, St, A, Range);
807 case ParsedAttr::AT_Unlikely:
808 return handleUnlikely(S, St, A, Range);
809 case ParsedAttr::AT_CodeAlign:
810 return handleCodeAlignAttr(S, St, A);
811 case ParsedAttr::AT_MSConstexpr:
812 return handleMSConstexprAttr(S, St, A, Range);
813 case ParsedAttr::AT_NoConvergent:
814 return handleNoConvergentAttr(S, St, A, Range);
815 case ParsedAttr::AT_Annotate:
816 return S.CreateAnnotationAttr(A);
817 case ParsedAttr::AT_Atomic:
818 return handleAtomicAttr(S, St, A, Range);
819 default:
820 if (Attr *AT = nullptr; A.getInfo().handleStmtAttribute(S, St, A, AT) !=
822 return AT;
823 }
824 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
825 // declaration attribute is not written on a statement, but this code is
826 // needed for attributes in Attr.td that do not list any subjects.
827 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
828 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
829 return nullptr;
830 }
831}
832
835 for (const ParsedAttr &AL : InAttrs) {
836 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
837 OutAttrs.push_back(A);
838 }
839
840 CheckForIncompatibleAttributes(*this, OutAttrs);
842}
843
848
850 SourceRange Range) {
851 if (A.getNumArgs() != 1 || !A.getArgAsExpr(0)) {
852 Diag(A.getLoc(), diag::err_attribute_wrong_number_arguments)
853 << A.getAttrName() << 1 << Range;
854 return ExprError();
855 }
856
857 auto *Assumption = A.getArgAsExpr(0);
858
859 if (DiagnoseUnexpandedParameterPack(Assumption)) {
860 return ExprError();
861 }
862
863 if (Assumption->getDependence() == ExprDependence::None) {
864 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
865 if (Res.isInvalid())
866 return ExprError();
867 Assumption = Res.get();
868 }
869
870 if (!getLangOpts().CPlusPlus23 &&
872 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
873
874 return Assumption;
875}
876
878 const IdentifierInfo *AttrName,
879 SourceRange Range) {
880 if (!Assumption)
881 return ExprError();
882
883 ExprResult Res = CheckPlaceholderExpr(Assumption);
884 if (Res.isInvalid())
885 return ExprError();
886
888 if (Res.isInvalid())
889 return ExprError();
890
891 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
892 if (Res.isInvalid())
893 return ExprError();
894
895 Assumption = Res.get();
896 if (Assumption->HasSideEffects(Context))
897 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
898 << AttrName << Range;
899
900 return Assumption;
901}
Defines the clang::ASTContext interface.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
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 Attr * handleNoConvergentAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
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 * handleAMDGPUAvailableVisibleAttr(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 Attr * handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL, SourceRange Range)
static void CheckForIncompatibleAttributes(Sema &S, const SmallVectorImpl< const Attr * > &Attrs)
static Attr * handleHLSLControlFlowHint(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
static Attr * handleHLSLLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A)
static bool isAtomicExprOrFence(const Expr *E)
Return true if E is an atomic expression or a fence.
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)
const LangOptions & getLangOpts() const
Definition ASTContext.h:980
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:943
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:942
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:46
unsigned getAttributeSpellingListIndex() const
const IdentifierInfo * getScopeName() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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:3700
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition Expr.h:144
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:105
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.
A simple pair of identifier info and location.
SourceLocation getLoc() const
IdentifierInfo * getIdentifierInfo() const
bool isCompatibleWithMSVC() const
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
unsigned getSemanticSpelling() const
If the parsed attribute has a semantic equivalent, and it would have a semantic Spelling enumeration ...
bool existsInTarget(const TargetInfo &Target) const
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition ParsedAttr.h:389
const ParsedAttrInfo & getInfo() const
Definition ParsedAttr.h:613
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
bool checkAtLeastNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at least as many args as Num.
AttributeCommonInfo::Kind getKind() const
Definition ParsedAttr.h:610
bool isInvalid() const
Definition ParsedAttr.h:344
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isFunctionScope() const
isFunctionScope() - Return true if this scope is a function scope.
Definition Scope.h:411
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1138
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 ...
ExprResult BuildCXXAssumeExpr(Expr *Assumption, const IdentifierInfo *AttrName, SourceRange Range)
ASTContext & Context
Definition Sema.h:1305
ASTContext & getASTContext() const
Definition Sema.h:936
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:929
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1340
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
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.
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)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, SourceRange Range)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:3085
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 ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8674
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Exposes information about the current target.
Definition TargetInfo.h:227
bool isAtomicType() const
Definition TypeBase.h:8933
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus23
@ AANT_ArgumentIntegerConstant
@ AANT_ArgumentIdentifier
ExprResult ExprError()
Definition Ownership.h:265
U cast(CodeGen::Address addr)
Definition Address.h:327
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
Describes how types, statements, expressions, and declarations should be printed.