Coverage Report

Created: 2018-09-25 23:22

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