Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaStmtAttr.cpp
Line
Count
Source (jump to first uncovered line)
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
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/EvaluatedExprVisitor.h"
15
#include "clang/Basic/SourceManager.h"
16
#include "clang/Basic/TargetInfo.h"
17
#include "clang/Sema/DelayedDiagnostic.h"
18
#include "clang/Sema/Lookup.h"
19
#include "clang/Sema/ScopeInfo.h"
20
#include "clang/Sema/SemaInternal.h"
21
#include "llvm/ADT/StringExtras.h"
22
23
using namespace clang;
24
using namespace sema;
25
26
static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
27
1.00k
                                   SourceRange Range) {
28
1.00k
  FallThroughAttr Attr(S.Context, A);
29
1.00k
  if (isa<SwitchCase>(St)) {
30
1
    S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
31
1
        << A << St->getBeginLoc();
32
1
    SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
33
1
    S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
34
1
        << FixItHint::CreateInsertion(L, ";");
35
1
    return nullptr;
36
1
  }
37
1.00k
  auto *FnScope = S.getCurFunction();
38
1.00k
  if (FnScope->SwitchStack.empty()) {
39
1
    S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
40
1
    return nullptr;
41
1
  }
42
43
  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
44
  // about using it as an extension.
45
1.00k
  if (!S.getLangOpts().CPlusPlus17 && 
A.isCXX11Attribute()972
&&
46
1.00k
      
!A.getScopeName()949
)
47
8
    S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
48
49
1.00k
  FnScope->setHasFallthroughStmt();
50
1.00k
  return ::new (S.Context) FallThroughAttr(S.Context, A);
51
1.00k
}
52
53
static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
54
5
                                SourceRange Range) {
55
5
  std::vector<StringRef> DiagnosticIdentifiers;
56
11
  for (unsigned I = 0, E = A.getNumArgs(); I != E; 
++I6
) {
57
6
    StringRef RuleName;
58
59
6
    if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
60
0
      return nullptr;
61
62
    // FIXME: Warn if the rule name is unknown. This is tricky because only
63
    // clang-tidy knows about available rules.
64
6
    DiagnosticIdentifiers.push_back(RuleName);
65
6
  }
66
67
5
  return ::new (S.Context) SuppressAttr(
68
5
      S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
69
5
}
70
71
static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
72
352
                                SourceRange) {
73
352
  IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
74
352
  IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
75
352
  IdentifierLoc *StateLoc = A.getArgAsIdent(2);
76
352
  Expr *ValueExpr = A.getArgAsExpr(3);
77
78
352
  StringRef PragmaName =
79
352
      llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
80
352
          .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
81
352
                 PragmaNameLoc->Ident->getName())
82
352
          .Default("clang loop");
83
84
  // This could be handled automatically by adding a Subjects definition in
85
  // Attr.td, but that would make the diagnostic behavior worse in this case
86
  // because the user spells this attribute as a pragma.
87
352
  if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) {
88
10
    std::string Pragma = "#pragma " + std::string(PragmaName);
89
10
    S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
90
10
    return nullptr;
91
10
  }
92
93
342
  LoopHintAttr::OptionType Option;
94
342
  LoopHintAttr::LoopHintState State;
95
96
342
  auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
97
342
                                    LoopHintAttr::LoopHintState S) {
98
79
    Option = O;
99
79
    State = S;
100
79
  };
101
102
342
  if (PragmaName == "nounroll") {
103
10
    SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
104
332
  } else if (PragmaName == "unroll") {
105
    // #pragma unroll N
106
56
    if (ValueExpr)
107
43
      SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
108
13
    else
109
13
      SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
110
276
  } else if (PragmaName == "nounroll_and_jam") {
111
5
    SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
112
271
  } else if (PragmaName == "unroll_and_jam") {
113
    // #pragma unroll_and_jam N
114
8
    if (ValueExpr)
115
5
      SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
116
3
    else
117
3
      SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
118
263
  } else {
119
    // #pragma clang loop ...
120
263
    assert(OptionLoc && OptionLoc->Ident &&
121
263
           "Attribute must have valid option info.");
122
0
    Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
123
263
                 OptionLoc->Ident->getName())
124
263
                 .Case("vectorize", LoopHintAttr::Vectorize)
125
263
                 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
126
263
                 .Case("interleave", LoopHintAttr::Interleave)
127
263
                 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
128
263
                 .Case("interleave_count", LoopHintAttr::InterleaveCount)
129
263
                 .Case("unroll", LoopHintAttr::Unroll)
130
263
                 .Case("unroll_count", LoopHintAttr::UnrollCount)
131
263
                 .Case("pipeline", LoopHintAttr::PipelineDisabled)
