1 //===- CallEvent.h - Wrapper for all function and method calls --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This file defines CallEvent and its subclasses, which represent path-
10 /// sensitive instances of different kinds of function and method calls
11 /// (C, C++, and Objective-C).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
17 
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/LLVM.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.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/ADT/iterator_range.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include <cassert>
47 #include <limits>
48 #include <utility>
49 
50 namespace clang {
51 
52 class LocationContext;
53 class ProgramPoint;
54 class ProgramPointTag;
55 class StackFrameContext;
56 
57 namespace ento {
58 
59 enum CallEventKind {
60   CE_Function,
61   CE_CXXMember,
62   CE_CXXMemberOperator,
63   CE_CXXDestructor,
64   CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
65   CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
66   CE_CXXConstructor,
67   CE_CXXInheritedConstructor,
68   CE_BEG_CXX_CONSTRUCTOR_CALLS = CE_CXXConstructor,
69   CE_END_CXX_CONSTRUCTOR_CALLS = CE_CXXInheritedConstructor,
70   CE_CXXAllocator,
71   CE_CXXDeallocator,
72   CE_BEG_FUNCTION_CALLS = CE_Function,
73   CE_END_FUNCTION_CALLS = CE_CXXDeallocator,
74   CE_Block,
75   CE_ObjCMessage
76 };
77 
78 class CallEvent;
79 class CallDescription;
80 
81 template<typename T = CallEvent>
82 class CallEventRef : public IntrusiveRefCntPtr<const T> {
83 public:
84   CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
85   CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
86 
87   CallEventRef<T> cloneWithState(ProgramStateRef State) const {
88     return this->get()->template cloneWithState<T>(State);
89   }
90 
91   // Allow implicit conversions to a superclass type, since CallEventRef
92   // behaves like a pointer-to-const.
93   template <typename SuperT>
94   operator CallEventRef<SuperT> () const {
95     return this->get();
96   }
97 };
98 
99 /// \class RuntimeDefinition
100 /// Defines the runtime definition of the called function.
101 ///
102 /// Encapsulates the information we have about which Decl will be used
103 /// when the call is executed on the given path. When dealing with dynamic
104 /// dispatch, the information is based on DynamicTypeInfo and might not be
105 /// precise.
106 class RuntimeDefinition {
107   /// The Declaration of the function which could be called at runtime.
108   /// NULL if not available.
109   const Decl *D = nullptr;
110 
111   /// The region representing an object (ObjC/C++) on which the method is
112   /// called. With dynamic dispatch, the method definition depends on the
113   /// runtime type of this object. NULL when the DynamicTypeInfo is
114   /// precise.
115   const MemRegion *R = nullptr;
116 
117 public:
118   RuntimeDefinition() = default;
119   RuntimeDefinition(const Decl *InD): D(InD) {}
120   RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
121 
122   const Decl *getDecl() { return D; }
123 
124   /// Check if the definition we have is precise.
125   /// If not, it is possible that the call dispatches to another definition at
126   /// execution time.
127   bool mayHaveOtherDefinitions() { return R != nullptr; }
128 
129   /// When other definitions are possible, returns the region whose runtime type
130   /// determines the method definition.
131   const MemRegion *getDispatchRegion() { return R; }
132 };
133 
134 /// Represents an abstract call to a function or method along a
135 /// particular path.
136 ///
137 /// CallEvents are created through the factory methods of CallEventManager.
138 ///
139 /// CallEvents should always be cheap to create and destroy. In order for
140 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
141 /// subclasses of CallEvent may not add any data members to the base class.
142 /// Use the "Data" and "Location" fields instead.
143 class CallEvent {
144 public:
145   using Kind = CallEventKind;
146 
147 private:
148   ProgramStateRef State;
149   const LocationContext *LCtx;
150   llvm::PointerUnion<const Expr *, const Decl *> Origin;
151 
152 protected:
153   // This is user data for subclasses.
154   const void *Data;
155 
156   // This is user data for subclasses.
157   // This should come right before RefCount, so that the two fields can be
158   // packed together on LP64 platforms.
159   SourceLocation Location;
160 
161 private:
162   template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
163 
164   mutable unsigned RefCount = 0;
165 
166   void Retain() const { ++RefCount; }
167   void Release() const;
168 
169 protected:
170   friend class CallEventManager;
171 
172   CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
173       : State(std::move(state)), LCtx(lctx), Origin(E) {}
174 
175   CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
176       : State(std::move(state)), LCtx(lctx), Origin(D) {}
177 
178   // DO NOT MAKE PUBLIC
179   CallEvent(const CallEvent &Original)
180       : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
181         Data(Original.Data), Location(Original.Location) {}
182 
183   /// Copies this CallEvent, with vtable intact, into a new block of memory.
184   virtual void cloneTo(void *Dest) const = 0;
185 
186   /// Get the value of arbitrary expressions at this point in the path.
187   SVal getSVal(const Stmt *S) const {
188     return getState()->getSVal(S, getLocationContext());
189   }
190 
191   using ValueList = SmallVectorImpl<SVal>;
192 
193   /// Used to specify non-argument regions that will be invalidated as a
194   /// result of this call.
195   virtual void getExtraInvalidatedValues(ValueList &Values,
196                  RegionAndSymbolInvalidationTraits *ETraits) const {}
197 
198 public:
199   CallEvent &operator=(const CallEvent &) = delete;
200   virtual ~CallEvent() = default;
201 
202   /// Returns the kind of call this is.
203   virtual Kind getKind() const = 0;
204   virtual StringRef getKindAsString() const = 0;
205 
206   /// Returns the declaration of the function or method that will be
207   /// called. May be null.
208   virtual const Decl *getDecl() const {
209     return Origin.dyn_cast<const Decl *>();
210   }
211 
212   /// The state in which the call is being evaluated.
213   const ProgramStateRef &getState() const {
214     return State;
215   }
216 
217   /// The context in which the call is being evaluated.
218   const LocationContext *getLocationContext() const {
219     return LCtx;
220   }
221 
222   /// Returns the definition of the function or method that will be
223   /// called.
224   virtual RuntimeDefinition getRuntimeDefinition() const = 0;
225 
226   /// Returns the expression whose value will be the result of this call.
227   /// May be null.
228   virtual const Expr *getOriginExpr() const {
229     return Origin.dyn_cast<const Expr *>();
230   }
231 
232   /// Returns the number of arguments (explicit and implicit).
233   ///
234   /// Note that this may be greater than the number of parameters in the
235   /// callee's declaration, and that it may include arguments not written in
236   /// the source.
237   virtual unsigned getNumArgs() const = 0;
238 
239   /// Returns true if the callee is known to be from a system header.
240   bool isInSystemHeader() const {
241     const Decl *D = getDecl();
242     if (!D)
243       return false;
244 
245     SourceLocation Loc = D->getLocation();
246     if (Loc.isValid()) {
247       const SourceManager &SM =
248         getState()->getStateManager().getContext().getSourceManager();
249       return SM.isInSystemHeader(D->getLocation());
250     }
251 
252     // Special case for implicitly-declared global operator new/delete.
253     // These should be considered system functions.
254     if (const auto *FD = dyn_cast<FunctionDecl>(D))
255       return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
256 
257     return false;
258   }
259 
260   /// Returns true if the CallEvent is a call to a function that matches
261   /// the CallDescription.
262   ///
263   /// Note that this function is not intended to be used to match Obj-C method
264   /// calls.
265   bool isCalled(const CallDescription &CD) const;
266 
267   /// Returns true whether the CallEvent is any of the CallDescriptions supplied
268   /// as a parameter.
269   template <typename FirstCallDesc, typename... CallDescs>
270   bool isCalled(const FirstCallDesc &First, const CallDescs &... Rest) const {
271     return isCalled(First) || isCalled(Rest...);
272   }
273 
274   /// Returns a source range for the entire call, suitable for
275   /// outputting in diagnostics.
276   virtual SourceRange getSourceRange() const {
277     return getOriginExpr()->getSourceRange();
278   }
279 
280   /// Returns the value of a given argument at the time of the call.
281   virtual SVal getArgSVal(unsigned Index) const;
282 
283   /// Returns the expression associated with a given argument.
284   /// May be null if this expression does not appear in the source.
285   virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
286 
287   /// Returns the source range for errors associated with this argument.
288   ///
289   /// May be invalid if the argument is not written in the source.
290   virtual SourceRange getArgSourceRange(unsigned Index) const;
291 
292   /// Returns the result type, adjusted for references.
293   QualType getResultType() const;
294 
295   /// Returns the return value of the call.
296   ///
297   /// This should only be called if the CallEvent was created using a state in
298   /// which the return value has already been bound to the origin expression.
299   SVal getReturnValue() const;
300 
301   /// Returns true if the type of any of the non-null arguments satisfies
302   /// the condition.
303   bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
304 
305   /// Returns true if any of the arguments appear to represent callbacks.
306   bool hasNonZeroCallbackArg() const;
307 
308   /// Returns true if any of the arguments is void*.
309   bool hasVoidPointerToNonConstArg() const;
310 
311   /// Returns true if any of the arguments are known to escape to long-
312   /// term storage, even if this method will not modify them.
313   // NOTE: The exact semantics of this are still being defined!
314   // We don't really want a list of hardcoded exceptions in the long run,
315   // but we don't want duplicated lists of known APIs in the short term either.
316   virtual bool argumentsMayEscape() const {
317     return hasNonZeroCallbackArg();
318   }
319 
320   /// Returns true if the callee is an externally-visible function in the
321   /// top-level namespace, such as \c malloc.
322   ///
323   /// You can use this call to determine that a particular function really is
324   /// a library function and not, say, a C++ member function with the same name.
325   ///
326   /// If a name is provided, the function must additionally match the given
327   /// name.
328   ///
329   /// Note that this deliberately excludes C++ library functions in the \c std
330   /// namespace, but will include C library functions accessed through the
331   /// \c std namespace. This also does not check if the function is declared
332   /// as 'extern "C"', or if it uses C++ name mangling.
333   // FIXME: Add a helper for checking namespaces.
334   // FIXME: Move this down to AnyFunctionCall once checkers have more
335   // precise callbacks.
336   bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
337 
338   /// Returns the name of the callee, if its name is a simple identifier.
339   ///
340   /// Note that this will fail for Objective-C methods, blocks, and C++
341   /// overloaded operators. The former is named by a Selector rather than a
342   /// simple identifier, and the latter two do not have names.
343   // FIXME: Move this down to AnyFunctionCall once checkers have more
344   // precise callbacks.
345   const IdentifierInfo *getCalleeIdentifier() const {
346     const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
347     if (!ND)
348       return nullptr;
349     return ND->getIdentifier();
350   }
351 
352   /// Returns an appropriate ProgramPoint for this call.
353   ProgramPoint getProgramPoint(bool IsPreVisit = false,
354                                const ProgramPointTag *Tag = nullptr) const;
355 
356   /// Returns a new state with all argument regions invalidated.
357   ///
358   /// This accepts an alternate state in case some processing has already
359   /// occurred.
360   ProgramStateRef invalidateRegions(unsigned BlockCount,
361                                     ProgramStateRef Orig = nullptr) const;
362 
363   using FrameBindingTy = std::pair<SVal, SVal>;
364   using BindingsTy = SmallVectorImpl<FrameBindingTy>;
365 
366   /// Populates the given SmallVector with the bindings in the callee's stack
367   /// frame at the start of this call.
368   virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
369                                             BindingsTy &Bindings) const = 0;
370 
371   /// Returns a copy of this CallEvent, but using the given state.
372   template <typename T>
373   CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
374 
375   /// Returns a copy of this CallEvent, but using the given state.
376   CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
377     return cloneWithState<CallEvent>(NewState);
378   }
379 
380   /// Returns true if this is a statement is a function or method call
381   /// of some kind.
382   static bool isCallStmt(const Stmt *S);
383 
384   /// Returns the result type of a function or method declaration.
385   ///
386   /// This will return a null QualType if the result type cannot be determined.
387   static QualType getDeclaredResultType(const Decl *D);
388 
389   /// Returns true if the given decl is known to be variadic.
390   ///
391   /// \p D must not be null.
392   static bool isVariadic(const Decl *D);
393 
394   /// Returns AnalysisDeclContext for the callee stack frame.
395   /// Currently may fail; returns null on failure.
396   AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
397 
398   /// Returns the callee stack frame. That stack frame will only be entered
399   /// during analysis if the call is inlined, but it may still be useful
400   /// in intermediate calculations even if the call isn't inlined.
401   /// May fail; returns null on failure.
402   const StackFrameContext *getCalleeStackFrame(unsigned BlockCount) const;
403 
404   /// Returns memory location for a parameter variable within the callee stack
405   /// frame. The behavior is undefined if the block count is different from the
406   /// one that is there when call happens. May fail; returns null on failure.
407   const ParamVarRegion *getParameterLocation(unsigned Index,
408                                              unsigned BlockCount) const;
409 
410   /// Returns true if on the current path, the argument was constructed by
411   /// calling a C++ constructor over it. This is an internal detail of the
412   /// analysis which doesn't necessarily represent the program semantics:
413   /// if we are supposed to construct an argument directly, we may still
414   /// not do that because we don't know how (i.e., construction context is
415   /// unavailable in the CFG or not supported by the analyzer).
416   bool isArgumentConstructedDirectly(unsigned Index) const {
417     // This assumes that the object was not yet removed from the state.
418     return ExprEngine::getObjectUnderConstruction(
419         getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue();
420   }
421 
422   /// Some calls have parameter numbering mismatched from argument numbering.
423   /// This function converts an argument index to the corresponding
424   /// parameter index. Returns None is the argument doesn't correspond
425   /// to any parameter variable.
426   virtual Optional<unsigned>
427   getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
428     return ASTArgumentIndex;
429   }
430 
431   /// Some call event sub-classes conveniently adjust mismatching AST indices
432   /// to match parameter indices. This function converts an argument index
433   /// as understood by CallEvent to the argument index as understood by the AST.
434   virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
435     return CallArgumentIndex;
436   }
437 
438   /// Returns the construction context of the call, if it is a C++ constructor
439   /// call or a call of a function returning a C++ class instance. Otherwise
440   /// return nullptr.
441   const ConstructionContext *getConstructionContext() const;
442 
443   /// If the call returns a C++ record type then the region of its return value
444   /// can be retrieved from its construction context.
445   Optional<SVal> getReturnValueUnderConstruction() const;
446 
447   // Iterator access to formal parameters and their types.
448 private:
449   struct GetTypeFn {
450     QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
451   };
452 
453 public:
454   /// Return call's formal parameters.
455   ///
456   /// Remember that the number of formal parameters may not match the number
457   /// of arguments for all calls. However, the first parameter will always
458   /// correspond with the argument value returned by \c getArgSVal(0).
459   virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
460 
461   using param_type_iterator =
462       llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
463 
464   /// Returns an iterator over the types of the call's formal parameters.
465   ///
466   /// This uses the callee decl found by default name lookup rather than the
467   /// definition because it represents a public interface, and probably has
468   /// more annotations.
469   param_type_iterator param_type_begin() const {
470     return llvm::map_iterator(parameters().begin(), GetTypeFn());
471   }
472   /// \sa param_type_begin()
473   param_type_iterator param_type_end() const {
474     return llvm::map_iterator(parameters().end(), GetTypeFn());
475   }
476 
477   // For debugging purposes only
478   void dump(raw_ostream &Out) const;
479   void dump() const;
480 };
481 
482 /// Represents a call to any sort of function that might have a
483 /// FunctionDecl.
484 class AnyFunctionCall : public CallEvent {
485 protected:
486   AnyFunctionCall(const Expr *E, ProgramStateRef St,
487                   const LocationContext *LCtx)
488       : CallEvent(E, St, LCtx) {}
489   AnyFunctionCall(const Decl *D, ProgramStateRef St,
490                   const LocationContext *LCtx)
491       : CallEvent(D, St, LCtx) {}
492   AnyFunctionCall(const AnyFunctionCall &Other) = default;
493 
494 public:
495   // This function is overridden by subclasses, but they must return
496   // a FunctionDecl.
497   const FunctionDecl *getDecl() const override {
498     return cast<FunctionDecl>(CallEvent::getDecl());
499   }
500 
501   RuntimeDefinition getRuntimeDefinition() const override;
502 
503   bool argumentsMayEscape() const override;
504 
505   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
506                                     BindingsTy &Bindings) const override;
507 
508   ArrayRef<ParmVarDecl *> parameters() const override;
509 
510   static bool classof(const CallEvent *CA) {
511     return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
512            CA->getKind() <= CE_END_FUNCTION_CALLS;
513   }
514 };
515 
516 /// Represents a C function or static C++ member function call.
517 ///
518 /// Example: \c fun()
519 class SimpleFunctionCall : public AnyFunctionCall {
520   friend class CallEventManager;
521 
522 protected:
523   SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
524                      const LocationContext *LCtx)
525       : AnyFunctionCall(CE, St, LCtx) {}
526   SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
527 
528   void cloneTo(void *Dest) const override {
529     new (Dest) SimpleFunctionCall(*this);
530   }
531 
532 public:
533   const CallExpr *getOriginExpr() const override {
534     return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
535   }
536 
537   const FunctionDecl *getDecl() const override;
538 
539   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
540 
541   const Expr *getArgExpr(unsigned Index) const override {
542     return getOriginExpr()->getArg(Index);
543   }
544 
545   Kind getKind() const override { return CE_Function; }
546   StringRef getKindAsString() const override { return "SimpleFunctionCall"; }
547 
548   static bool classof(const CallEvent *CA) {
549     return CA->getKind() == CE_Function;
550   }
551 };
552 
553 /// Represents a call to a block.
554 ///
555 /// Example: <tt>^{ statement-body }()</tt>
556 class BlockCall : public CallEvent {
557   friend class CallEventManager;
558 
559 protected:
560   BlockCall(const CallExpr *CE, ProgramStateRef St,
561             const LocationContext *LCtx)
562       : CallEvent(CE, St, LCtx) {}
563   BlockCall(const BlockCall &Other) = default;
564 
565   void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
566 
567   void getExtraInvalidatedValues(ValueList &Values,
568          RegionAndSymbolInvalidationTraits *ETraits) const override;
569 
570 public:
571   const CallExpr *getOriginExpr() const override {
572     return cast<CallExpr>(CallEvent::getOriginExpr());
573   }
574 
575   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
576 
577   const Expr *getArgExpr(unsigned Index) const override {
578     return getOriginExpr()->getArg(Index);
579   }
580 
581   /// Returns the region associated with this instance of the block.
582   ///
583   /// This may be NULL if the block's origin is unknown.
584   const BlockDataRegion *getBlockRegion() const;
585 
586   const BlockDecl *getDecl() const override {
587     const BlockDataRegion *BR = getBlockRegion();
588     if (!BR)
589       return nullptr;
590     return BR->getDecl();
591   }
592 
593   bool isConversionFromLambda() const {
594     const BlockDecl *BD = getDecl();
595     if (!BD)
596       return false;
597 
598     return BD->isConversionFromLambda();
599   }
600 
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");
607 
608     auto I = BR->referenced_vars_begin();
609     assert(I != BR->referenced_vars_end());
610 
611     return I.getCapturedRegion();
612   }
613 
614   RuntimeDefinition getRuntimeDefinition() const override {
615     if (!isConversionFromLambda())
616       return RuntimeDefinition(getDecl());
617 
618     // Clang converts lambdas to blocks with an implicit user-defined
619     // conversion operator method on the lambda record that looks (roughly)
620     // like:
621     //
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, ...); */
627     //   };
628     // }
629     //
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.
633     //
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();
640 
641     return RuntimeDefinition(LambdaCallOperator);
642   }
643 
644   bool argumentsMayEscape() const override {
645     return true;
646   }
647 
648   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
649                                     BindingsTy &Bindings) const override;
650 
651   ArrayRef<ParmVarDecl *> parameters() const override;
652 
653   Kind getKind() const override { return CE_Block; }
654   StringRef getKindAsString() const override { return "BlockCall"; }
655 
656   static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Block; }
657 };
658 
659 /// Represents a non-static C++ member function call, no matter how
660 /// it is written.
661 class CXXInstanceCall : public AnyFunctionCall {
662 protected:
663   CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
664                   const LocationContext *LCtx)
665       : AnyFunctionCall(CE, St, LCtx) {}
666   CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
667                   const LocationContext *LCtx)
668       : AnyFunctionCall(D, St, LCtx) {}
669   CXXInstanceCall(const CXXInstanceCall &Other) = default;
670 
671   void getExtraInvalidatedValues(ValueList &Values,
672          RegionAndSymbolInvalidationTraits *ETraits) const override;
673 
674 public:
675   /// Returns the expression representing the implicit 'this' object.
676   virtual const Expr *getCXXThisExpr() const { return nullptr; }
677 
678   /// Returns the value of the implicit 'this' object.
679   virtual SVal getCXXThisVal() const;
680 
681   const FunctionDecl *getDecl() const override;
682 
683   RuntimeDefinition getRuntimeDefinition() const override;
684 
685   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
686                                     BindingsTy &Bindings) const override;
687 
688   static bool classof(const CallEvent *CA) {
689     return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
690            CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
691   }
692 };
693 
694 /// Represents a non-static C++ member function call.
695 ///
696 /// Example: \c obj.fun()
697 class CXXMemberCall : public CXXInstanceCall {
698   friend class CallEventManager;
699 
700 protected:
701   CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
702                 const LocationContext *LCtx)
703       : CXXInstanceCall(CE, St, LCtx) {}
704   CXXMemberCall(const CXXMemberCall &Other) = default;
705 
706   void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
707 
708 public:
709   const CXXMemberCallExpr *getOriginExpr() const override {
710     return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
711   }
712 
713   unsigned getNumArgs() const override {
714     if (const CallExpr *CE = getOriginExpr())
715       return CE->getNumArgs();
716     return 0;
717   }
718 
719   const Expr *getArgExpr(unsigned Index) const override {
720     return getOriginExpr()->getArg(Index);
721   }
722 
723   const Expr *getCXXThisExpr() const override;
724 
725   RuntimeDefinition getRuntimeDefinition() const override;
726 
727   Kind getKind() const override { return CE_CXXMember; }
728   StringRef getKindAsString() const override { return "CXXMemberCall"; }
729 
730   static bool classof(const CallEvent *CA) {
731     return CA->getKind() == CE_CXXMember;
732   }
733 };
734 
735 /// Represents a C++ overloaded operator call where the operator is
736 /// implemented as a non-static member function.
737 ///
738 /// Example: <tt>iter + 1</tt>
739 class CXXMemberOperatorCall : public CXXInstanceCall {
740   friend class CallEventManager;
741 
742 protected:
743   CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
744                         const LocationContext *LCtx)
745       : CXXInstanceCall(CE, St, LCtx) {}
746   CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
747 
748   void cloneTo(void *Dest) const override {
749     new (Dest) CXXMemberOperatorCall(*this);
750   }
751 
752 public:
753   const CXXOperatorCallExpr *getOriginExpr() const override {
754     return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
755   }
756 
757   unsigned getNumArgs() const override {
758     return getOriginExpr()->getNumArgs() - 1;
759   }
760 
761   const Expr *getArgExpr(unsigned Index) const override {
762     return getOriginExpr()->getArg(Index + 1);
763   }
764 
765   const Expr *getCXXThisExpr() const override;
766 
767   Kind getKind() const override { return CE_CXXMemberOperator; }
768   StringRef getKindAsString() const override { return "CXXMemberOperatorCall"; }
769 
770   static bool classof(const CallEvent *CA) {
771     return CA->getKind() == CE_CXXMemberOperator;
772   }
773 
774   Optional<unsigned>
775   getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
776     // For member operator calls argument 0 on the expression corresponds
777     // to implicit this-parameter on the declaration.
778     return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1)
779                                   : None;
780   }
781 
782   unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
783     // For member operator calls argument 0 on the expression corresponds
784     // to implicit this-parameter on the declaration.
785     return CallArgumentIndex + 1;
786   }
787 
788   OverloadedOperatorKind getOverloadedOperator() const {
789     return getOriginExpr()->getOperator();
790   }
791 };
792 
793 /// Represents an implicit call to a C++ destructor.
794 ///
795 /// This can occur at the end of a scope (for automatic objects), at the end
796 /// of a full-expression (for temporaries), or as part of a delete.
797 class CXXDestructorCall : public CXXInstanceCall {
798   friend class CallEventManager;
799 
800 protected:
801   using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
802 
803   /// Creates an implicit destructor.
804   ///
805   /// \param DD The destructor that will be called.
806   /// \param Trigger The statement whose completion causes this destructor call.
807   /// \param Target The object region to be destructed.
808   /// \param St The path-sensitive state at this point in the program.
809   /// \param LCtx The location context at this point in the program.
810   CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
811                     const MemRegion *Target, bool IsBaseDestructor,
812                     ProgramStateRef St, const LocationContext *LCtx)
813       : CXXInstanceCall(DD, St, LCtx) {
814     Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
815     Location = Trigger->getEndLoc();
816   }
817 
818   CXXDestructorCall(const CXXDestructorCall &Other) = default;
819 
820   void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
821 
822 public:
823   SourceRange getSourceRange() const override { return Location; }
824   unsigned getNumArgs() const override { return 0; }
825 
826   RuntimeDefinition getRuntimeDefinition() const override;
827 
828   /// Returns the value of the implicit 'this' object.
829   SVal getCXXThisVal() const override;
830 
831   /// Returns true if this is a call to a base class destructor.
832   bool isBaseDestructor() const {
833     return DtorDataTy::getFromOpaqueValue(Data).getInt();
834   }
835 
836   Kind getKind() const override { return CE_CXXDestructor; }
837   StringRef getKindAsString() const override { return "CXXDestructorCall"; }
838 
839   static bool classof(const CallEvent *CA) {
840     return CA->getKind() == CE_CXXDestructor;
841   }
842 };
843 
844 /// Represents any constructor invocation. This includes regular constructors
845 /// and inherited constructors.
846 class AnyCXXConstructorCall : public AnyFunctionCall {
847 protected:
848   AnyCXXConstructorCall(const Expr *E, const MemRegion *Target,
849                         ProgramStateRef St, const LocationContext *LCtx)
850       : AnyFunctionCall(E, St, LCtx) {
851     assert(E && (isa<CXXConstructExpr>(E) || isa<CXXInheritedCtorInitExpr>(E)));
852     // Target may be null when the region is unknown.
853     Data = Target;
854   }
855 
856   void getExtraInvalidatedValues(ValueList &Values,
857          RegionAndSymbolInvalidationTraits *ETraits) const override;
858 
859   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
860                                     BindingsTy &Bindings) const override;
861 
862 public:
863   /// Returns the value of the implicit 'this' object.
864   SVal getCXXThisVal() const;
865 
866   static bool classof(const CallEvent *Call) {
867     return Call->getKind() >= CE_BEG_CXX_CONSTRUCTOR_CALLS &&
868            Call->getKind() <= CE_END_CXX_CONSTRUCTOR_CALLS;
869   }
870 };
871 
872 /// Represents a call to a C++ constructor.
873 ///
874 /// Example: \c T(1)
875 class CXXConstructorCall : public AnyCXXConstructorCall {
876   friend class CallEventManager;
877 
878 protected:
879   /// Creates a constructor call.
880   ///
881   /// \param CE The constructor expression as written in the source.
882   /// \param Target The region where the object should be constructed. If NULL,
883   ///               a new symbolic region will be used.
884   /// \param St The path-sensitive state at this point in the program.
885   /// \param LCtx The location context at this point in the program.
886   CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
887                      ProgramStateRef St, const LocationContext *LCtx)
888       : AnyCXXConstructorCall(CE, Target, St, LCtx) {}
889 
890   CXXConstructorCall(const CXXConstructorCall &Other) = default;
891 
892   void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
893 
894 public:
895   const CXXConstructExpr *getOriginExpr() const override {
896     return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
897   }
898 
899   const CXXConstructorDecl *getDecl() const override {
900     return getOriginExpr()->getConstructor();
901   }
902 
903   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
904 
905   const Expr *getArgExpr(unsigned Index) const override {
906     return getOriginExpr()->getArg(Index);
907   }
908 
909   Kind getKind() const override { return CE_CXXConstructor; }
910   StringRef getKindAsString() const override { return "CXXConstructorCall"; }
911 
912   static bool classof(const CallEvent *CA) {
913     return CA->getKind() == CE_CXXConstructor;
914   }
915 };
916 
917 /// Represents a call to a C++ inherited constructor.
918 ///
919 /// Example: \c class T : public S { using S::S; }; T(1);
920 ///
921 // Note, it is difficult to model the parameters. This is one of the reasons
922 // why we skip analysis of inheriting constructors as top-level functions.
923 // CXXInheritedCtorInitExpr doesn't take arguments and doesn't model parameter
924 // initialization because there is none: the arguments in the outer
925 // CXXConstructExpr directly initialize the parameters of the base class
926 // constructor, and no copies are made. (Making a copy of the parameter is
927 // incorrect, at least if it's done in an observable way.) The derived class
928 // constructor doesn't even exist in the formal model.
929 /// E.g., in:
930 ///
931 /// struct X { X *p = this; ~X() {} };
932 /// struct A { A(X x) : b(x.p == &x) {} bool b; };
933 /// struct B : A { using A::A; };
934 /// B b = X{};
935 ///
936 /// ... b.b is initialized to true.
937 class CXXInheritedConstructorCall : public AnyCXXConstructorCall {
938   friend class CallEventManager;
939 
940 protected:
941   CXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *CE,
942                               const MemRegion *Target, ProgramStateRef St,
943                               const LocationContext *LCtx)
944       : AnyCXXConstructorCall(CE, Target, St, LCtx) {}
945 
946   CXXInheritedConstructorCall(const CXXInheritedConstructorCall &Other) =
947       default;
948 
949   void cloneTo(void *Dest) const override {
950     new (Dest) CXXInheritedConstructorCall(*this);
951   }
952 
953 public:
954   const CXXInheritedCtorInitExpr *getOriginExpr() const override {
955     return cast<CXXInheritedCtorInitExpr>(AnyFunctionCall::getOriginExpr());
956   }
957 
958   const CXXConstructorDecl *getDecl() const override {
959     return getOriginExpr()->getConstructor();
960   }
961 
962   /// Obtain the stack frame of the inheriting constructor. Argument expressions
963   /// can be found on the call site of that stack frame.
964   const StackFrameContext *getInheritingStackFrame() const;
965 
966   /// Obtain the CXXConstructExpr for the sub-class that inherited the current
967   /// constructor (possibly indirectly). It's the statement that contains
968   /// argument expressions.
969   const CXXConstructExpr *getInheritingConstructor() const {
970     return cast<CXXConstructExpr>(getInheritingStackFrame()->getCallSite());
971   }
972 
973   unsigned getNumArgs() const override {
974     return getInheritingConstructor()->getNumArgs();
975   }
976 
977   const Expr *getArgExpr(unsigned Index) const override {
978     return getInheritingConstructor()->getArg(Index);
979   }
980 
981   SVal getArgSVal(unsigned Index) const override {
982     return getState()->getSVal(
983         getArgExpr(Index),
984         getInheritingStackFrame()->getParent()->getStackFrame());
985   }
986 
987   Kind getKind() const override { return CE_CXXInheritedConstructor; }
988   StringRef getKindAsString() const override {
989     return "CXXInheritedConstructorCall";
990   }
991 
992   static bool classof(const CallEvent *CA) {
993     return CA->getKind() == CE_CXXInheritedConstructor;
994   }
995 };
996 
997 /// Represents the memory allocation call in a C++ new-expression.
998 ///
999 /// This is a call to "operator new".
1000 class CXXAllocatorCall : public AnyFunctionCall {
1001   friend class CallEventManager;
1002 
1003 protected:
1004   CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
1005                    const LocationContext *LCtx)
1006       : AnyFunctionCall(E, St, LCtx) {}
1007   CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
1008 
1009   void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
1010 
1011 public:
1012   const CXXNewExpr *getOriginExpr() const override {
1013     return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
1014   }
1015 
1016   const FunctionDecl *getDecl() const override {
1017     return getOriginExpr()->getOperatorNew();
1018   }
1019 
1020   SVal getObjectUnderConstruction() const {
1021     return ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(),
1022                                                   getLocationContext())
1023         .getValue();
1024   }
1025 
1026   /// Number of non-placement arguments to the call. It is equal to 2 for
1027   /// C++17 aligned operator new() calls that have alignment implicitly
1028   /// passed as the second argument, and to 1 for other operator new() calls.
1029   unsigned getNumImplicitArgs() const {
1030     return getOriginExpr()->passAlignment() ? 2 : 1;
1031   }
1032 
1033   unsigned getNumArgs() const override {
1034     return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
1035   }
1036 
1037   const Expr *getArgExpr(unsigned Index) const override {
1038     // The first argument of an allocator call is the size of the allocation.
1039     if (Index < getNumImplicitArgs())
1040       return nullptr;
1041     return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs());
1042   }
1043 
1044   /// Number of placement arguments to the operator new() call. For example,
1045   /// standard std::nothrow operator new and standard placement new both have
1046   /// 1 implicit argument (size) and 1 placement argument, while regular
1047   /// operator new() has 1 implicit argument and 0 placement arguments.
1048   const Expr *getPlacementArgExpr(unsigned Index) const {
1049     return getOriginExpr()->getPlacementArg(Index);
1050   }
1051 
1052   Kind getKind() const override { return CE_CXXAllocator; }
1053   StringRef getKindAsString() const override { return "CXXAllocatorCall"; }
1054 
1055   static bool classof(const CallEvent *CE) {
1056     return CE->getKind() == CE_CXXAllocator;
1057   }
1058 };
1059 
1060 /// Represents the memory deallocation call in a C++ delete-expression.
1061 ///
1062 /// This is a call to "operator delete".
1063 // FIXME: CXXDeleteExpr isn't present for custom delete operators, or even for
1064 // some those that are in the standard library, like the no-throw or align_val
1065 // versions.
1066 // Some pointers:
1067 // http://lists.llvm.org/pipermail/cfe-dev/2020-April/065080.html
1068 // clang/test/Analysis/cxx-dynamic-memory-analysis-order.cpp
1069 // clang/unittests/StaticAnalyzer/CallEventTest.cpp
1070 class CXXDeallocatorCall : public AnyFunctionCall {
1071   friend class CallEventManager;
1072 
1073 protected:
1074   CXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef St,
1075                      const LocationContext *LCtx)
1076       : AnyFunctionCall(E, St, LCtx) {}
1077   CXXDeallocatorCall(const CXXDeallocatorCall &Other) = default;
1078 
1079   void cloneTo(void *Dest) const override {
1080     new (Dest) CXXDeallocatorCall(*this);
1081   }
1082 
1083 public:
1084   const CXXDeleteExpr *getOriginExpr() const override {
1085     return cast<CXXDeleteExpr>(AnyFunctionCall::getOriginExpr());
1086   }
1087 
1088   const FunctionDecl *getDecl() const override {
1089     return getOriginExpr()->getOperatorDelete();
1090   }
1091 
1092   unsigned getNumArgs() const override { return getDecl()->getNumParams(); }
1093 
1094   const Expr *getArgExpr(unsigned Index) const override {
1095     // CXXDeleteExpr's only have a single argument.
1096     return getOriginExpr()->getArgument();
1097   }
1098 
1099   Kind getKind() const override { return CE_CXXDeallocator; }
1100   StringRef getKindAsString() const override { return "CXXDeallocatorCall"; }
1101 
1102   static bool classof(const CallEvent *CE) {
1103     return CE->getKind() == CE_CXXDeallocator;
1104   }
1105 };
1106 
1107 /// Represents the ways an Objective-C message send can occur.
1108 //
1109 // Note to maintainers: OCM_Message should always be last, since it does not
1110 // need to fit in the Data field's low bits.
1111 enum ObjCMessageKind {
1112   OCM_PropertyAccess,
1113   OCM_Subscript,
1114   OCM_Message
1115 };
1116 
1117 /// Represents any expression that calls an Objective-C method.
1118 ///
1119 /// This includes all of the kinds listed in ObjCMessageKind.
1120 class ObjCMethodCall : public CallEvent {
1121   friend class CallEventManager;
1122 
1123   const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
1124 
1125 protected:
1126   ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
1127                  const LocationContext *LCtx)
1128       : CallEvent(Msg, St, LCtx) {
1129     Data = nullptr;
1130   }
1131 
1132   ObjCMethodCall(const ObjCMethodCall &Other) = default;
1133 
1134   void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
1135 
1136   void getExtraInvalidatedValues(ValueList &Values,
1137          RegionAndSymbolInvalidationTraits *ETraits) const override;
1138 
1139   /// Check if the selector may have multiple definitions (may have overrides).
1140   virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
1141                                         Selector Sel) const;
1142 
1143 public:
1144   const ObjCMessageExpr *getOriginExpr() const override {
1145     return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
1146   }
1147 
1148   const ObjCMethodDecl *getDecl() const override {
1149     return getOriginExpr()->getMethodDecl();
1150   }
1151 
1152   unsigned getNumArgs() const override {
1153     return getOriginExpr()->getNumArgs();
1154   }
1155 
1156   const Expr *getArgExpr(unsigned Index) const override {
1157     return getOriginExpr()->getArg(Index);
1158   }
1159 
1160   bool isInstanceMessage() const {
1161     return getOriginExpr()->isInstanceMessage();
1162   }
1163 
1164   ObjCMethodFamily getMethodFamily() const {
1165     return getOriginExpr()->getMethodFamily();
1166   }
1167 
1168   Selector getSelector() const {
1169     return getOriginExpr()->getSelector();
1170   }
1171 
1172   SourceRange getSourceRange() const override;
1173 
1174   /// Returns the value of the receiver at the time of this call.
1175   SVal getReceiverSVal() const;
1176 
1177   /// Get the interface for the receiver.
1178   ///
1179   /// This works whether this is an instance message or a class message.
1180   /// However, it currently just uses the static type of the receiver.
1181   const ObjCInterfaceDecl *getReceiverInterface() const {
1182     return getOriginExpr()->getReceiverInterface();
1183   }
1184 
1185   /// Checks if the receiver refers to 'self' or 'super'.
1186   bool isReceiverSelfOrSuper() const;
1187 
1188   /// Returns how the message was written in the source (property access,
1189   /// subscript, or explicit message send).
1190   ObjCMessageKind getMessageKind() const;
1191 
1192   /// Returns true if this property access or subscript is a setter (has the
1193   /// form of an assignment).
1194   bool isSetter() const {
1195     switch (getMessageKind()) {
1196     case OCM_Message:
1197       llvm_unreachable("This is not a pseudo-object access!");
1198     case OCM_PropertyAccess:
1199       return getNumArgs() > 0;
1200     case OCM_Subscript:
1201       return getNumArgs() > 1;
1202     }
1203     llvm_unreachable("Unknown message kind");
1204   }
1205 
1206   // Returns the property accessed by this method, either explicitly via
1207   // property syntax or implicitly via a getter or setter method. Returns
1208   // nullptr if the call is not a prooperty access.
1209   const ObjCPropertyDecl *getAccessedProperty() const;
1210 
1211   RuntimeDefinition getRuntimeDefinition() const override;
1212 
1213   bool argumentsMayEscape() const override;
1214 
1215   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1216                                     BindingsTy &Bindings) const override;
1217 
1218   ArrayRef<ParmVarDecl*> parameters() const override;
1219 
1220   Kind getKind() const override { return CE_ObjCMessage; }
1221   StringRef getKindAsString() const override { return "ObjCMethodCall"; }
1222 
1223   static bool classof(const CallEvent *CA) {
1224     return CA->getKind() == CE_ObjCMessage;
1225   }
1226 };
1227 
1228 enum CallDescriptionFlags : int {
1229   /// Describes a C standard function that is sometimes implemented as a macro
1230   /// that expands to a compiler builtin with some __builtin prefix.
1231   /// The builtin may as well have a few extra arguments on top of the requested
1232   /// number of arguments.
1233   CDF_MaybeBuiltin = 1 << 0,
1234 };
1235 
1236 /// This class represents a description of a function call using the number of
1237 /// arguments and the name of the function.
1238 class CallDescription {
1239   friend CallEvent;
1240 
1241   mutable IdentifierInfo *II = nullptr;
1242   mutable bool IsLookupDone = false;
1243   // The list of the qualified names used to identify the specified CallEvent,
1244   // e.g. "{a, b}" represent the qualified names, like "a::b".
1245   std::vector<const char *> QualifiedName;
1246   Optional<unsigned> RequiredArgs;
1247   Optional<size_t> RequiredParams;
1248   int Flags;
1249 
1250   // A constructor helper.
1251   static Optional<size_t> readRequiredParams(Optional<unsigned> RequiredArgs,
1252                                              Optional<size_t> RequiredParams) {
1253     if (RequiredParams)
1254       return RequiredParams;
1255     if (RequiredArgs)
1256       return static_cast<size_t>(*RequiredArgs);
1257     return None;
1258   }
1259 
1260 public:
1261   /// Constructs a CallDescription object.
1262   ///
1263   /// @param QualifiedName The list of the name qualifiers of the function that
1264   /// will be matched. The user is allowed to skip any of the qualifiers.
1265   /// For example, {"std", "basic_string", "c_str"} would match both
1266   /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
1267   ///
1268   /// @param RequiredArgs The number of arguments that is expected to match a
1269   /// call. Omit this parameter to match every occurrence of call with a given
1270   /// name regardless the number of arguments.
1271   CallDescription(int Flags, ArrayRef<const char *> QualifiedName,
1272                   Optional<unsigned> RequiredArgs = None,
1273                   Optional<size_t> RequiredParams = None)
1274       : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
1275         RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
1276         Flags(Flags) {}
1277 
1278   /// Construct a CallDescription with default flags.
1279   CallDescription(ArrayRef<const char *> QualifiedName,
1280                   Optional<unsigned> RequiredArgs = None,
1281                   Optional<size_t> RequiredParams = None)
1282       : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
1283 
1284   /// Get the name of the function that this object matches.
1285   StringRef getFunctionName() const { return QualifiedName.back(); }
1286 };
1287 
1288 /// An immutable map from CallDescriptions to arbitrary data. Provides a unified
1289 /// way for checkers to react on function calls.
1290 template <typename T> class CallDescriptionMap {
1291   // Some call descriptions aren't easily hashable (eg., the ones with qualified
1292   // names in which some sections are omitted), so let's put them
1293   // in a simple vector and use linear lookup.
1294   // TODO: Implement an actual map for fast lookup for "hashable" call
1295   // descriptions (eg., the ones for C functions that just match the name).
1296   std::vector<std::pair<CallDescription, T>> LinearMap;
1297 
1298 public:
1299   CallDescriptionMap(
1300       std::initializer_list<std::pair<CallDescription, T>> &&List)
1301       : LinearMap(List) {}
1302 
1303   ~CallDescriptionMap() = default;
1304 
1305   // These maps are usually stored once per checker, so let's make sure
1306   // we don't do redundant copies.
1307   CallDescriptionMap(const CallDescriptionMap &) = delete;
1308   CallDescriptionMap &operator=(const CallDescription &) = delete;
1309 
1310   const T *lookup(const CallEvent &Call) const {
1311     // Slow path: linear lookup.
1312     // TODO: Implement some sort of fast path.
1313     for (const std::pair<CallDescription, T> &I : LinearMap)
1314       if (Call.isCalled(I.first))
1315         return &I.second;
1316 
1317     return nullptr;
1318   }
1319 };
1320 
1321 /// Manages the lifetime of CallEvent objects.
1322 ///
1323 /// CallEventManager provides a way to create arbitrary CallEvents "on the
1324 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
1325 /// memory blocks. The CallEvents created by CallEventManager are only valid
1326 /// for the lifetime of the OwnedCallEvent that holds them; right now these
1327 /// objects cannot be copied and ownership cannot be transferred.
1328 class CallEventManager {
1329   friend class CallEvent;
1330 
1331   llvm::BumpPtrAllocator &Alloc;
1332   SmallVector<void *, 8> Cache;
1333 
1334   using CallEventTemplateTy = SimpleFunctionCall;
1335 
1336   void reclaim(const void *Memory) {
1337     Cache.push_back(const_cast<void *>(Memory));
1338   }
1339 
1340   /// Returns memory that can be initialized as a CallEvent.
1341   void *allocate() {
1342     if (Cache.empty())
1343       return Alloc.Allocate<CallEventTemplateTy>();
1344     else
1345       return Cache.pop_back_val();
1346   }
1347 
1348   template <typename T, typename Arg>
1349   T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1350     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1351                   "CallEvent subclasses are not all the same size");
1352     return new (allocate()) T(A, St, LCtx);
1353   }
1354 
1355   template <typename T, typename Arg1, typename Arg2>
1356   T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1357     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1358                   "CallEvent subclasses are not all the same size");
1359     return new (allocate()) T(A1, A2, St, LCtx);
1360   }
1361 
1362   template <typename T, typename Arg1, typename Arg2, typename Arg3>
1363   T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1364             const LocationContext *LCtx) {
1365     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1366                   "CallEvent subclasses are not all the same size");
1367     return new (allocate()) T(A1, A2, A3, St, LCtx);
1368   }
1369 
1370   template <typename T, typename Arg1, typename Arg2, typename Arg3,
1371             typename Arg4>
1372   T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1373             const LocationContext *LCtx) {
1374     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1375                   "CallEvent subclasses are not all the same size");
1376     return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1377   }
1378 
1379 public:
1380   CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1381 
1382   /// Gets an outside caller given a callee context.
1383   CallEventRef<>
1384   getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1385 
1386   /// Gets a call event for a function call, Objective-C method call,
1387   /// or a 'new' call.
1388   CallEventRef<>
1389   getCall(const Stmt *S, ProgramStateRef State,
1390           const LocationContext *LC);
1391 
1392   CallEventRef<>
1393   getSimpleCall(const CallExpr *E, ProgramStateRef State,
1394                 const LocationContext *LCtx);
1395 
1396   CallEventRef<ObjCMethodCall>
1397   getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1398                     const LocationContext *LCtx) {
1399     return create<ObjCMethodCall>(E, State, LCtx);
1400   }
1401 
1402   CallEventRef<CXXConstructorCall>
1403   getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1404                         ProgramStateRef State, const LocationContext *LCtx) {
1405     return create<CXXConstructorCall>(E, Target, State, LCtx);
1406   }
1407 
1408   CallEventRef<CXXInheritedConstructorCall>
1409   getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E,
1410                                  const MemRegion *Target, ProgramStateRef State,
1411                                  const LocationContext *LCtx) {
1412     return create<CXXInheritedConstructorCall>(E, Target, State, LCtx);
1413   }
1414 
1415   CallEventRef<CXXDestructorCall>
1416   getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1417                        const MemRegion *Target, bool IsBase,
1418                        ProgramStateRef State, const LocationContext *LCtx) {
1419     return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1420   }
1421 
1422   CallEventRef<CXXAllocatorCall>
1423   getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1424                       const LocationContext *LCtx) {
1425     return create<CXXAllocatorCall>(E, State, LCtx);
1426   }
1427 
1428   CallEventRef<CXXDeallocatorCall>
1429   getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State,
1430                         const LocationContext *LCtx) {
1431     return create<CXXDeallocatorCall>(E, State, LCtx);
1432   }
1433 };
1434 
1435 template <typename T>
1436 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1437   assert(isa<T>(*this) && "Cloning to unrelated type");
1438   static_assert(sizeof(T) == sizeof(CallEvent),
1439                 "Subclasses may not add fields");
1440 
1441   if (NewState == State)
1442     return cast<T>(this);
1443 
1444   CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1445   T *Copy = static_cast<T *>(Mgr.allocate());
1446   cloneTo(Copy);
1447   assert(Copy->getKind() == this->getKind() && "Bad copy");
1448 
1449   Copy->State = NewState;
1450   return Copy;
1451 }
1452 
1453 inline void CallEvent::Release() const {
1454   assert(RefCount > 0 && "Reference count is already zero.");
1455   --RefCount;
1456 
1457   if (RefCount > 0)
1458     return;
1459 
1460   CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1461   Mgr.reclaim(this);
1462 
1463   this->~CallEvent();
1464 }
1465 
1466 } // namespace ento
1467 
1468 } // namespace clang
1469 
1470 namespace llvm {
1471 
1472 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1473 template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1474   using SimpleType = const T *;
1475 
1476   static SimpleType
1477   getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1478     return Val.get();
1479   }
1480 };
1481 
1482 } // namespace llvm
1483 
1484 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
1485