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 (!S.getLangOpts().MicrosoftExt &&
318 (AIA.isMSVCForceInline() || AIA.isMSVCForceInlineCalls())) {
319 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored) << A;
320 return nullptr;
321 }
322 if (AIA.isMSVCForceInline()) {
323 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
324 << "[[msvc::forceinline_calls]]";
325 return nullptr;
326 }
327 if (!AIA.isClangAlwaysInline() && !AIA.isMSVCForceInlineCalls()) {
328 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
329 << "[[clang::always_inline]]";
330 return nullptr;
331 }
332
333 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, St, A))
334 return nullptr;
335
336 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
337}
338
339static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
340 SourceRange Range) {
341 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
342 if (!Res.isUsable())
343 return nullptr;
344
345 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
346}
347
348static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
349 SourceRange Range) {
350 // Validation is in Sema::ActOnAttributedStmt().
351 return ::new (S.Context) MustTailAttr(S.Context, A);
352}
353
354static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
355 SourceRange Range) {
356
357 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
358 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
359
360 return ::new (S.Context) LikelyAttr(S.Context, A);
361}
362
363static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
364 SourceRange Range) {
365
366 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
367 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
368
369 return ::new (S.Context) UnlikelyAttr(S.Context, A);
370}
371
373 Expr *E) {
374 if (!E->isValueDependent()) {
375 llvm::APSInt ArgVal;
377 if (Res.isInvalid())
378 return nullptr;
379 E = Res.get();
380
381 // This attribute requires an integer argument which is a constant power of
382 // two between 1 and 4096 inclusive.
383 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
384 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
385 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
386 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
387 << CI << CodeAlignAttr::MinimumAlignment
388 << CodeAlignAttr::MaximumAlignment << Value.value();
389 else
390 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
391 << CI << CodeAlignAttr::MinimumAlignment
392 << CodeAlignAttr::MaximumAlignment << E;
393 return nullptr;
394 }
395 }
396 return new (Context) CodeAlignAttr(Context, CI, E);
397}
398
399static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
400
401 Expr *E = A.getArgAsExpr(0);
402 return S.BuildCodeAlignAttr(A, E);
403}
404
405// Diagnose non-identical duplicates as a 'conflicting' loop attributes
406// and suppress duplicate errors in cases where the two match.
407template <typename LoopAttrT>
409 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
410 const auto *FirstItr = llvm::find_if(Attrs, FindFunc);
411
412 if (FirstItr == Attrs.end()) // no attributes found
413 return;
414
415 const auto *LastFoundItr = FirstItr;
416 std::optional<llvm::APSInt> FirstValue;
417
418 const auto *CAFA =
419 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
420 // Return early if first alignment expression is dependent (since we don't
421 // know what the effective size will be), and skip the loop entirely.
422 if (!CAFA)
423 return;
424
425 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
426 Attrs.end(), FindFunc))) {
427 const auto *CASA =
428 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
429 // If the value is dependent, we can not test anything.
430 if (!CASA)
431 return;
432 // Test the attribute values.
433 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
434 if (!FirstValue)
435 FirstValue = CAFA->getResultAsAPSInt();
436
437 if (llvm::APSInt::isSameValue(*FirstValue, SecondValue))
438 continue;
439
440 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
441 << *FirstItr;
442 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
443 }
444}
445
447 SourceRange Range) {
449 S.Diag(A.getLoc(), diag::warn_unknown_attribute_ignored)
450 << A << A.getRange();
451 return nullptr;
452 }
453 return ::new (S.Context) MSConstexprAttr(S.Context, A);
454}
455
456#define WANT_STMT_MERGE_LOGIC
457#include "clang/Sema/AttrParsedAttrImpl.inc"
458#undef WANT_STMT_MERGE_LOGIC
459
460static void
462 const SmallVectorImpl<const Attr *> &Attrs) {
463 // The vast majority of attributed statements will only have one attribute
464 // on them, so skip all of the checking in the common case.
465 if (Attrs.size() < 2)
466 return;
467
468 // First, check for the easy cases that are table-generated for us.
469 if (!DiagnoseMutualExclusions(S, Attrs))
470 return;
471
472 enum CategoryType {
473 // For the following categories, they come in two variants: a state form and
474 // a numeric form. The state form may be one of default, enable, and
475 // disable. The numeric form provides an integer hint (for example, unroll
476 // count) to the transformer.
477 Vectorize,
478 Interleave,
479 UnrollAndJam,
480 Pipeline,
481 // For unroll, default indicates full unrolling rather than enabling the
482 // transformation.
483 Unroll,
484 // The loop distribution transformation only has a state form that is
485 // exposed by #pragma clang loop distribute (enable | disable).
486 Distribute,
487 // The vector predication only has a state form that is exposed by
488 // #pragma clang loop vectorize_predicate (enable | disable).
489 VectorizePredicate,
490 // The LICM transformation only has a disable state form that is
491 // exposed by #pragma clang loop licm(disable).
492 LICM,
493 // This serves as a indicator to how many category are listed in this enum.
494 NumberOfCategories
495 };
496 // The following array accumulates the hints encountered while iterating
497 // through the attributes to check for compatibility.
498 struct {
499 const LoopHintAttr *StateAttr;
500 const LoopHintAttr *NumericAttr;
501 } HintAttrs[CategoryType::NumberOfCategories] = {};
502
503 for (const auto *I : Attrs) {
504 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
505
506 // Skip non loop hint attributes
507 if (!LH)
508 continue;
509
510 CategoryType Category = CategoryType::NumberOfCategories;
511 LoopHintAttr::OptionType Option = LH->getOption();
512 switch (Option) {
513 case LoopHintAttr::Vectorize:
514 case LoopHintAttr::VectorizeWidth:
515 Category = Vectorize;
516 break;
517 case LoopHintAttr::Interleave:
518 case LoopHintAttr::InterleaveCount:
519 Category = Interleave;
520 break;
521 case LoopHintAttr::Unroll:
522 case LoopHintAttr::UnrollCount:
523 Category = Unroll;
524 break;
525 case LoopHintAttr::UnrollAndJam:
526 case LoopHintAttr::UnrollAndJamCount:
527 Category = UnrollAndJam;
528 break;
529 case LoopHintAttr::Distribute:
530 // Perform the check for duplicated 'distribute' hints.
531 Category = Distribute;
532 break;
533 case LoopHintAttr::PipelineDisabled:
534 case LoopHintAttr::PipelineInitiationInterval:
535 Category = Pipeline;
536 break;
537 case LoopHintAttr::VectorizePredicate:
538 Category = VectorizePredicate;
539 break;
540 case LoopHintAttr::LICMDisabled:
541 Category = LICM;
542 break;
543 };
544
545 assert(Category != NumberOfCategories && "Unhandled loop hint option");
546 auto &CategoryState = HintAttrs[Category];
547 const LoopHintAttr *PrevAttr;
548 if (Option == LoopHintAttr::Vectorize ||
549 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
550 Option == LoopHintAttr::UnrollAndJam ||
551 Option == LoopHintAttr::VectorizePredicate ||
552 Option == LoopHintAttr::PipelineDisabled ||
553 Option == LoopHintAttr::LICMDisabled ||
554 Option == LoopHintAttr::Distribute) {
555 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
556 PrevAttr = CategoryState.StateAttr;
557 CategoryState.StateAttr = LH;
558 } else {
559 // Numeric hint. For example, vectorize_width(8).
560 PrevAttr = CategoryState.NumericAttr;
561 CategoryState.NumericAttr = LH;
562 }
563
565 SourceLocation OptionLoc = LH->getRange().getBegin();
566 if (PrevAttr)
567 // Cannot specify same type of attribute twice.
568 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
569 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
570 << LH->getDiagnosticName(Policy);
571
572 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
573 (Category == Unroll || Category == UnrollAndJam ||
574 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
575 // Disable hints are not compatible with numeric hints of the same
576 // category. As a special case, numeric unroll hints are also not
577 // compatible with enable or full form of the unroll pragma because these
578 // directives indicate full unrolling.
579 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
580 << /*Duplicate=*/false
581 << CategoryState.StateAttr->getDiagnosticName(Policy)
582 << CategoryState.NumericAttr->getDiagnosticName(Policy);
583 }
584 }
585}
586
588 SourceRange Range) {
589 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
590 // useful for OpenCL 1.x too and doesn't require HW support.
591 // opencl_unroll_hint can have 0 arguments (compiler
592 // determines unrolling factor) or 1 argument (the unroll factor provided
593 // by the user).
594 unsigned UnrollFactor = 0;
595 if (A.getNumArgs() == 1) {
596 Expr *E = A.getArgAsExpr(0);
597 std::optional<llvm::APSInt> ArgVal;
598
599 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
600 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
602 return nullptr;
603 }
604
605 int Val = ArgVal->getSExtValue();
606 if (Val <= 0) {
607 S.Diag(A.getRange().getBegin(),
608 diag::err_attribute_requires_positive_integer)
609 << A << /* positive */ 0;
610 return nullptr;
611 }
612 UnrollFactor = static_cast<unsigned>(Val);
613 }
614
615 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
616}
617
619 SourceRange Range) {
620
621 if (A.getSemanticSpelling() == HLSLLoopHintAttr::Spelling::Microsoft_loop &&
622 !A.checkAtMostNumArgs(S, 0))
623 return nullptr;
624
625 unsigned UnrollFactor = 0;
626 if (A.getNumArgs() == 1) {
627 Expr *E = A.getArgAsExpr(0);
628
629 if (S.CheckLoopHintExpr(E, St->getBeginLoc(),
630 /*AllowZero=*/false))
631 return nullptr;
632
633 std::optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(S.Context);
634 // CheckLoopHintExpr handles non int const cases
635 assert(ArgVal != std::nullopt && "ArgVal should be an integer constant.");
636 int Val = ArgVal->getSExtValue();
637 // CheckLoopHintExpr handles negative and zero cases
638 assert(Val > 0 && "Val should be a positive integer greater than zero.");
639 UnrollFactor = static_cast<unsigned>(Val);
640 }
641 return ::new (S.Context) HLSLLoopHintAttr(S.Context, A, UnrollFactor);
642}
643
645 SourceRange Range) {
646
647 return ::new (S.Context) HLSLControlFlowHintAttr(S.Context, A);
648}
649
650static Attr *handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL,
651 SourceRange Range) {
652 if (!AL.checkAtLeastNumArgs(S, 1))
653 return nullptr;
654
656 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
657 AtomicAttr::ConsumedOption Option;
658 StringRef OptionString;
659 SourceLocation Loc;
660
661 if (!AL.isArgIdent(ArgIndex)) {
662 S.Diag(AL.getArgAsExpr(ArgIndex)->getBeginLoc(),
663 diag::err_attribute_argument_type)
665 return nullptr;
666 }
667
668 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
669 OptionString = Ident->getIdentifierInfo()->getName();
670 Loc = Ident->getLoc();
671 if (!AtomicAttr::ConvertStrToConsumedOption(OptionString, Option)) {
672 S.Diag(Loc, diag::err_attribute_invalid_atomic_argument) << OptionString;
673 return nullptr;
674 }
675 Options.push_back(Option);
676 }
677
678 return ::new (S.Context)
679 AtomicAttr(S.Context, AL, Options.data(), Options.size());
680}
681
682static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
683 SourceRange Range) {
685 return nullptr;
686
687 // Unknown attributes are automatically warned on. Target-specific attributes
688 // which do not apply to the current target architecture are treated as
689 // though they were unknown attributes.
690 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
693 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
694 A.existsInTarget(*Aux)))) {
696 S.Diag(A.getLoc(), diag::err_keyword_not_supported_on_target)
697 << A << A.getRange();
698 } else if (A.isDeclspecAttribute()) {
699 S.Diag(A.getLoc(), diag::warn_unhandled_ms_attribute_ignored)
700 << A << A.getRange();
701 } else {
703 }
704 return nullptr;
705 }
706
707 if (S.checkCommonAttributeFeatures(St, A))
708 return nullptr;
709
710 switch (A.getKind()) {
711 case ParsedAttr::AT_AlwaysInline:
712 return handleAlwaysInlineAttr(S, St, A, Range);
713 case ParsedAttr::AT_CXXAssume:
714 return handleCXXAssumeAttr(S, St, A, Range);
715 case ParsedAttr::AT_FallThrough:
716 return handleFallThroughAttr(S, St, A, Range);
717 case ParsedAttr::AT_LoopHint:
718 return handleLoopHintAttr(S, St, A, Range);
719 case ParsedAttr::AT_HLSLLoopHint:
720 return handleHLSLLoopHintAttr(S, St, A, Range);
721 case ParsedAttr::AT_HLSLControlFlowHint:
722 return handleHLSLControlFlowHint(S, St, A, Range);
723 case ParsedAttr::AT_OpenCLUnrollHint:
724 return handleOpenCLUnrollHint(S, St, A, Range);
725 case ParsedAttr::AT_Suppress:
726 return handleSuppressAttr(S, St, A, Range);
727 case ParsedAttr::AT_NoMerge:
728 return handleNoMergeAttr(S, St, A, Range);
729 case ParsedAttr::AT_NoInline:
730 return handleNoInlineAttr(S, St, A, Range);
731 case ParsedAttr::AT_MustTail:
732 return handleMustTailAttr(S, St, A, Range);
733 case ParsedAttr::AT_Likely:
734 return handleLikely(S, St, A, Range);
735 case ParsedAttr::AT_Unlikely:
736 return handleUnlikely(S, St, A, Range);
737 case ParsedAttr::AT_CodeAlign:
738 return handleCodeAlignAttr(S, St, A);
739 case ParsedAttr::AT_MSConstexpr:
740 return handleMSConstexprAttr(S, St, A, Range);
741 case ParsedAttr::AT_NoConvergent:
742 return handleNoConvergentAttr(S, St, A, Range);
743 case ParsedAttr::AT_Annotate:
744 return S.CreateAnnotationAttr(A);
745 case ParsedAttr::AT_Atomic:
746 return handleAtomicAttr(S, St, A, Range);
747 default:
748 if (Attr *AT = nullptr; A.getInfo().handleStmtAttribute(S, St, A, AT) !=
750 return AT;
751 }
752 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
753 // declaration attribute is not written on a statement, but this code is
754 // needed for attributes in Attr.td that do not list any subjects.
755 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
756 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
757 return nullptr;
758 }
759}
760
763 for (const ParsedAttr &AL : InAttrs) {
764 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
765 OutAttrs.push_back(A);
766 }
767
768 CheckForIncompatibleAttributes(*this, OutAttrs);
770}
771
776
778 SourceRange Range) {
779 if (A.getNumArgs() != 1 || !A.getArgAsExpr(0)) {
780 Diag(A.getLoc(), diag::err_attribute_wrong_number_arguments)
781 << A.getAttrName() << 1 << Range;
782 return ExprError();
783 }
784
785 auto *Assumption = A.getArgAsExpr(0);
786
787 if (DiagnoseUnexpandedParameterPack(Assumption)) {
788 return ExprError();
789 }
790
791 if (Assumption->getDependence() == ExprDependence::None) {
792 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
793 if (Res.isInvalid())
794 return ExprError();
795 Assumption = Res.get();
796 }
797
798 if (!getLangOpts().CPlusPlus23 &&
800 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
801
802 return Assumption;
803}
804
806 const IdentifierInfo *AttrName,
807 SourceRange Range) {
808 if (!Assumption)
809 return ExprError();
810
811 ExprResult Res = CheckPlaceholderExpr(Assumption);
812 if (Res.isInvalid())
813 return ExprError();
814
816 if (Res.isInvalid())
817 return ExprError();
818
819 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
820 if (Res.isInvalid())
821 return ExprError();
822
823 Assumption = Res.get();
824 if (Assumption->HasSideEffects(Context))
825 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
826 << AttrName << Range;
827
828 return Assumption;
829}
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:104
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:1308
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:1341
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:3022
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:8743
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.