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/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"
30 class ProgramPointTag;
39 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
40 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
43 CE_BEG_FUNCTION_CALLS = CE_Function,
44 CE_END_FUNCTION_CALLS = CE_CXXAllocator,
50 class CallEventManager;
52 /// This class represents a description of a function call using the number of
53 /// arguments and the name of the function.
54 class CallDescription {
56 mutable IdentifierInfo *II;
58 unsigned RequiredArgs;
61 const static unsigned NoArgRequirement = ~0;
62 /// \brief Constructs a CallDescription object.
64 /// @param FuncName The name of the function that will be matched.
66 /// @param RequiredArgs The number of arguments that is expected to match a
67 /// call. Omit this parameter to match every occurance of call with a given
68 /// name regardless the number of arguments.
69 CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
70 : II(nullptr), FuncName(FuncName), RequiredArgs(RequiredArgs) {}
72 /// \brief Get the name of the function that this object matches.
73 StringRef getFunctionName() const { return FuncName; }
76 template<typename T = CallEvent>
77 class CallEventRef : public IntrusiveRefCntPtr<const T> {
79 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
80 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
82 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
83 return this->get()->template cloneWithState<T>(State);
86 // Allow implicit conversions to a superclass type, since CallEventRef
87 // behaves like a pointer-to-const.
88 template <typename SuperT>
89 operator CallEventRef<SuperT> () const {
94 /// \class RuntimeDefinition
95 /// \brief Defines the runtime definition of the called function.
97 /// Encapsulates the information we have about which Decl will be used
98 /// when the call is executed on the given path. When dealing with dynamic
99 /// dispatch, the information is based on DynamicTypeInfo and might not be
101 class RuntimeDefinition {
102 /// The Declaration of the function which could be called at runtime.
103 /// NULL if not available.
106 /// The region representing an object (ObjC/C++) on which the method is
107 /// called. With dynamic dispatch, the method definition depends on the
108 /// runtime type of this object. NULL when the DynamicTypeInfo is
113 RuntimeDefinition(): D(nullptr), R(nullptr) {}
114 RuntimeDefinition(const Decl *InD): D(InD), R(nullptr) {}
115 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
116 const Decl *getDecl() { return D; }
118 /// \brief Check if the definition we have is precise.
119 /// If not, it is possible that the call dispatches to another definition at
121 bool mayHaveOtherDefinitions() { return R != nullptr; }
123 /// When other definitions are possible, returns the region whose runtime type
124 /// determines the method definition.
125 const MemRegion *getDispatchRegion() { return R; }
128 /// \brief Represents an abstract call to a function or method along a
131 /// CallEvents are created through the factory methods of CallEventManager.
133 /// CallEvents should always be cheap to create and destroy. In order for
134 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
135 /// subclasses of CallEvent may not add any data members to the base class.
136 /// Use the "Data" and "Location" fields instead.
139 typedef CallEventKind Kind;
142 ProgramStateRef State;
143 const LocationContext *LCtx;
144 llvm::PointerUnion<const Expr *, const Decl *> Origin;
146 void operator=(const CallEvent &) = delete;
149 // This is user data for subclasses.
152 // This is user data for subclasses.
153 // This should come right before RefCount, so that the two fields can be
154 // packed together on LP64 platforms.
155 SourceLocation Location;
158 mutable unsigned RefCount;
160 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
161 void Retain() const { ++RefCount; }
162 void Release() const;
165 friend class CallEventManager;
167 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
168 : State(state), LCtx(lctx), Origin(E), RefCount(0) {}
170 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
171 : State(state), LCtx(lctx), Origin(D), RefCount(0) {}
173 // DO NOT MAKE PUBLIC
174 CallEvent(const CallEvent &Original)
175 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
176 Data(Original.Data), Location(Original.Location), RefCount(0) {}
178 /// Copies this CallEvent, with vtable intact, into a new block of memory.
179 virtual void cloneTo(void *Dest) const = 0;
181 /// \brief Get the value of arbitrary expressions at this point in the path.
182 SVal getSVal(const Stmt *S) const {
183 return getState()->getSVal(S, getLocationContext());
187 typedef SmallVectorImpl<SVal> ValueList;
189 /// \brief Used to specify non-argument regions that will be invalidated as a
190 /// result of this call.
191 virtual void getExtraInvalidatedValues(ValueList &Values,
192 RegionAndSymbolInvalidationTraits *ETraits) const {}
195 virtual ~CallEvent() {}
197 /// \brief Returns the kind of call this is.
198 virtual Kind getKind() const = 0;
200 /// \brief Returns the declaration of the function or method that will be
201 /// called. May be null.
202 virtual const Decl *getDecl() const {
203 return Origin.dyn_cast<const Decl *>();
206 /// \brief The state in which the call is being evaluated.
207 const ProgramStateRef &getState() const {
211 /// \brief The context in which the call is being evaluated.
212 const LocationContext *getLocationContext() const {
216 /// \brief Returns the definition of the function or method that will be
218 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
220 /// \brief Returns the expression whose value will be the result of this call.
222 const Expr *getOriginExpr() const {
223 return Origin.dyn_cast<const Expr *>();
226 /// \brief Returns the number of arguments (explicit and implicit).
228 /// Note that this may be greater than the number of parameters in the
229 /// callee's declaration, and that it may include arguments not written in
231 virtual unsigned getNumArgs() const = 0;
233 /// \brief Returns true if the callee is known to be from a system header.
234 bool isInSystemHeader() const {
235 const Decl *D = getDecl();
239 SourceLocation Loc = D->getLocation();
241 const SourceManager &SM =
242 getState()->getStateManager().getContext().getSourceManager();
243 return SM.isInSystemHeader(D->getLocation());
246 // Special case for implicitly-declared global operator new/delete.
247 // These should be considered system functions.
248 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
249 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
254 /// \brief Returns true if the CallEvent is a call to a function that matches
255 /// the CallDescription.
257 /// Note that this function is not intended to be used to match Obj-C method
259 bool isCalled(const CallDescription &CD) const;
261 /// \brief Returns a source range for the entire call, suitable for
262 /// outputting in diagnostics.
263 virtual SourceRange getSourceRange() const {
264 return getOriginExpr()->getSourceRange();
267 /// \brief Returns the value of a given argument at the time of the call.
268 virtual SVal getArgSVal(unsigned Index) const;
270 /// \brief Returns the expression associated with a given argument.
271 /// May be null if this expression does not appear in the source.
272 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
274 /// \brief Returns the source range for errors associated with this argument.
276 /// May be invalid if the argument is not written in the source.
277 virtual SourceRange getArgSourceRange(unsigned Index) const;
279 /// \brief Returns the result type, adjusted for references.
280 QualType getResultType() const;
282 /// \brief Returns the return value of the call.
284 /// This should only be called if the CallEvent was created using a state in
285 /// which the return value has already been bound to the origin expression.
286 SVal getReturnValue() const;
288 /// \brief Returns true if the type of any of the non-null arguments satisfies
290 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
292 /// \brief Returns true if any of the arguments appear to represent callbacks.
293 bool hasNonZeroCallbackArg() const;
295 /// \brief Returns true if any of the arguments is void*.
296 bool hasVoidPointerToNonConstArg() const;
298 /// \brief Returns true if any of the arguments are known to escape to long-
299 /// term storage, even if this method will not modify them.
300 // NOTE: The exact semantics of this are still being defined!
301 // We don't really want a list of hardcoded exceptions in the long run,
302 // but we don't want duplicated lists of known APIs in the short term either.
303 virtual bool argumentsMayEscape() const {
304 return hasNonZeroCallbackArg();
307 /// \brief Returns true if the callee is an externally-visible function in the
308 /// top-level namespace, such as \c malloc.
310 /// You can use this call to determine that a particular function really is
311 /// a library function and not, say, a C++ member function with the same name.
313 /// If a name is provided, the function must additionally match the given
316 /// Note that this deliberately excludes C++ library functions in the \c std
317 /// namespace, but will include C library functions accessed through the
318 /// \c std namespace. This also does not check if the function is declared
319 /// as 'extern "C"', or if it uses C++ name mangling.
320 // FIXME: Add a helper for checking namespaces.
321 // FIXME: Move this down to AnyFunctionCall once checkers have more
322 // precise callbacks.
323 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
325 /// \brief Returns the name of the callee, if its name is a simple identifier.
327 /// Note that this will fail for Objective-C methods, blocks, and C++
328 /// overloaded operators. The former is named by a Selector rather than a
329 /// simple identifier, and the latter two do not have names.
330 // FIXME: Move this down to AnyFunctionCall once checkers have more
331 // precise callbacks.
332 const IdentifierInfo *getCalleeIdentifier() const {
333 const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(getDecl());
336 return ND->getIdentifier();
339 /// \brief Returns an appropriate ProgramPoint for this call.
340 ProgramPoint getProgramPoint(bool IsPreVisit = false,
341 const ProgramPointTag *Tag = nullptr) const;
343 /// \brief Returns a new state with all argument regions invalidated.
345 /// This accepts an alternate state in case some processing has already
347 ProgramStateRef invalidateRegions(unsigned BlockCount,
348 ProgramStateRef Orig = nullptr) const;
350 typedef std::pair<Loc, SVal> FrameBindingTy;
351 typedef SmallVectorImpl<FrameBindingTy> BindingsTy;
353 /// Populates the given SmallVector with the bindings in the callee's stack
354 /// frame at the start of this call.
355 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
356 BindingsTy &Bindings) const = 0;
358 /// Returns a copy of this CallEvent, but using the given state.
359 template <typename T>
360 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
362 /// Returns a copy of this CallEvent, but using the given state.
363 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
364 return cloneWithState<CallEvent>(NewState);
367 /// \brief Returns true if this is a statement is a function or method call
369 static bool isCallStmt(const Stmt *S);
371 /// \brief Returns the result type of a function or method declaration.
373 /// This will return a null QualType if the result type cannot be determined.
374 static QualType getDeclaredResultType(const Decl *D);
376 /// \brief Returns true if the given decl is known to be variadic.
378 /// \p D must not be null.
379 static bool isVariadic(const Decl *D);
381 // Iterator access to formal parameters and their types.
383 typedef std::const_mem_fun_t<QualType, ParmVarDecl> get_type_fun;
386 /// Return call's formal parameters.
388 /// Remember that the number of formal parameters may not match the number
389 /// of arguments for all calls. However, the first parameter will always
390 /// correspond with the argument value returned by \c getArgSVal(0).
391 virtual ArrayRef<ParmVarDecl*> parameters() const = 0;
393 typedef llvm::mapped_iterator<ArrayRef<ParmVarDecl*>::iterator, get_type_fun>
396 /// Returns an iterator over the types of the call's formal parameters.
398 /// This uses the callee decl found by default name lookup rather than the
399 /// definition because it represents a public interface, and probably has
400 /// more annotations.
401 param_type_iterator param_type_begin() const {
402 return llvm::map_iterator(parameters().begin(),
403 get_type_fun(&ParmVarDecl::getType));
405 /// \sa param_type_begin()
406 param_type_iterator param_type_end() const {
407 return llvm::map_iterator(parameters().end(),
408 get_type_fun(&ParmVarDecl::getType));
411 // For debugging purposes only
412 void dump(raw_ostream &Out) const;
417 /// \brief Represents a call to any sort of function that might have a
419 class AnyFunctionCall : public CallEvent {
421 AnyFunctionCall(const Expr *E, ProgramStateRef St,
422 const LocationContext *LCtx)
423 : CallEvent(E, St, LCtx) {}
424 AnyFunctionCall(const Decl *D, ProgramStateRef St,
425 const LocationContext *LCtx)
426 : CallEvent(D, St, LCtx) {}
427 AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {}
430 // This function is overridden by subclasses, but they must return
432 const FunctionDecl *getDecl() const override {
433 return cast<FunctionDecl>(CallEvent::getDecl());
436 RuntimeDefinition getRuntimeDefinition() const override {
437 const FunctionDecl *FD = getDecl();
438 // Note that the AnalysisDeclContext will have the FunctionDecl with
439 // the definition (if one exists).
441 AnalysisDeclContext *AD =
442 getLocationContext()->getAnalysisDeclContext()->
443 getManager()->getContext(FD);
445 return RuntimeDefinition(AD->getDecl());
448 return RuntimeDefinition();
451 bool argumentsMayEscape() const override;
453 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
454 BindingsTy &Bindings) const override;
456 ArrayRef<ParmVarDecl *> parameters() const override;
458 static bool classof(const CallEvent *CA) {
459 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
460 CA->getKind() <= CE_END_FUNCTION_CALLS;
464 /// \brief Represents a C function or static C++ member function call.
466 /// Example: \c fun()
467 class SimpleFunctionCall : public AnyFunctionCall {
468 friend class CallEventManager;
471 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
472 const LocationContext *LCtx)
473 : AnyFunctionCall(CE, St, LCtx) {}
474 SimpleFunctionCall(const SimpleFunctionCall &Other)
475 : AnyFunctionCall(Other) {}
476 void cloneTo(void *Dest) const override {
477 new (Dest) SimpleFunctionCall(*this);
481 virtual const CallExpr *getOriginExpr() const {
482 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
485 const FunctionDecl *getDecl() const override;
487 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
489 const Expr *getArgExpr(unsigned Index) const override {
490 return getOriginExpr()->getArg(Index);
493 Kind getKind() const override { return CE_Function; }
495 static bool classof(const CallEvent *CA) {
496 return CA->getKind() == CE_Function;
500 /// \brief Represents a call to a block.
502 /// Example: <tt>^{ /* ... */ }()</tt>
503 class BlockCall : public CallEvent {
504 friend class CallEventManager;
507 BlockCall(const CallExpr *CE, ProgramStateRef St,
508 const LocationContext *LCtx)
509 : CallEvent(CE, St, LCtx) {}
511 BlockCall(const BlockCall &Other) : CallEvent(Other) {}
512 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
514 void getExtraInvalidatedValues(ValueList &Values,
515 RegionAndSymbolInvalidationTraits *ETraits) const override;
518 virtual const CallExpr *getOriginExpr() const {
519 return cast<CallExpr>(CallEvent::getOriginExpr());
522 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
524 const Expr *getArgExpr(unsigned Index) const override {
525 return getOriginExpr()->getArg(Index);
528 /// \brief Returns the region associated with this instance of the block.
530 /// This may be NULL if the block's origin is unknown.
531 const BlockDataRegion *getBlockRegion() const;
533 const BlockDecl *getDecl() const override {
534 const BlockDataRegion *BR = getBlockRegion();
537 return BR->getDecl();
540 bool isConversionFromLambda() const {
541 const BlockDecl *BD = getDecl();
545 return BD->isConversionFromLambda();
548 /// \brief For a block converted from a C++ lambda, returns the block
549 /// VarRegion for the variable holding the captured C++ lambda record.
550 const VarRegion *getRegionStoringCapturedLambda() const {
551 assert(isConversionFromLambda());
552 const BlockDataRegion *BR = getBlockRegion();
553 assert(BR && "Block converted from lambda must have a block region");
555 auto I = BR->referenced_vars_begin();
556 assert(I != BR->referenced_vars_end());
558 return I.getCapturedRegion();
561 RuntimeDefinition getRuntimeDefinition() const override {
562 if (!isConversionFromLambda())
563 return RuntimeDefinition(getDecl());
565 // Clang converts lambdas to blocks with an implicit user-defined
566 // conversion operator method on the lambda record that looks (roughly)
569 // typedef R(^block_type)(P1, P2, ...);
570 // operator block_type() const {
571 // auto Lambda = *this;
572 // return ^(P1 p1, P2 p2, ...){
573 // /* return Lambda(p1, p2, ...); */
577 // Here R is the return type of the lambda and P1, P2, ... are
578 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
579 // that is initialized to a copy of the lambda.
581 // Sema leaves the body of a lambda-converted block empty (it is
582 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
583 // the block body and analyze the operator() method on the captured lambda.
584 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
585 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
586 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
588 return RuntimeDefinition(LambdaCallOperator);
591 bool argumentsMayEscape() const override {
595 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
596 BindingsTy &Bindings) const override;
598 ArrayRef<ParmVarDecl*> parameters() const override;
600 Kind getKind() const override { return CE_Block; }
602 static bool classof(const CallEvent *CA) {
603 return CA->getKind() == CE_Block;
607 /// \brief Represents a non-static C++ member function call, no matter how
609 class CXXInstanceCall : public AnyFunctionCall {
611 void getExtraInvalidatedValues(ValueList &Values,
612 RegionAndSymbolInvalidationTraits *ETraits) const override;
614 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
615 const LocationContext *LCtx)
616 : AnyFunctionCall(CE, St, LCtx) {}
617 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
618 const LocationContext *LCtx)
619 : AnyFunctionCall(D, St, LCtx) {}
622 CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {}
625 /// \brief Returns the expression representing the implicit 'this' object.
626 virtual const Expr *getCXXThisExpr() const { return nullptr; }
628 /// \brief Returns the value of the implicit 'this' object.
629 virtual SVal getCXXThisVal() const;
631 const FunctionDecl *getDecl() const override;
633 RuntimeDefinition getRuntimeDefinition() const override;
635 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
636 BindingsTy &Bindings) const override;
638 static bool classof(const CallEvent *CA) {
639 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
640 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
644 /// \brief Represents a non-static C++ member function call.
646 /// Example: \c obj.fun()
647 class CXXMemberCall : public CXXInstanceCall {
648 friend class CallEventManager;
651 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
652 const LocationContext *LCtx)
653 : CXXInstanceCall(CE, St, LCtx) {}
655 CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
656 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
659 virtual const CXXMemberCallExpr *getOriginExpr() const {
660 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
663 unsigned getNumArgs() const override {
664 if (const CallExpr *CE = getOriginExpr())
665 return CE->getNumArgs();
669 const Expr *getArgExpr(unsigned Index) const override {
670 return getOriginExpr()->getArg(Index);
673 const Expr *getCXXThisExpr() const override;
675 RuntimeDefinition getRuntimeDefinition() const override;
677 Kind getKind() const override { return CE_CXXMember; }
679 static bool classof(const CallEvent *CA) {
680 return CA->getKind() == CE_CXXMember;
684 /// \brief Represents a C++ overloaded operator call where the operator is
685 /// implemented as a non-static member function.
687 /// Example: <tt>iter + 1</tt>
688 class CXXMemberOperatorCall : public CXXInstanceCall {
689 friend class CallEventManager;
692 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
693 const LocationContext *LCtx)
694 : CXXInstanceCall(CE, St, LCtx) {}
696 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
697 : CXXInstanceCall(Other) {}
698 void cloneTo(void *Dest) const override {
699 new (Dest) CXXMemberOperatorCall(*this);
703 virtual const CXXOperatorCallExpr *getOriginExpr() const {
704 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
707 unsigned getNumArgs() const override {
708 return getOriginExpr()->getNumArgs() - 1;
710 const Expr *getArgExpr(unsigned Index) const override {
711 return getOriginExpr()->getArg(Index + 1);
714 const Expr *getCXXThisExpr() const override;
716 Kind getKind() const override { return CE_CXXMemberOperator; }
718 static bool classof(const CallEvent *CA) {
719 return CA->getKind() == CE_CXXMemberOperator;
723 /// \brief Represents an implicit call to a C++ destructor.
725 /// This can occur at the end of a scope (for automatic objects), at the end
726 /// of a full-expression (for temporaries), or as part of a delete.
727 class CXXDestructorCall : public CXXInstanceCall {
728 friend class CallEventManager;
731 typedef llvm::PointerIntPair<const MemRegion *, 1, bool> DtorDataTy;
733 /// Creates an implicit destructor.
735 /// \param DD The destructor that will be called.
736 /// \param Trigger The statement whose completion causes this destructor call.
737 /// \param Target The object region to be destructed.
738 /// \param St The path-sensitive state at this point in the program.
739 /// \param LCtx The location context at this point in the program.
740 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
741 const MemRegion *Target, bool IsBaseDestructor,
742 ProgramStateRef St, const LocationContext *LCtx)
743 : CXXInstanceCall(DD, St, LCtx) {
744 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
745 Location = Trigger->getLocEnd();
748 CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {}
749 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
752 SourceRange getSourceRange() const override { return Location; }
753 unsigned getNumArgs() const override { return 0; }
755 RuntimeDefinition getRuntimeDefinition() const override;
757 /// \brief Returns the value of the implicit 'this' object.
758 SVal getCXXThisVal() const override;
760 /// Returns true if this is a call to a base class destructor.
761 bool isBaseDestructor() const {
762 return DtorDataTy::getFromOpaqueValue(Data).getInt();
765 Kind getKind() const override { return CE_CXXDestructor; }
767 static bool classof(const CallEvent *CA) {
768 return CA->getKind() == CE_CXXDestructor;
772 /// \brief Represents a call to a C++ constructor.
775 class CXXConstructorCall : public AnyFunctionCall {
776 friend class CallEventManager;
779 /// Creates a constructor call.
781 /// \param CE The constructor expression as written in the source.
782 /// \param Target The region where the object should be constructed. If NULL,
783 /// a new symbolic region will be used.
784 /// \param St The path-sensitive state at this point in the program.
785 /// \param LCtx The location context at this point in the program.
786 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
787 ProgramStateRef St, const LocationContext *LCtx)
788 : AnyFunctionCall(CE, St, LCtx) {
792 CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
793 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
795 void getExtraInvalidatedValues(ValueList &Values,
796 RegionAndSymbolInvalidationTraits *ETraits) const override;
799 virtual const CXXConstructExpr *getOriginExpr() const {
800 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
803 const CXXConstructorDecl *getDecl() const override {
804 return getOriginExpr()->getConstructor();
807 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
809 const Expr *getArgExpr(unsigned Index) const override {
810 return getOriginExpr()->getArg(Index);
813 /// \brief Returns the value of the implicit 'this' object.
814 SVal getCXXThisVal() const;
816 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
817 BindingsTy &Bindings) const override;
819 Kind getKind() const override { return CE_CXXConstructor; }
821 static bool classof(const CallEvent *CA) {
822 return CA->getKind() == CE_CXXConstructor;
826 /// \brief Represents the memory allocation call in a C++ new-expression.
828 /// This is a call to "operator new".
829 class CXXAllocatorCall : public AnyFunctionCall {
830 friend class CallEventManager;
833 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
834 const LocationContext *LCtx)
835 : AnyFunctionCall(E, St, LCtx) {}
837 CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
838 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
841 virtual const CXXNewExpr *getOriginExpr() const {
842 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
845 const FunctionDecl *getDecl() const override {
846 return getOriginExpr()->getOperatorNew();
849 unsigned getNumArgs() const override {
850 return getOriginExpr()->getNumPlacementArgs() + 1;
853 const Expr *getArgExpr(unsigned Index) const override {
854 // The first argument of an allocator call is the size of the allocation.
857 return getOriginExpr()->getPlacementArg(Index - 1);
860 Kind getKind() const override { return CE_CXXAllocator; }
862 static bool classof(const CallEvent *CE) {
863 return CE->getKind() == CE_CXXAllocator;
867 /// \brief Represents the ways an Objective-C message send can occur.
869 // Note to maintainers: OCM_Message should always be last, since it does not
870 // need to fit in the Data field's low bits.
871 enum ObjCMessageKind {
877 /// \brief Represents any expression that calls an Objective-C method.
879 /// This includes all of the kinds listed in ObjCMessageKind.
880 class ObjCMethodCall : public CallEvent {
881 friend class CallEventManager;
883 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
886 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
887 const LocationContext *LCtx)
888 : CallEvent(Msg, St, LCtx) {
892 ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
893 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
895 void getExtraInvalidatedValues(ValueList &Values,
896 RegionAndSymbolInvalidationTraits *ETraits) const override;
898 /// Check if the selector may have multiple definitions (may have overrides).
899 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
903 virtual const ObjCMessageExpr *getOriginExpr() const {
904 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
906 const ObjCMethodDecl *getDecl() const override {
907 return getOriginExpr()->getMethodDecl();
909 unsigned getNumArgs() const override {
910 return getOriginExpr()->getNumArgs();
912 const Expr *getArgExpr(unsigned Index) const override {
913 return getOriginExpr()->getArg(Index);
916 bool isInstanceMessage() const {
917 return getOriginExpr()->isInstanceMessage();
919 ObjCMethodFamily getMethodFamily() const {
920 return getOriginExpr()->getMethodFamily();
922 Selector getSelector() const {
923 return getOriginExpr()->getSelector();
926 SourceRange getSourceRange() const override;
928 /// \brief Returns the value of the receiver at the time of this call.
929 SVal getReceiverSVal() const;
931 /// \brief Return the value of 'self' if available.
932 SVal getSelfSVal() const;
934 /// \brief Get the interface for the receiver.
936 /// This works whether this is an instance message or a class message.
937 /// However, it currently just uses the static type of the receiver.
938 const ObjCInterfaceDecl *getReceiverInterface() const {
939 return getOriginExpr()->getReceiverInterface();
942 /// \brief Checks if the receiver refers to 'self' or 'super'.
943 bool isReceiverSelfOrSuper() const;
945 /// Returns how the message was written in the source (property access,
946 /// subscript, or explicit message send).
947 ObjCMessageKind getMessageKind() const;
949 /// Returns true if this property access or subscript is a setter (has the
950 /// form of an assignment).
951 bool isSetter() const {
952 switch (getMessageKind()) {
954 llvm_unreachable("This is not a pseudo-object access!");
955 case OCM_PropertyAccess:
956 return getNumArgs() > 0;
958 return getNumArgs() > 1;
960 llvm_unreachable("Unknown message kind");
963 // Returns the property accessed by this method, either explicitly via
964 // property syntax or implicitly via a getter or setter method. Returns
965 // nullptr if the call is not a prooperty access.
966 const ObjCPropertyDecl *getAccessedProperty() const;
968 RuntimeDefinition getRuntimeDefinition() const override;
970 bool argumentsMayEscape() const override;
972 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
973 BindingsTy &Bindings) const override;
975 ArrayRef<ParmVarDecl*> parameters() const override;
977 Kind getKind() const override { return CE_ObjCMessage; }
979 static bool classof(const CallEvent *CA) {
980 return CA->getKind() == CE_ObjCMessage;
985 /// \brief Manages the lifetime of CallEvent objects.
987 /// CallEventManager provides a way to create arbitrary CallEvents "on the
988 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
989 /// memory blocks. The CallEvents created by CallEventManager are only valid
990 /// for the lifetime of the OwnedCallEvent that holds them; right now these
991 /// objects cannot be copied and ownership cannot be transferred.
992 class CallEventManager {
993 friend class CallEvent;
995 llvm::BumpPtrAllocator &Alloc;
996 SmallVector<void *, 8> Cache;
997 typedef SimpleFunctionCall CallEventTemplateTy;
999 void reclaim(const void *Memory) {
1000 Cache.push_back(const_cast<void *>(Memory));
1003 /// Returns memory that can be initialized as a CallEvent.
1006 return Alloc.Allocate<CallEventTemplateTy>();
1008 return Cache.pop_back_val();
1011 template <typename T, typename Arg>
1012 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1013 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1014 "CallEvent subclasses are not all the same size");
1015 return new (allocate()) T(A, St, LCtx);
1018 template <typename T, typename Arg1, typename Arg2>
1019 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1020 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1021 "CallEvent subclasses are not all the same size");
1022 return new (allocate()) T(A1, A2, St, LCtx);
1025 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1026 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1027 const LocationContext *LCtx) {
1028 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1029 "CallEvent subclasses are not all the same size");
1030 return new (allocate()) T(A1, A2, A3, St, LCtx);
1033 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1035 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1036 const LocationContext *LCtx) {
1037 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1038 "CallEvent subclasses are not all the same size");
1039 return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1043 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1047 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1051 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1052 const LocationContext *LCtx);
1054 CallEventRef<ObjCMethodCall>
1055 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1056 const LocationContext *LCtx) {
1057 return create<ObjCMethodCall>(E, State, LCtx);
1060 CallEventRef<CXXConstructorCall>
1061 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1062 ProgramStateRef State, const LocationContext *LCtx) {
1063 return create<CXXConstructorCall>(E, Target, State, LCtx);
1066 CallEventRef<CXXDestructorCall>
1067 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1068 const MemRegion *Target, bool IsBase,
1069 ProgramStateRef State, const LocationContext *LCtx) {
1070 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1073 CallEventRef<CXXAllocatorCall>
1074 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1075 const LocationContext *LCtx) {
1076 return create<CXXAllocatorCall>(E, State, LCtx);
1081 template <typename T>
1082 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1083 assert(isa<T>(*this) && "Cloning to unrelated type");
1084 static_assert(sizeof(T) == sizeof(CallEvent),
1085 "Subclasses may not add fields");
1087 if (NewState == State)
1088 return cast<T>(this);
1090 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1091 T *Copy = static_cast<T *>(Mgr.allocate());
1093 assert(Copy->getKind() == this->getKind() && "Bad copy");
1095 Copy->State = NewState;
1099 inline void CallEvent::Release() const {
1100 assert(RefCount > 0 && "Reference count is already zero.");
1106 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1112 } // end namespace ento
1113 } // end namespace clang
1116 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1117 template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
1118 typedef const T *SimpleType;
1121 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {