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