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