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