132
263
                 .Case("pipeline_initiation_interval",
133
263
                       LoopHintAttr::PipelineInitiationInterval)
134
263
                 .Case("distribute", LoopHintAttr::Distribute)
135
263
                 .Default(LoopHintAttr::Vectorize);
136
263
    if (Option == LoopHintAttr::VectorizeWidth) {
137
52
      assert((ValueExpr || (StateLoc && StateLoc->Ident)) &&
138
52
             "Attribute must have a valid value expression or argument.");
139
52
      if (ValueExpr && 
S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())46
)
140
0
        return nullptr;
141
52
      if (StateLoc && 
StateLoc->Ident12
&&
StateLoc->Ident->isStr("scalable")12
)
142
7
        State = LoopHintAttr::ScalableWidth;
143
45
      else
144
45
        State = LoopHintAttr::FixedWidth;
145
211
    } else if (Option == LoopHintAttr::InterleaveCount ||
146
211
               
Option == LoopHintAttr::UnrollCount178
||
147
211
               
Option == LoopHintAttr::PipelineInitiationInterval160
) {
148
56
      assert(ValueExpr && "Attribute must have a valid value expression.");
149
56
      if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
150
0
        return nullptr;
151
56
      State = LoopHintAttr::Numeric;
152
155
    } else if (Option == LoopHintAttr::Vectorize ||
153
155
               
Option == LoopHintAttr::Interleave102
||
154
155
               
Option == LoopHintAttr::VectorizePredicate76
||
155
155
               
Option == LoopHintAttr::Unroll59
||
156
155
               
Option == LoopHintAttr::Distribute25
||
157
155
               
Option == LoopHintAttr::PipelineDisabled4
) {
158
155
      assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
159
155
      if (StateLoc->Ident->isStr("disable"))
160
76
        State = LoopHintAttr::Disable;
161
79
      else if (StateLoc->Ident->isStr("assume_safety"))
162
19
        State = LoopHintAttr::AssumeSafety;
163
60
      else if (StateLoc->Ident->isStr("full"))
164
10
        State = LoopHintAttr::Full;
165
50
      else if (StateLoc->Ident->isStr("enable"))
166
50
        State = LoopHintAttr::Enable;
167
0
      else
168
0
        llvm_unreachable("bad loop hint argument");
169
155
    } else
170
0
      llvm_unreachable("bad loop hint");
171
263
  }
172
173
342
  return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
174
342
}
175
176
namespace {
177
class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
178
  bool FoundCallExpr = false;
179
180
public:
181
  typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited;
182
183
23
  CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
184
185
23
  bool foundCallExpr() { return FoundCallExpr; }
186
187
20
  void VisitCallExpr(const CallExpr *E) { FoundCallExpr = true; }
188
1
  void VisitAsmStmt(const AsmStmt *S) { FoundCallExpr = true; }
189
190
23
  void Visit(const Stmt *St) {
191
23
    if (!St)
192
0
      return;
193
23
    ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St);
194
23
  }
195
};
196
} // namespace
197
198
static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
199
23
                               SourceRange Range) {
200
23
  NoMergeAttr NMA(S.Context, A);
201
23
  CallExprFinder CEF(S, St);
202
203
23
  if (!CEF.foundCallExpr()) {
204
6
    S.Diag(St->getBeginLoc(), diag::warn_nomerge_attribute_ignored_in_stmt)
205
6
        << NMA.getSpelling();
206
6
    return nullptr;
207
6
  }
208
209
17
  return ::new (S.Context) NoMergeAttr(S.Context, A);
210
23
}
211
212
static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
213
94
                                SourceRange Range) {
214
  // Validation is in Sema::ActOnAttributedStmt().
215
94
  return ::new (S.Context) MustTailAttr(S.Context, A);
216
94
}
217
218
static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
219
54
                          SourceRange Range) {
220
221
54
  if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && 
!A.getScopeName()49
)
222
49
    S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
223
224
54
  return ::new (S.Context) LikelyAttr(S.Context, A);
225
54
}
226
227
static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
228
77
                            SourceRange Range) {
229
230
77
  if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && 
!A.getScopeName()69
)
231
69
    S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
232
233
77
  return ::new (S.Context) UnlikelyAttr(S.Context, A);
