ScopeInfo.h revision 6afcf8875d4e447645cd7bf3733dd8e2eb8455dc
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_SCOPE_INFO_H
16#define LLVM_CLANG_SEMA_SCOPE_INFO_H
17
18#include "clang/AST/Type.h"
19#include "clang/Basic/PartialDiagnostic.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/SmallVector.h"
22
23namespace clang {
24
25class Decl;
26class BlockDecl;
27class CapturedDecl;
28class CXXMethodDecl;
29class ObjCPropertyDecl;
30class IdentifierInfo;
31class LabelDecl;
32class ReturnStmt;
33class Scope;
34class SwitchStmt;
35class VarDecl;
36class DeclRefExpr;
37class ObjCIvarRefExpr;
38class ObjCPropertyRefExpr;
39class ObjCMessageExpr;
40
41namespace sema {
42
43/// \brief Contains information about the compound statement currently being
44/// parsed.
45class CompoundScopeInfo {
46public:
47  CompoundScopeInfo()
48    : HasEmptyLoopBodies(false) { }
49
50  /// \brief Whether this compound stamement contains `for' or `while' loops
51  /// with empty bodies.
52  bool HasEmptyLoopBodies;
53
54  void setHasEmptyLoopBodies() {
55    HasEmptyLoopBodies = true;
56  }
57};
58
59class PossiblyUnreachableDiag {
60public:
61  PartialDiagnostic PD;
62  SourceLocation Loc;
63  const Stmt *stmt;
64
65  PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
66                          const Stmt *stmt)
67    : PD(PD), Loc(Loc), stmt(stmt) {}
68};
69
70/// \brief Retains information about a function, method, or block that is
71/// currently being parsed.
72class FunctionScopeInfo {
73protected:
74  enum ScopeKind {
75    SK_Function,
76    SK_Block,
77    SK_Lambda,
78    SK_CapturedRegion
79  };
80
81public:
82  /// \brief What kind of scope we are describing.
83  ///
84  ScopeKind Kind;
85
86  /// \brief Whether this function contains a VLA, \@try, try, C++
87  /// initializer, or anything else that can't be jumped past.
88  bool HasBranchProtectedScope;
89
90  /// \brief Whether this function contains any switches or direct gotos.
91  bool HasBranchIntoScope;
92
93  /// \brief Whether this function contains any indirect gotos.
94  bool HasIndirectGoto;
95
96  /// \brief Whether a statement was dropped because it was invalid.
97  bool HasDroppedStmt;
98
99  /// A flag that is set when parsing a method that must call super's
100  /// implementation, such as \c -dealloc, \c -finalize, or any method marked
101  /// with \c __attribute__((objc_requires_super)).
102  bool ObjCShouldCallSuper;
103
104  /// \brief Used to determine if errors occurred in this function or block.
105  DiagnosticErrorTrap ErrorTrap;
106
107  /// SwitchStack - This is the current set of active switch statements in the
108  /// block.
109  SmallVector<SwitchStmt*, 8> SwitchStack;
110
111  /// \brief The list of return statements that occur within the function or
112  /// block, if there is any chance of applying the named return value
113  /// optimization, or if we need to infer a return type.
114  SmallVector<ReturnStmt*, 4> Returns;
115
116  /// \brief The stack of currently active compound stamement scopes in the
117  /// function.
118  SmallVector<CompoundScopeInfo, 4> CompoundScopes;
119
120  /// \brief A list of PartialDiagnostics created but delayed within the
121  /// current function scope.  These diagnostics are vetted for reachability
122  /// prior to being emitted.
123  SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
124
125public:
126  /// Represents a simple identification of a weak object.
127  ///
128  /// Part of the implementation of -Wrepeated-use-of-weak.
129  ///
130  /// This is used to determine if two weak accesses refer to the same object.
131  /// Here are some examples of how various accesses are "profiled":
132  ///
133  /// Access Expression |     "Base" Decl     |          "Property" Decl
134  /// :---------------: | :-----------------: | :------------------------------:
135  /// self.property     | self (VarDecl)      | property (ObjCPropertyDecl)
136  /// self.implicitProp | self (VarDecl)      | -implicitProp (ObjCMethodDecl)
137  /// self->ivar.prop   | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
138  /// cxxObj.obj.prop   | obj (FieldDecl)     | prop (ObjCPropertyDecl)
139  /// [self foo].prop   | 0 (unknown)         | prop (ObjCPropertyDecl)
140  /// self.prop1.prop2  | prop1 (ObjCPropertyDecl)    | prop2 (ObjCPropertyDecl)
141  /// MyClass.prop      | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
142  /// weakVar           | 0 (known)           | weakVar (VarDecl)
143  /// self->weakIvar    | self (VarDecl)      | weakIvar (ObjCIvarDecl)
144  ///
145  /// Objects are identified with only two Decls to make it reasonably fast to
146  /// compare them.
147  class WeakObjectProfileTy {
148    /// The base object decl, as described in the class documentation.
149    ///
150    /// The extra flag is "true" if the Base and Property are enough to uniquely
151    /// identify the object in memory.
152    ///
153    /// \sa isExactProfile()
154    typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy;
155    BaseInfoTy Base;
156
157    /// The "property" decl, as described in the class documentation.
158    ///
159    /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
160    /// case of "implicit" properties (regular methods accessed via dot syntax).
161    const NamedDecl *Property;
162
163    /// Used to find the proper base profile for a given base expression.
164    static BaseInfoTy getBaseInfo(const Expr *BaseE);
165
166    // For use in DenseMap.
167    friend class DenseMapInfo;
168    inline WeakObjectProfileTy();
169    static inline WeakObjectProfileTy getSentinel();
170
171  public:
172    WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
173    WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
174    WeakObjectProfileTy(const DeclRefExpr *RE);
175    WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
176
177    const NamedDecl *getBase() const { return Base.getPointer(); }
178    const NamedDecl *getProperty() const { return Property; }
179
180    /// Returns true if the object base specifies a known object in memory,
181    /// rather than, say, an instance variable or property of another object.
182    ///
183    /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
184    /// considered an exact profile if \c foo is a local variable, even if
185    /// another variable \c foo2 refers to the same object as \c foo.
186    ///
187    /// For increased precision, accesses with base variables that are
188    /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
189    /// be exact, though this is not true for arbitrary variables
190    /// (foo.prop1.prop2).
191    bool isExactProfile() const {
192      return Base.getInt();
193    }
194
195    bool operator==(const WeakObjectProfileTy &Other) const {
196      return Base == Other.Base && Property == Other.Property;
197    }
198
199    // For use in DenseMap.
200    // We can't specialize the usual llvm::DenseMapInfo at the end of the file
201    // because by that point the DenseMap in FunctionScopeInfo has already been
202    // instantiated.
203    class DenseMapInfo {
204    public:
205      static inline WeakObjectProfileTy getEmptyKey() {
206        return WeakObjectProfileTy();
207      }
208      static inline WeakObjectProfileTy getTombstoneKey() {
209        return WeakObjectProfileTy::getSentinel();
210      }
211
212      static unsigned getHashValue(const WeakObjectProfileTy &Val) {
213        typedef std::pair<BaseInfoTy, const NamedDecl *> Pair;
214        return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
215                                                           Val.Property));
216      }
217
218      static bool isEqual(const WeakObjectProfileTy &LHS,
219                          const WeakObjectProfileTy &RHS) {
220        return LHS == RHS;
221      }
222    };
223  };
224
225  /// Represents a single use of a weak object.
226  ///
227  /// Stores both the expression and whether the access is potentially unsafe
228  /// (i.e. it could potentially be warned about).
229  ///
230  /// Part of the implementation of -Wrepeated-use-of-weak.
231  class WeakUseTy {
232    llvm::PointerIntPair<const Expr *, 1, bool> Rep;
233  public:
234    WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
235
236    const Expr *getUseExpr() const { return Rep.getPointer(); }
237    bool isUnsafe() const { return Rep.getInt(); }
238    void markSafe() { Rep.setInt(false); }
239
240    bool operator==(const WeakUseTy &Other) const {
241      return Rep == Other.Rep;
242    }
243  };
244
245  /// Used to collect uses of a particular weak object in a function body.
246  ///
247  /// Part of the implementation of -Wrepeated-use-of-weak.
248  typedef SmallVector<WeakUseTy, 4> WeakUseVector;
249
250  /// Used to collect all uses of weak objects in a function body.
251  ///
252  /// Part of the implementation of -Wrepeated-use-of-weak.
253  typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
254                              WeakObjectProfileTy::DenseMapInfo>
255          WeakObjectUseMap;
256
257private:
258  /// Used to collect all uses of weak objects in this function body.
259  ///
260  /// Part of the implementation of -Wrepeated-use-of-weak.
261  WeakObjectUseMap WeakObjectUses;
262
263public:
264  /// Record that a weak object was accessed.
265  ///
266  /// Part of the implementation of -Wrepeated-use-of-weak.
267  template <typename ExprT>
268  inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
269
270  void recordUseOfWeak(const ObjCMessageExpr *Msg,
271                       const ObjCPropertyDecl *Prop);
272
273  /// Record that a given expression is a "safe" access of a weak object (e.g.
274  /// assigning it to a strong variable.)
275  ///
276  /// Part of the implementation of -Wrepeated-use-of-weak.
277  void markSafeWeakUse(const Expr *E);
278
279  const WeakObjectUseMap &getWeakObjectUses() const {
280    return WeakObjectUses;
281  }
282
283  void setHasBranchIntoScope() {
284    HasBranchIntoScope = true;
285  }
286
287  void setHasBranchProtectedScope() {
288    HasBranchProtectedScope = true;
289  }
290
291  void setHasIndirectGoto() {
292    HasIndirectGoto = true;
293  }
294
295  void setHasDroppedStmt() {
296    HasDroppedStmt = true;
297  }
298
299  bool NeedsScopeChecking() const {
300    return !HasDroppedStmt &&
301        (HasIndirectGoto ||
302          (HasBranchProtectedScope && HasBranchIntoScope));
303  }
304
305  FunctionScopeInfo(DiagnosticsEngine &Diag)
306    : Kind(SK_Function),
307      HasBranchProtectedScope(false),
308      HasBranchIntoScope(false),
309      HasIndirectGoto(false),
310      HasDroppedStmt(false),
311      ObjCShouldCallSuper(false),
312      ErrorTrap(Diag) { }
313
314  virtual ~FunctionScopeInfo();
315
316  /// \brief Clear out the information in this function scope, making it
317  /// suitable for reuse.
318  void Clear();
319};
320
321class CapturingScopeInfo : public FunctionScopeInfo {
322public:
323  enum ImplicitCaptureStyle {
324    ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
325    ImpCap_CapturedRegion
326  };
327
328  ImplicitCaptureStyle ImpCaptureStyle;
329
330  class Capture {
331    // There are two categories of capture: capturing 'this', and capturing
332    // local variables.  There are three ways to capture a local variable:
333    // capture by copy in the C++11 sense, capture by reference
334    // in the C++11 sense, and __block capture.  Lambdas explicitly specify
335    // capture by copy or capture by reference.  For blocks, __block capture
336    // applies to variables with that annotation, variables of reference type
337    // are captured by reference, and other variables are captured by copy.
338    enum CaptureKind {
339      Cap_This, Cap_ByCopy, Cap_ByRef, Cap_Block
340    };
341
342    // The variable being captured (if we are not capturing 'this'),
343    // and misc bits descibing the capture.
344    llvm::PointerIntPair<VarDecl*, 2, CaptureKind> VarAndKind;
345
346    // Expression to initialize a field of the given type, and whether this
347    // is a nested capture; the expression is only required if we are
348    // capturing ByVal and the variable's type has a non-trivial
349    // copy constructor.
350    llvm::PointerIntPair<Expr*, 1, bool> CopyExprAndNested;
351
352    /// \brief The source location at which the first capture occurred..
353    SourceLocation Loc;
354
355    /// \brief The location of the ellipsis that expands a parameter pack.
356    SourceLocation EllipsisLoc;
357
358    /// \brief The type as it was captured, which is in effect the type of the
359    /// non-static data member that would hold the capture.
360    QualType CaptureType;
361
362  public:
363    Capture(VarDecl *Var, bool block, bool byRef, bool isNested,
364            SourceLocation Loc, SourceLocation EllipsisLoc,
365            QualType CaptureType, Expr *Cpy)
366      : VarAndKind(Var, block ? Cap_Block : byRef ? Cap_ByRef : Cap_ByCopy),
367        CopyExprAndNested(Cpy, isNested), Loc(Loc), EllipsisLoc(EllipsisLoc),
368        CaptureType(CaptureType){}
369
370    enum IsThisCapture { ThisCapture };
371    Capture(IsThisCapture, bool isNested, SourceLocation Loc,
372            QualType CaptureType, Expr *Cpy)
373      : VarAndKind(0, Cap_This), CopyExprAndNested(Cpy, isNested), Loc(Loc),
374        EllipsisLoc(), CaptureType(CaptureType) { }
375
376    bool isThisCapture() const { return VarAndKind.getInt() == Cap_This; }
377    bool isVariableCapture() const { return !isThisCapture(); }
378    bool isCopyCapture() const { return VarAndKind.getInt() == Cap_ByCopy; }
379    bool isReferenceCapture() const { return VarAndKind.getInt() == Cap_ByRef; }
380    bool isBlockCapture() const { return VarAndKind.getInt() == Cap_Block; }
381    bool isNested() { return CopyExprAndNested.getInt(); }
382
383    VarDecl *getVariable() const {
384      return VarAndKind.getPointer();
385    }
386
387    /// \brief Retrieve the location at which this variable was captured.
388    SourceLocation getLocation() const { return Loc; }
389
390    /// \brief Retrieve the source location of the ellipsis, whose presence
391    /// indicates that the capture is a pack expansion.
392    SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
393
394    /// \brief Retrieve the capture type for this capture, which is effectively
395    /// the type of the non-static data member in the lambda/block structure
396    /// that would store this capture.
397    QualType getCaptureType() const { return CaptureType; }
398
399    Expr *getCopyExpr() const {
400      return CopyExprAndNested.getPointer();
401    }
402  };
403
404  CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
405    : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0),
406      HasImplicitReturnType(false)
407     {}
408
409  /// CaptureMap - A map of captured variables to (index+1) into Captures.
410  llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
411
412  /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
413  /// zero if 'this' is not captured.
414  unsigned CXXThisCaptureIndex;
415
416  /// Captures - The captures.
417  SmallVector<Capture, 4> Captures;
418
419  /// \brief - Whether the target type of return statements in this context
420  /// is deduced (e.g. a lambda or block with omitted return type).
421  bool HasImplicitReturnType;
422
423  /// ReturnType - The target type of return statements in this context,
424  /// or null if unknown.
425  QualType ReturnType;
426
427  void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
428                  SourceLocation Loc, SourceLocation EllipsisLoc,
429                  QualType CaptureType, Expr *Cpy) {
430    Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
431                               EllipsisLoc, CaptureType, Cpy));
432    CaptureMap[Var] = Captures.size();
433  }
434
435  void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
436                      Expr *Cpy);
437
438  /// \brief Determine whether the C++ 'this' is captured.
439  bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
440
441  /// \brief Retrieve the capture of C++ 'this', if it has been captured.
442  Capture &getCXXThisCapture() {
443    assert(isCXXThisCaptured() && "this has not been captured");
444    return Captures[CXXThisCaptureIndex - 1];
445  }
446
447  /// \brief Determine whether the given variable has been captured.
448  bool isCaptured(VarDecl *Var) const {
449    return CaptureMap.count(Var);
450  }
451
452  /// \brief Retrieve the capture of the given variable, if it has been
453  /// captured already.
454  Capture &getCapture(VarDecl *Var) {
455    assert(isCaptured(Var) && "Variable has not been captured");
456    return Captures[CaptureMap[Var] - 1];
457  }
458
459  const Capture &getCapture(VarDecl *Var) const {
460    llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
461      = CaptureMap.find(Var);
462    assert(Known != CaptureMap.end() && "Variable has not been captured");
463    return Captures[Known->second - 1];
464  }
465
466  static bool classof(const FunctionScopeInfo *FSI) {
467    return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
468                                 || FSI->Kind == SK_CapturedRegion;
469  }
470};
471
472/// \brief Retains information about a block that is currently being parsed.
473class BlockScopeInfo : public CapturingScopeInfo {
474public:
475  BlockDecl *TheDecl;
476
477  /// TheScope - This is the scope for the block itself, which contains
478  /// arguments etc.
479  Scope *TheScope;
480
481  /// BlockType - The function type of the block, if one was given.
482  /// Its return type may be BuiltinType::Dependent.
483  QualType FunctionType;
484
485  BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
486    : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
487      TheScope(BlockScope)
488  {
489    Kind = SK_Block;
490  }
491
492  virtual ~BlockScopeInfo();
493
494  static bool classof(const FunctionScopeInfo *FSI) {
495    return FSI->Kind == SK_Block;
496  }
497};
498
499/// \brief Retains information about a captured region.
500class CapturedRegionScopeInfo: public CapturingScopeInfo {
501public:
502
503  enum CapturedRegionKind {
504    CR_Default
505  };
506
507  /// \brief The CapturedDecl for this statement.
508  CapturedDecl *TheCapturedDecl;
509  /// \brief The captured record type.
510  RecordDecl *TheRecordDecl;
511  /// \brief This is the enclosing scope of the captured region.
512  Scope *TheScope;
513  /// \brief The kind of captured region.
514  CapturedRegionKind CapRegionKind;
515
516  CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
517                          RecordDecl *RD, CapturedRegionKind K)
518    : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
519      TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S), CapRegionKind(K)
520  {
521    Kind = SK_CapturedRegion;
522  }
523
524  virtual ~CapturedRegionScopeInfo();
525
526  /// \brief A descriptive name for the kind of captured region this is.
527  StringRef getRegionName() const {
528    switch (CapRegionKind) {
529    case CR_Default:
530      return "default captured statement";
531    }
532  }
533
534  static bool classof(const FunctionScopeInfo *FSI) {
535    return FSI->Kind == SK_CapturedRegion;
536  }
537};
538
539class LambdaScopeInfo : public CapturingScopeInfo {
540public:
541  /// \brief The class that describes the lambda.
542  CXXRecordDecl *Lambda;
543
544  /// \brief The class that describes the lambda.
545  CXXMethodDecl *CallOperator;
546
547  /// \brief Source range covering the lambda introducer [...].
548  SourceRange IntroducerRange;
549
550  /// \brief The number of captures in the \c Captures list that are
551  /// explicit captures.
552  unsigned NumExplicitCaptures;
553
554  /// \brief Whether this is a mutable lambda.
555  bool Mutable;
556
557  /// \brief Whether the (empty) parameter list is explicit.
558  bool ExplicitParams;
559
560  /// \brief Whether any of the capture expressions requires cleanups.
561  bool ExprNeedsCleanups;
562
563  /// \brief Whether the lambda contains an unexpanded parameter pack.
564  bool ContainsUnexpandedParameterPack;
565
566  /// \brief Variables used to index into by-copy array captures.
567  SmallVector<VarDecl *, 4> ArrayIndexVars;
568
569  /// \brief Offsets into the ArrayIndexVars array at which each capture starts
570  /// its list of array index variables.
571  SmallVector<unsigned, 4> ArrayIndexStarts;
572
573  LambdaScopeInfo(DiagnosticsEngine &Diag, CXXRecordDecl *Lambda,
574                  CXXMethodDecl *CallOperator)
575    : CapturingScopeInfo(Diag, ImpCap_None), Lambda(Lambda),
576      CallOperator(CallOperator), NumExplicitCaptures(0), Mutable(false),
577      ExprNeedsCleanups(false), ContainsUnexpandedParameterPack(false)
578  {
579    Kind = SK_Lambda;
580  }
581
582  virtual ~LambdaScopeInfo();
583
584  /// \brief Note when
585  void finishedExplicitCaptures() {
586    NumExplicitCaptures = Captures.size();
587  }
588
589  static bool classof(const FunctionScopeInfo *FSI) {
590    return FSI->Kind == SK_Lambda;
591  }
592};
593
594
595FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
596  : Base(0, false), Property(0) {}
597
598FunctionScopeInfo::WeakObjectProfileTy
599FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
600  FunctionScopeInfo::WeakObjectProfileTy Result;
601  Result.Base.setInt(true);
602  return Result;
603}
604
605template <typename ExprT>
606void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
607  assert(E);
608  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
609  Uses.push_back(WeakUseTy(E, IsRead));
610}
611
612inline void
613CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
614                                   QualType CaptureType, Expr *Cpy) {
615  Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
616                             Cpy));
617  CXXThisCaptureIndex = Captures.size();
618
619  if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(this))
620    LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
621}
622
623} // end namespace sema
624} // end namespace clang
625
626#endif
627