]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaStmtAttr.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaStmtAttr.cpp
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
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"
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,
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, ";");
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
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
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)
311           << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
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()) {
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)
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
355 StmtResult Sema::ProcessStmtAttributes(Stmt *S,
356                                        const ParsedAttributesView &AttrList,
357                                        SourceRange Range) {
358   SmallVector<const Attr*, 8> Attrs;
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 }