1 //===- CallEvent.h - Wrapper for all function and method calls ----*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Analysis/AnalysisDeclContext.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"
31 class ProgramPointTag;
40 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
41 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
44 CE_BEG_FUNCTION_CALLS = CE_Function,
45 CE_END_FUNCTION_CALLS = CE_CXXAllocator,
51 class CallEventManager;
53 /// This class represents a description of a function call using the number of
54 /// arguments and the name of the function.
55 class CallDescription {
57 mutable IdentifierInfo *II;
58 mutable bool IsLookupDone;
60 unsigned RequiredArgs;
63 const static unsigned NoArgRequirement = ~0;
64 /// \brief Constructs a CallDescription object.
66 /// @param FuncName The name of the function that will be matched.
68 /// @param RequiredArgs The number of arguments that is expected to match a
69 /// call. Omit this parameter to match every occurance of call with a given
70 /// name regardless the number of arguments.
71 CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
72 : II(nullptr), IsLookupDone(false), FuncName(FuncName),
73 RequiredArgs(RequiredArgs) {}
75 /// \brief Get the name of the function that this object matches.
76 StringRef getFunctionName() const { return FuncName; }
79 template<typename T = CallEvent>
80 class CallEventRef : public IntrusiveRefCntPtr<const T> {
82 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
83 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
85 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
86 return this->get()->template cloneWithState<T>(State);
89 // Allow implicit conversions to a superclass type, since CallEventRef
90 // behaves like a pointer-to-const.
91 template <typename SuperT>
92 operator CallEventRef<SuperT> () const {
97 /// \class RuntimeDefinition
98 /// \brief Defines the runtime definition of the called function.
100 /// Encapsulates the information we have about which Decl will be used
101 /// when the call is executed on the given path. When dealing with dynamic
102 /// dispatch, the information is based on DynamicTypeInfo and might not be
104 class RuntimeDefinition {
105 /// The Declaration of the function which could be called at runtime.
106 /// NULL if not available.
109 /// The region representing an object (ObjC/C++) on which the method is
110 /// called. With dynamic dispatch, the method definition depends on the
111 /// runtime type of this object. NULL when the DynamicTypeInfo is
116 RuntimeDefinition(): D(nullptr), R(nullptr) {}
117 RuntimeDefinition(const Decl *InD): D(InD), R(nullptr) {}
118 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
119 const Decl *getDecl() { return D; }
121 /// \brief Check if the definition we have is precise.
122 /// If not, it is possible that the call dispatches to another definition at
124 bool mayHaveOtherDefinitions() { return R != nullptr; }
126 /// When other definitions are possible, returns the region whose runtime type
127 /// determines the method definition.
128 const MemRegion *getDispatchRegion() { return R; }
131 /// \brief Represents an abstract call to a function or method along a
134 /// CallEvents are created through the factory methods of CallEventManager.
136 /// CallEvents should always be cheap to create and destroy. In order for
137 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
138 /// subclasses of CallEvent may not add any data members to the base class.
139 /// Use the "Data" and "Location" fields instead.
142 typedef CallEventKind Kind;
145 ProgramStateRef State;
146 const LocationContext *LCtx;
147 llvm::PointerUnion<const Expr *, const Decl *> Origin;
149 void operator=(const CallEvent &) = delete;
152 // This is user data for subclasses.
155 // This is user data for subclasses.
156 // This should come right before RefCount, so that the two fields can be
157 // packed together on LP64 platforms.
158 SourceLocation Location;
161 mutable unsigned RefCount;
163 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
164 void Retain() const { ++RefCount; }
165 void Release() const;
168 friend class CallEventManager;
170 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
171 : State(std::move(state)), LCtx(lctx), Origin(E), RefCount(0) {}
173 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
174 : State(std::move(state)), LCtx(lctx), Origin(D), RefCount(0) {}
176 // DO NOT MAKE PUBLIC
177 CallEvent(const CallEvent &Original)
178 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
179 Data(Original.Data), Location(Original.Location), RefCount(0) {}
181 /// Copies this CallEvent, with vtable intact, into a new block of memory.
182 virtual void cloneTo(void *Dest) const = 0;
184 /// \brief Get the value of arbitrary expressions at this point in the path.
185 SVal getSVal(const Stmt *S) const {
186 return getState()->getSVal(S, getLocationContext());
190 typedef SmallVectorImpl<SVal> ValueList;
192 /// \brief Used to specify non-argument regions that will be invalidated as a
193 /// result of this call.
194 virtual void getExtraInvalidatedValues(ValueList &Values,
195 RegionAndSymbolInvalidationTraits *ETraits) const {}
198 virtual ~CallEvent() {}
200 /// \brief Returns the kind of call this is.
201 virtual Kind getKind() const = 0;
203 /// \brief Returns the declaration of the function or method that will be
204 /// called. May be null.
205 virtual const Decl *getDecl() const {
206 return Origin.dyn_cast<const Decl *>();
209 /// \brief The state in which the call is being evaluated.
210 const ProgramStateRef &getState() const {
214 /// \brief The context in which the call is being evaluated.
215 const LocationContext *getLocationContext() const {
219 /// \brief Returns the definition of the function or method that will be
221 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
223 /// \brief Returns the expression whose value will be the result of this call.
225 const Expr *getOriginExpr() const {
226 return Origin.dyn_cast<const Expr *>();
229 /// \brief Returns the number of arguments (explicit and implicit).
231 /// Note that this may be greater than the number of parameters in the
232 /// callee's declaration, and that it may include arguments not written in
234 virtual unsigned getNumArgs() const = 0;
236 /// \brief Returns true if the callee is known to be from a system header.
237 bool isInSystemHeader() const {
238 const Decl *D = getDecl();
242 SourceLocation Loc = D->getLocation();
244 const SourceManager &SM =
245 getState()->getStateManager().getContext().getSourceManager();
246 return SM.isInSystemHeader(D->getLocation());
249 // Special case for implicitly-declared global operator new/delete.
250 // These should be considered system functions.
251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
252 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
257 /// \brief Returns true if the CallEvent is a call to a function that matches
258 /// the CallDescription.
260 /// Note that this function is not intended to be used to match Obj-C method
262 bool isCalled(const CallDescription &CD) const;
264 /// \brief Returns a source range for the entire call, suitable for
265 /// outputting in diagnostics.
266 virtual SourceRange getSourceRange() const {
267 return getOriginExpr()->getSourceRange();
270 /// \brief Returns the value of a given argument at the time of the call.
271 virtual SVal getArgSVal(unsigned Index) const;
273 /// \brief Returns the expression associated with a given argument.
274 /// May be null if this expression does not appear in the source.
275 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
277 /// \brief Returns the source range for errors associated with this argument.
279 /// May be invalid if the argument is not written in the source.
280 virtual SourceRange getArgSourceRange(unsigned Index) const;
282 /// \brief Returns the result type, adjusted for references.
283 QualType getResultType() const;
285 /// \brief Returns the return value of the call.
287 /// This should only be called if the CallEvent was created using a state in
288 /// which the return value has already been bound to the origin expression.
289 SVal getReturnValue() const;
291 /// \brief Returns true if the type of any of the non-null arguments satisfies
293 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
295 /// \brief Returns true if any of the arguments appear to represent callbacks.
296 bool hasNonZeroCallbackArg() const;
298 /// \brief Returns true if any of the arguments is void*.
299 bool hasVoidPointerToNonConstArg() const;
301 /// \brief Returns true if any of the arguments are known to escape to long-
302 /// term storage, even if this method will not modify them.
303 // NOTE: The exact semantics of this are still being defined!
304 // We don't really want a list of hardcoded exceptions in the long run,
305 // but we don't want duplicated lists of known APIs in the short term either.
306 virtual bool argumentsMayEscape() const {
307 return hasNonZeroCallbackArg();
310 /// \brief Returns true if the callee is an externally-visible function in the
311 /// top-level namespace, such as \c malloc.
313 /// You can use this call to determine that a particular function really is
314 /// a library function and not, say, a C++ member function with the same name.
316 /// If a name is provided, the function must additionally match the given
319 /// Note that this deliberately excludes C++ library functions in the \c std
320 /// namespace, but will include C library functions accessed through the
321 /// \c std namespace. This also does not check if the function is declared
322 /// as 'extern "C"', or if it uses C++ name mangling.
323 // FIXME: Add a helper for checking namespaces.
324 // FIXME: Move this down to AnyFunctionCall once checkers have more
325 // precise callbacks.
326 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
328 /// \brief Returns the name of the callee, if its name is a simple identifier.
330 /// Note that this will fail for Objective-C methods, blocks, and C++
331 /// overloaded operators. The former is named by a Selector rather than a
332 /// simple identifier, and the latter two do not have names.
333 // FIXME: Move this down to AnyFunctionCall once checkers have more
334 // precise callbacks.
335 const IdentifierInfo *getCalleeIdentifier() const {
336 const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(getDecl());
339 return ND->getIdentifier();
342 /// \brief Returns an appropriate ProgramPoint for this call.
343 ProgramPoint getProgramPoint(bool IsPreVisit = false,
344 const ProgramPointTag *Tag = nullptr) const;
346 /// \brief Returns a new state with all argument regions invalidated.
348 /// This accepts an alternate state in case some processing has already
350 ProgramStateRef invalidateRegions(unsigned BlockCount,
351 ProgramStateRef Orig = nullptr) const;
353 typedef std::pair<Loc, SVal> FrameBindingTy;
354 typedef SmallVectorImpl<FrameBindingTy> BindingsTy;
356 /// Populates the given SmallVector with the bindings in the callee's stack
357 /// frame at the start of this call.
358 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
359 BindingsTy &Bindings) const = 0;
361 /// Returns a copy of this CallEvent, but using the given state.
362 template <typename T>
363 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
365 /// Returns a copy of this CallEvent, but using the given state.
366 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
367 return cloneWithState<CallEvent>(NewState);
370 /// \brief Returns true if this is a statement is a function or method call
372 static bool isCallStmt(const Stmt *S);
374 /// \brief Returns the result type of a function or method declaration.
376 /// This will return a null QualType if the result type cannot be determined.
377 static QualType getDeclaredResultType(const Decl *D);
379 /// \brief Returns true if the given decl is known to be variadic.
381 /// \p D must not be null.
382 static bool isVariadic(const Decl *D);
384 // Iterator access to formal parameters and their types.
387 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
391 /// Return call's formal parameters.
393 /// Remember that the number of formal parameters may not match the number
394 /// of arguments for all calls. However, the first parameter will always
395 /// correspond with the argument value returned by \c getArgSVal(0).
396 virtual ArrayRef<ParmVarDecl*> parameters() const = 0;
398 typedef llvm::mapped_iterator<ArrayRef<ParmVarDecl*>::iterator, GetTypeFn>
401 /// Returns an iterator over the types of the call's formal parameters.
403 /// This uses the callee decl found by default name lookup rather than the
404 /// definition because it represents a public interface, and probably has
405 /// more annotations.
406 param_type_iterator param_type_begin() const {
407 return llvm::map_iterator(parameters().begin(), GetTypeFn());
409 /// \sa param_type_begin()
410 param_type_iterator param_type_end() const {
411 return llvm::map_iterator(parameters().end(), GetTypeFn());
414 // For debugging purposes only
415 void dump(raw_ostream &Out) const;
420 /// \brief Represents a call to any sort of function that might have a
422 class AnyFunctionCall : public CallEvent {
424 AnyFunctionCall(const Expr *E, ProgramStateRef St,
425 const LocationContext *LCtx)
426 : CallEvent(E, St, LCtx) {}
427 AnyFunctionCall(const Decl *D, ProgramStateRef St,
428 const LocationContext *LCtx)
429 : CallEvent(D, St, LCtx) {}
430 AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {}
433 // This function is overridden by subclasses, but they must return
435 const FunctionDecl *getDecl() const override {
436 return cast<FunctionDecl>(CallEvent::getDecl());
439 RuntimeDefinition getRuntimeDefinition() const override;
441 bool argumentsMayEscape() const override;
443 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
444 BindingsTy &Bindings) const override;
446 ArrayRef<ParmVarDecl *> parameters() const override;
448 static bool classof(const CallEvent *CA) {
449 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
450 CA->getKind() <= CE_END_FUNCTION_CALLS;
454 /// \brief Represents a C function or static C++ member function call.
456 /// Example: \c fun()
457 class SimpleFunctionCall : public AnyFunctionCall {
458 friend class CallEventManager;
461 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
462 const LocationContext *LCtx)
463 : AnyFunctionCall(CE, St, LCtx) {}
464 SimpleFunctionCall(const SimpleFunctionCall &Other)
465 : AnyFunctionCall(Other) {}
466 void cloneTo(void *Dest) const override {
467 new (Dest) SimpleFunctionCall(*this);
471 virtual const CallExpr *getOriginExpr() const {
472 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
475 const FunctionDecl *getDecl() const override;
477 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
479 const Expr *getArgExpr(unsigned Index) const override {
480 return getOriginExpr()->getArg(Index);
483 Kind getKind() const override { return CE_Function; }
485 static bool classof(const CallEvent *CA) {
486 return CA->getKind() == CE_Function;
490 /// \brief Represents a call to a block.
492 /// Example: <tt>^{ /* ... */ }()</tt>
493 class BlockCall : public CallEvent {
494 friend class CallEventManager;
497 BlockCall(const CallExpr *CE, ProgramStateRef St,
498 const LocationContext *LCtx)
499 : CallEvent(CE, St, LCtx) {}
501 BlockCall(const BlockCall &Other) : CallEvent(Other) {}
502 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
504 void getExtraInvalidatedValues(ValueList &Values,
505 RegionAndSymbolInvalidationTraits *ETraits) const override;
508 virtual const CallExpr *getOriginExpr() const {
509 return cast<CallExpr>(CallEvent::getOriginExpr());
512 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
514 const Expr *getArgExpr(unsigned Index) const override {
515 return getOriginExpr()->getArg(Index);
518 /// \brief Returns the region associated with this instance of the block.
520 /// This may be NULL if the block's origin is unknown.
521 const BlockDataRegion *getBlockRegion() const;
523 const BlockDecl *getDecl() const override {
524 const BlockDataRegion *BR = getBlockRegion();
527 return BR->getDecl();
530 bool isConversionFromLambda() const {
531 const BlockDecl *BD = getDecl();
535 return BD->isConversionFromLambda();
538 /// \brief For a block converted from a C++ lambda, returns the block
539 /// VarRegion for the variable holding the captured C++ lambda record.
540 const VarRegion *getRegionStoringCapturedLambda() const {
541 assert(isConversionFromLambda());
542 const BlockDataRegion *BR = getBlockRegion();
543 assert(BR && "Block converted from lambda must have a block region");
545 auto I = BR->referenced_vars_begin();
546 assert(I != BR->referenced_vars_end());
548 return I.getCapturedRegion();
551 RuntimeDefinition getRuntimeDefinition() const override {
552 if (!isConversionFromLambda())
553 return RuntimeDefinition(getDecl());
555 // Clang converts lambdas to blocks with an implicit user-defined
556 // conversion operator method on the lambda record that looks (roughly)
559 // typedef R(^block_type)(P1, P2, ...);
560 // operator block_type() const {
561 // auto Lambda = *this;
562 // return ^(P1 p1, P2 p2, ...){
563 // /* return Lambda(p1, p2, ...); */
567 // Here R is the return type of the lambda and P1, P2, ... are
568 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
569 // that is initialized to a copy of the lambda.
571 // Sema leaves the body of a lambda-converted block empty (it is
572 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
573 // the block body and analyze the operator() method on the captured lambda.
574 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
575 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
576 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
578 return RuntimeDefinition(LambdaCallOperator);
581 bool argumentsMayEscape() const override {
585 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
586 BindingsTy &Bindings) const override;
588 ArrayRef<ParmVarDecl*> parameters() const override;
590 Kind getKind() const override { return CE_Block; }
592 static bool classof(const CallEvent *CA) {
593 return CA->getKind() == CE_Block;
597 /// \brief Represents a non-static C++ member function call, no matter how
599 class CXXInstanceCall : public AnyFunctionCall {
601 void getExtraInvalidatedValues(ValueList &Values,
602 RegionAndSymbolInvalidationTraits *ETraits) const override;
604 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
605 const LocationContext *LCtx)
606 : AnyFunctionCall(CE, St, LCtx) {}
607 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
608 const LocationContext *LCtx)
609 : AnyFunctionCall(D, St, LCtx) {}
612 CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {}
615 /// \brief Returns the expression representing the implicit 'this' object.
616 virtual const Expr *getCXXThisExpr() const { return nullptr; }
618 /// \brief Returns the value of the implicit 'this' object.
619 virtual SVal getCXXThisVal() const;
621 const FunctionDecl *getDecl() const override;
623 RuntimeDefinition getRuntimeDefinition() const override;
625 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
626 BindingsTy &Bindings) const override;
628 static bool classof(const CallEvent *CA) {
629 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
630 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
634 /// \brief Represents a non-static C++ member function call.
636 /// Example: \c obj.fun()
637 class CXXMemberCall : public CXXInstanceCall {
638 friend class CallEventManager;
641 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
642 const LocationContext *LCtx)
643 : CXXInstanceCall(CE, St, LCtx) {}
645 CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
646 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
649 virtual const CXXMemberCallExpr *getOriginExpr() const {
650 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
653 unsigned getNumArgs() const override {
654 if (const CallExpr *CE = getOriginExpr())
655 return CE->getNumArgs();
659 const Expr *getArgExpr(unsigned Index) const override {
660 return getOriginExpr()->getArg(Index);
663 const Expr *getCXXThisExpr() const override;
665 RuntimeDefinition getRuntimeDefinition() const override;
667 Kind getKind() const override { return CE_CXXMember; }
669 static bool classof(const CallEvent *CA) {
670 return CA->getKind() == CE_CXXMember;
674 /// \brief Represents a C++ overloaded operator call where the operator is
675 /// implemented as a non-static member function.
677 /// Example: <tt>iter + 1</tt>
678 class CXXMemberOperatorCall : public CXXInstanceCall {
679 friend class CallEventManager;
682 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
683 const LocationContext *LCtx)
684 : CXXInstanceCall(CE, St, LCtx) {}
686 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
687 : CXXInstanceCall(Other) {}
688 void cloneTo(void *Dest) const override {
689 new (Dest) CXXMemberOperatorCall(*this);
693 virtual const CXXOperatorCallExpr *getOriginExpr() const {
694 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
697 unsigned getNumArgs() const override {
698 return getOriginExpr()->getNumArgs() - 1;
700 const Expr *getArgExpr(unsigned Index) const override {
701 return getOriginExpr()->getArg(Index + 1);
704 const Expr *getCXXThisExpr() const override;
706 Kind getKind() const override { return CE_CXXMemberOperator; }
708 static bool classof(const CallEvent *CA) {
709 return CA->getKind() == CE_CXXMemberOperator;
713 /// \brief Represents an implicit call to a C++ destructor.
715 /// This can occur at the end of a scope (for automatic objects), at the end
716 /// of a full-expression (for temporaries), or as part of a delete.
717 class CXXDestructorCall : public CXXInstanceCall {
718 friend class CallEventManager;
721 typedef llvm::PointerIntPair<const MemRegion *, 1, bool> DtorDataTy;
723 /// Creates an implicit destructor.
725 /// \param DD The destructor that will be called.
726 /// \param Trigger The statement whose completion causes this destructor call.
727 /// \param Target The object region to be destructed.
728 /// \param St The path-sensitive state at this point in the program.
729 /// \param LCtx The location context at this point in the program.
730 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
731 const MemRegion *Target, bool IsBaseDestructor,
732 ProgramStateRef St, const LocationContext *LCtx)
733 : CXXInstanceCall(DD, St, LCtx) {
734 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
735 Location = Trigger->getLocEnd();
738 CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {}
739 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
742 SourceRange getSourceRange() const override { return Location; }
743 unsigned getNumArgs() const override { return 0; }
745 RuntimeDefinition getRuntimeDefinition() const override;
747 /// \brief Returns the value of the implicit 'this' object.
748 SVal getCXXThisVal() const override;
750 /// Returns true if this is a call to a base class destructor.
751 bool isBaseDestructor() const {
752 return DtorDataTy::getFromOpaqueValue(Data).getInt();
755 Kind getKind() const override { return CE_CXXDestructor; }
757 static bool classof(const CallEvent *CA) {
758 return CA->getKind() == CE_CXXDestructor;
762 /// \brief Represents a call to a C++ constructor.
765 class CXXConstructorCall : public AnyFunctionCall {
766 friend class CallEventManager;
769 /// Creates a constructor call.
771 /// \param CE The constructor expression as written in the source.
772 /// \param Target The region where the object should be constructed. If NULL,
773 /// a new symbolic region will be used.
774 /// \param St The path-sensitive state at this point in the program.
775 /// \param LCtx The location context at this point in the program.
776 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
777 ProgramStateRef St, const LocationContext *LCtx)
778 : AnyFunctionCall(CE, St, LCtx) {
782 CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
783 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
785 void getExtraInvalidatedValues(ValueList &Values,
786 RegionAndSymbolInvalidationTraits *ETraits) const override;
789 virtual const CXXConstructExpr *getOriginExpr() const {
790 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
793 const CXXConstructorDecl *getDecl() const override {
794 return getOriginExpr()->getConstructor();
797 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
799 const Expr *getArgExpr(unsigned Index) const override {
800 return getOriginExpr()->getArg(Index);
803 /// \brief Returns the value of the implicit 'this' object.
804 SVal getCXXThisVal() const;
806 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
807 BindingsTy &Bindings) const override;
809 Kind getKind() const override { return CE_CXXConstructor; }
811 static bool classof(const CallEvent *CA) {
812 return CA->getKind() == CE_CXXConstructor;
816 /// \brief Represents the memory allocation call in a C++ new-expression.
818 /// This is a call to "operator new".
819 class CXXAllocatorCall : public AnyFunctionCall {
820 friend class CallEventManager;
823 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
824 const LocationContext *LCtx)
825 : AnyFunctionCall(E, St, LCtx) {}
827 CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
828 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
831 virtual const CXXNewExpr *getOriginExpr() const {
832 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
835 const FunctionDecl *getDecl() const override {
836 return getOriginExpr()->getOperatorNew();
839 unsigned getNumArgs() const override {
840 return getOriginExpr()->getNumPlacementArgs() + 1;
843 const Expr *getArgExpr(unsigned Index) const override {
844 // The first argument of an allocator call is the size of the allocation.
847 return getOriginExpr()->getPlacementArg(Index - 1);
850 Kind getKind() const override { return CE_CXXAllocator; }
852 static bool classof(const CallEvent *CE) {
853 return CE->getKind() == CE_CXXAllocator;
857 /// \brief Represents the ways an Objective-C message send can occur.
859 // Note to maintainers: OCM_Message should always be last, since it does not
860 // need to fit in the Data field's low bits.
861 enum ObjCMessageKind {
867 /// \brief Represents any expression that calls an Objective-C method.
869 /// This includes all of the kinds listed in ObjCMessageKind.
870 class ObjCMethodCall : public CallEvent {
871 friend class CallEventManager;
873 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
876 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
877 const LocationContext *LCtx)
878 : CallEvent(Msg, St, LCtx) {
882 ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
883 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
885 void getExtraInvalidatedValues(ValueList &Values,
886 RegionAndSymbolInvalidationTraits *ETraits) const override;
888 /// Check if the selector may have multiple definitions (may have overrides).
889 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
893 virtual const ObjCMessageExpr *getOriginExpr() const {
894 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
896 const ObjCMethodDecl *getDecl() const override {
897 return getOriginExpr()->getMethodDecl();
899 unsigned getNumArgs() const override {
900 return getOriginExpr()->getNumArgs();
902 const Expr *getArgExpr(unsigned Index) const override {
903 return getOriginExpr()->getArg(Index);
906 bool isInstanceMessage() const {
907 return getOriginExpr()->isInstanceMessage();
909 ObjCMethodFamily getMethodFamily() const {
910 return getOriginExpr()->getMethodFamily();
912 Selector getSelector() const {
913 return getOriginExpr()->getSelector();
916 SourceRange getSourceRange() const override;
918 /// \brief Returns the value of the receiver at the time of this call.
919 SVal getReceiverSVal() const;
921 /// \brief Return the value of 'self' if available.
922 SVal getSelfSVal() const;
924 /// \brief Get the interface for the receiver.
926 /// This works whether this is an instance message or a class message.
927 /// However, it currently just uses the static type of the receiver.
928 const ObjCInterfaceDecl *getReceiverInterface() const {
929 return getOriginExpr()->getReceiverInterface();
932 /// \brief Checks if the receiver refers to 'self' or 'super'.
933 bool isReceiverSelfOrSuper() const;
935 /// Returns how the message was written in the source (property access,
936 /// subscript, or explicit message send).
937 ObjCMessageKind getMessageKind() const;
939 /// Returns true if this property access or subscript is a setter (has the
940 /// form of an assignment).
941 bool isSetter() const {
942 switch (getMessageKind()) {
944 llvm_unreachable("This is not a pseudo-object access!");
945 case OCM_PropertyAccess:
946 return getNumArgs() > 0;
948 return getNumArgs() > 1;
950 llvm_unreachable("Unknown message kind");
953 // Returns the property accessed by this method, either explicitly via
954 // property syntax or implicitly via a getter or setter method. Returns
955 // nullptr if the call is not a prooperty access.
956 const ObjCPropertyDecl *getAccessedProperty() const;
958 RuntimeDefinition getRuntimeDefinition() const override;
960 bool argumentsMayEscape() const override;
962 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
963 BindingsTy &Bindings) const override;
965 ArrayRef<ParmVarDecl*> parameters() const override;
967 Kind getKind() const override { return CE_ObjCMessage; }
969 static bool classof(const CallEvent *CA) {
970 return CA->getKind() == CE_ObjCMessage;
975 /// \brief Manages the lifetime of CallEvent objects.
977 /// CallEventManager provides a way to create arbitrary CallEvents "on the
978 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
979 /// memory blocks. The CallEvents created by CallEventManager are only valid
980 /// for the lifetime of the OwnedCallEvent that holds them; right now these
981 /// objects cannot be copied and ownership cannot be transferred.
982 class CallEventManager {
983 friend class CallEvent;
985 llvm::BumpPtrAllocator &Alloc;
986 SmallVector<void *, 8> Cache;
987 typedef SimpleFunctionCall CallEventTemplateTy;
989 void reclaim(const void *Memory) {
990 Cache.push_back(const_cast<void *>(Memory));
993 /// Returns memory that can be initialized as a CallEvent.
996 return Alloc.Allocate<CallEventTemplateTy>();
998 return Cache.pop_back_val();
1001 template <typename T, typename Arg>
1002 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1003 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1004 "CallEvent subclasses are not all the same size");
1005 return new (allocate()) T(A, St, LCtx);
1008 template <typename T, typename Arg1, typename Arg2>
1009 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1010 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1011 "CallEvent subclasses are not all the same size");
1012 return new (allocate()) T(A1, A2, St, LCtx);
1015 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1016 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1017 const LocationContext *LCtx) {
1018 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1019 "CallEvent subclasses are not all the same size");
1020 return new (allocate()) T(A1, A2, A3, St, LCtx);
1023 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1025 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1026 const LocationContext *LCtx) {
1027 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1028 "CallEvent subclasses are not all the same size");
1029 return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1033 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1037 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1041 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1042 const LocationContext *LCtx);
1044 CallEventRef<ObjCMethodCall>
1045 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1046 const LocationContext *LCtx) {
1047 return create<ObjCMethodCall>(E, State, LCtx);
1050 CallEventRef<CXXConstructorCall>
1051 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1052 ProgramStateRef State, const LocationContext *LCtx) {
1053 return create<CXXConstructorCall>(E, Target, State, LCtx);
1056 CallEventRef<CXXDestructorCall>
1057 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1058 const MemRegion *Target, bool IsBase,
1059 ProgramStateRef State, const LocationContext *LCtx) {
1060 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1063 CallEventRef<CXXAllocatorCall>
1064 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1065 const LocationContext *LCtx) {
1066 return create<CXXAllocatorCall>(E, State, LCtx);
1071 template <typename T>
1072 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1073 assert(isa<T>(*this) && "Cloning to unrelated type");
1074 static_assert(sizeof(T) == sizeof(CallEvent),
1075 "Subclasses may not add fields");
1077 if (NewState == State)
1078 return cast<T>(this);
1080 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1081 T *Copy = static_cast<T *>(Mgr.allocate());
1083 assert(Copy->getKind() == this->getKind() && "Bad copy");
1085 Copy->State = NewState;
1089 inline void CallEvent::Release() const {
1090 assert(RefCount > 0 && "Reference count is already zero.");
1096 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1102 } // end namespace ento
1103 } // end namespace clang
1106 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1107 template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
1108 typedef const T *SimpleType;
1111 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {