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