1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements stmt-related attribute processing.
12 //===----------------------------------------------------------------------===//
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(A.getRange(), S.Context,
28 A.getAttributeSpellingListIndex());
29 if (!isa<NullStmt>(St)) {
30 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
31 << Attr.getSpelling() << St->getBeginLoc();
32 if (isa<SwitchCase>(St)) {
33 SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
34 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
35 << FixItHint::CreateInsertion(L, ";");
39 auto *FnScope = S.getCurFunction();
40 if (FnScope->SwitchStack.empty()) {
41 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
45 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
46 // about using it as an extension.
47 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
49 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A.getName();
51 FnScope->setHasFallthroughStmt();
52 return ::new (S.Context) auto(Attr);
55 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
57 if (A.getNumArgs() < 1) {
58 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
62 std::vector<StringRef> DiagnosticIdentifiers;
63 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
66 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
69 // FIXME: Warn if the rule name is unknown. This is tricky because only
70 // clang-tidy knows about available rules.
71 DiagnosticIdentifiers.push_back(RuleName);
74 return ::new (S.Context) SuppressAttr(
75 A.getRange(), S.Context, DiagnosticIdentifiers.data(),
76 DiagnosticIdentifiers.size(), A.getAttributeSpellingListIndex());
79 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
81 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
82 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
83 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
84 Expr *ValueExpr = A.getArgAsExpr(3);
86 bool PragmaUnroll = PragmaNameLoc->Ident->getName() == "unroll";
87 bool PragmaNoUnroll = PragmaNameLoc->Ident->getName() == "nounroll";
88 bool PragmaUnrollAndJam = PragmaNameLoc->Ident->getName() == "unroll_and_jam";
89 bool PragmaNoUnrollAndJam =
90 PragmaNameLoc->Ident->getName() == "nounroll_and_jam";
91 if (St->getStmtClass() != Stmt::DoStmtClass &&
92 St->getStmtClass() != Stmt::ForStmtClass &&
93 St->getStmtClass() != Stmt::CXXForRangeStmtClass &&
94 St->getStmtClass() != Stmt::WhileStmtClass) {
96 llvm::StringSwitch<const char *>(PragmaNameLoc->Ident->getName())
97 .Case("unroll", "#pragma unroll")
98 .Case("nounroll", "#pragma nounroll")
99 .Case("unroll_and_jam", "#pragma unroll_and_jam")
100 .Case("nounroll_and_jam", "#pragma nounroll_and_jam")
101 .Default("#pragma clang loop");
102 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
106 LoopHintAttr::Spelling Spelling =
107 LoopHintAttr::Spelling(A.getAttributeSpellingListIndex());
108 LoopHintAttr::OptionType Option;
109 LoopHintAttr::LoopHintState State;
110 if (PragmaNoUnroll) {
112 Option = LoopHintAttr::Unroll;
113 State = LoopHintAttr::Disable;
114 } else if (PragmaUnroll) {
117 Option = LoopHintAttr::UnrollCount;
118 State = LoopHintAttr::Numeric;
121 Option = LoopHintAttr::Unroll;
122 State = LoopHintAttr::Enable;
124 } else if (PragmaNoUnrollAndJam) {
125 // #pragma nounroll_and_jam
126 Option = LoopHintAttr::UnrollAndJam;
127 State = LoopHintAttr::Disable;
128 } else if (PragmaUnrollAndJam) {
130 // #pragma unroll_and_jam N
131 Option = LoopHintAttr::UnrollAndJamCount;
132 State = LoopHintAttr::Numeric;
134 // #pragma unroll_and_jam
135 Option = LoopHintAttr::UnrollAndJam;
136 State = LoopHintAttr::Enable;
139 // #pragma clang loop ...
140 assert(OptionLoc && OptionLoc->Ident &&
141 "Attribute must have valid option info.");
142 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
143 OptionLoc->Ident->getName())
144 .Case("vectorize", LoopHintAttr::Vectorize)
145 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
146 .Case("interleave", LoopHintAttr::Interleave)
147 .Case("interleave_count", LoopHintAttr::InterleaveCount)
148 .Case("unroll", LoopHintAttr::Unroll)
149 .Case("unroll_count", LoopHintAttr::UnrollCount)
150 .Case("pipeline", LoopHintAttr::PipelineDisabled)
151 .Case("pipeline_initiation_interval",
152 LoopHintAttr::PipelineInitiationInterval)
153 .Case("distribute", LoopHintAttr::Distribute)
154 .Default(LoopHintAttr::Vectorize);
155 if (Option == LoopHintAttr::VectorizeWidth ||
156 Option == LoopHintAttr::InterleaveCount ||
157 Option == LoopHintAttr::UnrollCount ||
158 Option == LoopHintAttr::PipelineInitiationInterval) {
159 assert(ValueExpr && "Attribute must have a valid value expression.");
160 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
162 State = LoopHintAttr::Numeric;
163 } else if (Option == LoopHintAttr::Vectorize ||
164 Option == LoopHintAttr::Interleave ||
165 Option == LoopHintAttr::Unroll ||
166 Option == LoopHintAttr::Distribute ||
167 Option == LoopHintAttr::PipelineDisabled) {
168 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
169 if (StateLoc->Ident->isStr("disable"))
170 State = LoopHintAttr::Disable;
171 else if (StateLoc->Ident->isStr("assume_safety"))
172 State = LoopHintAttr::AssumeSafety;
173 else if (StateLoc->Ident->isStr("full"))
174 State = LoopHintAttr::Full;
175 else if (StateLoc->Ident->isStr("enable"))
176 State = LoopHintAttr::Enable;
178 llvm_unreachable("bad loop hint argument");
180 llvm_unreachable("bad loop hint");
183 return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State,
184 ValueExpr, A.getRange());
188 CheckForIncompatibleAttributes(Sema &S,
189 const SmallVectorImpl<const Attr *> &Attrs) {
190 // There are 6 categories of loop hints attributes: vectorize, interleave,
191 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
192 // come in two variants: a state form and a numeric form. The state form
193 // selectively defaults/enables/disables the transformation for the loop
194 // (for unroll, default indicates full unrolling rather than enabling the
195 // transformation). The numeric form form provides an integer hint (for
196 // example, unroll count) to the transformer. The following array accumulates
197 // the hints encountered while iterating through the attributes to check for
200 const LoopHintAttr *StateAttr;
201 const LoopHintAttr *NumericAttr;
202 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
203 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}};
205 for (const auto *I : Attrs) {
206 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
208 // Skip non loop hint attributes
212 LoopHintAttr::OptionType Option = LH->getOption();
222 case LoopHintAttr::Vectorize:
223 case LoopHintAttr::VectorizeWidth:
224 Category = Vectorize;
226 case LoopHintAttr::Interleave:
227 case LoopHintAttr::InterleaveCount:
228 Category = Interleave;
230 case LoopHintAttr::Unroll:
231 case LoopHintAttr::UnrollCount:
234 case LoopHintAttr::UnrollAndJam:
235 case LoopHintAttr::UnrollAndJamCount:
236 Category = UnrollAndJam;
238 case LoopHintAttr::Distribute:
239 // Perform the check for duplicated 'distribute' hints.
240 Category = Distribute;
242 case LoopHintAttr::PipelineDisabled:
243 case LoopHintAttr::PipelineInitiationInterval:
248 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
249 auto &CategoryState = HintAttrs[Category];
250 const LoopHintAttr *PrevAttr;
251 if (Option == LoopHintAttr::Vectorize ||
252 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
253 Option == LoopHintAttr::UnrollAndJam ||
254 Option == LoopHintAttr::PipelineDisabled ||
255 Option == LoopHintAttr::Distribute) {
256 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
257 PrevAttr = CategoryState.StateAttr;
258 CategoryState.StateAttr = LH;
260 // Numeric hint. For example, vectorize_width(8).
261 PrevAttr = CategoryState.NumericAttr;
262 CategoryState.NumericAttr = LH;
265 PrintingPolicy Policy(S.Context.getLangOpts());
266 SourceLocation OptionLoc = LH->getRange().getBegin();
268 // Cannot specify same type of attribute twice.
269 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
270 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
271 << LH->getDiagnosticName(Policy);
273 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
274 (Category == Unroll || Category == UnrollAndJam ||
275 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
276 // Disable hints are not compatible with numeric hints of the same
277 // category. As a special case, numeric unroll hints are also not
278 // compatible with enable or full form of the unroll pragma because these
279 // directives indicate full unrolling.
280 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
281 << /*Duplicate=*/false
282 << CategoryState.StateAttr->getDiagnosticName(Policy)
283 << CategoryState.NumericAttr->getDiagnosticName(Policy);
288 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
290 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
291 // useful for OpenCL 1.x too and doesn't require HW support.
292 // opencl_unroll_hint can have 0 arguments (compiler
293 // determines unrolling factor) or 1 argument (the unroll factor provided
296 unsigned NumArgs = A.getNumArgs();
299 S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1;
303 unsigned UnrollFactor = 0;
306 Expr *E = A.getArgAsExpr(0);
307 llvm::APSInt ArgVal(32);
309 if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
310 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
311 << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
315 int Val = ArgVal.getSExtValue();
318 S.Diag(A.getRange().getBegin(),
319 diag::err_attribute_requires_positive_integer)
320 << A << /* positive */ 0;
326 return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
329 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
331 switch (A.getKind()) {
332 case ParsedAttr::UnknownAttribute:
333 S.Diag(A.getLoc(), A.isDeclspecAttribute()
334 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
335 : (unsigned)diag::warn_unknown_attribute_ignored)
338 case ParsedAttr::AT_FallThrough:
339 return handleFallThroughAttr(S, St, A, Range);
340 case ParsedAttr::AT_LoopHint:
341 return handleLoopHintAttr(S, St, A, Range);
342 case ParsedAttr::AT_OpenCLUnrollHint:
343 return handleOpenCLUnrollHint(S, St, A, Range);
344 case ParsedAttr::AT_Suppress:
345 return handleSuppressAttr(S, St, A, Range);
347 // if we're here, then we parsed a known attribute, but didn't recognize
348 // it as a statement attribute => it is declaration attribute
349 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
350 << A.getName() << St->getBeginLoc();
355 StmtResult Sema::ProcessStmtAttributes(Stmt *S,
356 const ParsedAttributesView &AttrList,
358 SmallVector<const Attr*, 8> Attrs;
359 for (const ParsedAttr &AL : AttrList) {
360 if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range))
364 CheckForIncompatibleAttributes(*this, Attrs);
369 return ActOnAttributedStmt(Range.getBegin(), Attrs, S);