Coverage Report

Created: 2018-12-09 11:54

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Sema/ScopeInfo.h
Line
Count
Source (jump to first uncovered line)
1
//===- ScopeInfo.h - Information about a semantic context -------*- C++ -*-===//
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 defines FunctionScopeInfo and its subclasses, which contain
11
// information about a single function, block, lambda, or method body.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
16
#define LLVM_CLANG_SEMA_SCOPEINFO_H
17
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/Type.h"
20
#include "clang/Basic/CapturedStmt.h"
21
#include "clang/Basic/LLVM.h"
22
#include "clang/Basic/PartialDiagnostic.h"
23
#include "clang/Basic/SourceLocation.h"
24
#include "clang/Sema/CleanupInfo.h"
25
#include "llvm/ADT/DenseMap.h"
26
#include "llvm/ADT/DenseMapInfo.h"
27
#include "llvm/ADT/MapVector.h"
28
#include "llvm/ADT/PointerIntPair.h"
29
#include "llvm/ADT/SmallPtrSet.h"
30
#include "llvm/ADT/SmallSet.h"
31
#include "llvm/ADT/SmallVector.h"
32
#include "llvm/ADT/StringRef.h"
33
#include "llvm/ADT/StringSwitch.h"
34
#include "llvm/ADT/TinyPtrVector.h"
35
#include "llvm/Support/Casting.h"
36
#include "llvm/Support/ErrorHandling.h"
37
#include <algorithm>
38
#include <cassert>
39
#include <utility>
40
41
namespace clang {
42
43
class BlockDecl;
44
class CapturedDecl;
45
class CXXMethodDecl;
46
class CXXRecordDecl;
47
class ImplicitParamDecl;
48
class NamedDecl;
49
class ObjCIvarRefExpr;
50
class ObjCMessageExpr;
51
class ObjCPropertyDecl;
52
class ObjCPropertyRefExpr;
53
class ParmVarDecl;
54
class RecordDecl;
55
class ReturnStmt;
56
class Scope;
57
class Stmt;
58
class SwitchStmt;
59
class TemplateParameterList;
60
class TemplateTypeParmDecl;
61
class VarDecl;
62
63
namespace sema {
64
65
/// Contains information about the compound statement currently being
66
/// parsed.
67
class CompoundScopeInfo {
68
public:
69
  /// Whether this compound stamement contains `for' or `while' loops
70
  /// with empty bodies.
71
  bool HasEmptyLoopBodies = false;
72
73
  /// Whether this compound statement corresponds to a GNU statement
74
  /// expression.
75
  bool IsStmtExpr;
76
77
4.20M
  CompoundScopeInfo(bool IsStmtExpr) : IsStmtExpr(IsStmtExpr) {}
78
79
13.6k
  void setHasEmptyLoopBodies() {
80
13.6k
    HasEmptyLoopBodies = true;
81
13.6k
  }
82
};
83
84
class PossiblyUnreachableDiag {
85
public:
86
  PartialDiagnostic PD;
87
  SourceLocation Loc;
88
  const Stmt *stmt;
89
90
  PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
91
                          const Stmt *stmt)
92
64.2k
      : PD(PD), Loc(Loc), stmt(stmt) {}
93
};
94
95
/// Retains information about a function, method, or block that is
96
/// currently being parsed.
97
class FunctionScopeInfo {
98
protected:
99
  enum ScopeKind {
100
    SK_Function,
101
    SK_Block,
102
    SK_Lambda,
103
    SK_CapturedRegion
104
  };
105
106
public:
107
  /// What kind of scope we are describing.
108
  ScopeKind Kind : 3;
109
110
  /// Whether this function contains a VLA, \@try, try, C++
111
  /// initializer, or anything else that can't be jumped past.
112
  bool HasBranchProtectedScope : 1;
113
114
  /// Whether this function contains any switches or direct gotos.
115
  bool HasBranchIntoScope : 1;
116
117
  /// Whether this function contains any indirect gotos.
118
  bool HasIndirectGoto : 1;
119
120
  /// Whether a statement was dropped because it was invalid.
121
  bool HasDroppedStmt : 1;
122
123
  /// True if current scope is for OpenMP declare reduction combiner.
124
  bool HasOMPDeclareReductionCombiner : 1;
125
126
  /// Whether there is a fallthrough statement in this function.
127
  bool HasFallthroughStmt : 1;
128
129
  /// Whether we make reference to a declaration that could be
130
  /// unavailable.
131
  bool HasPotentialAvailabilityViolations : 1;
132
133
  /// A flag that is set when parsing a method that must call super's
134
  /// implementation, such as \c -dealloc, \c -finalize, or any method marked
135
  /// with \c __attribute__((objc_requires_super)).
136
  bool ObjCShouldCallSuper : 1;
137
138
  /// True when this is a method marked as a designated initializer.
139
  bool ObjCIsDesignatedInit : 1;
140
141
  /// This starts true for a method marked as designated initializer and will
142
  /// be set to false if there is an invocation to a designated initializer of
143
  /// the super class.
144
  bool ObjCWarnForNoDesignatedInitChain : 1;
145
146
  /// True when this is an initializer method not marked as a designated
147
  /// initializer within a class that has at least one initializer marked as a
148
  /// designated initializer.
149
  bool ObjCIsSecondaryInit : 1;
150
151
  /// This starts true for a secondary initializer method and will be set to
152
  /// false if there is an invocation of an initializer on 'self'.
153
  bool ObjCWarnForNoInitDelegation : 1;
154
155
  /// True only when this function has not already built, or attempted
156
  /// to build, the initial and final coroutine suspend points
157
  bool NeedsCoroutineSuspends : 1;
158
159
  /// An enumeration represeting the kind of the first coroutine statement
160
  /// in the function. One of co_return, co_await, or co_yield.
161
  unsigned char FirstCoroutineStmtKind : 2;
162
163
  /// First coroutine statement in the current function.
164
  /// (ex co_return, co_await, co_yield)
165
  SourceLocation FirstCoroutineStmtLoc;
166
167
  /// First 'return' statement in the current function.
168
  SourceLocation FirstReturnLoc;
169
170
  /// First C++ 'try' statement in the current function.
171
  SourceLocation FirstCXXTryLoc;
172
173
  /// First SEH '__try' statement in the current function.
174
  SourceLocation FirstSEHTryLoc;
175
176
  /// Used to determine if errors occurred in this function or block.
177
  DiagnosticErrorTrap ErrorTrap;
178
179
  /// A SwitchStmt, along with a flag indicating if its list of case statements
180
  /// is incomplete (because we dropped an invalid one while parsing).
181
  using SwitchInfo = llvm::PointerIntPair<SwitchStmt*, 1, bool>;
182
183
  /// SwitchStack - This is the current set of active switch statements in the
184
  /// block.
185
  SmallVector<SwitchInfo, 8> SwitchStack;
186
187
  /// The list of return statements that occur within the function or
188
  /// block, if there is any chance of applying the named return value
189
  /// optimization, or if we need to infer a return type.
190
  SmallVector<ReturnStmt*, 4> Returns;
191
192
  /// The promise object for this coroutine, if any.
193
  VarDecl *CoroutinePromise = nullptr;
194
195
  /// A mapping between the coroutine function parameters that were moved
196
  /// to the coroutine frame, and their move statements.
197
  llvm::SmallMapVector<ParmVarDecl *, Stmt *, 4> CoroutineParameterMoves;
198
199
  /// The initial and final coroutine suspend points.
200
  std::pair<Stmt *, Stmt *> CoroutineSuspends;
201
202
  /// The stack of currently active compound stamement scopes in the
203
  /// function.
204
  SmallVector<CompoundScopeInfo, 4> CompoundScopes;
205
206
  /// The set of blocks that are introduced in this function.
207
  llvm::SmallPtrSet<const BlockDecl *, 1> Blocks;
208
209
  /// The set of __block variables that are introduced in this function.
210
  llvm::TinyPtrVector<VarDecl *> ByrefBlockVars;
211
212
  /// A list of PartialDiagnostics created but delayed within the
213
  /// current function scope.  These diagnostics are vetted for reachability
214
  /// prior to being emitted.
215
  SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
216
217
  /// A list of parameters which have the nonnull attribute and are
218
  /// modified in the function.
219
  llvm::SmallPtrSet<const ParmVarDecl *, 8> ModifiedNonNullParams;
220
221
public:
222
  /// Represents a simple identification of a weak object.
223
  ///
224
  /// Part of the implementation of -Wrepeated-use-of-weak.
225
  ///
226
  /// This is used to determine if two weak accesses refer to the same object.
227
  /// Here are some examples of how various accesses are "profiled":
228
  ///
229
  /// Access Expression |     "Base" Decl     |          "Property" Decl
230
  /// :---------------: | :-----------------: | :------------------------------:
231
  /// self.property     | self (VarDecl)      | property (ObjCPropertyDecl)
232
  /// self.implicitProp | self (VarDecl)      | -implicitProp (ObjCMethodDecl)
233
  /// self->ivar.prop   | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
234
  /// cxxObj.obj.prop   | obj (FieldDecl)     | prop (ObjCPropertyDecl)
235
  /// [self foo].prop   | 0 (unknown)         | prop (ObjCPropertyDecl)
236
  /// self.prop1.prop2  | prop1 (ObjCPropertyDecl)    | prop2 (ObjCPropertyDecl)
237
  /// MyClass.prop      | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
238
  /// MyClass.foo.prop  | +foo (ObjCMethodDecl)       | -prop (ObjCPropertyDecl)
239
  /// weakVar           | 0 (known)           | weakVar (VarDecl)
240
  /// self->weakIvar    | self (VarDecl)      | weakIvar (ObjCIvarDecl)
241
  ///
242
  /// Objects are identified with only two Decls to make it reasonably fast to
243
  /// compare them.
244
  class WeakObjectProfileTy {
245
    /// The base object decl, as described in the class documentation.
246
    ///
247
    /// The extra flag is "true" if the Base and Property are enough to uniquely
248
    /// identify the object in memory.
249
    ///
250
    /// \sa isExactProfile()
251
    using BaseInfoTy = llvm::PointerIntPair<const NamedDecl *, 1, bool>;
252
    BaseInfoTy Base;
253
254
    /// The "property" decl, as described in the class documentation.
255
    ///
256
    /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
257
    /// case of "implicit" properties (regular methods accessed via dot syntax).
258
    const NamedDecl *Property = nullptr;
259
260
    /// Used to find the proper base profile for a given base expression.
261
    static BaseInfoTy getBaseInfo(const Expr *BaseE);
262
263
    inline WeakObjectProfileTy();
264
    static inline WeakObjectProfileTy getSentinel();
265
266
  public:
267
    WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
268
    WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
269
    WeakObjectProfileTy(const DeclRefExpr *RE);
270
    WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
271
272
18
    const NamedDecl *getBase() const { return Base.getPointer(); }
273
84
    const NamedDecl *getProperty() const { return Property; }
274
275
    /// Returns true if the object base specifies a known object in memory,
276
    /// rather than, say, an instance variable or property of another object.
277
    ///
278
    /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
279
    /// considered an exact profile if \c foo is a local variable, even if
280
    /// another variable \c foo2 refers to the same object as \c foo.
281
    ///
282
    /// For increased precision, accesses with base variables that are
283
    /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
284
    /// be exact, though this is not true for arbitrary variables
285
    /// (foo.prop1.prop2).
286
102
    bool isExactProfile() const {
287
102
      return Base.getInt();
288
102
    }
289
290
3.71M
    bool operator==(const WeakObjectProfileTy &Other) const {
291
3.71M
      return Base == Other.Base && 
Property == Other.Property3.71M
;
292
3.71M
    }
293
294
    // For use in DenseMap.
295
    // We can't specialize the usual llvm::DenseMapInfo at the end of the file
296
    // because by that point the DenseMap in FunctionScopeInfo has already been
297
    // instantiated.
298
    class DenseMapInfo {
299
    public:
300
966k
      static inline WeakObjectProfileTy getEmptyKey() {
301
966k
        return WeakObjectProfileTy();
302
966k
      }
303
304
458k
      static inline WeakObjectProfileTy getTombstoneKey() {
305
458k
        return WeakObjectProfileTy::getSentinel();
306
458k
      }
307
308
344
      static unsigned getHashValue(const WeakObjectProfileTy &Val) {
309
344
        using Pair = std::pair<BaseInfoTy, const NamedDecl *>;
310
344
311
344
        return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
312
344
                                                           Val.Property));
313
344
      }
314
315
      static bool isEqual(const WeakObjectProfileTy &LHS,
316
3.71M
                          const WeakObjectProfileTy &RHS) {
317
3.71M
        return LHS == RHS;
318
3.71M
      }
319
    };
320
  };
321
322
  /// Represents a single use of a weak object.
323
  ///
324
  /// Stores both the expression and whether the access is potentially unsafe
325
  /// (i.e. it could potentially be warned about).
326
  ///
327
  /// Part of the implementation of -Wrepeated-use-of-weak.
328
  class WeakUseTy {
329
    llvm::PointerIntPair<const Expr *, 1, bool> Rep;
330
331
  public:
332
324
    WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
333
334
486
    const Expr *getUseExpr() const { return Rep.getPointer(); }
335
270
    bool isUnsafe() const { return Rep.getInt(); }
336
44
    void markSafe() { Rep.setInt(false); }
337
338
50
    bool operator==(const WeakUseTy &Other) const {
339
50
      return Rep == Other.Rep;
340
50
    }
341
  };
342
343
  /// Used to collect uses of a particular weak object in a function body.
344
  ///
345
  /// Part of the implementation of -Wrepeated-use-of-weak.
346
  using WeakUseVector = SmallVector<WeakUseTy, 4>;
347
348
  /// Used to collect all uses of weak objects in a function body.
349
  ///
350
  /// Part of the implementation of -Wrepeated-use-of-weak.
351
  using WeakObjectUseMap =
352
      llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
353
                          WeakObjectProfileTy::DenseMapInfo>;
354
355
private:
356
  /// Used to collect all uses of weak objects in this function body.
357
  ///
358
  /// Part of the implementation of -Wrepeated-use-of-weak.
359
  WeakObjectUseMap WeakObjectUses;
360
361
protected:
362
5.82k
  FunctionScopeInfo(const FunctionScopeInfo&) = default;
363
364
public:
365
  FunctionScopeInfo(DiagnosticsEngine &Diag)
366
      : Kind(SK_Function), HasBranchProtectedScope(false),
367
        HasBranchIntoScope(false), HasIndirectGoto(false),
368
        HasDroppedStmt(false), HasOMPDeclareReductionCombiner(false),
369
        HasFallthroughStmt(false), HasPotentialAvailabilityViolations(false),
370
        ObjCShouldCallSuper(false), ObjCIsDesignatedInit(false),
371
        ObjCWarnForNoDesignatedInitChain(false), ObjCIsSecondaryInit(false),
372
        ObjCWarnForNoInitDelegation(false), NeedsCoroutineSuspends(true),
373
454k
        ErrorTrap(Diag) {}
374
375
  virtual ~FunctionScopeInfo();
376
377
  /// Record that a weak object was accessed.
378
  ///
379
  /// Part of the implementation of -Wrepeated-use-of-weak.
380
  template <typename ExprT>
381
  inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
382
383
  void recordUseOfWeak(const ObjCMessageExpr *Msg,
384
                       const ObjCPropertyDecl *Prop);
385
386
  /// Record that a given expression is a "safe" access of a weak object (e.g.
387
  /// assigning it to a strong variable.)
388
  ///
389
  /// Part of the implementation of -Wrepeated-use-of-weak.
390
  void markSafeWeakUse(const Expr *E);
391
392
111
  const WeakObjectUseMap &getWeakObjectUses() const {
393
111
    return WeakObjectUses;
394
111
  }
395
396
23.1k
  void setHasBranchIntoScope() {
397
23.1k
    HasBranchIntoScope = true;
398
23.1k
  }
399
400
1.68M
  void setHasBranchProtectedScope() {
401
1.68M
    HasBranchProtectedScope = true;
402
1.68M
  }
