CallEvent.h revision 1becab2120142b1be87d684a68d3bea98f5abfb5
1//===- CallEvent.h - Wrapper for all function and method calls ----*- 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/// \file This file defines CallEvent and its subclasses, which represent path-
11/// sensitive instances of different kinds of function and method calls
12/// (C, C++, and Objective-C).
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_STATICANALYZER_PATHSENSITIVE_CALL
17#define LLVM_CLANG_STATICANALYZER_PATHSENSITIVE_CALL
18
19#include "clang/Basic/SourceManager.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
25#include "llvm/ADT/PointerIntPair.h"
26
27namespace clang {
28class ProgramPoint;
29class ProgramPointTag;
30
31namespace ento {
32
33enum CallEventKind {
34  CE_Function,
35  CE_Block,
36  CE_BEG_SIMPLE_CALLS = CE_Function,
37  CE_END_SIMPLE_CALLS = CE_Block,
38  CE_CXXMember,
39  CE_CXXMemberOperator,
40  CE_CXXDestructor,
41  CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
42  CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
43  CE_CXXConstructor,
44  CE_CXXAllocator,
45  CE_BEG_FUNCTION_CALLS = CE_Function,
46  CE_END_FUNCTION_CALLS = CE_CXXAllocator,
47  CE_ObjCMessage
48};
49
50class CallEvent;
51class CallEventManager;
52
53template<typename T = CallEvent>
54class CallEventRef : public IntrusiveRefCntPtr<const T> {
55public:
56  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
57  CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
58
59  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
60    return this->getPtr()->template cloneWithState<T>(State);
61  }
62
63  // Allow implicit conversions to a superclass type, since CallEventRef
64  // behaves like a pointer-to-const.
65  template <typename SuperT>
66  operator CallEventRef<SuperT> () const {
67    return this->getPtr();
68  }
69};
70
71/// \class RuntimeDefinition
72/// \brief Defines the runtime definition of the called function.
73///
74/// Encapsulates the information we have about which Decl will be used
75/// when the call is executed on the given path. When dealing with dynamic
76/// dispatch, the information is based on DynamicTypeInfo and might not be
77/// precise.
78class RuntimeDefinition {
79  /// The Declaration of the function which could be called at runtime.
80  /// NULL if not available.
81  const Decl *D;
82
83  /// The region representing an object (ObjC/C++) on which the method is
84  /// called. With dynamic dispatch, the method definition depends on the
85  /// runtime type of this object. NULL when the DynamicTypeInfo is
86  /// precise.
87  const MemRegion *R;
88
89public:
90  RuntimeDefinition(): D(0), R(0) {}
91  RuntimeDefinition(const Decl *InD): D(InD), R(0) {}
92  RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
93  const Decl *getDecl() { return D; }
94
95  /// \brief Check if the definition we have is precise.
96  /// If not, it is possible that the call dispatches to another definition at
97  /// execution time.
98  bool mayHaveOtherDefinitions() { return R != 0; }
99
100  /// When other definitions are possible, returns the region whose runtime type
101  /// determines the method definition.
102  const MemRegion *getDispatchRegion() { return R; }
103};
104
105/// \brief Represents an abstract call to a function or method along a
106/// particular path.
107///
108/// CallEvents are created through the factory methods of CallEventManager.
109///
110/// CallEvents should always be cheap to create and destroy. In order for
111/// CallEventManager to be able to re-use CallEvent-sized memory blocks,
112/// subclasses of CallEvent may not add any data members to the base class.
113/// Use the "Data" and "Location" fields instead.
114class CallEvent {
115public:
116  typedef CallEventKind Kind;
117
118private:
119  ProgramStateRef State;
120  const LocationContext *LCtx;
121  llvm::PointerUnion<const Expr *, const Decl *> Origin;
122
123  // DO NOT IMPLEMENT
124  CallEvent &operator=(const CallEvent &);
125
126protected:
127  // This is user data for subclasses.
128  const void *Data;
129
130  // This is user data for subclasses.
131  // This should come right before RefCount, so that the two fields can be
132  // packed together on LP64 platforms.
133  SourceLocation Location;
134
135private:
136  mutable unsigned RefCount;
137
138  template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
139  void Retain() const { ++RefCount; }
140  void Release() const;
141
142protected:
143  friend class CallEventManager;
144
145  CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
146    : State(state), LCtx(lctx), Origin(E), RefCount(0) {}
147
148  CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
149    : State(state), LCtx(lctx), Origin(D), RefCount(0) {}
150
151  // DO NOT MAKE PUBLIC
152  CallEvent(const CallEvent &Original)
153    : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
154      Data(Original.Data), Location(Original.Location), RefCount(0) {}
155
156
157  ProgramStateRef getState() const {
158    return State;
159  }
160
161  const LocationContext *getLocationContext() const {
162    return LCtx;
163  }
164
165
166  /// Copies this CallEvent, with vtable intact, into a new block of memory.
167  virtual void cloneTo(void *Dest) const = 0;
168
169  /// \brief Get the value of arbitrary expressions at this point in the path.
170  SVal getSVal(const Stmt *S) const {
171    return getState()->getSVal(S, getLocationContext());
172  }
173
174
175  typedef SmallVectorImpl<const MemRegion *> RegionList;
176
177  /// \brief Used to specify non-argument regions that will be invalidated as a
178  /// result of this call.
179  virtual void getExtraInvalidatedRegions(RegionList &Regions) const {}
180
181  virtual QualType getDeclaredResultType() const = 0;
182
183public:
184  virtual ~CallEvent() {}
185
186  /// \brief Returns the kind of call this is.
187  virtual Kind getKind() const = 0;
188
189  /// \brief Returns the declaration of the function or method that will be
190  /// called. May be null.
191  virtual const Decl *getDecl() const {
192    return Origin.dyn_cast<const Decl *>();
193  }
194
195  /// \brief Returns the definition of the function or method that will be
196  /// called.
197  virtual RuntimeDefinition getRuntimeDefinition() const = 0;
198
199  /// \brief Returns the expression whose value will be the result of this call.
200  /// May be null.
201  const Expr *getOriginExpr() const {
202    return Origin.dyn_cast<const Expr *>();
203  }
204
205  /// \brief Returns the number of arguments (explicit and implicit).
206  ///
207  /// Note that this may be greater than the number of parameters in the
208  /// callee's declaration, and that it may include arguments not written in
209  /// the source.
210  virtual unsigned getNumArgs() const = 0;
211
212  /// \brief Returns true if the callee is known to be from a system header.
213  bool isInSystemHeader() const {
214    const Decl *D = getDecl();
215    if (!D)
216      return false;
217
218    SourceLocation Loc = D->getLocation();
219    if (Loc.isValid()) {
220      const SourceManager &SM =
221        getState()->getStateManager().getContext().getSourceManager();
222      return SM.isInSystemHeader(D->getLocation());
223    }
224
225    // Special case for implicitly-declared global operator new/delete.
226    // These should be considered system functions.
227    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
228      return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
229
230    return false;
231  }
232
233  /// \brief Returns a source range for the entire call, suitable for
234  /// outputting in diagnostics.
235  virtual SourceRange getSourceRange() const {
236    return getOriginExpr()->getSourceRange();
237  }
238
239  /// \brief Returns the value of a given argument at the time of the call.
240  virtual SVal getArgSVal(unsigned Index) const;
241
242  /// \brief Returns the expression associated with a given argument.
243  /// May be null if this expression does not appear in the source.
244  virtual const Expr *getArgExpr(unsigned Index) const { return 0; }
245
246  /// \brief Returns the source range for errors associated with this argument.
247  ///
248  /// May be invalid if the argument is not written in the source.
249  virtual SourceRange getArgSourceRange(unsigned Index) const;
250
251  /// \brief Returns the result type, adjusted for references.
252  QualType getResultType() const;
253
254  /// \brief Returns true if any of the arguments appear to represent callbacks.
255  bool hasNonZeroCallbackArg() const;
256
257  /// \brief Returns true if any of the arguments are known to escape to long-
258  /// term storage, even if this method will not modify them.
259  // NOTE: The exact semantics of this are still being defined!
260  // We don't really want a list of hardcoded exceptions in the long run,
261  // but we don't want duplicated lists of known APIs in the short term either.
262  virtual bool argumentsMayEscape() const {
263    return hasNonZeroCallbackArg();
264  }
265
266  /// \brief Returns an appropriate ProgramPoint for this call.
267  ProgramPoint getProgramPoint(bool IsPreVisit = false,
268                               const ProgramPointTag *Tag = 0) const;
269
270  /// \brief Returns a new state with all argument regions invalidated.
271  ///
272  /// This accepts an alternate state in case some processing has already
273  /// occurred.
274  ProgramStateRef invalidateRegions(unsigned BlockCount,
275                                    ProgramStateRef Orig = 0) const;
276
277  typedef std::pair<Loc, SVal> FrameBindingTy;
278  typedef SmallVectorImpl<FrameBindingTy> BindingsTy;
279
280  /// Populates the given SmallVector with the bindings in the callee's stack
281  /// frame at the start of this call.
282  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
283                                            BindingsTy &Bindings) const = 0;
284
285  /// Returns a copy of this CallEvent, but using the given state.
286  template <typename T>
287  CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
288
289  /// Returns a copy of this CallEvent, but using the given state.
290  CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
291    return cloneWithState<CallEvent>(NewState);
292  }
293
294  /// \brief Returns true if this is a statement that can be considered for
295  /// inlining.
296  ///
297  /// FIXME: This should go away once CallEvents are cheap and easy to
298  /// construct from ExplodedNodes.
299  static bool mayBeInlined(const Stmt *S);
300
301  // Iterator access to formal parameters and their types.
302private:
303  typedef std::const_mem_fun_t<QualType, ParmVarDecl> get_type_fun;
304
305public:
306  typedef const ParmVarDecl * const *param_iterator;
307
308  /// Returns an iterator over the call's formal parameters.
309  ///
310  /// If UseDefinitionParams is set, this will return the parameter decls
311  /// used in the callee's definition (suitable for inlining). Most of the
312  /// time it is better to use the decl found by name lookup, which likely
313  /// carries more annotations.
314  ///
315  /// Remember that the number of formal parameters may not match the number
316  /// of arguments for all calls. However, the first parameter will always
317  /// correspond with the argument value returned by \c getArgSVal(0).
318  ///
319  /// If the call has no accessible declaration (or definition, if
320  /// \p UseDefinitionParams is set), \c param_begin() will be equal to
321  /// \c param_end().
322  virtual param_iterator param_begin() const =0;
323  /// \sa param_begin()
324  virtual param_iterator param_end() const = 0;
325
326  typedef llvm::mapped_iterator<param_iterator, get_type_fun>
327    param_type_iterator;
328
329  /// Returns an iterator over the types of the call's formal parameters.
330  ///
331  /// This uses the callee decl found by default name lookup rather than the
332  /// definition because it represents a public interface, and probably has
333  /// more annotations.
334  param_type_iterator param_type_begin() const {
335    return llvm::map_iterator(param_begin(),
336                              get_type_fun(&ParmVarDecl::getType));
337  }
338  /// \sa param_type_begin()
339  param_type_iterator param_type_end() const {
340    return llvm::map_iterator(param_end(), get_type_fun(&ParmVarDecl::getType));
341  }
342
343  // For debugging purposes only
344  void dump(raw_ostream &Out) const;
345  LLVM_ATTRIBUTE_USED void dump() const;
346
347  static bool classof(const CallEvent *) { return true; }
348};
349
350
351/// \brief Represents a call to any sort of function that might have a
352/// FunctionDecl.
353class AnyFunctionCall : public CallEvent {
354protected:
355  AnyFunctionCall(const Expr *E, ProgramStateRef St,
356                  const LocationContext *LCtx)
357    : CallEvent(E, St, LCtx) {}
358  AnyFunctionCall(const Decl *D, ProgramStateRef St,
359                  const LocationContext *LCtx)
360    : CallEvent(D, St, LCtx) {}
361  AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {}
362
363  virtual QualType getDeclaredResultType() const;
364
365public:
366  // This function is overridden by subclasses, but they must return
367  // a FunctionDecl.
368  virtual const FunctionDecl *getDecl() const {
369    return cast<FunctionDecl>(CallEvent::getDecl());
370  }
371
372  virtual RuntimeDefinition getRuntimeDefinition() const {
373    const FunctionDecl *FD = getDecl();
374    // Note that hasBody() will fill FD with the definition FunctionDecl.
375    if (FD && FD->hasBody(FD))
376      return RuntimeDefinition(FD);
377    return RuntimeDefinition();
378  }
379
380  virtual bool argumentsMayEscape() const;
381
382  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
383                                            BindingsTy &Bindings) const;
384
385  virtual param_iterator param_begin() const;
386  virtual param_iterator param_end() const;
387
388  static bool classof(const CallEvent *CA) {
389    return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
390           CA->getKind() <= CE_END_FUNCTION_CALLS;
391  }
392};
393
394/// \brief Represents a call to a non-C++ function, written as a CallExpr.
395class SimpleCall : public AnyFunctionCall {
396protected:
397  SimpleCall(const CallExpr *CE, ProgramStateRef St,
398             const LocationContext *LCtx)
399    : AnyFunctionCall(CE, St, LCtx) {}
400  SimpleCall(const SimpleCall &Other) : AnyFunctionCall(Other) {}
401
402public:
403  virtual const CallExpr *getOriginExpr() const {
404    return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
405  }
406
407  virtual const FunctionDecl *getDecl() const;
408
409  virtual unsigned getNumArgs() const { return getOriginExpr()->getNumArgs(); }
410
411  virtual const Expr *getArgExpr(unsigned Index) const {
412    return getOriginExpr()->getArg(Index);
413  }
414
415  static bool classof(const CallEvent *CA) {
416    return CA->getKind() >= CE_BEG_SIMPLE_CALLS &&
417           CA->getKind() <= CE_END_SIMPLE_CALLS;
418  }
419};
420
421/// \brief Represents a C function or static C++ member function call.
422///
423/// Example: \c fun()
424class FunctionCall : public SimpleCall {
425  friend class CallEventManager;
426
427protected:
428  FunctionCall(const CallExpr *CE, ProgramStateRef St,
429               const LocationContext *LCtx)
430    : SimpleCall(CE, St, LCtx) {}
431
432  FunctionCall(const FunctionCall &Other) : SimpleCall(Other) {}
433  virtual void cloneTo(void *Dest) const { new (Dest) FunctionCall(*this); }
434
435public:
436  virtual Kind getKind() const { return CE_Function; }
437
438  static bool classof(const CallEvent *CA) {
439    return CA->getKind() == CE_Function;
440  }
441};
442
443/// \brief Represents a call to a block.
444///
445/// Example: <tt>^{ /* ... */ }()</tt>
446class BlockCall : public SimpleCall {
447  friend class CallEventManager;
448
449protected:
450  BlockCall(const CallExpr *CE, ProgramStateRef St,
451            const LocationContext *LCtx)
452    : SimpleCall(CE, St, LCtx) {}
453
454  BlockCall(const BlockCall &Other) : SimpleCall(Other) {}
455  virtual void cloneTo(void *Dest) const { new (Dest) BlockCall(*this); }
456
457  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
458
459  virtual QualType getDeclaredResultType() const;
460
461public:
462  /// \brief Returns the region associated with this instance of the block.
463  ///
464  /// This may be NULL if the block's origin is unknown.
465  const BlockDataRegion *getBlockRegion() const;
466
467  /// \brief Gets the declaration of the block.
468  ///
469  /// This is not an override of getDecl() because AnyFunctionCall has already
470  /// assumed that it's a FunctionDecl.
471  const BlockDecl *getBlockDecl() const {
472    const BlockDataRegion *BR = getBlockRegion();
473    if (!BR)
474      return 0;
475    return BR->getDecl();
476  }
477
478  virtual RuntimeDefinition getRuntimeDefinition() const {
479    return RuntimeDefinition(getBlockDecl());
480  }
481
482  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
483                                            BindingsTy &Bindings) const;
484
485  virtual param_iterator param_begin() const;
486  virtual param_iterator param_end() const;
487
488  virtual Kind getKind() const { return CE_Block; }
489
490  static bool classof(const CallEvent *CA) {
491    return CA->getKind() == CE_Block;
492  }
493};
494
495/// \brief Represents a non-static C++ member function call, no matter how
496/// it is written.
497class CXXInstanceCall : public AnyFunctionCall {
498protected:
499  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
500
501  CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
502                  const LocationContext *LCtx)
503    : AnyFunctionCall(CE, St, LCtx) {}
504  CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
505                  const LocationContext *LCtx)
506    : AnyFunctionCall(D, St, LCtx) {}
507
508
509  CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {}
510
511public:
512  /// \brief Returns the expression representing the implicit 'this' object.
513  virtual const Expr *getCXXThisExpr() const { return 0; }
514
515  /// \brief Returns the value of the implicit 'this' object.
516  virtual SVal getCXXThisVal() const {
517    const Expr *Base = getCXXThisExpr();
518    // FIXME: This doesn't handle an overloaded ->* operator.
519    if (!Base)
520      return UnknownVal();
521    return getSVal(Base);
522  }
523
524  virtual const FunctionDecl *getDecl() const;
525
526  virtual RuntimeDefinition getRuntimeDefinition() const;
527
528  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
529                                            BindingsTy &Bindings) const;
530
531  static bool classof(const CallEvent *CA) {
532    return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
533           CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
534  }
535};
536
537/// \brief Represents a non-static C++ member function call.
538///
539/// Example: \c obj.fun()
540class CXXMemberCall : public CXXInstanceCall {
541  friend class CallEventManager;
542
543protected:
544  CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
545                const LocationContext *LCtx)
546    : CXXInstanceCall(CE, St, LCtx) {}
547
548  CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
549  virtual void cloneTo(void *Dest) const { new (Dest) CXXMemberCall(*this); }
550
551public:
552  virtual const CXXMemberCallExpr *getOriginExpr() const {
553    return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
554  }
555
556  virtual unsigned getNumArgs() const {
557    if (const CallExpr *CE = getOriginExpr())
558      return CE->getNumArgs();
559    return 0;
560  }
561
562  virtual const Expr *getArgExpr(unsigned Index) const {
563    return getOriginExpr()->getArg(Index);
564  }
565
566  virtual const Expr *getCXXThisExpr() const;
567
568  virtual Kind getKind() const { return CE_CXXMember; }
569
570  static bool classof(const CallEvent *CA) {
571    return CA->getKind() == CE_CXXMember;
572  }
573};
574
575/// \brief Represents a C++ overloaded operator call where the operator is
576/// implemented as a non-static member function.
577///
578/// Example: <tt>iter + 1</tt>
579class CXXMemberOperatorCall : public CXXInstanceCall {
580  friend class CallEventManager;
581
582protected:
583  CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
584                        const LocationContext *LCtx)
585    : CXXInstanceCall(CE, St, LCtx) {}
586
587  CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
588    : CXXInstanceCall(Other) {}
589  virtual void cloneTo(void *Dest) const {
590    new (Dest) CXXMemberOperatorCall(*this);
591  }
592
593public:
594  virtual const CXXOperatorCallExpr *getOriginExpr() const {
595    return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
596  }
597
598  virtual unsigned getNumArgs() const {
599    return getOriginExpr()->getNumArgs() - 1;
600  }
601  virtual const Expr *getArgExpr(unsigned Index) const {
602    return getOriginExpr()->getArg(Index + 1);
603  }
604
605  virtual const Expr *getCXXThisExpr() const;
606
607  virtual Kind getKind() const { return CE_CXXMemberOperator; }
608
609  static bool classof(const CallEvent *CA) {
610    return CA->getKind() == CE_CXXMemberOperator;
611  }
612};
613
614/// \brief Represents an implicit call to a C++ destructor.
615///
616/// This can occur at the end of a scope (for automatic objects), at the end
617/// of a full-expression (for temporaries), or as part of a delete.
618class CXXDestructorCall : public CXXInstanceCall {
619  friend class CallEventManager;
620
621protected:
622  /// Creates an implicit destructor.
623  ///
624  /// \param DD The destructor that will be called.
625  /// \param Trigger The statement whose completion causes this destructor call.
626  /// \param Target The object region to be destructed.
627  /// \param St The path-sensitive state at this point in the program.
628  /// \param LCtx The location context at this point in the program.
629  CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
630                    const MemRegion *Target, ProgramStateRef St,
631                    const LocationContext *LCtx)
632    : CXXInstanceCall(DD, St, LCtx) {
633    Data = Target;
634    Location = Trigger->getLocEnd();
635  }
636
637  CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {}
638  virtual void cloneTo(void *Dest) const { new (Dest) CXXDestructorCall(*this); }
639
640public:
641  virtual SourceRange getSourceRange() const { return Location; }
642  virtual unsigned getNumArgs() const { return 0; }
643
644  /// \brief Returns the value of the implicit 'this' object.
645  virtual SVal getCXXThisVal() const;
646
647  virtual Kind getKind() const { return CE_CXXDestructor; }
648
649  static bool classof(const CallEvent *CA) {
650    return CA->getKind() == CE_CXXDestructor;
651  }
652};
653
654/// \brief Represents a call to a C++ constructor.
655///
656/// Example: \c T(1)
657class CXXConstructorCall : public AnyFunctionCall {
658  friend class CallEventManager;
659
660protected:
661  /// Creates a constructor call.
662  ///
663  /// \param CE The constructor expression as written in the source.
664  /// \param Target The region where the object should be constructed. If NULL,
665  ///               a new symbolic region will be used.
666  /// \param St The path-sensitive state at this point in the program.
667  /// \param LCtx The location context at this point in the program.
668  CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *target,
669                     ProgramStateRef St, const LocationContext *LCtx)
670    : AnyFunctionCall(CE, St, LCtx) {
671    Data = target;
672  }
673
674  CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
675  virtual void cloneTo(void *Dest) const { new (Dest) CXXConstructorCall(*this); }
676
677  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
678
679public:
680  virtual const CXXConstructExpr *getOriginExpr() const {
681    return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
682  }
683
684  virtual const CXXConstructorDecl *getDecl() const {
685    return getOriginExpr()->getConstructor();
686  }
687
688  virtual unsigned getNumArgs() const { return getOriginExpr()->getNumArgs(); }
689
690  virtual const Expr *getArgExpr(unsigned Index) const {
691    return getOriginExpr()->getArg(Index);
692  }
693
694  /// \brief Returns the value of the implicit 'this' object.
695  SVal getCXXThisVal() const;
696
697  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
698                                            BindingsTy &Bindings) const;
699
700  virtual Kind getKind() const { return CE_CXXConstructor; }
701
702  static bool classof(const CallEvent *CA) {
703    return CA->getKind() == CE_CXXConstructor;
704  }
705};
706
707/// \brief Represents the memory allocation call in a C++ new-expression.
708///
709/// This is a call to "operator new".
710class CXXAllocatorCall : public AnyFunctionCall {
711  friend class CallEventManager;
712
713protected:
714  CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
715                   const LocationContext *LCtx)
716    : AnyFunctionCall(E, St, LCtx) {}
717
718  CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
719  virtual void cloneTo(void *Dest) const { new (Dest) CXXAllocatorCall(*this); }
720
721public:
722  virtual const CXXNewExpr *getOriginExpr() const {
723    return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
724  }
725
726  virtual const FunctionDecl *getDecl() const {
727    return getOriginExpr()->getOperatorNew();
728  }
729
730  virtual unsigned getNumArgs() const {
731    return getOriginExpr()->getNumPlacementArgs() + 1;
732  }
733
734  virtual const Expr *getArgExpr(unsigned Index) const {
735    // The first argument of an allocator call is the size of the allocation.
736    if (Index == 0)
737      return 0;
738    return getOriginExpr()->getPlacementArg(Index - 1);
739  }
740
741  virtual Kind getKind() const { return CE_CXXAllocator; }
742
743  static bool classof(const CallEvent *CE) {
744    return CE->getKind() == CE_CXXAllocator;
745  }
746};
747
748/// \brief Represents the ways an Objective-C message send can occur.
749//
750// Note to maintainers: OCM_Message should always be last, since it does not
751// need to fit in the Data field's low bits.
752enum ObjCMessageKind {
753  OCM_PropertyAccess,
754  OCM_Subscript,
755  OCM_Message
756};
757
758/// \brief Represents any expression that calls an Objective-C method.
759///
760/// This includes all of the kinds listed in ObjCMessageKind.
761class ObjCMethodCall : public CallEvent {
762  friend class CallEventManager;
763
764  const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
765
766protected:
767  ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
768                 const LocationContext *LCtx)
769    : CallEvent(Msg, St, LCtx) {
770    Data = 0;
771  }
772
773  ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
774  virtual void cloneTo(void *Dest) const { new (Dest) ObjCMethodCall(*this); }
775
776  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
777
778  virtual QualType getDeclaredResultType() const;
779
780  /// Check if the selector may have multiple definitions (may have overrides).
781  virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
782                                        Selector Sel) const;
783
784public:
785  virtual const ObjCMessageExpr *getOriginExpr() const {
786    return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
787  }
788  virtual const ObjCMethodDecl *getDecl() const {
789    return getOriginExpr()->getMethodDecl();
790  }
791  virtual unsigned getNumArgs() const {
792    return getOriginExpr()->getNumArgs();
793  }
794  virtual const Expr *getArgExpr(unsigned Index) const {
795    return getOriginExpr()->getArg(Index);
796  }
797
798  bool isInstanceMessage() const {
799    return getOriginExpr()->isInstanceMessage();
800  }
801  ObjCMethodFamily getMethodFamily() const {
802    return getOriginExpr()->getMethodFamily();
803  }
804  Selector getSelector() const {
805    return getOriginExpr()->getSelector();
806  }
807
808  virtual SourceRange getSourceRange() const;
809
810  /// \brief Returns the value of the receiver at the time of this call.
811  SVal getReceiverSVal() const;
812
813  /// \brief Get the interface for the receiver.
814  ///
815  /// This works whether this is an instance message or a class message.
816  /// However, it currently just uses the static type of the receiver.
817  const ObjCInterfaceDecl *getReceiverInterface() const {
818    return getOriginExpr()->getReceiverInterface();
819  }
820
821  /// Returns how the message was written in the source (property access,
822  /// subscript, or explicit message send).
823  ObjCMessageKind getMessageKind() const;
824
825  /// Returns true if this property access or subscript is a setter (has the
826  /// form of an assignment).
827  bool isSetter() const {
828    switch (getMessageKind()) {
829    case OCM_Message:
830      llvm_unreachable("This is not a pseudo-object access!");
831    case OCM_PropertyAccess:
832      return getNumArgs() > 0;
833    case OCM_Subscript:
834      return getNumArgs() > 1;
835    }
836    llvm_unreachable("Unknown message kind");
837  }
838
839  virtual RuntimeDefinition getRuntimeDefinition() const;
840
841  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
842                                            BindingsTy &Bindings) const;
843
844  virtual param_iterator param_begin() const;
845  virtual param_iterator param_end() const;
846
847  virtual Kind getKind() const { return CE_ObjCMessage; }
848
849  static bool classof(const CallEvent *CA) {
850    return CA->getKind() == CE_ObjCMessage;
851  }
852};
853
854
855/// \brief Manages the lifetime of CallEvent objects.
856///
857/// CallEventManager provides a way to create arbitrary CallEvents "on the
858/// stack" as if they were value objects by keeping a cache of CallEvent-sized
859/// memory blocks. The CallEvents created by CallEventManager are only valid
860/// for the lifetime of the OwnedCallEvent that holds them; right now these
861/// objects cannot be copied and ownership cannot be transferred.
862class CallEventManager {
863  friend class CallEvent;
864
865  llvm::BumpPtrAllocator &Alloc;
866  SmallVector<void *, 8> Cache;
867
868  void reclaim(const void *Memory) {
869    Cache.push_back(const_cast<void *>(Memory));
870  }
871
872  /// Returns memory that can be initialized as a CallEvent.
873  void *allocate() {
874    if (Cache.empty())
875      return Alloc.Allocate<FunctionCall>();
876    else
877      return Cache.pop_back_val();
878  }
879
880  template <typename T, typename Arg>
881  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
882    return new (allocate()) T(A, St, LCtx);
883  }
884
885  template <typename T, typename Arg1, typename Arg2>
886  T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
887    return new (allocate()) T(A1, A2, St, LCtx);
888  }
889
890  template <typename T, typename Arg1, typename Arg2, typename Arg3>
891  T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
892            const LocationContext *LCtx) {
893    return new (allocate()) T(A1, A2, A3, St, LCtx);
894  }
895
896public:
897  CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
898
899
900  CallEventRef<>
901  getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
902
903
904  CallEventRef<>
905  getSimpleCall(const CallExpr *E, ProgramStateRef State,
906                const LocationContext *LCtx);
907
908  CallEventRef<ObjCMethodCall>
909  getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
910                    const LocationContext *LCtx) {
911    return create<ObjCMethodCall>(E, State, LCtx);
912  }
913
914  CallEventRef<CXXConstructorCall>
915  getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
916                        ProgramStateRef State, const LocationContext *LCtx) {
917    return create<CXXConstructorCall>(E, Target, State, LCtx);
918  }
919
920  CallEventRef<CXXDestructorCall>
921  getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
922                       const MemRegion *Target, ProgramStateRef State,
923                       const LocationContext *LCtx) {
924    return create<CXXDestructorCall>(DD, Trigger, Target, State, LCtx);
925  }
926
927  CallEventRef<CXXAllocatorCall>
928  getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
929                      const LocationContext *LCtx) {
930    return create<CXXAllocatorCall>(E, State, LCtx);
931  }
932};
933
934
935template <typename T>
936CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
937  assert(isa<T>(*this) && "Cloning to unrelated type");
938  assert(sizeof(T) == sizeof(CallEvent) && "Subclasses may not add fields");
939
940  if (NewState == State)
941    return cast<T>(this);
942
943  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
944  T *Copy = static_cast<T *>(Mgr.allocate());
945  cloneTo(Copy);
946  assert(Copy->getKind() == this->getKind() && "Bad copy");
947
948  Copy->State = NewState;
949  return Copy;
950}
951
952inline void CallEvent::Release() const {
953  assert(RefCount > 0 && "Reference count is already zero.");
954  --RefCount;
955
956  if (RefCount > 0)
957    return;
958
959  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
960  Mgr.reclaim(this);
961
962  this->~CallEvent();
963}
964
965} // end namespace ento
966} // end namespace clang
967
968namespace llvm {
969  // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
970  template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
971    typedef const T *SimpleType;
972
973    static SimpleType
974    getSimplifiedValue(const clang::ento::CallEventRef<T>& Val) {
975      return Val.getPtr();
976    }
977  };
978}
979
980#endif
981