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/Sema/SemaInternal.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Sema/DelayedDiagnostic.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "llvm/ADT/StringExtras.h"
21 using namespace clang;
24 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
26 FallThroughAttr Attr(A.getRange(), S.Context,
27 A.getAttributeSpellingListIndex());
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.getName();
50 FnScope->setHasFallthroughStmt();
51 return ::new (S.Context) auto(Attr);
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 A.getRange(), S.Context, DiagnosticIdentifiers.data(),
75 DiagnosticIdentifiers.size(), A.getAttributeSpellingListIndex());
78 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
80 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
81 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
82 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
83 Expr *ValueExpr = A.getArgAsExpr(3);
85 StringRef PragmaName =
86 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
87 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
88 PragmaNameLoc->Ident->getName())
89 .Default("clang loop");
91 if (St->getStmtClass() != Stmt::DoStmtClass &&
92 St->getStmtClass() != Stmt::ForStmtClass &&
93 St->getStmtClass() != Stmt::CXXForRangeStmtClass &&
94 St->getStmtClass() != Stmt::WhileStmtClass) {
95 std::string Pragma = "#pragma " + std::string(PragmaName);
96 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
100 LoopHintAttr::Spelling Spelling =
101 LoopHintAttr::Spelling(A.getAttributeSpellingListIndex());
102 LoopHintAttr::OptionType Option;
103 LoopHintAttr::LoopHintState State;
105 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
106 LoopHintAttr::LoopHintState S) {
111 if (PragmaName == "nounroll") {
112 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
113 } else if (PragmaName == "unroll") {
116 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
118 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
119 } else if (PragmaName == "nounroll_and_jam") {
120 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
121 } else if (PragmaName == "unroll_and_jam") {
122 // #pragma unroll_and_jam N
124 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
126 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
128 // #pragma clang loop ...
129 assert(OptionLoc && OptionLoc->Ident &&
130 "Attribute must have valid option info.");
131 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
132 OptionLoc->Ident->getName())
133 .Case("vectorize", LoopHintAttr::Vectorize)
134 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
135 .Case("interleave", LoopHintAttr::Interleave)
136 .Case("interleave_count", LoopHintAttr::InterleaveCount)
137 .Case("unroll", LoopHintAttr::Unroll)
138 .Case("unroll_count", LoopHintAttr::UnrollCount)
139 .Case("pipeline", LoopHintAttr::PipelineDisabled)
140 .Case("pipeline_initiation_interval",
141 LoopHintAttr::PipelineInitiationInterval)
142 .Case("distribute", LoopHintAttr::Distribute)
143 .Default(LoopHintAttr::Vectorize);
144 if (Option == LoopHintAttr::VectorizeWidth ||
145 Option == LoopHintAttr::InterleaveCount ||
146 Option == LoopHintAttr::UnrollCount ||
147 Option == LoopHintAttr::PipelineInitiationInterval) {
148 assert(ValueExpr && "Attribute must have a valid value expression.");
149 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
151 State = LoopHintAttr::Numeric;
152 } else if (Option == LoopHintAttr::Vectorize ||
153 Option == LoopHintAttr::Interleave ||
154 Option == LoopHintAttr::Unroll ||
155 Option == LoopHintAttr::Distribute ||
156 Option == LoopHintAttr::PipelineDisabled) {
157 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
158 if (StateLoc->Ident->isStr("disable"))
159 State = LoopHintAttr::Disable;
160 else if (StateLoc->Ident->isStr("assume_safety"))
161 State = LoopHintAttr::AssumeSafety;
162 else if (StateLoc->Ident->isStr("full"))
163 State = LoopHintAttr::Full;
164 else if (StateLoc->Ident->isStr("enable"))
165 State = LoopHintAttr::Enable;
167 llvm_unreachable("bad loop hint argument");
169 llvm_unreachable("bad loop hint");
172 return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State,
173 ValueExpr, A.getRange());
177 CheckForIncompatibleAttributes(Sema &S,
178 const SmallVectorImpl<const Attr *> &Attrs) {
179 // There are 6 categories of loop hints attributes: vectorize, interleave,
180 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
181 // come in two variants: a state form and a numeric form. The state form
182 // selectively defaults/enables/disables the transformation for the loop
183 // (for unroll, default indicates full unrolling rather than enabling the
184 // transformation). The numeric form form provides an integer hint (for
185 // example, unroll count) to the transformer. The following array accumulates
186 // the hints encountered while iterating through the attributes to check for
189 const LoopHintAttr *StateAttr;
190 const LoopHintAttr *NumericAttr;
191 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
192 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}};
194 for (const auto *I : Attrs) {
195 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
197 // Skip non loop hint attributes
201 LoopHintAttr::OptionType Option = LH->getOption();
211 case LoopHintAttr::Vectorize:
212 case LoopHintAttr::VectorizeWidth:
213 Category = Vectorize;
215 case LoopHintAttr::Interleave:
216 case LoopHintAttr::InterleaveCount:
217 Category = Interleave;
219 case LoopHintAttr::Unroll:
220 case LoopHintAttr::UnrollCount:
223 case LoopHintAttr::UnrollAndJam:
224 case LoopHintAttr::UnrollAndJamCount:
225 Category = UnrollAndJam;
227 case LoopHintAttr::Distribute:
228 // Perform the check for duplicated 'distribute' hints.
229 Category = Distribute;
231 case LoopHintAttr::PipelineDisabled:
232 case LoopHintAttr::PipelineInitiationInterval:
237 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
238 auto &CategoryState = HintAttrs[Category];
239 const LoopHintAttr *PrevAttr;
240 if (Option == LoopHintAttr::Vectorize ||
241 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
242 Option == LoopHintAttr::UnrollAndJam ||
243 Option == LoopHintAttr::PipelineDisabled ||
244 Option == LoopHintAttr::Distribute) {
245 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
246 PrevAttr = CategoryState.StateAttr;
247 CategoryState.StateAttr = LH;
249 // Numeric hint. For example, vectorize_width(8).
250 PrevAttr = CategoryState.NumericAttr;
251 CategoryState.NumericAttr = LH;
254 PrintingPolicy Policy(S.Context.getLangOpts());
255 SourceLocation OptionLoc = LH->getRange().getBegin();
257 // Cannot specify same type of attribute twice.
258 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
259 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
260 << LH->getDiagnosticName(Policy);
262 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
263 (Category == Unroll || Category == UnrollAndJam ||
264 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
265 // Disable hints are not compatible with numeric hints of the same
266 // category. As a special case, numeric unroll hints are also not
267 // compatible with enable or full form of the unroll pragma because these
268 // directives indicate full unrolling.
269 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
270 << /*Duplicate=*/false
271 << CategoryState.StateAttr->getDiagnosticName(Policy)
272 << CategoryState.NumericAttr->getDiagnosticName(Policy);
277 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
279 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
280 // useful for OpenCL 1.x too and doesn't require HW support.
281 // opencl_unroll_hint can have 0 arguments (compiler
282 // determines unrolling factor) or 1 argument (the unroll factor provided
285 unsigned NumArgs = A.getNumArgs();
288 S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1;
292 unsigned UnrollFactor = 0;
295 Expr *E = A.getArgAsExpr(0);
296 llvm::APSInt ArgVal(32);
298 if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
299 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
300 << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
304 int Val = ArgVal.getSExtValue();
307 S.Diag(A.getRange().getBegin(),
308 diag::err_attribute_requires_positive_integer)
309 << A << /* positive */ 0;
315 return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
318 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
320 switch (A.getKind()) {
321 case ParsedAttr::UnknownAttribute:
322 S.Diag(A.getLoc(), A.isDeclspecAttribute()
323 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
324 : (unsigned)diag::warn_unknown_attribute_ignored)
327 case ParsedAttr::AT_FallThrough:
328 return handleFallThroughAttr(S, St, A, Range);
329 case ParsedAttr::AT_LoopHint:
330 return handleLoopHintAttr(S, St, A, Range);
331 case ParsedAttr::AT_OpenCLUnrollHint:
332 return handleOpenCLUnrollHint(S, St, A, Range);
333 case ParsedAttr::AT_Suppress:
334 return handleSuppressAttr(S, St, A, Range);
336 // if we're here, then we parsed a known attribute, but didn't recognize
337 // it as a statement attribute => it is declaration attribute
338 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
339 << A.getName() << St->getBeginLoc();
344 StmtResult Sema::ProcessStmtAttributes(Stmt *S,
345 const ParsedAttributesView &AttrList,
347 SmallVector<const Attr*, 8> Attrs;
348 for (const ParsedAttr &AL : AttrList) {
349 if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range))
353 CheckForIncompatibleAttributes(*this, Attrs);
358 return ActOnAttributedStmt(Range.getBegin(), Attrs, S);