403
404
136
  void setHasIndirectGoto() {
405
136
    HasIndirectGoto = true;
406
136
  }
407
408
0
  void setHasDroppedStmt() {
409
0
    HasDroppedStmt = true;
410
0
  }
411
412
626
  void setHasOMPDeclareReductionCombiner() {
413
626
    HasOMPDeclareReductionCombiner = true;
414
626
  }
415
416
893
  void setHasFallthroughStmt() {
417
893
    HasFallthroughStmt = true;
418
893
  }
419
420
12.2k
  void setHasCXXTry(SourceLocation TryLoc) {
421
12.2k
    setHasBranchProtectedScope();
422
12.2k
    FirstCXXTryLoc = TryLoc;
423
12.2k
  }
424
425
252
  void setHasSEHTry(SourceLocation TryLoc) {
426
252
    setHasBranchProtectedScope();
427
252
    FirstSEHTryLoc = TryLoc;
428
252
  }
429
430
3.08M
  bool NeedsScopeChecking() const {
431
3.08M
    return !HasDroppedStmt &&
432
3.08M
        (HasIndirectGoto ||
433
3.08M
          
(3.08M
HasBranchProtectedScope3.08M
&&
HasBranchIntoScope393k
));
434
3.08M
  }
435
436
  // Add a block introduced in this function.
437
2.50k
  void addBlock(const BlockDecl *BD) {
438
2.50k
    Blocks.insert(BD);
439
2.50k
  }
440
441
  // Add a __block variable introduced in this function.
442
246
  void addByrefBlockVar(VarDecl *VD) {
443
246
    ByrefBlockVars.push_back(VD);
444
246
  }
445
446
837k
  bool isCoroutine() const { return !FirstCoroutineStmtLoc.isInvalid(); }
447
448
242
  void setFirstCoroutineStmt(SourceLocation Loc, StringRef Keyword) {
449
242
    assert(FirstCoroutineStmtLoc.isInvalid() &&
450
242
                   "first coroutine statement location already set");
451
242
    FirstCoroutineStmtLoc = Loc;
452
242
    FirstCoroutineStmtKind = llvm::StringSwitch<unsigned char>(Keyword)
453
242
            .Case("co_return", 0)
454
242
            .Case("co_await", 1)
455
242
            .Case("co_yield", 2);
456
242
  }
457
458
19
  StringRef getFirstCoroutineStmtKeyword() const {
459
19
    assert(FirstCoroutineStmtLoc.isValid()
460
19
                   && "no coroutine statement available");
461
19
    switch (FirstCoroutineStmtKind) {
462
19
    
case 0: return "co_return"10
;
463
19
    
case 1: return "co_await"4
;
464
19
    
case 2: return "co_yield"5
;
465
19
    default:
466
0
      llvm_unreachable("FirstCoroutineStmtKind has an invalid value");
467
0
    };
468
0
  }
469
470
230
  void setNeedsCoroutineSuspends(bool value = true) {
471
230
    assert((!value || CoroutineSuspends.first == nullptr) &&
472
230
            "we already have valid suspend points");
473
230
    NeedsCoroutineSuspends = value;
474
230
  }
475
476
222
  bool hasInvalidCoroutineSuspends() const {
477
222
    return !NeedsCoroutineSuspends && CoroutineSuspends.first == nullptr;
478
222
  }
479
480
221
  void setCoroutineSuspends(Stmt *Initial, Stmt *Final) {
481
221
    assert(Initial && Final && "suspend points cannot be null");
482
221
    assert(CoroutineSuspends.first == nullptr && "suspend points already set");
483
221
    NeedsCoroutineSuspends = false;
484
221
    CoroutineSuspends.first = Initial;
485
221
    CoroutineSuspends.second = Final;
486
221
  }
487
488
  /// Clear out the information in this function scope, making it
489
  /// suitable for reuse.
490
  void Clear();
491
};
492
493
class Capture {
494
  // There are three categories of capture: capturing 'this', capturing
495
  // local variables, and C++1y initialized captures (which can have an
496
  // arbitrary initializer, and don't really capture in the traditional
497
  // sense at all).
498
  //
499
  // There are three ways to capture a local variable:
500
  //  - capture by copy in the C++11 sense,
501
  //  - capture by reference in the C++11 sense, and
502
  //  - __block capture.
503
  // Lambdas explicitly specify capture by copy or capture by reference.
504
  // For blocks, __block capture applies to variables with that annotation,
505
  // variables of reference type are captured by reference, and other
506
  // variables are captured by copy.
507
  enum CaptureKind {
508
    Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
509
  };
510
  enum {
511
    IsNestedCapture = 0x1,
512
    IsThisCaptured = 0x2
513
  };
514
515
  /// The variable being captured (if we are not capturing 'this') and whether
516
  /// this is a nested capture, and whether we are capturing 'this'
517
  llvm::PointerIntPair<VarDecl*, 2> VarAndNestedAndThis;
518
519
  /// Expression to initialize a field of the given type, and the kind of
520
  /// capture (if this is a capture and not an init-capture). The expression
521
  /// is only required if we are capturing ByVal and the variable's type has
522
  /// a non-trivial copy constructor.
523
  llvm::PointerIntPair<void *, 2, CaptureKind> InitExprAndCaptureKind;
524
525
  /// The source location at which the first capture occurred.
526
  SourceLocation Loc;
527
528
  /// The location of the ellipsis that expands a parameter pack.
529
  SourceLocation EllipsisLoc;
530
531
  /// The type as it was captured, which is in effect the type of the
532
  /// non-static data member that would hold the capture.
533
  QualType CaptureType;
534
535
  /// Whether an explicit capture has been odr-used in the body of the
536
  /// lambda.
537
  bool ODRUsed = false;
538
539
  /// Whether an explicit capture has been non-odr-used in the body of
540
  /// the lambda.
541
  bool NonODRUsed = false;
542
543
public:
544
  Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
545
          SourceLocation Loc, SourceLocation EllipsisLoc,
546
          QualType CaptureType, Expr *Cpy)
