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