Coverage Report

Created: 2019-02-21 13:17

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