547
      : VarAndNestedAndThis(Var, IsNested ? IsNestedCapture : 0),
548
        InitExprAndCaptureKind(
549
            Cpy, !Var ? Cap_VLA : Block ? Cap_Block : ByRef ? Cap_ByRef
550
                                                            : Cap_ByCopy),
551
232k
        Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
552
553
  enum IsThisCapture { ThisCapture };
554
  Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
555
          QualType CaptureType, Expr *Cpy, const bool ByCopy)
556
      : VarAndNestedAndThis(
557
            nullptr, (IsThisCaptured | (IsNested ? IsNestedCapture : 0))),
558
        InitExprAndCaptureKind(Cpy, ByCopy ? Cap_ByCopy : Cap_ByRef),
559
8.06k
        Loc(Loc), CaptureType(CaptureType) {}
560
561
225k
  bool isThisCapture() const {
562
225k
    return VarAndNestedAndThis.getInt() & IsThisCaptured;
563
225k
  }
564
565
64
  bool isVariableCapture() const {
566
64
    return !isThisCapture() && !isVLATypeCapture();
567
64
  }
568
569
181k
  bool isCopyCapture() const {
570
181k
    return InitExprAndCaptureKind.getInt() == Cap_ByCopy;
571
181k
  }
572
573
204k
  bool isReferenceCapture() const {
574
204k
    return InitExprAndCaptureKind.getInt() == Cap_ByRef;
575
204k
  }
576
577
2.77k
  bool isBlockCapture() const {
578
2.77k
    return InitExprAndCaptureKind.getInt() == Cap_Block;
579
2.77k
  }
580
581
215k
  bool isVLATypeCapture() const {
582
215k
    return InitExprAndCaptureKind.getInt() == Cap_VLA;
583
215k
  }
584
585
2.77k
  bool isNested() const {
586
2.77k
    return VarAndNestedAndThis.getInt() & IsNestedCapture;
587
2.77k
  }
588
589
1.01k
  bool isODRUsed() const { return ODRUsed; }
590
412
  bool isNonODRUsed() const { return NonODRUsed; }
591
176k
  void markUsed(bool IsODRUse) { (IsODRUse ? 
ODRUsed72.6k
:
NonODRUsed104k
) = true; }
592
593
215k
  VarDecl *getVariable() const {
594
215k
    assert(isVariableCapture());
595
215k
    return VarAndNestedAndThis.getPointer();
596
215k
  }
597
598
  /// Retrieve the location at which this variable was captured.
599
223k
  SourceLocation getLocation() const { return Loc; }
600
601
  /// Retrieve the source location of the ellipsis, whose presence
602
  /// indicates that the capture is a pack expansion.
603
4.21k
  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
604
605
  /// Retrieve the capture type for this capture, which is effectively
606
  /// the type of the non-static data member in the lambda/block structure
607
  /// that would store this capture.
608
174k
  QualType getCaptureType() const {
609
174k
    assert(!isThisCapture());
610
174k
    return CaptureType;
611
174k
  }
612
613
219k
  Expr *getInitExpr() const {
614
219k
    assert(!isVLATypeCapture() && "no init expression for type capture");
615
219k
    return static_cast<Expr *>(InitExprAndCaptureKind.getPointer());
616
219k
  }
617
};
618
619
class CapturingScopeInfo : public FunctionScopeInfo {
620
protected:
621
5.82k
  CapturingScopeInfo(const CapturingScopeInfo&) = default;
622
623
public:
624
  enum ImplicitCaptureStyle {
625
    ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
626
    ImpCap_CapturedRegion
627
  };
628
629
  ImplicitCaptureStyle ImpCaptureStyle;
630
631
  CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
632
301k
      : FunctionScopeInfo(Diag), ImpCaptureStyle(Style) {}
633
634
  /// CaptureMap - A map of captured variables to (index+1) into Captures.
635
  llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
636
637
  /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
638
  /// zero if 'this' is not captured.
639
  unsigned CXXThisCaptureIndex = 0;
640
641
  /// Captures - The captures.
642
  SmallVector<Capture, 4> Captures;
643
644
  /// - Whether the target type of return statements in this context
645
  /// is deduced (e.g. a lambda or block with omitted return type).
646
  bool HasImplicitReturnType = false;
647
648
  /// ReturnType - The target type of return statements in this context,
649
  /// or null if unknown.
650
  QualType ReturnType;
651
652
  void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
653
                  SourceLocation Loc, SourceLocation EllipsisLoc,
654
227k
                  QualType CaptureType, Expr *Cpy) {
655
227k
    Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
656
227k
                               EllipsisLoc, CaptureType, Cpy));
657
227k
    CaptureMap[Var] = Captures.size();
658
227k
  }
659
660
5.56k
  void addVLATypeCapture(SourceLocation Loc, QualType CaptureType) {
661
5.56k
    Captures.push_back(Capture(/*Var*/ nullptr, /*isBlock*/ false,
662
5.56k
                               /*isByref*/ false, /*isNested*/ false, Loc,
663
5.56k
                               /*EllipsisLoc*/ SourceLocation(), CaptureType,
664
5.56k
                               /*Cpy*/ nullptr));
665
5.56k
  }
