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