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/ExprEngine.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
35 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/IntrusiveRefCntPtr.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
52 class LocationContext;
54 class ProgramPointTag;
55 class StackFrameContext;
64 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
65 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
68 CE_BEG_FUNCTION_CALLS = CE_Function,
69 CE_END_FUNCTION_CALLS = CE_CXXAllocator,
76 /// This class represents a description of a function call using the number of
77 /// arguments and the name of the function.
78 class CallDescription {
81 mutable IdentifierInfo *II = nullptr;
82 mutable bool IsLookupDone = false;
84 unsigned RequiredArgs;
87 const static unsigned NoArgRequirement = std::numeric_limits<unsigned>::max();
89 /// Constructs a CallDescription object.
91 /// @param FuncName The name of the function that will be matched.
93 /// @param RequiredArgs The number of arguments that is expected to match a
94 /// call. Omit this parameter to match every occurrence of call with a given
95 /// name regardless the number of arguments.
96 CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
97 : FuncName(FuncName), RequiredArgs(RequiredArgs) {}
99 /// Get the name of the function that this object matches.
100 StringRef getFunctionName() const { return FuncName; }
103 template<typename T = CallEvent>
104 class CallEventRef : public IntrusiveRefCntPtr<const T> {
106 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
107 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
109 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
110 return this->get()->template cloneWithState<T>(State);
113 // Allow implicit conversions to a superclass type, since CallEventRef
114 // behaves like a pointer-to-const.
115 template <typename SuperT>
116 operator CallEventRef<SuperT> () const {
121 /// \class RuntimeDefinition
122 /// Defines the runtime definition of the called function.
124 /// Encapsulates the information we have about which Decl will be used
125 /// when the call is executed on the given path. When dealing with dynamic
126 /// dispatch, the information is based on DynamicTypeInfo and might not be
128 class RuntimeDefinition {
129 /// The Declaration of the function which could be called at runtime.
130 /// NULL if not available.
131 const Decl *D = nullptr;
133 /// The region representing an object (ObjC/C++) on which the method is
134 /// called. With dynamic dispatch, the method definition depends on the
135 /// runtime type of this object. NULL when the DynamicTypeInfo is
137 const MemRegion *R = nullptr;
140 RuntimeDefinition() = default;
141 RuntimeDefinition(const Decl *InD): D(InD) {}
142 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
144 const Decl *getDecl() { return D; }
146 /// Check if the definition we have is precise.
147 /// If not, it is possible that the call dispatches to another definition at
149 bool mayHaveOtherDefinitions() { return R != nullptr; }
151 /// When other definitions are possible, returns the region whose runtime type
152 /// determines the method definition.
153 const MemRegion *getDispatchRegion() { return R; }
156 /// Represents an abstract call to a function or method along a
159 /// CallEvents are created through the factory methods of CallEventManager.
161 /// CallEvents should always be cheap to create and destroy. In order for
162 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
163 /// subclasses of CallEvent may not add any data members to the base class.
164 /// Use the "Data" and "Location" fields instead.
167 using Kind = CallEventKind;
170 ProgramStateRef State;
171 const LocationContext *LCtx;
172 llvm::PointerUnion<const Expr *, const Decl *> Origin;
175 // This is user data for subclasses.
178 // This is user data for subclasses.
179 // This should come right before RefCount, so that the two fields can be
180 // packed together on LP64 platforms.
181 SourceLocation Location;
184 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
186 mutable unsigned RefCount = 0;
188 void Retain() const { ++RefCount; }
189 void Release() const;
192 friend class CallEventManager;
194 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
195 : State(std::move(state)), LCtx(lctx), Origin(E) {}
197 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
198 : State(std::move(state)), LCtx(lctx), Origin(D) {}
200 // DO NOT MAKE PUBLIC
201 CallEvent(const CallEvent &Original)
202 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
203 Data(Original.Data), Location(Original.Location) {}
205 /// Copies this CallEvent, with vtable intact, into a new block of memory.
206 virtual void cloneTo(void *Dest) const = 0;
208 /// Get the value of arbitrary expressions at this point in the path.
209 SVal getSVal(const Stmt *S) const {
210 return getState()->getSVal(S, getLocationContext());
213 using ValueList = SmallVectorImpl<SVal>;
215 /// Used to specify non-argument regions that will be invalidated as a
216 /// result of this call.
217 virtual void getExtraInvalidatedValues(ValueList &Values,
218 RegionAndSymbolInvalidationTraits *ETraits) const {}
221 CallEvent &operator=(const CallEvent &) = delete;
222 virtual ~CallEvent() = default;
224 /// Returns the kind of call this is.
225 virtual Kind getKind() const = 0;
227 /// Returns the declaration of the function or method that will be
228 /// called. May be null.
229 virtual const Decl *getDecl() const {
230 return Origin.dyn_cast<const Decl *>();
233 /// The state in which the call is being evaluated.
234 const ProgramStateRef &getState() const {
238 /// The context in which the call is being evaluated.
239 const LocationContext *getLocationContext() const {
243 /// Returns the definition of the function or method that will be
245 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
247 /// Returns the expression whose value will be the result of this call.
249 const Expr *getOriginExpr() const {
250 return Origin.dyn_cast<const Expr *>();
253 /// Returns the number of arguments (explicit and implicit).
255 /// Note that this may be greater than the number of parameters in the
256 /// callee's declaration, and that it may include arguments not written in
258 virtual unsigned getNumArgs() const = 0;
260 /// Returns true if the callee is known to be from a system header.
261 bool isInSystemHeader() const {
262 const Decl *D = getDecl();
266 SourceLocation Loc = D->getLocation();
268 const SourceManager &SM =
269 getState()->getStateManager().getContext().getSourceManager();
270 return SM.isInSystemHeader(D->getLocation());
273 // Special case for implicitly-declared global operator new/delete.
274 // These should be considered system functions.
275 if (const auto *FD = dyn_cast<FunctionDecl>(D))
276 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
281 /// Returns true if the CallEvent is a call to a function that matches
282 /// the CallDescription.
284 /// Note that this function is not intended to be used to match Obj-C method
286 bool isCalled(const CallDescription &CD) const;
288 /// Returns a source range for the entire call, suitable for
289 /// outputting in diagnostics.
290 virtual SourceRange getSourceRange() const {
291 return getOriginExpr()->getSourceRange();
294 /// Returns the value of a given argument at the time of the call.
295 virtual SVal getArgSVal(unsigned Index) const;
297 /// Returns the expression associated with a given argument.
298 /// May be null if this expression does not appear in the source.
299 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
301 /// Returns the source range for errors associated with this argument.
303 /// May be invalid if the argument is not written in the source.
304 virtual SourceRange getArgSourceRange(unsigned Index) const;
306 /// Returns the result type, adjusted for references.
307 QualType getResultType() const;
309 /// Returns the return value of the call.
311 /// This should only be called if the CallEvent was created using a state in
312 /// which the return value has already been bound to the origin expression.
313 SVal getReturnValue() const;
315 /// Returns true if the type of any of the non-null arguments satisfies
317 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
319 /// Returns true if any of the arguments appear to represent callbacks.
320 bool hasNonZeroCallbackArg() const;
322 /// Returns true if any of the arguments is void*.
323 bool hasVoidPointerToNonConstArg() const;
325 /// Returns true if any of the arguments are known to escape to long-
326 /// term storage, even if this method will not modify them.
327 // NOTE: The exact semantics of this are still being defined!
328 // We don't really want a list of hardcoded exceptions in the long run,
329 // but we don't want duplicated lists of known APIs in the short term either.
330 virtual bool argumentsMayEscape() const {
331 return hasNonZeroCallbackArg();
334 /// Returns true if the callee is an externally-visible function in the
335 /// top-level namespace, such as \c malloc.
337 /// You can use this call to determine that a particular function really is
338 /// a library function and not, say, a C++ member function with the same name.
340 /// If a name is provided, the function must additionally match the given
343 /// Note that this deliberately excludes C++ library functions in the \c std
344 /// namespace, but will include C library functions accessed through the
345 /// \c std namespace. This also does not check if the function is declared
346 /// as 'extern "C"', or if it uses C++ name mangling.
347 // FIXME: Add a helper for checking namespaces.
348 // FIXME: Move this down to AnyFunctionCall once checkers have more
349 // precise callbacks.
350 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
352 /// Returns the name of the callee, if its name is a simple identifier.
354 /// Note that this will fail for Objective-C methods, blocks, and C++
355 /// overloaded operators. The former is named by a Selector rather than a
356 /// simple identifier, and the latter two do not have names.
357 // FIXME: Move this down to AnyFunctionCall once checkers have more
358 // precise callbacks.
359 const IdentifierInfo *getCalleeIdentifier() const {
360 const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
363 return ND->getIdentifier();
366 /// Returns an appropriate ProgramPoint for this call.
367 ProgramPoint getProgramPoint(bool IsPreVisit = false,
368 const ProgramPointTag *Tag = nullptr) const;
370 /// Returns a new state with all argument regions invalidated.
372 /// This accepts an alternate state in case some processing has already
374 ProgramStateRef invalidateRegions(unsigned BlockCount,
375 ProgramStateRef Orig = nullptr) const;
377 using FrameBindingTy = std::pair<Loc, SVal>;
378 using BindingsTy = SmallVectorImpl<FrameBindingTy>;
380 /// Populates the given SmallVector with the bindings in the callee's stack
381 /// frame at the start of this call.
382 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
383 BindingsTy &Bindings) const = 0;
385 /// Returns a copy of this CallEvent, but using the given state.
386 template <typename T>
387 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
389 /// Returns a copy of this CallEvent, but using the given state.
390 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
391 return cloneWithState<CallEvent>(NewState);
394 /// Returns true if this is a statement is a function or method call
396 static bool isCallStmt(const Stmt *S);
398 /// Returns the result type of a function or method declaration.
400 /// This will return a null QualType if the result type cannot be determined.
401 static QualType getDeclaredResultType(const Decl *D);
403 /// Returns true if the given decl is known to be variadic.
405 /// \p D must not be null.
406 static bool isVariadic(const Decl *D);
408 /// Returns AnalysisDeclContext for the callee stack frame.
409 /// Currently may fail; returns null on failure.
410 AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
412 /// Returns the callee stack frame. That stack frame will only be entered
413 /// during analysis if the call is inlined, but it may still be useful
414 /// in intermediate calculations even if the call isn't inlined.
415 /// May fail; returns null on failure.
416 const StackFrameContext *getCalleeStackFrame() const;
418 /// Returns memory location for a parameter variable within the callee stack
419 /// frame. May fail; returns null on failure.
420 const VarRegion *getParameterLocation(unsigned Index) const;
422 /// Returns true if on the current path, the argument was constructed by
423 /// calling a C++ constructor over it. This is an internal detail of the
424 /// analysis which doesn't necessarily represent the program semantics:
425 /// if we are supposed to construct an argument directly, we may still
426 /// not do that because we don't know how (i.e., construction context is
427 /// unavailable in the CFG or not supported by the analyzer).
428 bool isArgumentConstructedDirectly(unsigned Index) const {
429 // This assumes that the object was not yet removed from the state.
430 return ExprEngine::getObjectUnderConstruction(
431 getState(), {getOriginExpr(), Index}, getCalleeStackFrame()).hasValue();
434 /// Some calls have parameter numbering mismatched from argument numbering.
435 /// This function converts an argument index to the corresponding
436 /// parameter index. Returns None is the argument doesn't correspond
437 /// to any parameter variable.
438 Optional<unsigned> getAdjustedParameterIndex(unsigned ArgumentIndex) const {
439 if (dyn_cast_or_null<CXXOperatorCallExpr>(getOriginExpr()) &&
440 dyn_cast_or_null<CXXMethodDecl>(getDecl())) {
441 // For member operator calls argument 0 on the expression corresponds
442 // to implicit this-parameter on the declaration.
443 return (ArgumentIndex > 0) ? Optional<unsigned>(ArgumentIndex - 1) : None;
445 return ArgumentIndex;
448 // Iterator access to formal parameters and their types.
451 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
455 /// Return call's formal parameters.
457 /// Remember that the number of formal parameters may not match the number
458 /// of arguments for all calls. However, the first parameter will always
459 /// correspond with the argument value returned by \c getArgSVal(0).
460 virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
462 using param_type_iterator =
463 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
465 /// Returns an iterator over the types of the call's formal parameters.
467 /// This uses the callee decl found by default name lookup rather than the
468 /// definition because it represents a public interface, and probably has
469 /// more annotations.
470 param_type_iterator param_type_begin() const {
471 return llvm::map_iterator(parameters().begin(), GetTypeFn());
473 /// \sa param_type_begin()
474 param_type_iterator param_type_end() const {
475 return llvm::map_iterator(parameters().end(), GetTypeFn());
478 // For debugging purposes only
479 void dump(raw_ostream &Out) const;
483 /// Represents a call to any sort of function that might have a
485 class AnyFunctionCall : public CallEvent {
487 AnyFunctionCall(const Expr *E, ProgramStateRef St,
488 const LocationContext *LCtx)
489 : CallEvent(E, St, LCtx) {}
490 AnyFunctionCall(const Decl *D, ProgramStateRef St,
491 const LocationContext *LCtx)
492 : CallEvent(D, St, LCtx) {}
493 AnyFunctionCall(const AnyFunctionCall &Other) = default;
496 // This function is overridden by subclasses, but they must return
498 const FunctionDecl *getDecl() const override {
499 return cast<FunctionDecl>(CallEvent::getDecl());
502 RuntimeDefinition getRuntimeDefinition() const override;
504 bool argumentsMayEscape() const override;
506 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
507 BindingsTy &Bindings) const override;
509 ArrayRef<ParmVarDecl *> parameters() const override;
511 static bool classof(const CallEvent *CA) {
512 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
513 CA->getKind() <= CE_END_FUNCTION_CALLS;
517 /// Represents a C function or static C++ member function call.
519 /// Example: \c fun()
520 class SimpleFunctionCall : public AnyFunctionCall {
521 friend class CallEventManager;
524 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
525 const LocationContext *LCtx)
526 : AnyFunctionCall(CE, St, LCtx) {}
527 SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
529 void cloneTo(void *Dest) const override {
530 new (Dest) SimpleFunctionCall(*this);
534 virtual const CallExpr *getOriginExpr() const {
535 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
538 const FunctionDecl *getDecl() const override;
540 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
542 const Expr *getArgExpr(unsigned Index) const override {
543 return getOriginExpr()->getArg(Index);
546 Kind getKind() const override { return CE_Function; }
548 static bool classof(const CallEvent *CA) {
549 return CA->getKind() == CE_Function;
553 /// Represents a call to a block.
555 /// Example: <tt>^{ /* ... */ }()</tt>
556 class BlockCall : public CallEvent {
557 friend class CallEventManager;
560 BlockCall(const CallExpr *CE, ProgramStateRef St,
561 const LocationContext *LCtx)
562 : CallEvent(CE, St, LCtx) {}
563 BlockCall(const BlockCall &Other) = default;
565 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
567 void getExtraInvalidatedValues(ValueList &Values,
568 RegionAndSymbolInvalidationTraits *ETraits) const override;
571 virtual const CallExpr *getOriginExpr() const {
572 return cast<CallExpr>(CallEvent::getOriginExpr());
575 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
577 const Expr *getArgExpr(unsigned Index) const override {
578 return getOriginExpr()->getArg(Index);
581 /// Returns the region associated with this instance of the block.
583 /// This may be NULL if the block's origin is unknown.
584 const BlockDataRegion *getBlockRegion() const;
586 const BlockDecl *getDecl() const override {
587 const BlockDataRegion *BR = getBlockRegion();
590 return BR->getDecl();
593 bool isConversionFromLambda() const {
594 const BlockDecl *BD = getDecl();
598 return BD->isConversionFromLambda();
601 /// For a block converted from a C++ lambda, returns the block
602 /// VarRegion for the variable holding the captured C++ lambda record.
603 const VarRegion *getRegionStoringCapturedLambda() const {
604 assert(isConversionFromLambda());
605 const BlockDataRegion *BR = getBlockRegion();
606 assert(BR && "Block converted from lambda must have a block region");
608 auto I = BR->referenced_vars_begin();
609 assert(I != BR->referenced_vars_end());
611 return I.getCapturedRegion();
614 RuntimeDefinition getRuntimeDefinition() const override {
615 if (!isConversionFromLambda())
616 return RuntimeDefinition(getDecl());
618 // Clang converts lambdas to blocks with an implicit user-defined
619 // conversion operator method on the lambda record that looks (roughly)
622 // typedef R(^block_type)(P1, P2, ...);
623 // operator block_type() const {
624 // auto Lambda = *this;
625 // return ^(P1 p1, P2 p2, ...){
626 // /* return Lambda(p1, p2, ...); */
630 // Here R is the return type of the lambda and P1, P2, ... are
631 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
632 // that is initialized to a copy of the lambda.
634 // Sema leaves the body of a lambda-converted block empty (it is
635 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
636 // the block body and analyze the operator() method on the captured lambda.
637 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
638 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
639 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
641 return RuntimeDefinition(LambdaCallOperator);
644 bool argumentsMayEscape() const override {
648 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
649 BindingsTy &Bindings) const override;
651 ArrayRef<ParmVarDecl*> parameters() const override;
653 Kind getKind() const override { return CE_Block; }
655 static bool classof(const CallEvent *CA) {
656 return CA->getKind() == CE_Block;
660 /// Represents a non-static C++ member function call, no matter how
662 class CXXInstanceCall : public AnyFunctionCall {
664 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
665 const LocationContext *LCtx)
666 : AnyFunctionCall(CE, St, LCtx) {}
667 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
668 const LocationContext *LCtx)
669 : AnyFunctionCall(D, St, LCtx) {}
670 CXXInstanceCall(const CXXInstanceCall &Other) = default;
672 void getExtraInvalidatedValues(ValueList &Values,
673 RegionAndSymbolInvalidationTraits *ETraits) const override;
676 /// Returns the expression representing the implicit 'this' object.
677 virtual const Expr *getCXXThisExpr() const { return nullptr; }
679 /// Returns the value of the implicit 'this' object.
680 virtual SVal getCXXThisVal() const;
682 const FunctionDecl *getDecl() const override;
684 RuntimeDefinition getRuntimeDefinition() const override;
686 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
687 BindingsTy &Bindings) const override;
689 static bool classof(const CallEvent *CA) {
690 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
691 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
695 /// Represents a non-static C++ member function call.
697 /// Example: \c obj.fun()
698 class CXXMemberCall : public CXXInstanceCall {
699 friend class CallEventManager;
702 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
703 const LocationContext *LCtx)
704 : CXXInstanceCall(CE, St, LCtx) {}
705 CXXMemberCall(const CXXMemberCall &Other) = default;
707 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
710 virtual const CXXMemberCallExpr *getOriginExpr() const {
711 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
714 unsigned getNumArgs() const override {
715 if (const CallExpr *CE = getOriginExpr())
716 return CE->getNumArgs();
720 const Expr *getArgExpr(unsigned Index) const override {
721 return getOriginExpr()->getArg(Index);
724 const Expr *getCXXThisExpr() const override;
726 RuntimeDefinition getRuntimeDefinition() const override;
728 Kind getKind() const override { return CE_CXXMember; }
730 static bool classof(const CallEvent *CA) {
731 return CA->getKind() == CE_CXXMember;
735 /// Represents a C++ overloaded operator call where the operator is
736 /// implemented as a non-static member function.
738 /// Example: <tt>iter + 1</tt>
739 class CXXMemberOperatorCall : public CXXInstanceCall {
740 friend class CallEventManager;
743 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
744 const LocationContext *LCtx)
745 : CXXInstanceCall(CE, St, LCtx) {}
746 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
748 void cloneTo(void *Dest) const override {
749 new (Dest) CXXMemberOperatorCall(*this);
753 virtual const CXXOperatorCallExpr *getOriginExpr() const {
754 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
757 unsigned getNumArgs() const override {
758 return getOriginExpr()->getNumArgs() - 1;
761 const Expr *getArgExpr(unsigned Index) const override {
762 return getOriginExpr()->getArg(Index + 1);
765 const Expr *getCXXThisExpr() const override;
767 Kind getKind() const override { return CE_CXXMemberOperator; }
769 static bool classof(const CallEvent *CA) {
770 return CA->getKind() == CE_CXXMemberOperator;
774 /// Represents an implicit call to a C++ destructor.
776 /// This can occur at the end of a scope (for automatic objects), at the end
777 /// of a full-expression (for temporaries), or as part of a delete.
778 class CXXDestructorCall : public CXXInstanceCall {
779 friend class CallEventManager;
782 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
784 /// Creates an implicit destructor.
786 /// \param DD The destructor that will be called.
787 /// \param Trigger The statement whose completion causes this destructor call.
788 /// \param Target The object region to be destructed.
789 /// \param St The path-sensitive state at this point in the program.
790 /// \param LCtx The location context at this point in the program.
791 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
792 const MemRegion *Target, bool IsBaseDestructor,
793 ProgramStateRef St, const LocationContext *LCtx)
794 : CXXInstanceCall(DD, St, LCtx) {
795 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
796 Location = Trigger->getLocEnd();
799 CXXDestructorCall(const CXXDestructorCall &Other) = default;
801 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
804 SourceRange getSourceRange() const override { return Location; }
805 unsigned getNumArgs() const override { return 0; }
807 RuntimeDefinition getRuntimeDefinition() const override;
809 /// Returns the value of the implicit 'this' object.
810 SVal getCXXThisVal() const override;
812 /// Returns true if this is a call to a base class destructor.
813 bool isBaseDestructor() const {
814 return DtorDataTy::getFromOpaqueValue(Data).getInt();
817 Kind getKind() const override { return CE_CXXDestructor; }
819 static bool classof(const CallEvent *CA) {
820 return CA->getKind() == CE_CXXDestructor;
824 /// Represents a call to a C++ constructor.
827 class CXXConstructorCall : public AnyFunctionCall {
828 friend class CallEventManager;
831 /// Creates a constructor call.
833 /// \param CE The constructor expression as written in the source.
834 /// \param Target The region where the object should be constructed. If NULL,
835 /// a new symbolic region will be used.
836 /// \param St The path-sensitive state at this point in the program.
837 /// \param LCtx The location context at this point in the program.
838 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
839 ProgramStateRef St, const LocationContext *LCtx)
840 : AnyFunctionCall(CE, St, LCtx) {
844 CXXConstructorCall(const CXXConstructorCall &Other) = default;
846 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
848 void getExtraInvalidatedValues(ValueList &Values,
849 RegionAndSymbolInvalidationTraits *ETraits) const override;
852 virtual const CXXConstructExpr *getOriginExpr() const {
853 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
856 const CXXConstructorDecl *getDecl() const override {
857 return getOriginExpr()->getConstructor();
860 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
862 const Expr *getArgExpr(unsigned Index) const override {
863 return getOriginExpr()->getArg(Index);
866 /// Returns the value of the implicit 'this' object.
867 SVal getCXXThisVal() const;
869 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
870 BindingsTy &Bindings) const override;
872 Kind getKind() const override { return CE_CXXConstructor; }
874 static bool classof(const CallEvent *CA) {
875 return CA->getKind() == CE_CXXConstructor;
879 /// Represents the memory allocation call in a C++ new-expression.
881 /// This is a call to "operator new".
882 class CXXAllocatorCall : public AnyFunctionCall {
883 friend class CallEventManager;
886 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
887 const LocationContext *LCtx)
888 : AnyFunctionCall(E, St, LCtx) {}
889 CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
891 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
894 virtual const CXXNewExpr *getOriginExpr() const {
895 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
898 const FunctionDecl *getDecl() const override {
899 return getOriginExpr()->getOperatorNew();
902 unsigned getNumArgs() const override {
903 return getOriginExpr()->getNumPlacementArgs() + 1;
906 const Expr *getArgExpr(unsigned Index) const override {
907 // The first argument of an allocator call is the size of the allocation.
910 return getOriginExpr()->getPlacementArg(Index - 1);
913 Kind getKind() const override { return CE_CXXAllocator; }
915 static bool classof(const CallEvent *CE) {
916 return CE->getKind() == CE_CXXAllocator;
920 /// Represents the ways an Objective-C message send can occur.
922 // Note to maintainers: OCM_Message should always be last, since it does not
923 // need to fit in the Data field's low bits.
924 enum ObjCMessageKind {
930 /// Represents any expression that calls an Objective-C method.
932 /// This includes all of the kinds listed in ObjCMessageKind.
933 class ObjCMethodCall : public CallEvent {
934 friend class CallEventManager;
936 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
939 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
940 const LocationContext *LCtx)
941 : CallEvent(Msg, St, LCtx) {
945 ObjCMethodCall(const ObjCMethodCall &Other) = default;
947 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
949 void getExtraInvalidatedValues(ValueList &Values,
950 RegionAndSymbolInvalidationTraits *ETraits) const override;
952 /// Check if the selector may have multiple definitions (may have overrides).
953 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
957 virtual const ObjCMessageExpr *getOriginExpr() const {
958 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
961 const ObjCMethodDecl *getDecl() const override {
962 return getOriginExpr()->getMethodDecl();
965 unsigned getNumArgs() const override {
966 return getOriginExpr()->getNumArgs();
969 const Expr *getArgExpr(unsigned Index) const override {
970 return getOriginExpr()->getArg(Index);
973 bool isInstanceMessage() const {
974 return getOriginExpr()->isInstanceMessage();
977 ObjCMethodFamily getMethodFamily() const {
978 return getOriginExpr()->getMethodFamily();
981 Selector getSelector() const {
982 return getOriginExpr()->getSelector();
985 SourceRange getSourceRange() const override;
987 /// Returns the value of the receiver at the time of this call.
988 SVal getReceiverSVal() const;
990 /// Return the value of 'self' if available.
991 SVal getSelfSVal() const;
993 /// Get the interface for the receiver.
995 /// This works whether this is an instance message or a class message.
996 /// However, it currently just uses the static type of the receiver.
997 const ObjCInterfaceDecl *getReceiverInterface() const {
998 return getOriginExpr()->getReceiverInterface();
1001 /// Checks if the receiver refers to 'self' or 'super'.
1002 bool isReceiverSelfOrSuper() const;
1004 /// Returns how the message was written in the source (property access,
1005 /// subscript, or explicit message send).
1006 ObjCMessageKind getMessageKind() const;
1008 /// Returns true if this property access or subscript is a setter (has the
1009 /// form of an assignment).
1010 bool isSetter() const {
1011 switch (getMessageKind()) {
1013 llvm_unreachable("This is not a pseudo-object access!");
1014 case OCM_PropertyAccess:
1015 return getNumArgs() > 0;
1017 return getNumArgs() > 1;
1019 llvm_unreachable("Unknown message kind");
1022 // Returns the property accessed by this method, either explicitly via
1023 // property syntax or implicitly via a getter or setter method. Returns
1024 // nullptr if the call is not a prooperty access.
1025 const ObjCPropertyDecl *getAccessedProperty() const;
1027 RuntimeDefinition getRuntimeDefinition() const override;
1029 bool argumentsMayEscape() const override;
1031 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1032 BindingsTy &Bindings) const override;
1034 ArrayRef<ParmVarDecl*> parameters() const override;
1036 Kind getKind() const override { return CE_ObjCMessage; }
1038 static bool classof(const CallEvent *CA) {
1039 return CA->getKind() == CE_ObjCMessage;
1043 /// Manages the lifetime of CallEvent objects.
1045 /// CallEventManager provides a way to create arbitrary CallEvents "on the
1046 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
1047 /// memory blocks. The CallEvents created by CallEventManager are only valid
1048 /// for the lifetime of the OwnedCallEvent that holds them; right now these
1049 /// objects cannot be copied and ownership cannot be transferred.
1050 class CallEventManager {
1051 friend class CallEvent;
1053 llvm::BumpPtrAllocator &Alloc;
1054 SmallVector<void *, 8> Cache;
1056 using CallEventTemplateTy = SimpleFunctionCall;
1058 void reclaim(const void *Memory) {
1059 Cache.push_back(const_cast<void *>(Memory));
1062 /// Returns memory that can be initialized as a CallEvent.
1065 return Alloc.Allocate<CallEventTemplateTy>();
1067 return Cache.pop_back_val();
1070 template <typename T, typename Arg>
1071 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1072 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1073 "CallEvent subclasses are not all the same size");
1074 return new (allocate()) T(A, St, LCtx);
1077 template <typename T, typename Arg1, typename Arg2>
1078 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1079 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1080 "CallEvent subclasses are not all the same size");
1081 return new (allocate()) T(A1, A2, St, LCtx);
1084 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1085 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1086 const LocationContext *LCtx) {
1087 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1088 "CallEvent subclasses are not all the same size");
1089 return new (allocate()) T(A1, A2, A3, St, LCtx);
1092 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1094 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1095 const LocationContext *LCtx) {
1096 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1097 "CallEvent subclasses are not all the same size");
1098 return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1102 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1105 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1108 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1109 const LocationContext *LCtx);
1111 CallEventRef<ObjCMethodCall>
1112 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1113 const LocationContext *LCtx) {
1114 return create<ObjCMethodCall>(E, State, LCtx);
1117 CallEventRef<CXXConstructorCall>
1118 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1119 ProgramStateRef State, const LocationContext *LCtx) {
1120 return create<CXXConstructorCall>(E, Target, State, LCtx);
1123 CallEventRef<CXXDestructorCall>
1124 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1125 const MemRegion *Target, bool IsBase,
1126 ProgramStateRef State, const LocationContext *LCtx) {
1127 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1130 CallEventRef<CXXAllocatorCall>
1131 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1132 const LocationContext *LCtx) {
1133 return create<CXXAllocatorCall>(E, State, LCtx);
1137 template <typename T>
1138 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1139 assert(isa<T>(*this) && "Cloning to unrelated type");
1140 static_assert(sizeof(T) == sizeof(CallEvent),
1141 "Subclasses may not add fields");
1143 if (NewState == State)
1144 return cast<T>(this);
1146 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1147 T *Copy = static_cast<T *>(Mgr.allocate());
1149 assert(Copy->getKind() == this->getKind() && "Bad copy");
1151 Copy->State = NewState;
1155 inline void CallEvent::Release() const {
1156 assert(RefCount > 0 && "Reference count is already zero.");
1162 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1170 } // namespace clang
1174 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1175 template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1176 using SimpleType = const T *;
1179 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1186 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H