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;
83 // The list of the qualified names used to identify the specified CallEvent,
84 // e.g. "{a, b}" represent the qualified names, like "a::b".
85 std::vector<const char *> QualifiedName;
86 unsigned RequiredArgs;
89 const static unsigned NoArgRequirement = std::numeric_limits<unsigned>::max();
91 /// Constructs a CallDescription object.
93 /// @param QualifiedName The list of the name qualifiers of the function that
94 /// will be matched. The user is allowed to skip any of the qualifiers.
95 /// For example, {"std", "basic_string", "c_str"} would match both
96 /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
98 /// @param RequiredArgs The number of arguments that is expected to match a
99 /// call. Omit this parameter to match every occurrence of call with a given
100 /// name regardless the number of arguments.
101 CallDescription(ArrayRef<const char *> QualifiedName,
102 unsigned RequiredArgs = NoArgRequirement)
103 : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
105 /// Get the name of the function that this object matches.
106 StringRef getFunctionName() const { return QualifiedName.back(); }
109 template<typename T = CallEvent>
110 class CallEventRef : public IntrusiveRefCntPtr<const T> {
112 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
113 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
115 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
116 return this->get()->template cloneWithState<T>(State);
119 // Allow implicit conversions to a superclass type, since CallEventRef
120 // behaves like a pointer-to-const.
121 template <typename SuperT>
122 operator CallEventRef<SuperT> () const {
127 /// \class RuntimeDefinition
128 /// Defines the runtime definition of the called function.
130 /// Encapsulates the information we have about which Decl will be used
131 /// when the call is executed on the given path. When dealing with dynamic
132 /// dispatch, the information is based on DynamicTypeInfo and might not be
134 class RuntimeDefinition {
135 /// The Declaration of the function which could be called at runtime.
136 /// NULL if not available.
137 const Decl *D = nullptr;
139 /// The region representing an object (ObjC/C++) on which the method is
140 /// called. With dynamic dispatch, the method definition depends on the
141 /// runtime type of this object. NULL when the DynamicTypeInfo is
143 const MemRegion *R = nullptr;
146 RuntimeDefinition() = default;
147 RuntimeDefinition(const Decl *InD): D(InD) {}
148 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
150 const Decl *getDecl() { return D; }
152 /// Check if the definition we have is precise.
153 /// If not, it is possible that the call dispatches to another definition at
155 bool mayHaveOtherDefinitions() { return R != nullptr; }
157 /// When other definitions are possible, returns the region whose runtime type
158 /// determines the method definition.
159 const MemRegion *getDispatchRegion() { return R; }
162 /// Represents an abstract call to a function or method along a
165 /// CallEvents are created through the factory methods of CallEventManager.
167 /// CallEvents should always be cheap to create and destroy. In order for
168 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
169 /// subclasses of CallEvent may not add any data members to the base class.
170 /// Use the "Data" and "Location" fields instead.
173 using Kind = CallEventKind;
176 ProgramStateRef State;
177 const LocationContext *LCtx;
178 llvm::PointerUnion<const Expr *, const Decl *> Origin;
181 // This is user data for subclasses.
184 // This is user data for subclasses.
185 // This should come right before RefCount, so that the two fields can be
186 // packed together on LP64 platforms.
187 SourceLocation Location;
190 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
192 mutable unsigned RefCount = 0;
194 void Retain() const { ++RefCount; }
195 void Release() const;
198 friend class CallEventManager;
200 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
201 : State(std::move(state)), LCtx(lctx), Origin(E) {}
203 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
204 : State(std::move(state)), LCtx(lctx), Origin(D) {}
206 // DO NOT MAKE PUBLIC
207 CallEvent(const CallEvent &Original)
208 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
209 Data(Original.Data), Location(Original.Location) {}
211 /// Copies this CallEvent, with vtable intact, into a new block of memory.
212 virtual void cloneTo(void *Dest) const = 0;
214 /// Get the value of arbitrary expressions at this point in the path.
215 SVal getSVal(const Stmt *S) const {
216 return getState()->getSVal(S, getLocationContext());
219 using ValueList = SmallVectorImpl<SVal>;
221 /// Used to specify non-argument regions that will be invalidated as a
222 /// result of this call.
223 virtual void getExtraInvalidatedValues(ValueList &Values,
224 RegionAndSymbolInvalidationTraits *ETraits) const {}
227 CallEvent &operator=(const CallEvent &) = delete;
228 virtual ~CallEvent() = default;
230 /// Returns the kind of call this is.
231 virtual Kind getKind() const = 0;
233 /// Returns the declaration of the function or method that will be
234 /// called. May be null.
235 virtual const Decl *getDecl() const {
236 return Origin.dyn_cast<const Decl *>();
239 /// The state in which the call is being evaluated.
240 const ProgramStateRef &getState() const {
244 /// The context in which the call is being evaluated.
245 const LocationContext *getLocationContext() const {
249 /// Returns the definition of the function or method that will be
251 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
253 /// Returns the expression whose value will be the result of this call.
255 const Expr *getOriginExpr() const {
256 return Origin.dyn_cast<const Expr *>();
259 /// Returns the number of arguments (explicit and implicit).
261 /// Note that this may be greater than the number of parameters in the
262 /// callee's declaration, and that it may include arguments not written in
264 virtual unsigned getNumArgs() const = 0;
266 /// Returns true if the callee is known to be from a system header.
267 bool isInSystemHeader() const {
268 const Decl *D = getDecl();
272 SourceLocation Loc = D->getLocation();
274 const SourceManager &SM =
275 getState()->getStateManager().getContext().getSourceManager();
276 return SM.isInSystemHeader(D->getLocation());
279 // Special case for implicitly-declared global operator new/delete.
280 // These should be considered system functions.
281 if (const auto *FD = dyn_cast<FunctionDecl>(D))
282 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
287 /// Returns true if the CallEvent is a call to a function that matches
288 /// the CallDescription.
290 /// Note that this function is not intended to be used to match Obj-C method
292 bool isCalled(const CallDescription &CD) const;
294 /// Returns a source range for the entire call, suitable for
295 /// outputting in diagnostics.
296 virtual SourceRange getSourceRange() const {
297 return getOriginExpr()->getSourceRange();
300 /// Returns the value of a given argument at the time of the call.
301 virtual SVal getArgSVal(unsigned Index) const;
303 /// Returns the expression associated with a given argument.
304 /// May be null if this expression does not appear in the source.
305 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
307 /// Returns the source range for errors associated with this argument.
309 /// May be invalid if the argument is not written in the source.
310 virtual SourceRange getArgSourceRange(unsigned Index) const;
312 /// Returns the result type, adjusted for references.
313 QualType getResultType() const;
315 /// Returns the return value of the call.
317 /// This should only be called if the CallEvent was created using a state in
318 /// which the return value has already been bound to the origin expression.
319 SVal getReturnValue() const;
321 /// Returns true if the type of any of the non-null arguments satisfies
323 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
325 /// Returns true if any of the arguments appear to represent callbacks.
326 bool hasNonZeroCallbackArg() const;
328 /// Returns true if any of the arguments is void*.
329 bool hasVoidPointerToNonConstArg() const;
331 /// Returns true if any of the arguments are known to escape to long-
332 /// term storage, even if this method will not modify them.
333 // NOTE: The exact semantics of this are still being defined!
334 // We don't really want a list of hardcoded exceptions in the long run,
335 // but we don't want duplicated lists of known APIs in the short term either.
336 virtual bool argumentsMayEscape() const {
337 return hasNonZeroCallbackArg();
340 /// Returns true if the callee is an externally-visible function in the
341 /// top-level namespace, such as \c malloc.
343 /// You can use this call to determine that a particular function really is
344 /// a library function and not, say, a C++ member function with the same name.
346 /// If a name is provided, the function must additionally match the given
349 /// Note that this deliberately excludes C++ library functions in the \c std
350 /// namespace, but will include C library functions accessed through the
351 /// \c std namespace. This also does not check if the function is declared
352 /// as 'extern "C"', or if it uses C++ name mangling.
353 // FIXME: Add a helper for checking namespaces.
354 // FIXME: Move this down to AnyFunctionCall once checkers have more
355 // precise callbacks.
356 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
358 /// Returns the name of the callee, if its name is a simple identifier.
360 /// Note that this will fail for Objective-C methods, blocks, and C++
361 /// overloaded operators. The former is named by a Selector rather than a
362 /// simple identifier, and the latter two do not have names.
363 // FIXME: Move this down to AnyFunctionCall once checkers have more
364 // precise callbacks.
365 const IdentifierInfo *getCalleeIdentifier() const {
366 const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
369 return ND->getIdentifier();
372 /// Returns an appropriate ProgramPoint for this call.
373 ProgramPoint getProgramPoint(bool IsPreVisit = false,
374 const ProgramPointTag *Tag = nullptr) const;
376 /// Returns a new state with all argument regions invalidated.
378 /// This accepts an alternate state in case some processing has already
380 ProgramStateRef invalidateRegions(unsigned BlockCount,
381 ProgramStateRef Orig = nullptr) const;
383 using FrameBindingTy = std::pair<Loc, SVal>;
384 using BindingsTy = SmallVectorImpl<FrameBindingTy>;
386 /// Populates the given SmallVector with the bindings in the callee's stack
387 /// frame at the start of this call.
388 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
389 BindingsTy &Bindings) const = 0;
391 /// Returns a copy of this CallEvent, but using the given state.
392 template <typename T>
393 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
395 /// Returns a copy of this CallEvent, but using the given state.
396 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
397 return cloneWithState<CallEvent>(NewState);
400 /// Returns true if this is a statement is a function or method call
402 static bool isCallStmt(const Stmt *S);
404 /// Returns the result type of a function or method declaration.
406 /// This will return a null QualType if the result type cannot be determined.
407 static QualType getDeclaredResultType(const Decl *D);
409 /// Returns true if the given decl is known to be variadic.
411 /// \p D must not be null.
412 static bool isVariadic(const Decl *D);
414 /// Returns AnalysisDeclContext for the callee stack frame.
415 /// Currently may fail; returns null on failure.
416 AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
418 /// Returns the callee stack frame. That stack frame will only be entered
419 /// during analysis if the call is inlined, but it may still be useful
420 /// in intermediate calculations even if the call isn't inlined.
421 /// May fail; returns null on failure.
422 const StackFrameContext *getCalleeStackFrame() const;
424 /// Returns memory location for a parameter variable within the callee stack
425 /// frame. May fail; returns null on failure.
426 const VarRegion *getParameterLocation(unsigned Index) const;
428 /// Returns true if on the current path, the argument was constructed by
429 /// calling a C++ constructor over it. This is an internal detail of the
430 /// analysis which doesn't necessarily represent the program semantics:
431 /// if we are supposed to construct an argument directly, we may still
432 /// not do that because we don't know how (i.e., construction context is
433 /// unavailable in the CFG or not supported by the analyzer).
434 bool isArgumentConstructedDirectly(unsigned Index) const {
435 // This assumes that the object was not yet removed from the state.
436 return ExprEngine::getObjectUnderConstruction(
437 getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue();
440 /// Some calls have parameter numbering mismatched from argument numbering.
441 /// This function converts an argument index to the corresponding
442 /// parameter index. Returns None is the argument doesn't correspond
443 /// to any parameter variable.
444 virtual Optional<unsigned>
445 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
446 return ASTArgumentIndex;
449 /// Some call event sub-classes conveniently adjust mismatching AST indices
450 /// to match parameter indices. This function converts an argument index
451 /// as understood by CallEvent to the argument index as understood by the AST.
452 virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
453 return CallArgumentIndex;
456 // Iterator access to formal parameters and their types.
459 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
463 /// Return call's formal parameters.
465 /// Remember that the number of formal parameters may not match the number
466 /// of arguments for all calls. However, the first parameter will always
467 /// correspond with the argument value returned by \c getArgSVal(0).
468 virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
470 using param_type_iterator =
471 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
473 /// Returns an iterator over the types of the call's formal parameters.
475 /// This uses the callee decl found by default name lookup rather than the
476 /// definition because it represents a public interface, and probably has
477 /// more annotations.
478 param_type_iterator param_type_begin() const {
479 return llvm::map_iterator(parameters().begin(), GetTypeFn());
481 /// \sa param_type_begin()
482 param_type_iterator param_type_end() const {
483 return llvm::map_iterator(parameters().end(), GetTypeFn());
486 // For debugging purposes only
487 void dump(raw_ostream &Out) const;
491 /// Represents a call to any sort of function that might have a
493 class AnyFunctionCall : public CallEvent {
495 AnyFunctionCall(const Expr *E, ProgramStateRef St,
496 const LocationContext *LCtx)
497 : CallEvent(E, St, LCtx) {}
498 AnyFunctionCall(const Decl *D, ProgramStateRef St,
499 const LocationContext *LCtx)
500 : CallEvent(D, St, LCtx) {}
501 AnyFunctionCall(const AnyFunctionCall &Other) = default;
504 // This function is overridden by subclasses, but they must return
506 const FunctionDecl *getDecl() const override {
507 return cast<FunctionDecl>(CallEvent::getDecl());
510 RuntimeDefinition getRuntimeDefinition() const override;
512 bool argumentsMayEscape() const override;
514 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
515 BindingsTy &Bindings) const override;
517 ArrayRef<ParmVarDecl *> parameters() const override;
519 static bool classof(const CallEvent *CA) {
520 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
521 CA->getKind() <= CE_END_FUNCTION_CALLS;
525 /// Represents a C function or static C++ member function call.
527 /// Example: \c fun()
528 class SimpleFunctionCall : public AnyFunctionCall {
529 friend class CallEventManager;
532 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
533 const LocationContext *LCtx)
534 : AnyFunctionCall(CE, St, LCtx) {}
535 SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
537 void cloneTo(void *Dest) const override {
538 new (Dest) SimpleFunctionCall(*this);
542 virtual const CallExpr *getOriginExpr() const {
543 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
546 const FunctionDecl *getDecl() const override;
548 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
550 const Expr *getArgExpr(unsigned Index) const override {
551 return getOriginExpr()->getArg(Index);
554 Kind getKind() const override { return CE_Function; }
556 static bool classof(const CallEvent *CA) {
557 return CA->getKind() == CE_Function;
561 /// Represents a call to a block.
563 /// Example: <tt>^{ /* ... */ }()</tt>
564 class BlockCall : public CallEvent {
565 friend class CallEventManager;
568 BlockCall(const CallExpr *CE, ProgramStateRef St,
569 const LocationContext *LCtx)
570 : CallEvent(CE, St, LCtx) {}
571 BlockCall(const BlockCall &Other) = default;
573 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
575 void getExtraInvalidatedValues(ValueList &Values,
576 RegionAndSymbolInvalidationTraits *ETraits) const override;
579 virtual const CallExpr *getOriginExpr() const {
580 return cast<CallExpr>(CallEvent::getOriginExpr());
583 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
585 const Expr *getArgExpr(unsigned Index) const override {
586 return getOriginExpr()->getArg(Index);
589 /// Returns the region associated with this instance of the block.
591 /// This may be NULL if the block's origin is unknown.
592 const BlockDataRegion *getBlockRegion() const;
594 const BlockDecl *getDecl() const override {
595 const BlockDataRegion *BR = getBlockRegion();
598 return BR->getDecl();
601 bool isConversionFromLambda() const {
602 const BlockDecl *BD = getDecl();
606 return BD->isConversionFromLambda();
609 /// For a block converted from a C++ lambda, returns the block
610 /// VarRegion for the variable holding the captured C++ lambda record.
611 const VarRegion *getRegionStoringCapturedLambda() const {
612 assert(isConversionFromLambda());
613 const BlockDataRegion *BR = getBlockRegion();
614 assert(BR && "Block converted from lambda must have a block region");
616 auto I = BR->referenced_vars_begin();
617 assert(I != BR->referenced_vars_end());
619 return I.getCapturedRegion();
622 RuntimeDefinition getRuntimeDefinition() const override {
623 if (!isConversionFromLambda())
624 return RuntimeDefinition(getDecl());
626 // Clang converts lambdas to blocks with an implicit user-defined
627 // conversion operator method on the lambda record that looks (roughly)
630 // typedef R(^block_type)(P1, P2, ...);
631 // operator block_type() const {
632 // auto Lambda = *this;
633 // return ^(P1 p1, P2 p2, ...){
634 // /* return Lambda(p1, p2, ...); */
638 // Here R is the return type of the lambda and P1, P2, ... are
639 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
640 // that is initialized to a copy of the lambda.
642 // Sema leaves the body of a lambda-converted block empty (it is
643 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
644 // the block body and analyze the operator() method on the captured lambda.
645 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
646 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
647 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
649 return RuntimeDefinition(LambdaCallOperator);
652 bool argumentsMayEscape() const override {
656 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
657 BindingsTy &Bindings) const override;
659 ArrayRef<ParmVarDecl*> parameters() const override;
661 Kind getKind() const override { return CE_Block; }
663 static bool classof(const CallEvent *CA) {
664 return CA->getKind() == CE_Block;
668 /// Represents a non-static C++ member function call, no matter how
670 class CXXInstanceCall : public AnyFunctionCall {
672 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
673 const LocationContext *LCtx)
674 : AnyFunctionCall(CE, St, LCtx) {}
675 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
676 const LocationContext *LCtx)
677 : AnyFunctionCall(D, St, LCtx) {}
678 CXXInstanceCall(const CXXInstanceCall &Other) = default;
680 void getExtraInvalidatedValues(ValueList &Values,
681 RegionAndSymbolInvalidationTraits *ETraits) const override;
684 /// Returns the expression representing the implicit 'this' object.
685 virtual const Expr *getCXXThisExpr() const { return nullptr; }
687 /// Returns the value of the implicit 'this' object.
688 virtual SVal getCXXThisVal() const;
690 const FunctionDecl *getDecl() const override;
692 RuntimeDefinition getRuntimeDefinition() const override;
694 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
695 BindingsTy &Bindings) const override;
697 static bool classof(const CallEvent *CA) {
698 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
699 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
703 /// Represents a non-static C++ member function call.
705 /// Example: \c obj.fun()
706 class CXXMemberCall : public CXXInstanceCall {
707 friend class CallEventManager;
710 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
711 const LocationContext *LCtx)
712 : CXXInstanceCall(CE, St, LCtx) {}
713 CXXMemberCall(const CXXMemberCall &Other) = default;
715 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
718 virtual const CXXMemberCallExpr *getOriginExpr() const {
719 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
722 unsigned getNumArgs() const override {
723 if (const CallExpr *CE = getOriginExpr())
724 return CE->getNumArgs();
728 const Expr *getArgExpr(unsigned Index) const override {
729 return getOriginExpr()->getArg(Index);
732 const Expr *getCXXThisExpr() const override;
734 RuntimeDefinition getRuntimeDefinition() const override;
736 Kind getKind() const override { return CE_CXXMember; }
738 static bool classof(const CallEvent *CA) {
739 return CA->getKind() == CE_CXXMember;
743 /// Represents a C++ overloaded operator call where the operator is
744 /// implemented as a non-static member function.
746 /// Example: <tt>iter + 1</tt>
747 class CXXMemberOperatorCall : public CXXInstanceCall {
748 friend class CallEventManager;
751 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
752 const LocationContext *LCtx)
753 : CXXInstanceCall(CE, St, LCtx) {}
754 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
756 void cloneTo(void *Dest) const override {
757 new (Dest) CXXMemberOperatorCall(*this);
761 virtual const CXXOperatorCallExpr *getOriginExpr() const {
762 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
765 unsigned getNumArgs() const override {
766 return getOriginExpr()->getNumArgs() - 1;
769 const Expr *getArgExpr(unsigned Index) const override {
770 return getOriginExpr()->getArg(Index + 1);
773 const Expr *getCXXThisExpr() const override;
775 Kind getKind() const override { return CE_CXXMemberOperator; }
777 static bool classof(const CallEvent *CA) {
778 return CA->getKind() == CE_CXXMemberOperator;
782 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
783 // For member operator calls argument 0 on the expression corresponds
784 // to implicit this-parameter on the declaration.
785 return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1)
789 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
790 // For member operator calls argument 0 on the expression corresponds
791 // to implicit this-parameter on the declaration.
792 return CallArgumentIndex + 1;
796 /// Represents an implicit call to a C++ destructor.
798 /// This can occur at the end of a scope (for automatic objects), at the end
799 /// of a full-expression (for temporaries), or as part of a delete.
800 class CXXDestructorCall : public CXXInstanceCall {
801 friend class CallEventManager;
804 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
806 /// Creates an implicit destructor.
808 /// \param DD The destructor that will be called.
809 /// \param Trigger The statement whose completion causes this destructor call.
810 /// \param Target The object region to be destructed.
811 /// \param St The path-sensitive state at this point in the program.
812 /// \param LCtx The location context at this point in the program.
813 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
814 const MemRegion *Target, bool IsBaseDestructor,
815 ProgramStateRef St, const LocationContext *LCtx)
816 : CXXInstanceCall(DD, St, LCtx) {
817 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
818 Location = Trigger->getEndLoc();
821 CXXDestructorCall(const CXXDestructorCall &Other) = default;
823 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
826 SourceRange getSourceRange() const override { return Location; }
827 unsigned getNumArgs() const override { return 0; }
829 RuntimeDefinition getRuntimeDefinition() const override;
831 /// Returns the value of the implicit 'this' object.
832 SVal getCXXThisVal() const override;
834 /// Returns true if this is a call to a base class destructor.
835 bool isBaseDestructor() const {
836 return DtorDataTy::getFromOpaqueValue(Data).getInt();
839 Kind getKind() const override { return CE_CXXDestructor; }
841 static bool classof(const CallEvent *CA) {
842 return CA->getKind() == CE_CXXDestructor;
846 /// Represents a call to a C++ constructor.
849 class CXXConstructorCall : public AnyFunctionCall {
850 friend class CallEventManager;
853 /// Creates a constructor call.
855 /// \param CE The constructor expression as written in the source.
856 /// \param Target The region where the object should be constructed. If NULL,
857 /// a new symbolic region will be used.
858 /// \param St The path-sensitive state at this point in the program.
859 /// \param LCtx The location context at this point in the program.
860 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
861 ProgramStateRef St, const LocationContext *LCtx)
862 : AnyFunctionCall(CE, St, LCtx) {
866 CXXConstructorCall(const CXXConstructorCall &Other) = default;
868 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
870 void getExtraInvalidatedValues(ValueList &Values,
871 RegionAndSymbolInvalidationTraits *ETraits) const override;
874 virtual const CXXConstructExpr *getOriginExpr() const {
875 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
878 const CXXConstructorDecl *getDecl() const override {
879 return getOriginExpr()->getConstructor();
882 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
884 const Expr *getArgExpr(unsigned Index) const override {
885 return getOriginExpr()->getArg(Index);
888 /// Returns the value of the implicit 'this' object.
889 SVal getCXXThisVal() const;
891 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
892 BindingsTy &Bindings) const override;
894 Kind getKind() const override { return CE_CXXConstructor; }
896 static bool classof(const CallEvent *CA) {
897 return CA->getKind() == CE_CXXConstructor;
901 /// Represents the memory allocation call in a C++ new-expression.
903 /// This is a call to "operator new".
904 class CXXAllocatorCall : public AnyFunctionCall {
905 friend class CallEventManager;
908 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
909 const LocationContext *LCtx)
910 : AnyFunctionCall(E, St, LCtx) {}
911 CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
913 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
916 virtual const CXXNewExpr *getOriginExpr() const {
917 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
920 const FunctionDecl *getDecl() const override {
921 return getOriginExpr()->getOperatorNew();
924 /// Number of non-placement arguments to the call. It is equal to 2 for
925 /// C++17 aligned operator new() calls that have alignment implicitly
926 /// passed as the second argument, and to 1 for other operator new() calls.
927 unsigned getNumImplicitArgs() const {
928 return getOriginExpr()->passAlignment() ? 2 : 1;
931 unsigned getNumArgs() const override {
932 return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
935 const Expr *getArgExpr(unsigned Index) const override {
936 // The first argument of an allocator call is the size of the allocation.
937 if (Index < getNumImplicitArgs())
939 return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs());
942 /// Number of placement arguments to the operator new() call. For example,
943 /// standard std::nothrow operator new and standard placement new both have
944 /// 1 implicit argument (size) and 1 placement argument, while regular
945 /// operator new() has 1 implicit argument and 0 placement arguments.
946 const Expr *getPlacementArgExpr(unsigned Index) const {
947 return getOriginExpr()->getPlacementArg(Index);
950 Kind getKind() const override { return CE_CXXAllocator; }
952 static bool classof(const CallEvent *CE) {
953 return CE->getKind() == CE_CXXAllocator;
957 /// Represents the ways an Objective-C message send can occur.
959 // Note to maintainers: OCM_Message should always be last, since it does not
960 // need to fit in the Data field's low bits.
961 enum ObjCMessageKind {
967 /// Represents any expression that calls an Objective-C method.
969 /// This includes all of the kinds listed in ObjCMessageKind.
970 class ObjCMethodCall : public CallEvent {
971 friend class CallEventManager;
973 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
976 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
977 const LocationContext *LCtx)
978 : CallEvent(Msg, St, LCtx) {
982 ObjCMethodCall(const ObjCMethodCall &Other) = default;
984 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
986 void getExtraInvalidatedValues(ValueList &Values,
987 RegionAndSymbolInvalidationTraits *ETraits) const override;
989 /// Check if the selector may have multiple definitions (may have overrides).
990 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
994 virtual const ObjCMessageExpr *getOriginExpr() const {
995 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
998 const ObjCMethodDecl *getDecl() const override {
999 return getOriginExpr()->getMethodDecl();
1002 unsigned getNumArgs() const override {
1003 return getOriginExpr()->getNumArgs();
1006 const Expr *getArgExpr(unsigned Index) const override {
1007 return getOriginExpr()->getArg(Index);
1010 bool isInstanceMessage() const {
1011 return getOriginExpr()->isInstanceMessage();
1014 ObjCMethodFamily getMethodFamily() const {
1015 return getOriginExpr()->getMethodFamily();
1018 Selector getSelector() const {
1019 return getOriginExpr()->getSelector();
1022 SourceRange getSourceRange() const override;
1024 /// Returns the value of the receiver at the time of this call.
1025 SVal getReceiverSVal() const;
1027 /// Return the value of 'self' if available.
1028 SVal getSelfSVal() const;
1030 /// Get the interface for the receiver.
1032 /// This works whether this is an instance message or a class message.
1033 /// However, it currently just uses the static type of the receiver.
1034 const ObjCInterfaceDecl *getReceiverInterface() const {
1035 return getOriginExpr()->getReceiverInterface();
1038 /// Checks if the receiver refers to 'self' or 'super'.
1039 bool isReceiverSelfOrSuper() const;
1041 /// Returns how the message was written in the source (property access,
1042 /// subscript, or explicit message send).
1043 ObjCMessageKind getMessageKind() const;
1045 /// Returns true if this property access or subscript is a setter (has the
1046 /// form of an assignment).
1047 bool isSetter() const {
1048 switch (getMessageKind()) {
1050 llvm_unreachable("This is not a pseudo-object access!");
1051 case OCM_PropertyAccess:
1052 return getNumArgs() > 0;
1054 return getNumArgs() > 1;
1056 llvm_unreachable("Unknown message kind");
1059 // Returns the property accessed by this method, either explicitly via
1060 // property syntax or implicitly via a getter or setter method. Returns
1061 // nullptr if the call is not a prooperty access.
1062 const ObjCPropertyDecl *getAccessedProperty() const;
1064 RuntimeDefinition getRuntimeDefinition() const override;
1066 bool argumentsMayEscape() const override;
1068 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1069 BindingsTy &Bindings) const override;
1071 ArrayRef<ParmVarDecl*> parameters() const override;
1073 Kind getKind() const override { return CE_ObjCMessage; }
1075 static bool classof(const CallEvent *CA) {
1076 return CA->getKind() == CE_ObjCMessage;
1080 /// Manages the lifetime of CallEvent objects.
1082 /// CallEventManager provides a way to create arbitrary CallEvents "on the
1083 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
1084 /// memory blocks. The CallEvents created by CallEventManager are only valid
1085 /// for the lifetime of the OwnedCallEvent that holds them; right now these
1086 /// objects cannot be copied and ownership cannot be transferred.
1087 class CallEventManager {
1088 friend class CallEvent;
1090 llvm::BumpPtrAllocator &Alloc;
1091 SmallVector<void *, 8> Cache;
1093 using CallEventTemplateTy = SimpleFunctionCall;
1095 void reclaim(const void *Memory) {
1096 Cache.push_back(const_cast<void *>(Memory));
1099 /// Returns memory that can be initialized as a CallEvent.
1102 return Alloc.Allocate<CallEventTemplateTy>();
1104 return Cache.pop_back_val();
1107 template <typename T, typename Arg>
1108 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110 "CallEvent subclasses are not all the same size");
1111 return new (allocate()) T(A, St, LCtx);
1114 template <typename T, typename Arg1, typename Arg2>
1115 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1116 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1117 "CallEvent subclasses are not all the same size");
1118 return new (allocate()) T(A1, A2, St, LCtx);
1121 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1122 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1123 const LocationContext *LCtx) {
1124 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1125 "CallEvent subclasses are not all the same size");
1126 return new (allocate()) T(A1, A2, A3, St, LCtx);
1129 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1131 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1132 const LocationContext *LCtx) {
1133 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1134 "CallEvent subclasses are not all the same size");
1135 return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1139 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1141 /// Gets an outside caller given a callee context.
1143 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1145 /// Gets a call event for a function call, Objective-C method call,
1146 /// or a 'new' call.
1148 getCall(const Stmt *S, ProgramStateRef State,
1149 const LocationContext *LC);
1152 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1153 const LocationContext *LCtx);
1155 CallEventRef<ObjCMethodCall>
1156 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1157 const LocationContext *LCtx) {
1158 return create<ObjCMethodCall>(E, State, LCtx);
1161 CallEventRef<CXXConstructorCall>
1162 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1163 ProgramStateRef State, const LocationContext *LCtx) {
1164 return create<CXXConstructorCall>(E, Target, State, LCtx);
1167 CallEventRef<CXXDestructorCall>
1168 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1169 const MemRegion *Target, bool IsBase,
1170 ProgramStateRef State, const LocationContext *LCtx) {
1171 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1174 CallEventRef<CXXAllocatorCall>
1175 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1176 const LocationContext *LCtx) {
1177 return create<CXXAllocatorCall>(E, State, LCtx);
1181 template <typename T>
1182 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1183 assert(isa<T>(*this) && "Cloning to unrelated type");
1184 static_assert(sizeof(T) == sizeof(CallEvent),
1185 "Subclasses may not add fields");
1187 if (NewState == State)
1188 return cast<T>(this);
1190 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1191 T *Copy = static_cast<T *>(Mgr.allocate());
1193 assert(Copy->getKind() == this->getKind() && "Bad copy");
1195 Copy->State = NewState;
1199 inline void CallEvent::Release() const {
1200 assert(RefCount > 0 && "Reference count is already zero.");
1206 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1214 } // namespace clang
1218 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1219 template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1220 using SimpleType = const T *;
1223 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1230 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H