666
667
  // Note, we do not need to add the type of 'this' since that is always
668
  // retrievable from Sema::getCurrentThisType - and is also encoded within the
669
  // type of the corresponding FieldDecl.
670
  void addThisCapture(bool isNested, SourceLocation Loc,
671
                      Expr *Cpy, bool ByCopy);
672
673
  /// Determine whether the C++ 'this' is captured.
674
3.53k
  bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
675
676
  /// Retrieve the capture of C++ 'this', if it has been captured.
677
1.86k
  Capture &getCXXThisCapture() {
678
1.86k
    assert(isCXXThisCaptured() && "this has not been captured");
679
1.86k
    return Captures[CXXThisCaptureIndex - 1];
680
1.86k
  }
681
682
  /// Determine whether the given variable has been captured.
683
100
  bool isCaptured(VarDecl *Var) const {
684
100
    return CaptureMap.count(Var);
685
100
  }
686
687
  /// Determine whether the given variable-array type has been captured.
688
  bool isVLATypeCaptured(const VariableArrayType *VAT) const;
689
690
  /// Retrieve the capture of the given variable, if it has been
691
  /// captured already.
692
521k
  Capture &getCapture(VarDecl *Var) {
693
521k
    assert(isCaptured(Var) && "Variable has not been captured");
694
521k
    return Captures[CaptureMap[Var] - 1];
695
521k
  }
696
697
0
  const Capture &getCapture(VarDecl *Var) const {
698
0
    llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
699
0
      = CaptureMap.find(Var);
700
0
    assert(Known != CaptureMap.end() && "Variable has not been captured");
701
0
    return Captures[Known->second - 1];
702
0
  }
703
704
17.1M
  static bool classof(const FunctionScopeInfo *FSI) {
705
17.1M
    return FSI->Kind == SK_Block || 
FSI->Kind == SK_Lambda17.1M
706
17.1M
                                 || 
FSI->Kind == SK_CapturedRegion17.0M
;
707
17.1M
  }
708
};
709
710
/// Retains information about a block that is currently being parsed.
711
class BlockScopeInfo final : public CapturingScopeInfo {
712
public:
713
  BlockDecl *TheDecl;
714
715
  /// TheScope - This is the scope for the block itself, which contains
716
  /// arguments etc.
717
  Scope *TheScope;
718
719
  /// BlockType - The function type of the block, if one was given.
720
  /// Its return type may be BuiltinType::Dependent.
721
  QualType FunctionType;
722
723
  BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
724
      : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
725
2.62k
        TheScope(BlockScope) {
726
2.62k
    Kind = SK_Block;
727
2.62k
  }
728
729
  ~BlockScopeInfo() override;
730
731
1.65M
  static bool classof(const FunctionScopeInfo *FSI) {
732
1.65M
    return FSI->Kind == SK_Block;
733
1.65M
  }
734
};
735
736
/// Retains information about a captured region.
737
class CapturedRegionScopeInfo final : public CapturingScopeInfo {
738
public:
739
  /// The CapturedDecl for this statement.
740
  CapturedDecl *TheCapturedDecl;
741
742
  /// The captured record type.
743
  RecordDecl *TheRecordDecl;
744
745
  /// This is the enclosing scope of the captured region.
746
  Scope *TheScope;
747
748
  /// The implicit parameter for the captured variables.
749
  ImplicitParamDecl *ContextParam;
750
751
  /// The kind of captured region.
752
  unsigned short CapRegionKind;
753
754
  unsigned short OpenMPLevel;
755
756
  CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
757
                          RecordDecl *RD, ImplicitParamDecl *Context,
758
                          CapturedRegionKind K, unsigned OpenMPLevel)
759
      : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
760
        TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
761
292k
        ContextParam(Context), CapRegionKind(K), OpenMPLevel(OpenMPLevel) {
762
292k
    Kind = SK_CapturedRegion;
763
292k
  }
764
765
  ~CapturedRegionScopeInfo() override;
766
767
  /// A descriptive name for the kind of captured region this is.
768
123
  StringRef getRegionName() const {
769
123
    switch (CapRegionKind) {
770
123
    case CR_Default:
771
1
      return "default captured statement";
772
123
    case CR_ObjCAtFinally:
773
0
      return "Objective-C @finally statement";
774
123
    case CR_OpenMP:
775
122
      return "OpenMP region";
776
0
    }
777
0
    llvm_unreachable("Invalid captured region kind!");
778
0
  }
779
780
2.09M
  static bool classof(const FunctionScopeInfo *FSI) {
781
2.09M
    return FSI->Kind == SK_CapturedRegion;
782
2.09M
  }
