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