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