783
};
784
785
class LambdaScopeInfo final : public CapturingScopeInfo {
786
public:
787
  /// The class that describes the lambda.
788
  CXXRecordDecl *Lambda = nullptr;
789
790
  /// The lambda's compiler-generated \c operator().
791
  CXXMethodDecl *CallOperator = nullptr;
792
793
  /// Source range covering the lambda introducer [...].
794
  SourceRange IntroducerRange;
795
796
  /// Source location of the '&' or '=' specifying the default capture
797
  /// type, if any.
798
  SourceLocation CaptureDefaultLoc;
799
800
  /// The number of captures in the \c Captures list that are
801
  /// explicit captures.
802
  unsigned NumExplicitCaptures = 0;
803
804
  /// Whether this is a mutable lambda.
805
  bool Mutable = false;
806
807
  /// Whether the (empty) parameter list is explicit.
808
  bool ExplicitParams = false;
809
810
  /// Whether any of the capture expressions requires cleanups.
811
  CleanupInfo Cleanup;
812
813
  /// Whether the lambda contains an unexpanded parameter pack.
814
  bool ContainsUnexpandedParameterPack = false;
815
816
  /// If this is a generic lambda, use this as the depth of
817
  /// each 'auto' parameter, during initial AST construction.
818
  unsigned AutoTemplateParameterDepth = 0;
819
820
  /// Store the list of the auto parameters for a generic lambda.
821
  /// If this is a generic lambda, store the list of the auto
822
  /// parameters converted into TemplateTypeParmDecls into a vector
823
  /// that can be used to construct the generic lambda's template
824
  /// parameter list, during initial AST construction.
825
  SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams;
826
827
  /// If this is a generic lambda, and the template parameter
828
  /// list has been created (from the AutoTemplateParams) then
829
  /// store a reference to it (cache it to avoid reconstructing it).
830
  TemplateParameterList *GLTemplateParameterList = nullptr;
831
832
  /// Contains all variable-referring-expressions (i.e. DeclRefExprs
833
  ///  or MemberExprs) that refer to local variables in a generic lambda
834
  ///  or a lambda in a potentially-evaluated-if-used context.
835
  ///
836
  ///  Potentially capturable variables of a nested lambda that might need
837
  ///   to be captured by the lambda are housed here.
838
  ///  This is specifically useful for generic lambdas or
839
  ///  lambdas within a potentially evaluated-if-used context.
840
  ///  If an enclosing variable is named in an expression of a lambda nested
841
  ///  within a generic lambda, we don't always know know whether the variable
842
  ///  will truly be odr-used (i.e. need to be captured) by that nested lambda,
843
  ///  until its instantiation. But we still need to capture it in the
844
  ///  enclosing lambda if all intervening lambdas can capture the variable.
845
  llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
846
847
  /// Contains all variable-referring-expressions that refer
848
  ///  to local variables that are usable as constant expressions and
849
  ///  do not involve an odr-use (they may still need to be captured
850
  ///  if the enclosing full-expression is instantiation dependent).
851
  llvm::SmallSet<Expr *, 8> NonODRUsedCapturingExprs;
852
853
  /// A map of explicit capture indices to their introducer source ranges.
854
  llvm::DenseMap<unsigned, SourceRange> ExplicitCaptureRanges;
855
856
  /// Contains all of the variables defined in this lambda that shadow variables
857
  /// that were defined in parent contexts. Used to avoid warnings when the
858
  /// shadowed variables are uncaptured by this lambda.
859
  struct ShadowedOuterDecl {
860
    const VarDecl *VD;
861
    const VarDecl *ShadowedDecl;
862
  };
863
  llvm::SmallVector<ShadowedOuterDecl, 4> ShadowingDecls;
864
865
  SourceLocation PotentialThisCaptureLocation;
866
867
  LambdaScopeInfo(DiagnosticsEngine &Diag)
868
6.89k
      : CapturingScopeInfo(Diag, ImpCap_None) {
869
6.89k
    Kind = SK_Lambda;
870
6.89k
  }
871
872
  /// Note when all explicit captures have been added.
873
5.86k
  void finishedExplicitCaptures() {
874
5.86k
    NumExplicitCaptures = Captures.size();
875
5.86k
  }
876
877
23.4M
  static bool classof(const FunctionScopeInfo *FSI) {
878
23.4M
    return FSI->Kind == SK_Lambda;
879
23.4M
  }
880
881
  /// Is this scope known to be for a generic lambda? (This will be false until
882
  /// we parse the first 'auto'-typed parameter.
883
0
  bool isGenericLambda() const {
884
0
    return !AutoTemplateParams.empty() || GLTemplateParameterList;
885
0
  }
886
887
  /// Add a variable that might potentially be captured by the
888
  /// lambda and therefore the enclosing lambdas.
889
  ///
890
  /// This is also used by enclosing lambda's to speculatively capture
891
  /// variables that nested lambda's - depending on their enclosing
892
  /// specialization - might need to capture.
893
  /// Consider:
894
  /// void f(int, int); <-- don't capture
895
  /// void f(const int&, double); <-- capture
896
  /// void foo() {
897
  ///   const int x = 10;
898
  ///   auto L = [=](auto a) { // capture 'x'
899
  ///      return [=](auto b) {
900
  ///        f(x, a);  // we may or may not need to capture 'x'
901
  ///      };
902
  ///   };
903
  /// }
904
507
  void addPotentialCapture(Expr *VarExpr) {
905
507
    assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr));
906
507
    PotentiallyCapturingExprs.push_back(VarExpr);
907
507
  }
908
909
19
  void addPotentialThisCapture(SourceLocation Loc) {
910
19
    PotentialThisCaptureLocation = Loc;
911
19
  }
912
913
406
  bool hasPotentialThisCapture() const {
914
406
    return PotentialThisCaptureLocation.isValid();
915
406
  }
916
917
  /// Mark a variable's reference in a lambda as non-odr using.
918
  ///
919
  /// For generic lambdas, if a variable is named in a potentially evaluated
920
  /// expression, where the enclosing full expression is dependent then we
921
  /// must capture the variable (given a default capture).
