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