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/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/IntrusiveRefCntPtr.h"
37 #include "llvm/ADT/PointerIntPair.h"
38 #include "llvm/ADT/PointerUnion.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/Allocator.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
51 class LocationContext;
53 class ProgramPointTag;
54 class StackFrameContext;
63 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
64 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
67 CE_BEG_FUNCTION_CALLS = CE_Function,
68 CE_END_FUNCTION_CALLS = CE_CXXAllocator,
75 /// This class represents a description of a function call using the number of
76 /// arguments and the name of the function.
77 class CallDescription {
80 mutable IdentifierInfo *II = nullptr;
81 mutable bool IsLookupDone = false;
83 unsigned RequiredArgs;
86 const static unsigned NoArgRequirement = std::numeric_limits<unsigned>::max();
88 /// Constructs a CallDescription object.
90 /// @param FuncName The name of the function that will be matched.
92 /// @param RequiredArgs The number of arguments that is expected to match a
93 /// call. Omit this parameter to match every occurrence of call with a given
94 /// name regardless the number of arguments.
95 CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
96 : FuncName(FuncName), RequiredArgs(RequiredArgs) {}
98 /// Get the name of the function that this object matches.
99 StringRef getFunctionName() const { return FuncName; }
102 template<typename T = CallEvent>
103 class CallEventRef : public IntrusiveRefCntPtr<const T> {
105 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
106 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
108 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
109 return this->get()->template cloneWithState<T>(State);
112 // Allow implicit conversions to a superclass type, since CallEventRef
113 // behaves like a pointer-to-const.
114 template <typename SuperT>
115 operator CallEventRef<SuperT> () const {
120 /// \class RuntimeDefinition
121 /// Defines the runtime definition of the called function.
123 /// Encapsulates the information we have about which Decl will be used
124 /// when the call is executed on the given path. When dealing with dynamic
125 /// dispatch, the information is based on DynamicTypeInfo and might not be
127 class RuntimeDefinition {
128 /// The Declaration of the function which could be called at runtime.
129 /// NULL if not available.
130 const Decl *D = nullptr;
132 /// The region representing an object (ObjC/C++) on which the method is
133 /// called. With dynamic dispatch, the method definition depends on the
134 /// runtime type of this object. NULL when the DynamicTypeInfo is
136 const MemRegion *R = nullptr;
139 RuntimeDefinition() = default;
140 RuntimeDefinition(const Decl *InD): D(InD) {}
141 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
143 const Decl *getDecl() { return D; }
145 /// Check if the definition we have is precise.
146 /// If not, it is possible that the call dispatches to another definition at
148 bool mayHaveOtherDefinitions() { return R != nullptr; }
150 /// When other definitions are possible, returns the region whose runtime type
151 /// determines the method definition.
152 const MemRegion *getDispatchRegion() { return R; }
155 /// Represents an abstract call to a function or method along a
158 /// CallEvents are created through the factory methods of CallEventManager.
160 /// CallEvents should always be cheap to create and destroy. In order for
161 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
162 /// subclasses of CallEvent may not add any data members to the base class.
163 /// Use the "Data" and "Location" fields instead.
166 using Kind = CallEventKind;
169 ProgramStateRef State;
170 const LocationContext *LCtx;
171 llvm::PointerUnion<const Expr *, const Decl *> Origin;
174 // This is user data for subclasses.
177 // This is user data for subclasses.
178 // This should come right before RefCount, so that the two fields can be
179 // packed together on LP64 platforms.
180 SourceLocation Location;
183 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
185 mutable unsigned RefCount = 0;
187 void Retain() const { ++RefCount; }
188 void Release() const;
191 friend class CallEventManager;
193 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
194 : State(std::move(state)), LCtx(lctx), Origin(E) {}
196 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
197 : State(std::move(state)), LCtx(lctx), Origin(D) {}
199 // DO NOT MAKE PUBLIC
200 CallEvent(const CallEvent &Original)
201 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
202 Data(Original.Data), Location(Original.Location) {}
204 /// Copies this CallEvent, with vtable intact, into a new block of memory.
205 virtual void cloneTo(void *Dest) const = 0;
207 /// Get the value of arbitrary expressions at this point in the path.
208 SVal getSVal(const Stmt *S) const {
209 return getState()->getSVal(S, getLocationContext());
212 using ValueList = SmallVectorImpl<SVal>;
214 /// Used to specify non-argument regions that will be invalidated as a
215 /// result of this call.
216 virtual void getExtraInvalidatedValues(ValueList &Values,
217 RegionAndSymbolInvalidationTraits *ETraits) const {}
220 CallEvent &operator=(const CallEvent &) = delete;
221 virtual ~CallEvent() = default;
223 /// Returns the kind of call this is.
224 virtual Kind getKind() const = 0;
226 /// Returns the declaration of the function or method that will be
227 /// called. May be null.
228 virtual const Decl *getDecl() const {
229 return Origin.dyn_cast<const Decl *>();
232 /// The state in which the call is being evaluated.
233 const ProgramStateRef &getState() const {
237 /// The context in which the call is being evaluated.
238 const LocationContext *getLocationContext() const {
242 /// Returns the definition of the function or method that will be
244 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
246 /// Returns the expression whose value will be the result of this call.
248 const Expr *getOriginExpr() const {
249 return Origin.dyn_cast<const Expr *>();
252 /// Returns the number of arguments (explicit and implicit).
254 /// Note that this may be greater than the number of parameters in the
255 /// callee's declaration, and that it may include arguments not written in
257 virtual unsigned getNumArgs() const = 0;
259 /// Returns true if the callee is known to be from a system header.
260 bool isInSystemHeader() const {
261 const Decl *D = getDecl();
265 SourceLocation Loc = D->getLocation();
267 const SourceManager &SM =
268 getState()->getStateManager().getContext().getSourceManager();
269 return SM.isInSystemHeader(D->getLocation());
272 // Special case for implicitly-declared global operator new/delete.
273 // These should be considered system functions.
274 if (const auto *FD = dyn_cast<FunctionDecl>(D))
275 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
280 /// Returns true if the CallEvent is a call to a function that matches
281 /// the CallDescription.
283 /// Note that this function is not intended to be used to match Obj-C method
285 bool isCalled(const CallDescription &CD) const;
287 /// Returns a source range for the entire call, suitable for
288 /// outputting in diagnostics.
289 virtual SourceRange getSourceRange() const {
290 return getOriginExpr()->getSourceRange();
293 /// Returns the value of a given argument at the time of the call.
294 virtual SVal getArgSVal(unsigned Index) const;
296 /// Returns the expression associated with a given argument.
297 /// May be null if this expression does not appear in the source.
298 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
300 /// Returns the source range for errors associated with this argument.
302 /// May be invalid if the argument is not written in the source.
303 virtual SourceRange getArgSourceRange(unsigned Index) const;
305 /// Returns the result type, adjusted for references.
306 QualType getResultType() const;
308 /// Returns the return value of the call.
310 /// This should only be called if the CallEvent was created using a state in
311 /// which the return value has already been bound to the origin expression.
312 SVal getReturnValue() const;
314 /// Returns true if the type of any of the non-null arguments satisfies
316 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
318 /// Returns true if any of the arguments appear to represent callbacks.
319 bool hasNonZeroCallbackArg() const;
321 /// Returns true if any of the arguments is void*.
322 bool hasVoidPointerToNonConstArg() const;
324 /// Returns true if any of the arguments are known to escape to long-
325 /// term storage, even if this method will not modify them.
326 // NOTE: The exact semantics of this are still being defined!
327 // We don't really want a list of hardcoded exceptions in the long run,
328 // but we don't want duplicated lists of known APIs in the short term either.
329 virtual bool argumentsMayEscape() const {
330 return hasNonZeroCallbackArg();
333 /// Returns true if the callee is an externally-visible function in the
334 /// top-level namespace, such as \c malloc.
336 /// You can use this call to determine that a particular function really is
337 /// a library function and not, say, a C++ member function with the same name.
339 /// If a name is provided, the function must additionally match the given
342 /// Note that this deliberately excludes C++ library functions in the \c std
343 /// namespace, but will include C library functions accessed through the
344 /// \c std namespace. This also does not check if the function is declared
345 /// as 'extern "C"', or if it uses C++ name mangling.
346 // FIXME: Add a helper for checking namespaces.
347 // FIXME: Move this down to AnyFunctionCall once checkers have more
348 // precise callbacks.
349 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
351 /// Returns the name of the callee, if its name is a simple identifier.
353 /// Note that this will fail for Objective-C methods, blocks, and C++
354 /// overloaded operators. The former is named by a Selector rather than a
355 /// simple identifier, and the latter two do not have names.
356 // FIXME: Move this down to AnyFunctionCall once checkers have more
357 // precise callbacks.
358 const IdentifierInfo *getCalleeIdentifier() const {
359 const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
362 return ND->getIdentifier();
365 /// Returns an appropriate ProgramPoint for this call.
366 ProgramPoint getProgramPoint(bool IsPreVisit = false,
367 const ProgramPointTag *Tag = nullptr) const;
369 /// Returns a new state with all argument regions invalidated.
371 /// This accepts an alternate state in case some processing has already
373 ProgramStateRef invalidateRegions(unsigned BlockCount,
374 ProgramStateRef Orig = nullptr) const;
376 using FrameBindingTy = std::pair<Loc, SVal>;
377 using BindingsTy = SmallVectorImpl<FrameBindingTy>;
379 /// Populates the given SmallVector with the bindings in the callee's stack
380 /// frame at the start of this call.
381 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
382 BindingsTy &Bindings) const = 0;
384 /// Returns a copy of this CallEvent, but using the given state.
385 template <typename T>
386 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
388 /// Returns a copy of this CallEvent, but using the given state.
389 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
390 return cloneWithState<CallEvent>(NewState);
393 /// Returns true if this is a statement is a function or method call
395 static bool isCallStmt(const Stmt *S);
397 /// Returns the result type of a function or method declaration.
399 /// This will return a null QualType if the result type cannot be determined.
400 static QualType getDeclaredResultType(const Decl *D);
402 /// Returns true if the given decl is known to be variadic.
404 /// \p D must not be null.
405 static bool isVariadic(const Decl *D);
407 // Iterator access to formal parameters and their types.
410 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
414 /// Return call's formal parameters.
416 /// Remember that the number of formal parameters may not match the number
417 /// of arguments for all calls. However, the first parameter will always
418 /// correspond with the argument value returned by \c getArgSVal(0).
419 virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
421 using param_type_iterator =
422 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
424 /// Returns an iterator over the types of the call's formal parameters.
426 /// This uses the callee decl found by default name lookup rather than the
427 /// definition because it represents a public interface, and probably has
428 /// more annotations.
429 param_type_iterator param_type_begin() const {
430 return llvm::map_iterator(parameters().begin(), GetTypeFn());
432 /// \sa param_type_begin()
433 param_type_iterator param_type_end() const {
434 return llvm::map_iterator(parameters().end(), GetTypeFn());
437 // For debugging purposes only
438 void dump(raw_ostream &Out) const;
442 /// Represents a call to any sort of function that might have a
444 class AnyFunctionCall : public CallEvent {
446 AnyFunctionCall(const Expr *E, ProgramStateRef St,
447 const LocationContext *LCtx)
448 : CallEvent(E, St, LCtx) {}
449 AnyFunctionCall(const Decl *D, ProgramStateRef St,
450 const LocationContext *LCtx)
451 : CallEvent(D, St, LCtx) {}
452 AnyFunctionCall(const AnyFunctionCall &Other) = default;
455 // This function is overridden by subclasses, but they must return
457 const FunctionDecl *getDecl() const override {
458 return cast<FunctionDecl>(CallEvent::getDecl());
461 RuntimeDefinition getRuntimeDefinition() const override;
463 bool argumentsMayEscape() const override;
465 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
466 BindingsTy &Bindings) const override;
468 ArrayRef<ParmVarDecl *> parameters() const override;
470 static bool classof(const CallEvent *CA) {
471 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
472 CA->getKind() <= CE_END_FUNCTION_CALLS;
476 /// Represents a C function or static C++ member function call.
478 /// Example: \c fun()
479 class SimpleFunctionCall : public AnyFunctionCall {
480 friend class CallEventManager;
483 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
484 const LocationContext *LCtx)
485 : AnyFunctionCall(CE, St, LCtx) {}
486 SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
488 void cloneTo(void *Dest) const override {
489 new (Dest) SimpleFunctionCall(*this);
493 virtual const CallExpr *getOriginExpr() const {
494 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
497 const FunctionDecl *getDecl() const override;
499 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
501 const Expr *getArgExpr(unsigned Index) const override {
502 return getOriginExpr()->getArg(Index);
505 Kind getKind() const override { return CE_Function; }
507 static bool classof(const CallEvent *CA) {
508 return CA->getKind() == CE_Function;
512 /// Represents a call to a block.
514 /// Example: <tt>^{ /* ... */ }()</tt>
515 class BlockCall : public CallEvent {
516 friend class CallEventManager;
519 BlockCall(const CallExpr *CE, ProgramStateRef St,
520 const LocationContext *LCtx)
521 : CallEvent(CE, St, LCtx) {}
522 BlockCall(const BlockCall &Other) = default;
524 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
526 void getExtraInvalidatedValues(ValueList &Values,
527 RegionAndSymbolInvalidationTraits *ETraits) const override;
530 virtual const CallExpr *getOriginExpr() const {
531 return cast<CallExpr>(CallEvent::getOriginExpr());
534 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
536 const Expr *getArgExpr(unsigned Index) const override {
537 return getOriginExpr()->getArg(Index);
540 /// Returns the region associated with this instance of the block.
542 /// This may be NULL if the block's origin is unknown.
543 const BlockDataRegion *getBlockRegion() const;
545 const BlockDecl *getDecl() const override {
546 const BlockDataRegion *BR = getBlockRegion();
549 return BR->getDecl();
552 bool isConversionFromLambda() const {
553 const BlockDecl *BD = getDecl();
557 return BD->isConversionFromLambda();
560 /// For a block converted from a C++ lambda, returns the block
561 /// VarRegion for the variable holding the captured C++ lambda record.
562 const VarRegion *getRegionStoringCapturedLambda() const {
563 assert(isConversionFromLambda());
564 const BlockDataRegion *BR = getBlockRegion();
565 assert(BR && "Block converted from lambda must have a block region");
567 auto I = BR->referenced_vars_begin();
568 assert(I != BR->referenced_vars_end());
570 return I.getCapturedRegion();
573 RuntimeDefinition getRuntimeDefinition() const override {
574 if (!isConversionFromLambda())
575 return RuntimeDefinition(getDecl());
577 // Clang converts lambdas to blocks with an implicit user-defined
578 // conversion operator method on the lambda record that looks (roughly)
581 // typedef R(^block_type)(P1, P2, ...);
582 // operator block_type() const {
583 // auto Lambda = *this;
584 // return ^(P1 p1, P2 p2, ...){
585 // /* return Lambda(p1, p2, ...); */
589 // Here R is the return type of the lambda and P1, P2, ... are
590 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
591 // that is initialized to a copy of the lambda.
593 // Sema leaves the body of a lambda-converted block empty (it is
594 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
595 // the block body and analyze the operator() method on the captured lambda.
596 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
597 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
598 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
600 return RuntimeDefinition(LambdaCallOperator);
603 bool argumentsMayEscape() const override {
607 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
608 BindingsTy &Bindings) const override;
610 ArrayRef<ParmVarDecl*> parameters() const override;
612 Kind getKind() const override { return CE_Block; }
614 static bool classof(const CallEvent *CA) {
615 return CA->getKind() == CE_Block;
619 /// Represents a non-static C++ member function call, no matter how
621 class CXXInstanceCall : public AnyFunctionCall {
623 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
624 const LocationContext *LCtx)
625 : AnyFunctionCall(CE, St, LCtx) {}
626 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
627 const LocationContext *LCtx)
628 : AnyFunctionCall(D, St, LCtx) {}
629 CXXInstanceCall(const CXXInstanceCall &Other) = default;
631 void getExtraInvalidatedValues(ValueList &Values,
632 RegionAndSymbolInvalidationTraits *ETraits) const override;
635 /// Returns the expression representing the implicit 'this' object.
636 virtual const Expr *getCXXThisExpr() const { return nullptr; }
638 /// Returns the value of the implicit 'this' object.
639 virtual SVal getCXXThisVal() const;
641 const FunctionDecl *getDecl() const override;
643 RuntimeDefinition getRuntimeDefinition() const override;
645 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
646 BindingsTy &Bindings) const override;
648 static bool classof(const CallEvent *CA) {
649 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
650 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
654 /// Represents a non-static C++ member function call.
656 /// Example: \c obj.fun()
657 class CXXMemberCall : public CXXInstanceCall {
658 friend class CallEventManager;
661 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
662 const LocationContext *LCtx)
663 : CXXInstanceCall(CE, St, LCtx) {}
664 CXXMemberCall(const CXXMemberCall &Other) = default;
666 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
669 virtual const CXXMemberCallExpr *getOriginExpr() const {
670 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
673 unsigned getNumArgs() const override {
674 if (const CallExpr *CE = getOriginExpr())
675 return CE->getNumArgs();
679 const Expr *getArgExpr(unsigned Index) const override {
680 return getOriginExpr()->getArg(Index);
683 const Expr *getCXXThisExpr() const override;
685 RuntimeDefinition getRuntimeDefinition() const override;
687 Kind getKind() const override { return CE_CXXMember; }
689 static bool classof(const CallEvent *CA) {
690 return CA->getKind() == CE_CXXMember;
694 /// Represents a C++ overloaded operator call where the operator is
695 /// implemented as a non-static member function.
697 /// Example: <tt>iter + 1</tt>
698 class CXXMemberOperatorCall : public CXXInstanceCall {
699 friend class CallEventManager;
702 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
703 const LocationContext *LCtx)
704 : CXXInstanceCall(CE, St, LCtx) {}
705 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
707 void cloneTo(void *Dest) const override {
708 new (Dest) CXXMemberOperatorCall(*this);
712 virtual const CXXOperatorCallExpr *getOriginExpr() const {
713 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
716 unsigned getNumArgs() const override {
717 return getOriginExpr()->getNumArgs() - 1;
720 const Expr *getArgExpr(unsigned Index) const override {
721 return getOriginExpr()->getArg(Index + 1);
724 const Expr *getCXXThisExpr() const override;
726 Kind getKind() const override { return CE_CXXMemberOperator; }
728 static bool classof(const CallEvent *CA) {
729 return CA->getKind() == CE_CXXMemberOperator;
733 /// Represents an implicit call to a C++ destructor.
735 /// This can occur at the end of a scope (for automatic objects), at the end
736 /// of a full-expression (for temporaries), or as part of a delete.
737 class CXXDestructorCall : public CXXInstanceCall {
738 friend class CallEventManager;
741 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
743 /// Creates an implicit destructor.
745 /// \param DD The destructor that will be called.
746 /// \param Trigger The statement whose completion causes this destructor call.
747 /// \param Target The object region to be destructed.
748 /// \param St The path-sensitive state at this point in the program.
749 /// \param LCtx The location context at this point in the program.
750 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
751 const MemRegion *Target, bool IsBaseDestructor,
752 ProgramStateRef St, const LocationContext *LCtx)
753 : CXXInstanceCall(DD, St, LCtx) {
754 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
755 Location = Trigger->getLocEnd();
758 CXXDestructorCall(const CXXDestructorCall &Other) = default;
760 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
763 SourceRange getSourceRange() const override { return Location; }
764 unsigned getNumArgs() const override { return 0; }
766 RuntimeDefinition getRuntimeDefinition() const override;
768 /// Returns the value of the implicit 'this' object.
769 SVal getCXXThisVal() const override;
771 /// Returns true if this is a call to a base class destructor.
772 bool isBaseDestructor() const {
773 return DtorDataTy::getFromOpaqueValue(Data).getInt();
776 Kind getKind() const override { return CE_CXXDestructor; }
778 static bool classof(const CallEvent *CA) {
779 return CA->getKind() == CE_CXXDestructor;
783 /// Represents a call to a C++ constructor.
786 class CXXConstructorCall : public AnyFunctionCall {
787 friend class CallEventManager;
790 /// Creates a constructor call.
792 /// \param CE The constructor expression as written in the source.
793 /// \param Target The region where the object should be constructed. If NULL,
794 /// a new symbolic region will be used.
795 /// \param St The path-sensitive state at this point in the program.
796 /// \param LCtx The location context at this point in the program.
797 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
798 ProgramStateRef St, const LocationContext *LCtx)
799 : AnyFunctionCall(CE, St, LCtx) {
803 CXXConstructorCall(const CXXConstructorCall &Other) = default;
805 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
807 void getExtraInvalidatedValues(ValueList &Values,
808 RegionAndSymbolInvalidationTraits *ETraits) const override;
811 virtual const CXXConstructExpr *getOriginExpr() const {
812 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
815 const CXXConstructorDecl *getDecl() const override {
816 return getOriginExpr()->getConstructor();
819 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
821 const Expr *getArgExpr(unsigned Index) const override {
822 return getOriginExpr()->getArg(Index);
825 /// Returns the value of the implicit 'this' object.
826 SVal getCXXThisVal() const;
828 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
829 BindingsTy &Bindings) const override;
831 Kind getKind() const override { return CE_CXXConstructor; }
833 static bool classof(const CallEvent *CA) {
834 return CA->getKind() == CE_CXXConstructor;
838 /// Represents the memory allocation call in a C++ new-expression.
840 /// This is a call to "operator new".
841 class CXXAllocatorCall : public AnyFunctionCall {
842 friend class CallEventManager;
845 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
846 const LocationContext *LCtx)
847 : AnyFunctionCall(E, St, LCtx) {}
848 CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
850 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
853 virtual const CXXNewExpr *getOriginExpr() const {
854 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
857 const FunctionDecl *getDecl() const override {
858 return getOriginExpr()->getOperatorNew();
861 unsigned getNumArgs() const override {
862 return getOriginExpr()->getNumPlacementArgs() + 1;
865 const Expr *getArgExpr(unsigned Index) const override {
866 // The first argument of an allocator call is the size of the allocation.
869 return getOriginExpr()->getPlacementArg(Index - 1);
872 Kind getKind() const override { return CE_CXXAllocator; }
874 static bool classof(const CallEvent *CE) {
875 return CE->getKind() == CE_CXXAllocator;
879 /// Represents the ways an Objective-C message send can occur.
881 // Note to maintainers: OCM_Message should always be last, since it does not
882 // need to fit in the Data field's low bits.
883 enum ObjCMessageKind {
889 /// Represents any expression that calls an Objective-C method.
891 /// This includes all of the kinds listed in ObjCMessageKind.
892 class ObjCMethodCall : public CallEvent {
893 friend class CallEventManager;
895 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
898 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
899 const LocationContext *LCtx)
900 : CallEvent(Msg, St, LCtx) {
904 ObjCMethodCall(const ObjCMethodCall &Other) = default;
906 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
908 void getExtraInvalidatedValues(ValueList &Values,
909 RegionAndSymbolInvalidationTraits *ETraits) const override;
911 /// Check if the selector may have multiple definitions (may have overrides).
912 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
916 virtual const ObjCMessageExpr *getOriginExpr() const {
917 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
920 const ObjCMethodDecl *getDecl() const override {
921 return getOriginExpr()->getMethodDecl();
924 unsigned getNumArgs() const override {
925 return getOriginExpr()->getNumArgs();
928 const Expr *getArgExpr(unsigned Index) const override {
929 return getOriginExpr()->getArg(Index);
932 bool isInstanceMessage() const {
933 return getOriginExpr()->isInstanceMessage();
936 ObjCMethodFamily getMethodFamily() const {
937 return getOriginExpr()->getMethodFamily();
940 Selector getSelector() const {
941 return getOriginExpr()->getSelector();
944 SourceRange getSourceRange() const override;
946 /// Returns the value of the receiver at the time of this call.
947 SVal getReceiverSVal() const;
949 /// Return the value of 'self' if available.
950 SVal getSelfSVal() const;
952 /// Get the interface for the receiver.
954 /// This works whether this is an instance message or a class message.
955 /// However, it currently just uses the static type of the receiver.
956 const ObjCInterfaceDecl *getReceiverInterface() const {
957 return getOriginExpr()->getReceiverInterface();
960 /// Checks if the receiver refers to 'self' or 'super'.
961 bool isReceiverSelfOrSuper() const;
963 /// Returns how the message was written in the source (property access,
964 /// subscript, or explicit message send).
965 ObjCMessageKind getMessageKind() const;
967 /// Returns true if this property access or subscript is a setter (has the
968 /// form of an assignment).
969 bool isSetter() const {
970 switch (getMessageKind()) {
972 llvm_unreachable("This is not a pseudo-object access!");
973 case OCM_PropertyAccess:
974 return getNumArgs() > 0;
976 return getNumArgs() > 1;
978 llvm_unreachable("Unknown message kind");
981 // Returns the property accessed by this method, either explicitly via
982 // property syntax or implicitly via a getter or setter method. Returns
983 // nullptr if the call is not a prooperty access.
984 const ObjCPropertyDecl *getAccessedProperty() const;
986 RuntimeDefinition getRuntimeDefinition() const override;
988 bool argumentsMayEscape() const override;
990 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
991 BindingsTy &Bindings) const override;
993 ArrayRef<ParmVarDecl*> parameters() const override;
995 Kind getKind() const override { return CE_ObjCMessage; }
997 static bool classof(const CallEvent *CA) {
998 return CA->getKind() == CE_ObjCMessage;
1002 /// Manages the lifetime of CallEvent objects.
1004 /// CallEventManager provides a way to create arbitrary CallEvents "on the
1005 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
1006 /// memory blocks. The CallEvents created by CallEventManager are only valid
1007 /// for the lifetime of the OwnedCallEvent that holds them; right now these
1008 /// objects cannot be copied and ownership cannot be transferred.
1009 class CallEventManager {
1010 friend class CallEvent;
1012 llvm::BumpPtrAllocator &Alloc;
1013 SmallVector<void *, 8> Cache;
1015 using CallEventTemplateTy = SimpleFunctionCall;
1017 void reclaim(const void *Memory) {
1018 Cache.push_back(const_cast<void *>(Memory));
1021 /// Returns memory that can be initialized as a CallEvent.
1024 return Alloc.Allocate<CallEventTemplateTy>();
1026 return Cache.pop_back_val();
1029 template <typename T, typename Arg>
1030 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1031 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1032 "CallEvent subclasses are not all the same size");
1033 return new (allocate()) T(A, St, LCtx);
1036 template <typename T, typename Arg1, typename Arg2>
1037 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1038 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1039 "CallEvent subclasses are not all the same size");
1040 return new (allocate()) T(A1, A2, St, LCtx);
1043 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1044 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1045 const LocationContext *LCtx) {
1046 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1047 "CallEvent subclasses are not all the same size");
1048 return new (allocate()) T(A1, A2, A3, St, LCtx);
1051 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1053 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1054 const LocationContext *LCtx) {
1055 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1056 "CallEvent subclasses are not all the same size");
1057 return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1061 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1064 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1067 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1068 const LocationContext *LCtx);
1070 CallEventRef<ObjCMethodCall>
1071 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1072 const LocationContext *LCtx) {
1073 return create<ObjCMethodCall>(E, State, LCtx);
1076 CallEventRef<CXXConstructorCall>
1077 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1078 ProgramStateRef State, const LocationContext *LCtx) {
1079 return create<CXXConstructorCall>(E, Target, State, LCtx);
1082 CallEventRef<CXXDestructorCall>
1083 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1084 const MemRegion *Target, bool IsBase,
1085 ProgramStateRef State, const LocationContext *LCtx) {
1086 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1089 CallEventRef<CXXAllocatorCall>
1090 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1091 const LocationContext *LCtx) {
1092 return create<CXXAllocatorCall>(E, State, LCtx);
1096 template <typename T>
1097 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1098 assert(isa<T>(*this) && "Cloning to unrelated type");
1099 static_assert(sizeof(T) == sizeof(CallEvent),
1100 "Subclasses may not add fields");
1102 if (NewState == State)
1103 return cast<T>(this);
1105 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1106 T *Copy = static_cast<T *>(Mgr.allocate());
1108 assert(Copy->getKind() == this->getKind() && "Bad copy");
1110 Copy->State = NewState;
1114 inline void CallEvent::Release() const {
1115 assert(RefCount > 0 && "Reference count is already zero.");
1121 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1129 } // namespace clang
1133 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1134 template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1135 using SimpleType = const T *;
1138 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1145 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H