1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements stmt-related attribute processing.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/EvaluatedExprVisitor.h"
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Sema/DelayedDiagnostic.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "llvm/ADT/StringExtras.h"
22 using namespace clang;
25 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
27 FallThroughAttr Attr(S.Context, A);
28 if (!isa<NullStmt>(St)) {
29 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
30 << Attr.getSpelling() << St->getBeginLoc();
31 if (isa<SwitchCase>(St)) {
32 SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
33 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
34 << FixItHint::CreateInsertion(L, ";");
38 auto *FnScope = S.getCurFunction();
39 if (FnScope->SwitchStack.empty()) {
40 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
44 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
45 // about using it as an extension.
46 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
48 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
50 FnScope->setHasFallthroughStmt();
51 return ::new (S.Context) FallThroughAttr(S.Context, A);
54 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
56 if (A.getNumArgs() < 1) {
57 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
61 std::vector<StringRef> DiagnosticIdentifiers;
62 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
65 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
68 // FIXME: Warn if the rule name is unknown. This is tricky because only
69 // clang-tidy knows about available rules.
70 DiagnosticIdentifiers.push_back(RuleName);
73 return ::new (S.Context) SuppressAttr(
74 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
77 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
79 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
80 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
81 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
82 Expr *ValueExpr = A.getArgAsExpr(3);
84 StringRef PragmaName =
85 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
86 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
87 PragmaNameLoc->Ident->getName())
88 .Default("clang loop");
90 if (St->getStmtClass() != Stmt::DoStmtClass &&
91 St->getStmtClass() != Stmt::ForStmtClass &&
92 St->getStmtClass() != Stmt::CXXForRangeStmtClass &&
93 St->getStmtClass() != Stmt::WhileStmtClass) {
94 std::string Pragma = "#pragma " + std::string(PragmaName);
95 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
99 LoopHintAttr::OptionType Option;
100 LoopHintAttr::LoopHintState State;
102 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
103 LoopHintAttr::LoopHintState S) {
108 if (PragmaName == "nounroll") {
109 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
110 } else if (PragmaName == "unroll") {
113 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
115 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
116 } else if (PragmaName == "nounroll_and_jam") {
117 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
118 } else if (PragmaName == "unroll_and_jam") {
119 // #pragma unroll_and_jam N
121 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
123 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
125 // #pragma clang loop ...
126 assert(OptionLoc && OptionLoc->Ident &&
127 "Attribute must have valid option info.");
128 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
129 OptionLoc->Ident->getName())
130 .Case("vectorize", LoopHintAttr::Vectorize)
131 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
132 .Case("interleave", LoopHintAttr::Interleave)
133 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
134 .Case("interleave_count", LoopHintAttr::InterleaveCount)
135 .Case("unroll", LoopHintAttr::Unroll)
136 .Case("unroll_count", LoopHintAttr::UnrollCount)
137 .Case("pipeline", LoopHintAttr::PipelineDisabled)
138 .Case("pipeline_initiation_interval",
139 LoopHintAttr::PipelineInitiationInterval)
140 .Case("distribute", LoopHintAttr::Distribute)
141 .Default(LoopHintAttr::Vectorize);
142 if (Option == LoopHintAttr::VectorizeWidth ||
143 Option == LoopHintAttr::InterleaveCount ||
144 Option == LoopHintAttr::UnrollCount ||
145 Option == LoopHintAttr::PipelineInitiationInterval) {
146 assert(ValueExpr && "Attribute must have a valid value expression.");
147 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
149 State = LoopHintAttr::Numeric;
150 } else if (Option == LoopHintAttr::Vectorize ||
151 Option == LoopHintAttr::Interleave ||
152 Option == LoopHintAttr::VectorizePredicate ||
153 Option == LoopHintAttr::Unroll ||
154 Option == LoopHintAttr::Distribute ||
155 Option == LoopHintAttr::PipelineDisabled) {
156 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
157 if (StateLoc->Ident->isStr("disable"))
158 State = LoopHintAttr::Disable;
159 else if (StateLoc->Ident->isStr("assume_safety"))
160 State = LoopHintAttr::AssumeSafety;
161 else if (StateLoc->Ident->isStr("full"))
162 State = LoopHintAttr::Full;
163 else if (StateLoc->Ident->isStr("enable"))
164 State = LoopHintAttr::Enable;
166 llvm_unreachable("bad loop hint argument");
168 llvm_unreachable("bad loop hint");
171 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
175 class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
176 bool FoundCallExpr = false;
179 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited;
181 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
183 bool foundCallExpr() { return FoundCallExpr; }
185 void VisitCallExpr(const CallExpr *E) { FoundCallExpr = true; }
187 void Visit(const Stmt *St) {
190 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St);
195 static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
197 NoMergeAttr NMA(S.Context, A);
198 if (S.CheckAttrNoArgs(A))
201 CallExprFinder CEF(S, St);
203 if (!CEF.foundCallExpr()) {
204 S.Diag(St->getBeginLoc(), diag::warn_nomerge_attribute_ignored_in_stmt)
205 << NMA.getSpelling();
209 return ::new (S.Context) NoMergeAttr(S.Context, A);
213 CheckForIncompatibleAttributes(Sema &S,
214 const SmallVectorImpl<const Attr *> &Attrs) {
215 // There are 6 categories of loop hints attributes: vectorize, interleave,
216 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
217 // come in two variants: a state form and a numeric form. The state form
218 // selectively defaults/enables/disables the transformation for the loop
219 // (for unroll, default indicates full unrolling rather than enabling the
220 // transformation). The numeric form form provides an integer hint (for
221 // example, unroll count) to the transformer. The following array accumulates
222 // the hints encountered while iterating through the attributes to check for
225 const LoopHintAttr *StateAttr;
226 const LoopHintAttr *NumericAttr;
227 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
228 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
231 for (const auto *I : Attrs) {
232 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
234 // Skip non loop hint attributes
238 LoopHintAttr::OptionType Option = LH->getOption();
249 case LoopHintAttr::Vectorize:
250 case LoopHintAttr::VectorizeWidth:
251 Category = Vectorize;
253 case LoopHintAttr::Interleave:
254 case LoopHintAttr::InterleaveCount:
255 Category = Interleave;
257 case LoopHintAttr::Unroll:
258 case LoopHintAttr::UnrollCount:
261 case LoopHintAttr::UnrollAndJam:
262 case LoopHintAttr::UnrollAndJamCount:
263 Category = UnrollAndJam;
265 case LoopHintAttr::Distribute:
266 // Perform the check for duplicated 'distribute' hints.
267 Category = Distribute;
269 case LoopHintAttr::PipelineDisabled:
270 case LoopHintAttr::PipelineInitiationInterval:
273 case LoopHintAttr::VectorizePredicate:
274 Category = VectorizePredicate;
278 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
279 auto &CategoryState = HintAttrs[Category];
280 const LoopHintAttr *PrevAttr;
281 if (Option == LoopHintAttr::Vectorize ||
282 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
283 Option == LoopHintAttr::UnrollAndJam ||
284 Option == LoopHintAttr::VectorizePredicate ||
285 Option == LoopHintAttr::PipelineDisabled ||
286 Option == LoopHintAttr::Distribute) {
287 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
288 PrevAttr = CategoryState.StateAttr;
289 CategoryState.StateAttr = LH;
291 // Numeric hint. For example, vectorize_width(8).
292 PrevAttr = CategoryState.NumericAttr;
293 CategoryState.NumericAttr = LH;
296 PrintingPolicy Policy(S.Context.getLangOpts());
297 SourceLocation OptionLoc = LH->getRange().getBegin();
299 // Cannot specify same type of attribute twice.
300 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
301 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
302 << LH->getDiagnosticName(Policy);
304 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
305 (Category == Unroll || Category == UnrollAndJam ||
306 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
307 // Disable hints are not compatible with numeric hints of the same
308 // category. As a special case, numeric unroll hints are also not
309 // compatible with enable or full form of the unroll pragma because these
310 // directives indicate full unrolling.
311 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
312 << /*Duplicate=*/false
313 << CategoryState.StateAttr->getDiagnosticName(Policy)
314 << CategoryState.NumericAttr->getDiagnosticName(Policy);
319 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
321 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
322 // useful for OpenCL 1.x too and doesn't require HW support.
323 // opencl_unroll_hint can have 0 arguments (compiler
324 // determines unrolling factor) or 1 argument (the unroll factor provided
327 unsigned NumArgs = A.getNumArgs();
330 S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1;
334 unsigned UnrollFactor = 0;
337 Expr *E = A.getArgAsExpr(0);
338 llvm::APSInt ArgVal(32);
340 if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
341 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
342 << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
346 int Val = ArgVal.getSExtValue();
349 S.Diag(A.getRange().getBegin(),
350 diag::err_attribute_requires_positive_integer)
351 << A << /* positive */ 0;
357 return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
360 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
362 switch (A.getKind()) {
363 case ParsedAttr::UnknownAttribute:
364 S.Diag(A.getLoc(), A.isDeclspecAttribute()
365 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
366 : (unsigned)diag::warn_unknown_attribute_ignored)
369 case ParsedAttr::AT_FallThrough:
370 return handleFallThroughAttr(S, St, A, Range);
371 case ParsedAttr::AT_LoopHint:
372 return handleLoopHintAttr(S, St, A, Range);
373 case ParsedAttr::AT_OpenCLUnrollHint:
374 return handleOpenCLUnrollHint(S, St, A, Range);
375 case ParsedAttr::AT_Suppress:
376 return handleSuppressAttr(S, St, A, Range);
377 case ParsedAttr::AT_NoMerge:
378 return handleNoMergeAttr(S, St, A, Range);
380 // if we're here, then we parsed a known attribute, but didn't recognize
381 // it as a statement attribute => it is declaration attribute
382 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
383 << A << St->getBeginLoc();
388 StmtResult Sema::ProcessStmtAttributes(Stmt *S,
389 const ParsedAttributesView &AttrList,
391 SmallVector<const Attr*, 8> Attrs;
392 for (const ParsedAttr &AL : AttrList) {
393 if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range))
397 CheckForIncompatibleAttributes(*this, Attrs);
402 return ActOnAttributedStmt(Range.getBegin(), Attrs, S);