234
77
}
235
236
#define WANT_STMT_MERGE_LOGIC
237
#include "clang/Sema/AttrParsedAttrImpl.inc"
238
#undef WANT_STMT_MERGE_LOGIC
239
240
static void
241
CheckForIncompatibleAttributes(Sema &S,
242
5.16k
                               const SmallVectorImpl<const Attr *> &Attrs) {
243
  // The vast majority of attributed statements will only have one attribute
244
  // on them, so skip all of the checking in the common case.
245
5.16k
  if (Attrs.size() < 2)
246
5.07k
    return;
247
248
  // First, check for the easy cases that are table-generated for us.
249
86
  if (!DiagnoseMutualExclusions(S, Attrs))
250
2
    return;
251
252
  // There are 6 categories of loop hints attributes: vectorize, interleave,
253
  // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
254
  // come in two variants: a state form and a numeric form.  The state form
255
  // selectively defaults/enables/disables the transformation for the loop
256
  // (for unroll, default indicates full unrolling rather than enabling the
257
  // transformation). The numeric form form provides an integer hint (for
258
  // example, unroll count) to the transformer. The following array accumulates
259
  // the hints encountered while iterating through the attributes to check for
260
  // compatibility.
261
84
  struct {
262
84
    const LoopHintAttr *StateAttr;
263
84
    const LoopHintAttr *NumericAttr;
264
84
  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
265
84
                   {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
266
84
                   {nullptr, nullptr}};
267
268
246
  for (const auto *I : Attrs) {
269
246
    const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
270
271
    // Skip non loop hint attributes
272
246
    if (!LH)
273
12
      continue;
274
275
234
    LoopHintAttr::OptionType Option = LH->getOption();
276
234
    enum {
277
234
      Vectorize,
278
234
      Interleave,
279
234
      Unroll,
280
234
      UnrollAndJam,
281
234
      Distribute,
282
234
      Pipeline,
283
234
      VectorizePredicate
284
234
    } Category;
285
234
    switch (Option) {
286
36
    case LoopHintAttr::Vectorize:
287
71
    case LoopHintAttr::VectorizeWidth:
288
71
      Category = Vectorize;
289
71
      break;
290
26
    case LoopHintAttr::Interleave:
291
56
    case LoopHintAttr::InterleaveCount:
292
56
      Category = Interleave;
293
56
      break;
294
38
    case LoopHintAttr::Unroll:
295
64
    case LoopHintAttr::UnrollCount:
296
64
      Category = Unroll;
297
64
      break;
298
4
    case LoopHintAttr::UnrollAndJam:
299
5
    case LoopHintAttr::UnrollAndJamCount:
300
5
      Category = UnrollAndJam;
301
5
      break;
302
18
    case LoopHintAttr::Distribute:
303
      // Perform the check for duplicated 'distribute' hints.
304
18
      Category = Distribute;
305
18
      break;
306
1
    case LoopHintAttr::PipelineDisabled:
307
4
    case LoopHintAttr::PipelineInitiationInterval:
308
4
      Category = Pipeline;
309
4
      break;
310
16
    case LoopHintAttr::VectorizePredicate:
311
16
      Category = VectorizePredicate;
312
16
      break;
313
234
    };
314
315
234
    assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
316
0
    auto &CategoryState = HintAttrs[Category];
317
234
    const LoopHintAttr *PrevAttr;
318
234
    if (Option == LoopHintAttr::Vectorize ||
319
234
        
Option == LoopHintAttr::Interleave198
||
Option == LoopHintAttr::Unroll172
||
320
234
        
Option == LoopHintAttr::UnrollAndJam134
||
321
234
        
Option == LoopHintAttr::VectorizePredicate130
||
322
234
        
Option == LoopHintAttr::PipelineDisabled114
||
323
234
        
Option == LoopHintAttr::Distribute113
) {
324
      // Enable|Disable|AssumeSafety hint.  For example, vectorize(enable).
325
139
      PrevAttr = CategoryState.StateAttr;
326
139
      CategoryState.StateAttr = LH;
327
139
    } else {
328
      // Numeric hint.  For example, vectorize_width(8).
329
95
      PrevAttr = CategoryState.NumericAttr;
330
95
      CategoryState.NumericAttr = LH;
331
95
    }
332
333
234
    PrintingPolicy Policy(S.Context.getLangOpts());
334
234
    SourceLocation OptionLoc = LH->getRange().getBegin();
335
234
    if (PrevAttr)
336
      // Cannot specify same type of attribute twice.
337
14
      S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
338
14
          << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
339
14
          << LH->getDiagnosticName(Policy);
340
341
234
    if (CategoryState.StateAttr && 
CategoryState.NumericAttr148
&&
342
234
        
(18
Category == Unroll18
||
Category == UnrollAndJam10
||
343
18
         
CategoryState.StateAttr->getState() == LoopHintAttr::Disable9
)) {
344
      // Disable hints are not compatible with numeric hints of the same
345
      // category.  As a special case, numeric unroll hints are also not
346
      // compatible with enable or full form of the unroll pragma because these
347
      // directives indicate full unrolling.
348
14
      S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
349
14
          << /*Duplicate=*/false
350
14
          << CategoryState.StateAttr->getDiagnosticName(Policy)
351
14
          << CategoryState.NumericAttr->getDiagnosticName(Policy);
352
14
    }
353
234
  }
354
84
}
355
356
static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
357
21
                                    SourceRange Range) {
358
  // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
359
  // useful for OpenCL 1.x too and doesn't require HW support.
360
  // opencl_unroll_hint can have 0 arguments (compiler
361
  // determines unrolling factor) or 1 argument (the unroll factor provided
362
  // by the user).
363
21
  unsigned UnrollFactor = 0;
364
21
  if (A.getNumArgs() == 1) {
365
15
    Expr *E = A.getArgAsExpr(0);
366
15
    Optional<llvm::APSInt> ArgVal;
367
368
15
    if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
369
1
      S.Diag(A.getLoc(), diag::err_attribute_argument_type)
370
1
          << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
371
1
      return nullptr;
372
1
    }
373
374
14
    int Val = ArgVal->getSExtValue();
375
14
    if (Val <= 0) {
376
1
      S.Diag(A.getRange().getBegin(),
377
1
             diag::err_attribute_requires_positive_integer)
378
1
          << A << /* positive */ 0;
379
1
      return nullptr;
380
1
    }
381
13
    UnrollFactor = static_cast<unsigned>(Val);
382
13
  }
