clang  8.0.0svn
SemaStmtAttr.cpp
Go to the documentation of this file.
1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements stmt-related attribute processing.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/AST/ASTContext.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "llvm/ADT/StringExtras.h"
21 
22 using namespace clang;
23 using namespace sema;
24 
25 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
26  SourceRange Range) {
27  FallThroughAttr Attr(A.getRange(), S.Context,
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)) {
34  S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
35  << FixItHint::CreateInsertion(L, ";");
36  }
37  return nullptr;
38  }
39  auto *FnScope = S.getCurFunction();
40  if (FnScope->SwitchStack.empty()) {
41  S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
42  return nullptr;
43  }
44 
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() &&
48  !A.getScopeName())
49  S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A.getName();
50 
51  FnScope->setHasFallthroughStmt();
52  return ::new (S.Context) auto(Attr);
53 }
54 
55 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
56  SourceRange Range) {
57  if (A.getNumArgs() < 1) {
58  S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
59  return nullptr;
60  }
61 
62  std::vector<StringRef> DiagnosticIdentifiers;
63  for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
64  StringRef RuleName;
65 
66  if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
67  return nullptr;
68 
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);
72  }
73 
74  return ::new (S.Context) SuppressAttr(
75  A.getRange(), S.Context, DiagnosticIdentifiers.data(),
76  DiagnosticIdentifiers.size(), A.getAttributeSpellingListIndex());
77 }
78 
79 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
80  SourceRange) {
81  IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
82  IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
83  IdentifierLoc *StateLoc = A.getArgAsIdent(2);
84  Expr *ValueExpr = A.getArgAsExpr(3);
85 
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) {
95  const char *Pragma =
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;
103  return nullptr;
104  }
105 
106  LoopHintAttr::Spelling Spelling =
107  LoopHintAttr::Spelling(A.getAttributeSpellingListIndex());
108  LoopHintAttr::OptionType Option;
109  LoopHintAttr::LoopHintState State;
110  if (PragmaNoUnroll) {
111  // #pragma nounroll
112  Option = LoopHintAttr::Unroll;
113  State = LoopHintAttr::Disable;
114  } else if (PragmaUnroll) {
115  if (ValueExpr) {
116  // #pragma unroll N
117  Option = LoopHintAttr::UnrollCount;
118  State = LoopHintAttr::Numeric;
119  } else {
120  // #pragma unroll
121  Option = LoopHintAttr::Unroll;
122  State = LoopHintAttr::Enable;
123  }
124  } else if (PragmaNoUnrollAndJam) {
125  // #pragma nounroll_and_jam
126  Option = LoopHintAttr::UnrollAndJam;
127  State = LoopHintAttr::Disable;
128  } else if (PragmaUnrollAndJam) {
129  if (ValueExpr) {
130  // #pragma unroll_and_jam N
131  Option = LoopHintAttr::UnrollAndJamCount;
132  State = LoopHintAttr::Numeric;
133  } else {
134  // #pragma unroll_and_jam
135  Option = LoopHintAttr::UnrollAndJam;
136  State = LoopHintAttr::Enable;
137  }
138  } else {
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()))
161  return nullptr;
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;
177  else
178  llvm_unreachable("bad loop hint argument");
179  } else
180  llvm_unreachable("bad loop hint");
181  }
182 
183  return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State,
184  ValueExpr, A.getRange());
185 }
186 
187 static void
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
198  // compatibility.
199  struct {
200  const LoopHintAttr *StateAttr;
201  const LoopHintAttr *NumericAttr;
202  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
203  {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}};
204 
205  for (const auto *I : Attrs) {
206  const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
207 
208  // Skip non loop hint attributes
209  if (!LH)
210  continue;
211 
212  LoopHintAttr::OptionType Option = LH->getOption();
213  enum {
214  Vectorize,
215  Interleave,
216  Unroll,
217  UnrollAndJam,
218  Distribute,
219  Pipeline
220  } Category;
221  switch (Option) {
222  case LoopHintAttr::Vectorize:
223  case LoopHintAttr::VectorizeWidth:
224  Category = Vectorize;
225  break;
226  case LoopHintAttr::Interleave:
227  case LoopHintAttr::InterleaveCount:
228  Category = Interleave;
229  break;
230  case LoopHintAttr::Unroll:
231  case LoopHintAttr::UnrollCount:
232  Category = Unroll;
233  break;
234  case LoopHintAttr::UnrollAndJam:
235  case LoopHintAttr::UnrollAndJamCount:
236  Category = UnrollAndJam;
237  break;
238  case LoopHintAttr::Distribute:
239  // Perform the check for duplicated 'distribute' hints.
240  Category = Distribute;
241  break;
242  case LoopHintAttr::PipelineDisabled:
243  case LoopHintAttr::PipelineInitiationInterval:
244  Category = Pipeline;
245  break;
246  };
247 
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;
259  } else {
260  // Numeric hint. For example, vectorize_width(8).
261  PrevAttr = CategoryState.NumericAttr;
262  CategoryState.NumericAttr = LH;
263  }
264 
265  PrintingPolicy Policy(S.Context.getLangOpts());
266  SourceLocation OptionLoc = LH->getRange().getBegin();
267  if (PrevAttr)
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);
272 
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);
284  }
285  }
286 }
287 
288 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
289  SourceRange Range) {
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
294  // by the user).
295 
296  unsigned NumArgs = A.getNumArgs();
297 
298  if (NumArgs > 1) {
299  S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1;
300  return nullptr;
301  }
302 
303  unsigned UnrollFactor = 0;
304 
305  if (NumArgs == 1) {
306  Expr *E = A.getArgAsExpr(0);
307  llvm::APSInt ArgVal(32);
308 
309  if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
310  S.Diag(A.getLoc(), diag::err_attribute_argument_type)
312  return nullptr;
313  }
314 
315  int Val = ArgVal.getSExtValue();
316 
317  if (Val <= 0) {
318  S.Diag(A.getRange().getBegin(),
319  diag::err_attribute_requires_positive_integer)
320  << A << /* positive */ 0;
321  return nullptr;
322  }
323  UnrollFactor = Val;
324  }
325 
326  return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
327 }
328 
329 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
330  SourceRange Range) {
331  switch (A.getKind()) {
333  S.Diag(A.getLoc(), A.isDeclspecAttribute()
334  ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
335  : (unsigned)diag::warn_unknown_attribute_ignored)
336  << A.getName();
337  return nullptr;
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);
346  default:
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();
351  return nullptr;
352  }
353 }
354 
356  const ParsedAttributesView &AttrList,
357  SourceRange Range) {
359  for (const ParsedAttr &AL : AttrList) {
360  if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range))
361  Attrs.push_back(a);
362  }
363 
364  CheckForIncompatibleAttributes(*this, Attrs);
365 
366  if (Attrs.empty())
367  return S;
368 
369  return ActOnAttributedStmt(Range.getBegin(), Attrs, S);
370 }
Defines the clang::ASTContext interface.
const char * getSpelling() const
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3248
bool isDeclspecAttribute() const
Definition: ParsedAttr.h:403
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:1308
IdentifierInfo * Ident
Definition: ParsedAttr.h:97
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:460
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
static Attr * handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
bool isCXX11Attribute() const
Definition: ParsedAttr.h:406
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
unsigned getAttributeSpellingListIndex() const
Get an index into the attribute spelling list defined in Attr.td.
Definition: ParsedAttr.cpp:157
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:288
int Category
Definition: Format.cpp:1632
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:448
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
static Attr * handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
This represents one expression.
Definition: Expr.h:106
Kind getKind() const
Definition: ParsedAttr.h:443
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
SourceLocation getEnd() const
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:95
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:157
Encodes a location in the source.
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
SourceRange getRange() const
Definition: ParsedAttr.h:380
StringRef getName() const
Return the actual identifier string.
Dataflow Directional Tag Classes.
StmtClass getStmtClass() const
Definition: Stmt.h:1029
SourceLocation getLoc() const
Definition: ParsedAttr.h:379
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:378
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:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
static Attr * handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
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:324
SourceLocation getBegin() const
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:468
static Attr * handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange)
Attr - This represents one attribute.
Definition: Attr.h:44
IdentifierInfo * getScopeName() const
Definition: ParsedAttr.h:383