clang  9.0.0
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 
14 #include "clang/AST/ASTContext.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "llvm/ADT/StringExtras.h"
20 
21 using namespace clang;
22 using namespace sema;
23 
24 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
25  SourceRange Range) {
26  FallThroughAttr Attr(A.getRange(), S.Context,
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)) {
33  S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
34  << FixItHint::CreateInsertion(L, ";");
35  }
36  return nullptr;
37  }
38  auto *FnScope = S.getCurFunction();
39  if (FnScope->SwitchStack.empty()) {
40  S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
41  return nullptr;
42  }
43 
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() &&
47  !A.getScopeName())
48  S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A.getName();
49 
50  FnScope->setHasFallthroughStmt();
51  return ::new (S.Context) auto(Attr);
52 }
53 
54 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
55  SourceRange Range) {
56  if (A.getNumArgs() < 1) {
57  S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
58  return nullptr;
59  }
60 
61  std::vector<StringRef> DiagnosticIdentifiers;
62  for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
63  StringRef RuleName;
64 
65  if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
66  return nullptr;
67 
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);
71  }
72 
73  return ::new (S.Context) SuppressAttr(
74  A.getRange(), S.Context, DiagnosticIdentifiers.data(),
75  DiagnosticIdentifiers.size(), A.getAttributeSpellingListIndex());
76 }
77 
78 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
79  SourceRange) {
80  IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
81  IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
82  IdentifierLoc *StateLoc = A.getArgAsIdent(2);
83  Expr *ValueExpr = A.getArgAsExpr(3);
84 
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");
90 
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;
97  return nullptr;
98  }
99 
100  LoopHintAttr::Spelling Spelling =
101  LoopHintAttr::Spelling(A.getAttributeSpellingListIndex());
102  LoopHintAttr::OptionType Option;
103  LoopHintAttr::LoopHintState State;
104 
105  auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
106  LoopHintAttr::LoopHintState S) {
107  Option = O;
108  State = S;
109  };
110 
111  if (PragmaName == "nounroll") {
112  SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
113  } else if (PragmaName == "unroll") {
114  // #pragma unroll N
115  if (ValueExpr)
116  SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
117  else
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
123  if (ValueExpr)
124  SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
125  else
126  SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
127  } else {
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()))
150  return nullptr;
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;
166  else
167  llvm_unreachable("bad loop hint argument");
168  } else
169  llvm_unreachable("bad loop hint");
170  }
171 
172  return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State,
173  ValueExpr, A.getRange());
174 }
175 
176 static void
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
187  // compatibility.
188  struct {
189  const LoopHintAttr *StateAttr;
190  const LoopHintAttr *NumericAttr;
191  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
192  {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}};
193 
194  for (const auto *I : Attrs) {
195  const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
196 
197  // Skip non loop hint attributes
198  if (!LH)
199  continue;
200 
201  LoopHintAttr::OptionType Option = LH->getOption();
202  enum {
203  Vectorize,
204  Interleave,
205  Unroll,
206  UnrollAndJam,
207  Distribute,
208  Pipeline
209  } Category;
210  switch (Option) {
211  case LoopHintAttr::Vectorize:
212  case LoopHintAttr::VectorizeWidth:
213  Category = Vectorize;
214  break;
215  case LoopHintAttr::Interleave:
216  case LoopHintAttr::InterleaveCount:
217  Category = Interleave;
218  break;
219  case LoopHintAttr::Unroll:
220  case LoopHintAttr::UnrollCount:
221  Category = Unroll;
222  break;
223  case LoopHintAttr::UnrollAndJam:
224  case LoopHintAttr::UnrollAndJamCount:
225  Category = UnrollAndJam;
226  break;
227  case LoopHintAttr::Distribute:
228  // Perform the check for duplicated 'distribute' hints.
229  Category = Distribute;
230  break;
231  case LoopHintAttr::PipelineDisabled:
232  case LoopHintAttr::PipelineInitiationInterval:
233  Category = Pipeline;
234  break;
235  };
236 
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;
248  } else {
249  // Numeric hint. For example, vectorize_width(8).
250  PrevAttr = CategoryState.NumericAttr;
251  CategoryState.NumericAttr = LH;
252  }
253 
254  PrintingPolicy Policy(S.Context.getLangOpts());
255  SourceLocation OptionLoc = LH->getRange().getBegin();
256  if (PrevAttr)
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);
261 
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);
273  }
274  }
275 }
276 
277 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
278  SourceRange Range) {
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
283  // by the user).
284 
285  unsigned NumArgs = A.getNumArgs();
286 
287  if (NumArgs > 1) {
288  S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1;
289  return nullptr;
290  }
291 
292  unsigned UnrollFactor = 0;
293 
294  if (NumArgs == 1) {
295  Expr *E = A.getArgAsExpr(0);
296  llvm::APSInt ArgVal(32);
297 
298  if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
299  S.Diag(A.getLoc(), diag::err_attribute_argument_type)
301  return nullptr;
302  }
303 
304  int Val = ArgVal.getSExtValue();
305 
306  if (Val <= 0) {
307  S.Diag(A.getRange().getBegin(),
308  diag::err_attribute_requires_positive_integer)
309  << A << /* positive */ 0;
310  return nullptr;
311  }
312  UnrollFactor = Val;
313  }
314 
315  return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
316 }
317 
318 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
319  SourceRange Range) {
320  switch (A.getKind()) {
322  S.Diag(A.getLoc(), A.isDeclspecAttribute()
323  ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
324  : (unsigned)diag::warn_unknown_attribute_ignored)
325  << A.getName();
326  return nullptr;
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);
335  default:
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();
340  return nullptr;
341  }
342 }
343 
345  const ParsedAttributesView &AttrList,
346  SourceRange Range) {
348  for (const ParsedAttr &AL : AttrList) {
349  if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range))
350  Attrs.push_back(a);
351  }
352 
353  CheckForIncompatibleAttributes(*this, Attrs);
354 
355  if (Attrs.empty())
356  return S;
357 
358  return ActOnAttributedStmt(Range.getBegin(), Attrs, S);
359 }
Defines the clang::ASTContext interface.
const char * getSpelling() const
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3347
bool isDeclspecAttribute() const
Definition: ParsedAttr.h:408
static void CheckForIncompatibleAttributes(Sema &S, const SmallVectorImpl< const Attr *> &Attrs)
Stmt - This represents one statement.
Definition: Stmt.h:66
Defines the SourceManager interface.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1362
IdentifierInfo * Ident
Definition: ParsedAttr.h:96
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:470
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:47
static Attr * handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
bool isCXX11Attribute() const
Definition: ParsedAttr.h:411
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:37
unsigned getAttributeSpellingListIndex() const
Get an index into the attribute spelling list defined in Attr.td.
Definition: ParsedAttr.cpp:156
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
LineState State
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:263
int Category
Definition: Format.cpp:1714
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:458
const LangOptions & getLangOpts() const
Definition: Sema.h:1285
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:328
static Attr * handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
This represents one expression.
Definition: Expr.h:108
Kind getKind() const
Definition: ParsedAttr.h:453
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
SourceLocation getEnd() const
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:94
static Attr * ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
Encodes a location in the source.
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:116
SourceRange getRange() const
Definition: ParsedAttr.h:385
StringRef getName() const
Return the actual identifier string.
Dataflow Directional Tag Classes.
StmtClass getStmtClass() const
Definition: Stmt.h:1087
SourceLocation getLoc() const
Definition: ParsedAttr.h:384
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
IdentifierInfo * getName() const
Definition: ParsedAttr.h:383
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:92
StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range)
Stmt attributes - this routine is the top level dispatcher.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1439
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:251
static Attr * handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
a
Definition: emmintrin.h:320
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument ArgNum of Attr is a ASCII string literal.
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:374
SourceLocation getBegin() const
const LangOptions & getLangOpts() const
Definition: ASTContext.h:710
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:478
static Attr * handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange)
Attr - This represents one attribute.
Definition: Attr.h:43
IdentifierInfo * getScopeName() const
Definition: ParsedAttr.h:388