922
  /// This is accomplished by recording all references to variables
923
  /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
924
  /// PotentialCaptures. All such variables have to be captured by that lambda,
925
  /// except for as described below.
926
  /// If that variable is usable as a constant expression and is named in a
927
  /// manner that does not involve its odr-use (e.g. undergoes
928
  /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
929
  /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
930
  /// if we can determine that the full expression is not instantiation-
931
  /// dependent, then we can entirely avoid its capture.
932
  ///
933
  ///   const int n = 0;
934
  ///   [&] (auto x) {
935
  ///     (void)+n + x;
936
  ///   };
937
  /// Interestingly, this strategy would involve a capture of n, even though
938
  /// it's obviously not odr-used here, because the full-expression is
939
  /// instantiation-dependent.  It could be useful to avoid capturing such
940
  /// variables, even when they are referred to in an instantiation-dependent
941
  /// expression, if we can unambiguously determine that they shall never be
942
  /// odr-used.  This would involve removal of the variable-referring-expression
943
  /// from the array of PotentialCaptures during the lvalue-to-rvalue
944
  /// conversions.  But per the working draft N3797, (post-chicago 2013) we must
945
  /// capture such variables.
946
  /// Before anyone is tempted to implement a strategy for not-capturing 'n',
947
  /// consider the insightful warning in:
948
  ///    /cfe-commits/Week-of-Mon-20131104/092596.html
949
  /// "The problem is that the set of captures for a lambda is part of the ABI
950
  ///  (since lambda layout can be made visible through inline functions and the
951
  ///  like), and there are no guarantees as to which cases we'll manage to build
952
  ///  an lvalue-to-rvalue conversion in, when parsing a template -- some
953
  ///  seemingly harmless change elsewhere in Sema could cause us to start or stop
954
  ///  building such a node. So we need a rule that anyone can implement and get
955
  ///  exactly the same result".
956
621
  void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
957
621
    assert(isa<DeclRefExpr>(CapturingVarExpr)
958
621
        || isa<MemberExpr>(CapturingVarExpr));
959
621
    NonODRUsedCapturingExprs.insert(CapturingVarExpr);
960
621
  }
961
506
  bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
962
506
    assert(isa<DeclRefExpr>(CapturingVarExpr)
963
506
      || isa<MemberExpr>(CapturingVarExpr));
964
506
    return NonODRUsedCapturingExprs.count(CapturingVarExpr);
965
506
  }
966
0
  void removePotentialCapture(Expr *E) {
967
0
    PotentiallyCapturingExprs.erase(
968
0
        std::remove(PotentiallyCapturingExprs.begin(),
969
0
            PotentiallyCapturingExprs.end(), E),
970
0
        PotentiallyCapturingExprs.end());
971
0
  }
972
406
  void clearPotentialCaptures() {
973
406
    PotentiallyCapturingExprs.clear();
974
406
    PotentialThisCaptureLocation = SourceLocation();
975
406
  }
976
24.2k
  unsigned getNumPotentialVariableCaptures() const {
977
24.2k
    return PotentiallyCapturingExprs.size();
978
24.2k
  }
979
980
23.8k
  bool hasPotentialCaptures() const {
981
23.8k
    return getNumPotentialVariableCaptures() ||
982
23.8k
                                  
PotentialThisCaptureLocation.isValid()23.4k
;
983
23.8k
  }
984
985
  // When passed the index, returns the VarDecl and Expr associated
986
  // with the index.
987
  void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const;
988
};
989
990
FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
991
1.42M
    : Base(nullptr, false) {}
992
993
FunctionScopeInfo::WeakObjectProfileTy
994
458k
FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
995
458k
  FunctionScopeInfo::WeakObjectProfileTy Result;
996
458k
  Result.Base.setInt(true);
997
458k
  return Result;
998
458k
}
999
1000
template <typename ExprT>
1001
254
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1002
254
  assert(E);
1003
254
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1004
254
  Uses.push_back(WeakUseTy(E, IsRead));
1005
254
}
void clang::sema::FunctionScopeInfo::recordUseOfWeak<clang::DeclRefExpr>(clang::DeclRefExpr const*, bool)
Line
Count
Source
1001
26
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1002
26
  assert(E);
1003
26
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1004
26
  Uses.push_back(WeakUseTy(E, IsRead));
1005
26
}
void clang::sema::FunctionScopeInfo::recordUseOfWeak<clang::ObjCIvarRefExpr>(clang::ObjCIvarRefExpr const*, bool)
Line
Count
Source
1001
24
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1002
24
  assert(E);
1003
24
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1004
24
  Uses.push_back(WeakUseTy(E, IsRead));
1005
24
}
void clang::sema::FunctionScopeInfo::recordUseOfWeak<clang::ObjCPropertyRefExpr>(clang::ObjCPropertyRefExpr const*, bool)
Line
Count
Source
1001
204
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1002
204
  assert(E);
1003
204
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1004
204
  Uses.push_back(WeakUseTy(E, IsRead));
1005
204
}
1006
1007
inline void
1008
CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
1009
                                   Expr *Cpy,
1010
8.06k
                                   const bool ByCopy) {
1011
8.06k
  Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, QualType(),
1012
8.06k
                             Cpy, ByCopy));
1013
8.06k
  CXXThisCaptureIndex = Captures.size();
1014
8.06k
}
1015
1016
} // namespace sema
1017
1018
} // namespace clang
1019
1020
#endif // LLVM_CLANG_SEMA_SCOPEINFO_H