clang 23.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 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
42 // about using it as an extension.
43 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
44 !A.getScopeName())
45 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
46
47 FnScope->setHasFallthroughStmt();
48 return ::new (S.Context) FallThroughAttr(S.Context, A);
49}
50
51static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
52 SourceRange Range) {
53 if (A.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress &&
54 A.getNumArgs() < 1) {
55 // Suppression attribute with GSL spelling requires at least 1 argument.
56 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
57 return nullptr;
58 }
59
60 std::vector<StringRef> DiagnosticIdentifiers;
61 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
62 StringRef RuleName;
63
64 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
65 return nullptr;
66
67 DiagnosticIdentifiers.push_back(RuleName);
68 }
69
70 return ::new (S.Context) SuppressAttr(
71 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
72}
73
74static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
76 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
77 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
78 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
79 Expr *ValueExpr = A.getArgAsExpr(3);
80
81 StringRef PragmaName =
82 llvm::StringSwitch<StringRef>(
83 PragmaNameLoc->getIdentifierInfo()->getName())
84 .Cases({"unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam"},
85 PragmaNameLoc->getIdentifierInfo()->getName())
86 .Default("clang loop");
87
88 // This could be handled automatically by adding a Subjects definition in
89 // Attr.td, but that would make the diagnostic behavior worse in this case
90 // because the user spells this attribute as a pragma.
92 std::string Pragma = "#pragma " + std::string(PragmaName);
93 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
94 return nullptr;
95 }
96
97 LoopHintAttr::OptionType Option;
98 LoopHintAttr::LoopHintState State;
99
100 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
101 LoopHintAttr::LoopHintState S) {
102 Option = O;
103 State = S;
104 };
105
106 if (PragmaName == "nounroll") {
107 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
108 } else if (PragmaName == "unroll") {
109 // #pragma unroll N
110 if (ValueExpr) {
111 if (!ValueExpr->isValueDependent()) {
112 auto Value = ValueExpr->EvaluateKnownConstInt(S.getASTContext());
113 if (Value.isZero() || Value.isOne())
114 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
115 else
116 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
117 } else
118 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
119 } else
120 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
121 } else if (PragmaName == "nounroll_and_jam") {
122 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
123 } else if (PragmaName == "unroll_and_jam") {
124 // #pragma unroll_and_jam N
125 if (ValueExpr)
126 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
127 else
128 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
129 } else {
130 // #pragma clang loop ...
131 assert(OptionLoc && OptionLoc->getIdentifierInfo() &&
132 "Attribute must have valid option info.");
133 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
134 OptionLoc->getIdentifierInfo()->getName())
135 .Case("vectorize", LoopHintAttr::Vectorize)
136 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
137 .Case("interleave", LoopHintAttr::Interleave)
138 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
139 .Case("interleave_count", LoopHintAttr::InterleaveCount)
140 .Case("unroll", LoopHintAttr::Unroll)
141 .Case("unroll_count", LoopHintAttr::UnrollCount)
142 .Case("pipeline", LoopHintAttr::PipelineDisabled)
143 .Case("pipeline_initiation_interval",
144 LoopHintAttr::PipelineInitiationInterval)
145 .Case("distribute", LoopHintAttr::Distribute)
146 .Case("licm", LoopHintAttr::LICMDisabled)
147 .Default(LoopHintAttr::Vectorize);
148 if (Option == LoopHintAttr::VectorizeWidth) {
149 assert((ValueExpr || (StateLoc && StateLoc->getIdentifierInfo())) &&
150 "Attribute must have a valid value expression or argument.");
151 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc(),
152 /*AllowZero=*/false))
153 return nullptr;
154 if (StateLoc && StateLoc->getIdentifierInfo() &&
155 StateLoc->getIdentifierInfo()->isStr("scalable"))
156 State = LoopHintAttr::ScalableWidth;
157 else
158 State = LoopHintAttr::FixedWidth;
159 } else if (Option == LoopHintAttr::InterleaveCount ||
160 Option == LoopHintAttr::UnrollCount ||
161 Option == LoopHintAttr::PipelineInitiationInterval) {
162 assert(ValueExpr && "Attribute must have a valid value expression.");
163 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc(),
164 /*AllowZero=*/false))
165 return nullptr;
166 State = LoopHintAttr::Numeric;
167 } else if (Option == LoopHintAttr::Vectorize ||
168 Option == LoopHintAttr::Interleave ||
169 Option == LoopHintAttr::VectorizePredicate ||
170 Option == LoopHintAttr::Unroll ||
171 Option == LoopHintAttr::Distribute ||
172 Option == LoopHintAttr::PipelineDisabled ||
173 Option == LoopHintAttr::LICMDisabled) {
174 assert(StateLoc && StateLoc->getIdentifierInfo() &&
175 "Loop hint must have an argument");
176 if (StateLoc->getIdentifierInfo()->isStr("disable"))
177 State = LoopHintAttr::Disable;
178 else if (StateLoc->getIdentifierInfo()->isStr("assume_safety"))
179 State = LoopHintAttr::AssumeSafety;
180 else if (StateLoc->getIdentifierInfo()->isStr("full"))
181 State = LoopHintAttr::Full;
182 else if (StateLoc->getIdentifierInfo()->isStr("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(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(St);
216 }
217};
218} // namespace
219
220static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
221 SourceRange Range) {
222 CallExprFinder CEF(S, St);
223
224 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
225 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
226 << A;
227 return nullptr;
228 }
229
230 return ::new (S.Context) NoMergeAttr(S.Context, A);
231}
232
234 SourceRange Range) {
235 CallExprFinder CEF(S, St);
236
237 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
238 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
239 << A;
240 return nullptr;
241 }
242
243 return ::new (S.Context) NoConvergentAttr(S.Context, A);
244}
245
246template <typename OtherAttr, int DiagIdx>
247static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt,
248 const Stmt *CurSt,
249 const AttributeCommonInfo &A) {
250 CallExprFinder OrigCEF(SemaRef, OrigSt);
251 CallExprFinder CEF(SemaRef, CurSt);
252
253 // If the call expressions lists are equal in size, we can skip
254 // previously emitted diagnostics. However, if the statement has a pack
255 // expansion, we have no way of telling which CallExpr is the instantiated
256 // version of the other. In this case, we will end up re-diagnosing in the
257 // instantiation.
258 // ie: [[clang::always_inline]] non_dependent(), (other_call<Pack>()...)
259 // will diagnose nondependent again.
260 bool CanSuppressDiag =
261 OrigSt && CEF.getCallExprs().size() == OrigCEF.getCallExprs().size();
262
263 if (!CEF.foundCallExpr()) {
264 return SemaRef.Diag(CurSt->getBeginLoc(),
265 diag::warn_attribute_ignored_no_calls_in_stmt)
266 << A;
267 }
268
269 for (const auto &Tup :
270 llvm::zip_longest(OrigCEF.getCallExprs(), CEF.getCallExprs())) {
271 // If the original call expression already had a callee, we already
272 // diagnosed this, so skip it here. We can't skip if there isn't a 1:1
273 // relationship between the two lists of call expressions.
274 if (!CanSuppressDiag || !(*std::get<0>(Tup))->getCalleeDecl()) {
275 const Decl *Callee = (*std::get<1>(Tup))->getCalleeDecl();
276 if (Callee &&
277 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
278 SemaRef.Diag(CurSt->getBeginLoc(),
279 diag::warn_function_stmt_attribute_precedence)
280 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
281 SemaRef.Diag(Callee->getBeginLoc(), diag::note_conflicting_attribute);
282 }
283 }
284 }
285
286 return false;
287}
288
289bool Sema::CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
290 const AttributeCommonInfo &A) {
291 return CheckStmtInlineAttr<AlwaysInlineAttr, 0>(*this, OrigSt, CurSt, A);
292}
293
294bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
295 const AttributeCommonInfo &A) {
296 return CheckStmtInlineAttr<NoInlineAttr, 2>(*this, OrigSt, CurSt, A);
297}
298
299static Attr *handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
300 SourceRange Range) {
301 NoInlineAttr NIA(S.Context, A);
302 if (!NIA.isStmtNoInline()) {
303 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
304 << "[[clang::noinline]]";
305 return nullptr;
306 }
307
308 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, St, A))
309 return nullptr;
310
311 return ::new (S.Context) NoInlineAttr(S.Context, A);
312}
313
315 SourceRange Range) {
316 AlwaysInlineAttr AIA(S.Context, A);
317 if (!AIA.isClangAlwaysInline()) {
318 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
319 << "[[clang::always_inline]]";
320 return nullptr;
321 }
322
323 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, St, A))
324 return nullptr;
325
326 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
327}
328
329static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
330 SourceRange Range) {
331 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
332 if (!Res.isUsable())
333 return nullptr;
334
335 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
336}
337
338static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
339 SourceRange Range) {
340 // Validation is in Sema::ActOnAttributedStmt().
341 return ::new (S.Context) MustTailAttr(S.Context, A);
342}
343
344static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
345 SourceRange Range) {
346
347 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
348 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
349
350 return ::new (S.Context) LikelyAttr(S.Context, A);
351}
352
353static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
354 SourceRange Range) {
355
356 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
357 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
358
359 return ::new (S.Context) UnlikelyAttr(S.Context, A);
360}
361
363 Expr *E) {
364 if (!E->isValueDependent()) {
365 llvm::APSInt ArgVal;
367 if (Res.isInvalid())
368 return nullptr;
369 E = Res.get();
370
371 // This attribute requires an integer argument which is a constant power of
372 // two between 1 and 4096 inclusive.
373 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
374 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
375 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
376 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
377 << CI << CodeAlignAttr::MinimumAlignment
378 << CodeAlignAttr::MaximumAlignment << Value.value();
379 else
380 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
381 << CI << CodeAlignAttr::MinimumAlignment
382 << CodeAlignAttr::MaximumAlignment << E;
383 return nullptr;
384 }
385 }
386 return new (Context) CodeAlignAttr(Context, CI, E);
387}
388
389static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
390
391 Expr *E = A.getArgAsExpr(0);
392 return S.BuildCodeAlignAttr(A, E);
393}
394
395// Diagnose non-identical duplicates as a 'conflicting' loop attributes
396// and suppress duplicate errors in cases where the two match.
397template <typename LoopAttrT>
399 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
400 const auto *FirstItr = llvm::find_if(Attrs, FindFunc);
401
402 if (FirstItr == Attrs.end()) // no attributes found
403 return;
404
405 const auto *LastFoundItr = FirstItr;
406 std::optional<llvm::APSInt> FirstValue;
407
408 const auto *CAFA =
409 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
410 // Return early if first alignment expression is dependent (since we don't
411 // know what the effective size will be), and skip the loop entirely.
412 if (!CAFA)
413 return;
414
415 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
416 Attrs.end(), FindFunc))) {
417 const auto *CASA =
418 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
419 // If the value is dependent, we can not test anything.
420 if (!CASA)
421 return;
422 // Test the attribute values.
423 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
424 if (!FirstValue)
425 FirstValue = CAFA->getResultAsAPSInt();
426
427 if (llvm::APSInt::isSameValue(*FirstValue, SecondValue))
428 continue;
429
430 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
431 << *FirstItr;
432 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
433 }
434}
435
437 SourceRange Range) {
439 S.Diag(A.getLoc(), diag::warn_unknown_attribute_ignored)
440 << A << A.getRange();
441 return nullptr;
442 }
443 return ::new (S.Context) MSConstexprAttr(S.Context, A);
444}
445
446#define WANT_STMT_MERGE_LOGIC
447#include "clang/Sema/AttrParsedAttrImpl.inc"
448#undef WANT_STMT_MERGE_LOGIC
449
450static void
452 const SmallVectorImpl<const Attr *> &Attrs) {
453 // The vast majority of attributed statements will only have one attribute
454 // on them, so skip all of the checking in the common case.
455 if (Attrs.size() < 2)
456 return;
457
458 // First, check for the easy cases that are table-generated for us.
459 if (!DiagnoseMutualExclusions(S, Attrs))
460 return;
461
462 enum CategoryType {
463 // For the following categories, they come in two variants: a state form and
464 // a numeric form. The state form may be one of default, enable, and
465 // disable. The numeric form provides an integer hint (for example, unroll
466 // count) to the transformer.
467 Vectorize,
468 Interleave,
469 UnrollAndJam,
470 Pipeline,
471 // For unroll, default indicates full unrolling rather than enabling the
472 // transformation.
473 Unroll,
474 // The loop distribution transformation only has a state form that is
475 // exposed by #pragma clang loop distribute (enable | disable).
476 Distribute,
477 // The vector predication only has a state form that is exposed by
478 // #pragma clang loop vectorize_predicate (enable | disable).
479 VectorizePredicate,
480 // The LICM transformation only has a disable state form that is
481 // exposed by #pragma clang loop licm(disable).
482 LICM,
483 // This serves as a indicator to how many category are listed in this enum.
484 NumberOfCategories
485 };
486 // The following array accumulates the hints encountered while iterating
487 // through the attributes to check for compatibility.
488 struct {
489 const LoopHintAttr *StateAttr;
490 const LoopHintAttr *NumericAttr;
491 } HintAttrs[CategoryType::NumberOfCategories] = {};
492
493 for (const auto *I : Attrs) {
494 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
495
496 // Skip non loop hint attributes
497 if (!LH)
498 continue;
499
500 CategoryType Category = CategoryType::NumberOfCategories;
501 LoopHintAttr::OptionType Option = LH->getOption();
502 switch (Option) {
503 case LoopHintAttr::Vectorize:
504 case LoopHintAttr::VectorizeWidth:
505 Category = Vectorize;
506 break;
507 case LoopHintAttr::Interleave:
508 case LoopHintAttr::InterleaveCount:
509 Category = Interleave;
510 break;
511 case LoopHintAttr::Unroll:
512 case LoopHintAttr::UnrollCount:
513 Category = Unroll;
514 break;
515 case LoopHintAttr::UnrollAndJam:
516 case LoopHintAttr::UnrollAndJamCount:
517 Category = UnrollAndJam;
518 break;
519 case LoopHintAttr::Distribute:
520 // Perform the check for duplicated 'distribute' hints.
521 Category = Distribute;
522 break;
523 case LoopHintAttr::PipelineDisabled:
524 case LoopHintAttr::PipelineInitiationInterval:
525 Category = Pipeline;
526 break;
527 case LoopHintAttr::VectorizePredicate:
528 Category = VectorizePredicate;
529 break;
530 case LoopHintAttr::LICMDisabled:
531 Category = LICM;
532 break;
533 };
534
535 assert(Category != NumberOfCategories && "Unhandled loop hint option");
536 auto &CategoryState = HintAttrs[Category];
537 const LoopHintAttr *PrevAttr;
538 if (Option == LoopHintAttr::Vectorize ||
539 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
540 Option == LoopHintAttr::UnrollAndJam ||
541 Option == LoopHintAttr::VectorizePredicate ||
542 Option == LoopHintAttr::PipelineDisabled ||
543 Option == LoopHintAttr::LICMDisabled ||
544 Option == LoopHintAttr::Distribute) {
545 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
546 PrevAttr = CategoryState.StateAttr;
547 CategoryState.StateAttr = LH;
548 } else {
549 // Numeric hint. For example, vectorize_width(8).
550 PrevAttr = CategoryState.NumericAttr;
551 CategoryState.NumericAttr = LH;
552 }
553
555 SourceLocation OptionLoc = LH->getRange().getBegin();
556 if (PrevAttr)
557 // Cannot specify same type of attribute twice.
558 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
559 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
560 << LH->getDiagnosticName(Policy);
561
562 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
563 (Category == Unroll || Category == UnrollAndJam ||
564 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
565 // Disable hints are not compatible with numeric hints of the same
566 // category. As a special case, numeric unroll hints are also not
567 // compatible with enable or full form of the unroll pragma because these
568 // directives indicate full unrolling.
569 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
570 << /*Duplicate=*/false
571 << CategoryState.StateAttr->getDiagnosticName(Policy)
572 << CategoryState.NumericAttr->getDiagnosticName(Policy);
573 }
574 }
575}
576
578 SourceRange Range) {
579 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
580 // useful for OpenCL 1.x too and doesn't require HW support.
581 // opencl_unroll_hint can have 0 arguments (compiler
582 // determines unrolling factor) or 1 argument (the unroll factor provided
583 // by the user).
584 unsigned UnrollFactor = 0;
585 if (A.getNumArgs() == 1) {
586 Expr *E = A.getArgAsExpr(0);
587 std::optional<llvm::APSInt> ArgVal;
588
589 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
590 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
592 return nullptr;
593 }
594
595 int Val = ArgVal->getSExtValue();
596 if (Val <= 0) {
597 S.Diag(A.getRange().getBegin(),
598 diag::err_attribute_requires_positive_integer)
599 << A << /* positive */ 0;
600 return nullptr;
601 }
602 UnrollFactor = static_cast<unsigned>(Val);
603 }
604
605 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
606}
607
609 SourceRange Range) {
610
611 if (A.getSemanticSpelling() == HLSLLoopHintAttr::Spelling::Microsoft_loop &&
612 !A.checkAtMostNumArgs(S, 0))
613 return nullptr;
614
615 unsigned UnrollFactor = 0;
616 if (A.getNumArgs() == 1) {
617 Expr *E = A.getArgAsExpr(0);
618
619 if (S.CheckLoopHintExpr(E, St->getBeginLoc(),
620 /*AllowZero=*/false))
621 return nullptr;
622
623 std::optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(S.Context);
624 // CheckLoopHintExpr handles non int const cases
625 assert(ArgVal != std::nullopt && "ArgVal should be an integer constant.");
626 int Val = ArgVal->getSExtValue();
627 // CheckLoopHintExpr handles negative and zero cases
628 assert(Val > 0 && "Val should be a positive integer greater than zero.");
629 UnrollFactor = static_cast<unsigned>(Val);
630 }
631 return ::new (S.Context) HLSLLoopHintAttr(S.Context, A, UnrollFactor);
632}
633
635 SourceRange Range) {
636
637 return ::new (S.Context) HLSLControlFlowHintAttr(S.Context, A);
638}
639
640static Attr *handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL,
641 SourceRange Range) {
642 if (!AL.checkAtLeastNumArgs(S, 1))
643 return nullptr;
644
646 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
647 AtomicAttr::ConsumedOption Option;
648 StringRef OptionString;
649 SourceLocation Loc;
650
651 if (!AL.isArgIdent(ArgIndex)) {
652 S.Diag(AL.getArgAsExpr(ArgIndex)->getBeginLoc(),
653 diag::err_attribute_argument_type)
655 return nullptr;
656 }
657
658 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
659 OptionString = Ident->getIdentifierInfo()->getName();
660 Loc = Ident->getLoc();
661 if (!AtomicAttr::ConvertStrToConsumedOption(OptionString, Option)) {
662 S.Diag(Loc, diag::err_attribute_invalid_atomic_argument) << OptionString;
663 return nullptr;
664 }
665 Options.push_back(Option);
666 }
667
668 return ::new (S.Context)
669 AtomicAttr(S.Context, AL, Options.data(), Options.size());
670}
671
672static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
673 SourceRange Range) {
675 return nullptr;
676
677 // Unknown attributes are automatically warned on. Target-specific attributes
678 // which do not apply to the current target architecture are treated as
679 // though they were unknown attributes.
680 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
683 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
684 A.existsInTarget(*Aux)))) {
686 S.Diag(A.getLoc(), diag::err_keyword_not_supported_on_target)
687 << A << A.getRange();
688 } else if (A.isDeclspecAttribute()) {
689 S.Diag(A.getLoc(), diag::warn_unhandled_ms_attribute_ignored)
690 << A << A.getRange();
691 } else {
693 }
694 return nullptr;
695 }
696
697 if (S.checkCommonAttributeFeatures(St, A))
698 return nullptr;
699
700 switch (A.getKind()) {
701 case ParsedAttr::AT_AlwaysInline:
702 return handleAlwaysInlineAttr(S, St, A, Range);
703 case ParsedAttr::AT_CXXAssume:
704 return handleCXXAssumeAttr(S, St, A, Range);
705 case ParsedAttr::AT_FallThrough:
706 return handleFallThroughAttr(S, St, A, Range);
707 case ParsedAttr::AT_LoopHint:
708 return handleLoopHintAttr(S, St, A, Range);
709 case ParsedAttr::AT_HLSLLoopHint:
710 return handleHLSLLoopHintAttr(S, St, A, Range);
711 case ParsedAttr::AT_HLSLControlFlowHint:
712 return handleHLSLControlFlowHint(S, St, A, Range);
713 case ParsedAttr::AT_OpenCLUnrollHint:
714 return handleOpenCLUnrollHint(S, St, A, Range);
715 case ParsedAttr::AT_Suppress:
716 return handleSuppressAttr(S, St, A, Range);
717 case ParsedAttr::AT_NoMerge:
718 return handleNoMergeAttr(S, St, A, Range);
719 case ParsedAttr::AT_NoInline:
720 return handleNoInlineAttr(S, St, A, Range);
721 case ParsedAttr::AT_MustTail:
722 return handleMustTailAttr(S, St, A, Range);
723 case ParsedAttr::AT_Likely:
724 return handleLikely(S, St, A, Range);
725 case ParsedAttr::AT_Unlikely:
726 return handleUnlikely(S, St, A, Range);
727 case ParsedAttr::AT_CodeAlign:
728 return handleCodeAlignAttr(S, St, A);
729 case ParsedAttr::AT_MSConstexpr:
730 return handleMSConstexprAttr(S, St, A, Range);
731 case ParsedAttr::AT_NoConvergent:
732 return handleNoConvergentAttr(S, St, A, Range);
733 case ParsedAttr::AT_Annotate:
734 return S.CreateAnnotationAttr(A);
735 case ParsedAttr::AT_Atomic:
736 return handleAtomicAttr(S, St, A, Range);
737 default:
738 if (Attr *AT = nullptr; A.getInfo().handleStmtAttribute(S, St, A, AT) !=
740 return AT;
741 }
742 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
743 // declaration attribute is not written on a statement, but this code is
744 // needed for attributes in Attr.td that do not list any subjects.
745 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
746 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
747 return nullptr;
748 }
749}
750
753 for (const ParsedAttr &AL : InAttrs) {
754 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
755 OutAttrs.push_back(A);
756 }
757
758 CheckForIncompatibleAttributes(*this, OutAttrs);
760}
761
766
768 SourceRange Range) {
769 if (A.getNumArgs() != 1 || !A.getArgAsExpr(0)) {
770 Diag(A.getLoc(), diag::err_attribute_wrong_number_arguments)
771 << A.getAttrName() << 1 << Range;
772 return ExprError();
773 }
774
775 auto *Assumption = A.getArgAsExpr(0);
776
777 if (DiagnoseUnexpandedParameterPack(Assumption)) {
778 return ExprError();
779 }
780
781 if (Assumption->getDependence() == ExprDependence::None) {
782 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
783 if (Res.isInvalid())
784 return ExprError();
785 Assumption = Res.get();
786 }
787
788 if (!getLangOpts().CPlusPlus23 &&
790 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
791
792 return Assumption;
793}
794
796 const IdentifierInfo *AttrName,
797 SourceRange Range) {
798 if (!Assumption)
799 return ExprError();
800
801 ExprResult Res = CheckPlaceholderExpr(Assumption);
802 if (Res.isInvalid())
803 return ExprError();
804
806 if (Res.isInvalid())
807 return ExprError();
808
809 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
810 if (Res.isInvalid())
811 return ExprError();
812
813 Assumption = Res.get();
814 if (Assumption->HasSideEffects(Context))
815 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
816 << AttrName << Range;
817
818 return Assumption;
819}
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 * 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 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:952
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:918
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:917
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
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.
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
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:3688
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:103
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
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:868
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:1304
ASTContext & getASTContext() const
Definition Sema.h:939
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1337
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:3008
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:8730
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:86
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
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
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.