383
384
19
  return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
385
21
}
386
387
static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
388
1.72k
                                  SourceRange Range) {
389
1.72k
  if (A.isInvalid() || 
A.getKind() == ParsedAttr::IgnoredAttribute1.72k
)
390
2
    return nullptr;
391
392
  // Unknown attributes are automatically warned on. Target-specific attributes
393
  // which do not apply to the current target architecture are treated as
394
  // though they were unknown attributes.
395
1.72k
  const TargetInfo *Aux = S.Context.getAuxTargetInfo();
396
1.72k
  if (A.getKind() == ParsedAttr::UnknownAttribute ||
397
1.72k
      
!(1.69k
A.existsInTarget(S.Context.getTargetInfo())1.69k
||
398
1.69k
        
(0
S.Context.getLangOpts().SYCLIsDevice0
&&
Aux0
&&
399
32
         
A.existsInTarget(*Aux)0
))) {
400
32
    S.Diag(A.getLoc(), A.isDeclspecAttribute()
401
32
                           ? 
(unsigned)diag::warn_unhandled_ms_attribute_ignored0
402
32
                           : (unsigned)diag::warn_unknown_attribute_ignored)
403
32
        << A << A.getRange();
404
32
    return nullptr;
405
32
  }
406
407
1.69k
  if (S.checkCommonAttributeFeatures(St, A))
408
52
    return nullptr;
409
410
1.63k
  switch (A.getKind()) {
411
1.00k
  case ParsedAttr::AT_FallThrough:
412
1.00k
    return handleFallThroughAttr(S, St, A, Range);
413
352
  case ParsedAttr::AT_LoopHint:
414
352
    return handleLoopHintAttr(S, St, A, Range);
415
21
  case ParsedAttr::AT_OpenCLUnrollHint:
416
21
    return handleOpenCLUnrollHint(S, St, A, Range);
417
5
  case ParsedAttr::AT_Suppress:
418
5
    return handleSuppressAttr(S, St, A, Range);
419
23
  case ParsedAttr::AT_NoMerge:
420
23
    return handleNoMergeAttr(S, St, A, Range);
421
94
  case ParsedAttr::AT_MustTail:
422
94
    return handleMustTailAttr(S, St, A, Range);
423
54
  case ParsedAttr::AT_Likely:
424
54
    return handleLikely(S, St, A, Range);
425
77
  case ParsedAttr::AT_Unlikely:
426
77
    return handleUnlikely(S, St, A, Range);
427
8
  default:
428
    // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
429
    // declaration attribute is not written on a statement, but this code is
430
    // needed for attributes in Attr.td that do not list any subjects.
431
8
    S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
432
8
        << A << St->getBeginLoc();
433
8
    return nullptr;
434
1.63k
  }
435
1.63k
}
436
437
void Sema::ProcessStmtAttributes(Stmt *S,
438
                                 const ParsedAttributesWithRange &InAttrs,
439
5.16k
                                 SmallVectorImpl<const Attr *> &OutAttrs) {
440
5.16k
  for (const ParsedAttr &AL : InAttrs) {
441
1.72k
    if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
442
1.61k
      OutAttrs.push_back(A);
443
1.72k
  }
444
445
5.16k
  CheckForIncompatibleAttributes(*this, OutAttrs);
446
5.16k
}