Coverage Report

Created: 2018-11-16 02:38

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
Line
Count
Source (jump to first uncovered line)
1
//===- CallEvent.h - Wrapper for all function and method calls --*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
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).
13
//
14
//===----------------------------------------------------------------------===//
15
16
#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
17
#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
18
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"
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_CXXAllocator,
68
  CE_BEG_FUNCTION_CALLS = CE_Function,
69
  CE_END_FUNCTION_CALLS = CE_CXXAllocator,
70
  CE_Block,
71
  CE_ObjCMessage
72
};
73
74
class CallEvent;
75
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 {
79
  friend CallEvent;
80
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;
87
88
public:
89
  const static unsigned NoArgRequirement = std::numeric_limits<unsigned>::max();
90
91
  /// Constructs a CallDescription object.
92
  ///
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().
97
  ///
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
948k
      : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
104
105
  /// Get the name of the function that this object matches.
106
426
  StringRef getFunctionName() const { return QualifiedName.back(); }
107
};
108
109
template<typename T = CallEvent>
110
class CallEventRef : public IntrusiveRefCntPtr<const T> {
111
public:
112
649k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::ObjCMethodCall>::CallEventRef(clang::ento::ObjCMethodCall const*)
Line
Count
Source
112
24.1k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CallEvent>::CallEventRef(clang::ento::CallEvent const*)
Line
Count
Source
112
595k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CXXConstructorCall>::CallEventRef(clang::ento::CXXConstructorCall const*)
Line
Count
Source
112
24.1k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CXXAllocatorCall>::CallEventRef(clang::ento::CXXAllocatorCall const*)
Line
Count
Source
112
2.63k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CXXDestructorCall>::CallEventRef(clang::ento::CXXDestructorCall const*)
Line
Count
Source
112
2.63k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
113
46.8k
  CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
114
115
29.5k
  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
116
29.5k
    return this->get()->template cloneWithState<T>(State);
117
29.5k
  }
clang::ento::CallEventRef<clang::ento::CallEvent>::cloneWithState(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
115
26.0k
  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
116
26.0k
    return this->get()->template cloneWithState<T>(State);
117
26.0k
  }
clang::ento::CallEventRef<clang::ento::ObjCMethodCall>::cloneWithState(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
115
3.50k
  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
116
3.50k
    return this->get()->template cloneWithState<T>(State);
117
3.50k
  }
118
119
  // Allow implicit conversions to a superclass type, since CallEventRef
120
  // behaves like a pointer-to-const.
121
  template <typename SuperT>
122
11.8k
  operator CallEventRef<SuperT> () const {
123
11.8k
    return this->get();
124
11.8k
  }
clang::ento::CallEventRef<clang::ento::CXXConstructorCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
122
8.72k
  operator CallEventRef<SuperT> () const {
123
8.72k
    return this->get();
124
8.72k
  }
clang::ento::CallEventRef<clang::ento::CXXAllocatorCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
122
672
  operator CallEventRef<SuperT> () const {
123
672
    return this->get();
124
672
  }
clang::ento::CallEventRef<clang::ento::ObjCMethodCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
122
1.13k
  operator CallEventRef<SuperT> () const {
123
1.13k
    return this->get();
124
1.13k
  }
clang::ento::CallEventRef<clang::ento::CXXDestructorCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
122
1.36k
  operator CallEventRef<SuperT> () const {
123
1.36k
    return this->get();
124
1.36k
  }
125
};
126
127
/// \class RuntimeDefinition
128
/// Defines the runtime definition of the called function.
129
///
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
133
/// precise.
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;
138
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
142
  /// precise.
143
  const MemRegion *R = nullptr;
144
145
public:
146
29.5k
  RuntimeDefinition() = default;
147
22.7k
  RuntimeDefinition(const Decl *InD): D(InD) {}
148
2.41k
  RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
149
150
56.0k
  const Decl *getDecl() { return D; }
151
152
  /// Check if the definition we have is precise.
153
  /// If not, it is possible that the call dispatches to another definition at
154
  /// execution time.
155
20.6k
  bool mayHaveOtherDefinitions() { return R != nullptr; }
156
157
  /// When other definitions are possible, returns the region whose runtime type
158
  /// determines the method definition.
159
15
  const MemRegion *getDispatchRegion() { return R; }
160
};
161
162
/// Represents an abstract call to a function or method along a
163
/// particular path.
164
///
165
/// CallEvents are created through the factory methods of CallEventManager.
166
///
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.
171
class CallEvent {
172
public:
173
  using Kind = CallEventKind;
174
175
private:
176
  ProgramStateRef State;
177
  const LocationContext *LCtx;
178
  llvm::PointerUnion<const Expr *, const Decl *> Origin;
179
180
protected:
181
  // This is user data for subclasses.
182
  const void *Data;
183
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;
188
189
private:
190
  template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
191
192
  mutable unsigned RefCount = 0;
193
194
696k
  void Retain() const { ++RefCount; }
195
  void Release() const;
196
197
protected:
198
  friend class CallEventManager;
199
200
  CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
201
130k
      : State(std::move(state)), LCtx(lctx), Origin(E) {}
202
203
  CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
204
2.63k
      : State(std::move(state)), LCtx(lctx), Origin(D) {}
205
206
  // DO NOT MAKE PUBLIC
207
  CallEvent(const CallEvent &Original)
208
      : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
209
130k
        Data(Original.Data), Location(Original.Location) {}
210
211
  /// Copies this CallEvent, with vtable intact, into a new block of memory.
212
  virtual void cloneTo(void *Dest) const = 0;
213
214
  /// Get the value of arbitrary expressions at this point in the path.
215
227k
  SVal getSVal(const Stmt *S) const {
216
227k
    return getState()->getSVal(S, getLocationContext());
217
227k
  }
218
219
  using ValueList = SmallVectorImpl<SVal>;
220
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
18.0k
                 RegionAndSymbolInvalidationTraits *ETraits) const {}
225
226
public:
227
  CallEvent &operator=(const CallEvent &) = delete;
228
263k
  virtual ~CallEvent() = default;
229
230
  /// Returns the kind of call this is.
231
  virtual Kind getKind() const = 0;
232
233
  /// Returns the declaration of the function or method that will be
234
  /// called. May be null.
235
29.3k
  virtual const Decl *getDecl() const {
236
29.3k
    return Origin.dyn_cast<const Decl *>();
237
29.3k
  }
238
239
  /// The state in which the call is being evaluated.
240
379k
  const ProgramStateRef &getState() const {
241
379k
    return State;
242
379k
  }
243
244
  /// The context in which the call is being evaluated.
245
864k
  const LocationContext *getLocationContext() const {
246
864k
    return LCtx;
247
864k
  }
248
249
  /// Returns the definition of the function or method that will be
250
  /// called.
251
  virtual RuntimeDefinition getRuntimeDefinition() const = 0;
252
253
  /// Returns the expression whose value will be the result of this call.
254
  /// May be null.
255
2.60M
  const Expr *getOriginExpr() const {
256
2.60M
    return Origin.dyn_cast<const Expr *>();
257
2.60M
  }
258
259
  /// Returns the number of arguments (explicit and implicit).
260
  ///
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
263
  /// the source.
264
  virtual unsigned getNumArgs() const = 0;
265
266
  /// Returns true if the callee is known to be from a system header.
267
28.3k
  bool isInSystemHeader() const {
268
28.3k
    const Decl *D = getDecl();
269
28.3k
    if (!D)
270
69
      return false;
271
28.2k
272
28.2k
    SourceLocation Loc = D->getLocation();
273
28.2k
    if (Loc.isValid()) {
274
27.5k
      const SourceManager &SM =
275
27.5k
        getState()->getStateManager().getContext().getSourceManager();
276
27.5k
      return SM.isInSystemHeader(D->getLocation());
277
27.5k
    }
278
667
279
667
    // Special case for implicitly-declared global operator new/delete.
280
667
    // These should be considered system functions.
281
667
    if (const auto *FD = dyn_cast<FunctionDecl>(D))
282
667
      return FD->isOverloadedOperator() && 
FD->isImplicit()666
&&
FD->isGlobal()666
;
283
0
284
0
    return false;
285
0
  }
286
287
  /// Returns true if the CallEvent is a call to a function that matches
288
  /// the CallDescription.
289
  ///
290
  /// Note that this function is not intended to be used to match Obj-C method
291
  /// calls.
292
  bool isCalled(const CallDescription &CD) const;
293
294
  /// Returns a source range for the entire call, suitable for
295
  /// outputting in diagnostics.
296
68
  virtual SourceRange getSourceRange() const {
297
68
    return getOriginExpr()->getSourceRange();
298
68
  }
299
300
  /// Returns the value of a given argument at the time of the call.
301
  virtual SVal getArgSVal(unsigned Index) const;
302
303
  /// Returns the expression associated with a given argument.
304
  /// May be null if this expression does not appear in the source.
305
0
  virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
306
307
  /// Returns the source range for errors associated with this argument.
308
  ///
309
  /// May be invalid if the argument is not written in the source.
310
  virtual SourceRange getArgSourceRange(unsigned Index) const;
311
312
  /// Returns the result type, adjusted for references.
313
  QualType getResultType() const;
314
315
  /// Returns the return value of the call.
316
  ///
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;
320
321
  /// Returns true if the type of any of the non-null arguments satisfies
322
  /// the condition.
323
  bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
324
325
  /// Returns true if any of the arguments appear to represent callbacks.
326
  bool hasNonZeroCallbackArg() const;
327
328
  /// Returns true if any of the arguments is void*.
329
  bool hasVoidPointerToNonConstArg() const;
330
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
24.1k
  virtual bool argumentsMayEscape() const {
337
24.1k
    return hasNonZeroCallbackArg();
338
24.1k
  }
339
340
  /// Returns true if the callee is an externally-visible function in the
341
  /// top-level namespace, such as \c malloc.
342
  ///
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.
345
  ///
346
  /// If a name is provided, the function must additionally match the given
347
  /// name.
348
  ///
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;
357
358
  /// Returns the name of the callee, if its name is a simple identifier.
359
  ///
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
48.8k
  const IdentifierInfo *getCalleeIdentifier() const {
366
48.8k
    const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
367
48.8k
    if (!ND)
368
1
      return nullptr;
369
48.8k
    return ND->getIdentifier();
370
48.8k
  }
371
372
  /// Returns an appropriate ProgramPoint for this call.
373
  ProgramPoint getProgramPoint(bool IsPreVisit = false,
374
                               const ProgramPointTag *Tag = nullptr) const;
375
376
  /// Returns a new state with all argument regions invalidated.
377
  ///
378
  /// This accepts an alternate state in case some processing has already
379
  /// occurred.
380
  ProgramStateRef invalidateRegions(unsigned BlockCount,
381
                                    ProgramStateRef Orig = nullptr) const;
382
383
  using FrameBindingTy = std::pair<Loc, SVal>;
384
  using BindingsTy = SmallVectorImpl<FrameBindingTy>;
385
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;
390
391
  /// Returns a copy of this CallEvent, but using the given state.
392
  template <typename T>
393
  CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
394
395
  /// Returns a copy of this CallEvent, but using the given state.
396
459k
  CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
397
459k
    return cloneWithState<CallEvent>(NewState);
398
459k
  }
399
400
  /// Returns true if this is a statement is a function or method call
401
  /// of some kind.
402
  static bool isCallStmt(const Stmt *S);
403
404
  /// Returns the result type of a function or method declaration.
405
  ///
406
  /// This will return a null QualType if the result type cannot be determined.
407
  static QualType getDeclaredResultType(const Decl *D);
408
409
  /// Returns true if the given decl is known to be variadic.
410
  ///
411
  /// \p D must not be null.
412
  static bool isVariadic(const Decl *D);
413
414
  /// Returns AnalysisDeclContext for the callee stack frame.
415
  /// Currently may fail; returns null on failure.
416
  AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
417
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;
423
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;
427
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
32.0k
  bool isArgumentConstructedDirectly(unsigned Index) const {
435
32.0k
    // This assumes that the object was not yet removed from the state.
436
32.0k
    return ExprEngine::getObjectUnderConstruction(
437
32.0k
        getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue();
438
32.0k
  }
439
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
663
  getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
446
663
    return ASTArgumentIndex;
447
663
  }
448
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
57.2k
  virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
453
57.2k
    return CallArgumentIndex;
454
57.2k
  }
455
456
  // Iterator access to formal parameters and their types.
457
private:
458
  struct GetTypeFn {
459
60.8k
    QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
460
  };
461
462
public:
463
  /// Return call's formal parameters.
464
  ///
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;
469
470
  using param_type_iterator =
471
      llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
472
473
  /// Returns an iterator over the types of the call's formal parameters.
474
  ///
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
71.6k
  param_type_iterator param_type_begin() const {
479
71.6k
    return llvm::map_iterator(parameters().begin(), GetTypeFn());
480
71.6k
  }
481
  /// \sa param_type_begin()
482
71.6k
  param_type_iterator param_type_end() const {
483
71.6k
    return llvm::map_iterator(parameters().end(), GetTypeFn());
484
71.6k
  }
485
486
  // For debugging purposes only
487
  void dump(raw_ostream &Out) const;
488
  void dump() const;
489
};
490
491
/// Represents a call to any sort of function that might have a
492
/// FunctionDecl.
493
class AnyFunctionCall : public CallEvent {
494
protected:
495
  AnyFunctionCall(const Expr *E, ProgramStateRef St,
496
                  const LocationContext *LCtx)
497
124k
      : CallEvent(E, St, LCtx) {}
498
  AnyFunctionCall(const Decl *D, ProgramStateRef St,
499
                  const LocationContext *LCtx)
500
2.63k
      : CallEvent(D, St, LCtx) {}
501
103k
  AnyFunctionCall(const AnyFunctionCall &Other) = default;
502
503
public:
504
  // This function is overridden by subclasses, but they must return
505
  // a FunctionDecl.
506
29.3k
  const FunctionDecl *getDecl() const override {
507
29.3k
    return cast<FunctionDecl>(CallEvent::getDecl());
508
29.3k
  }
509
510
  RuntimeDefinition getRuntimeDefinition() const override;
511
512
  bool argumentsMayEscape() const override;
513
514
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
515
                                    BindingsTy &Bindings) const override;
516
517
  ArrayRef<ParmVarDecl *> parameters() const override;
518
519
45.3k
  static bool classof(const CallEvent *CA) {
520
45.3k
    return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
521
45.3k
           CA->getKind() <= CE_END_FUNCTION_CALLS;
522
45.3k
  }
523
};
524
525
/// Represents a C function or static C++ member function call.
526
///
527
/// Example: \c fun()
528
class SimpleFunctionCall : public AnyFunctionCall {
529
  friend class CallEventManager;
530
531
protected:
532
  SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
533
                     const LocationContext *LCtx)
534
84.4k
      : AnyFunctionCall(CE, St, LCtx) {}
535
57.3k
  SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
536
537
57.3k
  void cloneTo(void *Dest) const override {
538
57.3k
    new (Dest) SimpleFunctionCall(*this);
539
57.3k
  }
540
541
public:
542
1.00M
  virtual const CallExpr *getOriginExpr() const {
543
1.00M
    return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
544
1.00M
  }
545
546
  const FunctionDecl *getDecl() const override;
547
548
257k
  unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
549
550
176k
  const Expr *getArgExpr(unsigned Index) const override {
551
176k
    return getOriginExpr()->getArg(Index);
552
176k
  }
553
554
446k
  Kind getKind() const override { return CE_Function; }
555
556
1.34k
  static bool classof(const CallEvent *CA) {
557
1.34k
    return CA->getKind() == CE_Function;
558
1.34k
  }
559
};
560
561
/// Represents a call to a block.
562
///
563
/// Example: <tt>^{ /* ... */ }()</tt>
564
class BlockCall : public CallEvent {
565
  friend class CallEventManager;
566
567
protected:
568
  BlockCall(const CallExpr *CE, ProgramStateRef St,
569
            const LocationContext *LCtx)
570
539
      : CallEvent(CE, St, LCtx) {}
571
223
  BlockCall(const BlockCall &Other) = default;
572
573
223
  void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
574
575
  void getExtraInvalidatedValues(ValueList &Values,
576
         RegionAndSymbolInvalidationTraits *ETraits) const override;
577
578
public:
579
3.52k
  virtual const CallExpr *getOriginExpr() const {
580
3.52k
    return cast<CallExpr>(CallEvent::getOriginExpr());
581
3.52k
  }
582
583
1.06k
  unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
584
585
262
  const Expr *getArgExpr(unsigned Index) const override {
586
262
    return getOriginExpr()->getArg(Index);
587
262
  }
588
589
  /// Returns the region associated with this instance of the block.
590
  ///
591
  /// This may be NULL if the block's origin is unknown.
592
  const BlockDataRegion *getBlockRegion() const;
593
594
2.00k
  const BlockDecl *getDecl() const override {
595
2.00k
    const BlockDataRegion *BR = getBlockRegion();
596
2.00k
    if (!BR)
597
78
      return nullptr;
598
1.92k
    return BR->getDecl();
599
1.92k
  }
600
601
518
  bool isConversionFromLambda() const {
602
518
    const BlockDecl *BD = getDecl();
603
518
    if (!BD)
604
9
      return false;
605
509
606
509
    return BD->isConversionFromLambda();
607
509
  }
608
609
  /// For a block converted from a C++ lambda, returns the block
610
  /// VarRegion for the variable holding the captured C++ lambda record.
611
14
  const VarRegion *getRegionStoringCapturedLambda() const {
612
14
    assert(isConversionFromLambda());
613
14
    const BlockDataRegion *BR = getBlockRegion();
614
14
    assert(BR && "Block converted from lambda must have a block region");
615
14
616
14
    auto I = BR->referenced_vars_begin();
617
14
    assert(I != BR->referenced_vars_end());
618
14
619
14
    return I.getCapturedRegion();
620
14
  }
621
622
186
  RuntimeDefinition getRuntimeDefinition() const override {
623
186
    if (!isConversionFromLambda())
624
179
      return RuntimeDefinition(getDecl());
625
7
626
7
    // Clang converts lambdas to blocks with an implicit user-defined
627
7
    // conversion operator method on the lambda record that looks (roughly)
628
7
    // like:
629
7
    //
630
7
    // typedef R(^block_type)(P1, P2, ...);
631
7
    // operator block_type() const {
632
7
    //   auto Lambda = *this;
633
7
    //   return ^(P1 p1, P2 p2, ...){
634
7
    //     /* return Lambda(p1, p2, ...); */
635
7
    //   };
636
7
    // }
637
7
    //
638
7
    // Here R is the return type of the lambda and P1, P2, ... are
639
7
    // its parameter types. 'Lambda' is a fake VarDecl captured by the block
640
7
    // that is initialized to a copy of the lambda.
641
7
    //
642
7
    // Sema leaves the body of a lambda-converted block empty (it is
643
7
    // produced by CodeGen), so we can't analyze it directly. Instead, we skip
644
7
    // the block body and analyze the operator() method on the captured lambda.
645
7
    const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
646
7
    const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
647
7
    CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
648
7
649
7
    return RuntimeDefinition(LambdaCallOperator);
650
7
  }
651
652
17
  bool argumentsMayEscape() const override {
653
17
    return true;
654
17
  }
655
656
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
657
                                    BindingsTy &Bindings) const override;
658
659
  ArrayRef<ParmVarDecl*> parameters() const override;
660
661
2.29k
  Kind getKind() const override { return CE_Block; }
662
663
0
  static bool classof(const CallEvent *CA) {
664
0
    return CA->getKind() == CE_Block;
665
0
  }
666
};
667
668
/// Represents a non-static C++ member function call, no matter how
669
/// it is written.
670
class CXXInstanceCall : public AnyFunctionCall {
671
protected:
672
  CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
673
                  const LocationContext *LCtx)
674
13.3k
      : AnyFunctionCall(CE, St, LCtx) {}
675
  CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
676
                  const LocationContext *LCtx)
677
2.63k
      : AnyFunctionCall(D, St, LCtx) {}
678
10.1k
  CXXInstanceCall(const CXXInstanceCall &Other) = default;
679
680
  void getExtraInvalidatedValues(ValueList &Values,
681
         RegionAndSymbolInvalidationTraits *ETraits) const override;
682
683
public:
684
  /// Returns the expression representing the implicit 'this' object.
685
59
  virtual const Expr *getCXXThisExpr() const { return nullptr; }
686
687
  /// Returns the value of the implicit 'this' object.
688
  virtual SVal getCXXThisVal() const;
689
690
  const FunctionDecl *getDecl() const override;
691
692
  RuntimeDefinition getRuntimeDefinition() const override;
693
694
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
695
                                    BindingsTy &Bindings) const override;
696
697
150k
  static bool classof(const CallEvent *CA) {
698
150k
    return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
699
150k
           
CA->getKind() <= CE_END_CXX_INSTANCE_CALLS63.1k
;
700
150k
  }
701
};
702
703
/// Represents a non-static C++ member function call.
704
///
705
/// Example: \c obj.fun()
706
class CXXMemberCall : public CXXInstanceCall {
707
  friend class CallEventManager;
708
709
protected:
710
  CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
711
                const LocationContext *LCtx)
712
10.3k
      : CXXInstanceCall(CE, St, LCtx) {}
713
5.72k
  CXXMemberCall(const CXXMemberCall &Other) = default;
714
715
5.72k
  void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
716
717
public:
718
52.7k
  virtual const CXXMemberCallExpr *getOriginExpr() const {
719
52.7k
    return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
720
52.7k
  }
721
722
25.0k
  unsigned getNumArgs() const override {
723
25.0k
    if (const CallExpr *CE = getOriginExpr())
724
25.0k
      return CE->getNumArgs();
725
0
    return 0;
726
0
  }
727
728
9.60k
  const Expr *getArgExpr(unsigned Index) const override {
729
9.60k
    return getOriginExpr()->getArg(Index);
730
9.60k
  }
731
732
  const Expr *getCXXThisExpr() const override;
733
734
  RuntimeDefinition getRuntimeDefinition() const override;
735
736
66.4k
  Kind getKind() const override { return CE_CXXMember; }
737
738
1.39k
  static bool classof(const CallEvent *CA) {
739
1.39k
    return CA->getKind() == CE_CXXMember;
740
1.39k
  }
741
};
742
743
/// Represents a C++ overloaded operator call where the operator is
744
/// implemented as a non-static member function.
745
///
746
/// Example: <tt>iter + 1</tt>
747
class CXXMemberOperatorCall : public CXXInstanceCall {
748
  friend class CallEventManager;
749
750
protected:
751
  CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
752
                        const LocationContext *LCtx)
753
3.00k
      : CXXInstanceCall(CE, St, LCtx) {}
754
2.58k
  CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
755
756
2.58k
  void cloneTo(void *Dest) const override {
757
2.58k
    new (Dest) CXXMemberOperatorCall(*this);
758
2.58k
  }
759
760
public:
761
17.0k
  virtual const CXXOperatorCallExpr *getOriginExpr() const {
762
17.0k
    return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
763
17.0k
  }
764
765
7.40k
  unsigned getNumArgs() const override {
766
7.40k
    return getOriginExpr()->getNumArgs() - 1;
767
7.40k
  }
768
769
3.87k
  const Expr *getArgExpr(unsigned Index) const override {
770
3.87k
    return getOriginExpr()->getArg(Index + 1);
771
3.87k
  }
772
773
  const Expr *getCXXThisExpr() const override;
774
775
24.9k
  Kind getKind() const override { return CE_CXXMemberOperator; }
776
777
1.25k
  static bool classof(const CallEvent *CA) {
778
1.25k
    return CA->getKind() == CE_CXXMemberOperator;
779
1.25k
  }
780
781
  Optional<unsigned>
782
4
  getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
783
4
    // For member operator calls argument 0 on the expression corresponds
784
4
    // to implicit this-parameter on the declaration.
785
4
    return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1)
786
4
                                  : 
None0
;
787
4
  }
788
789
709
  unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
790
709
    // For member operator calls argument 0 on the expression corresponds
791
709
    // to implicit this-parameter on the declaration.
792
709
    return CallArgumentIndex + 1;
793
709
  }
794
};
795
796
/// Represents an implicit call to a C++ destructor.
797
///
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;
802
803
protected:
804
  using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
805
806
  /// Creates an implicit destructor.
807
  ///
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
2.63k
      : CXXInstanceCall(DD, St, LCtx) {
817
2.63k
    Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
818
2.63k
    Location = Trigger->getEndLoc();
819
2.63k
  }
820
821
1.85k
  CXXDestructorCall(const CXXDestructorCall &Other) = default;
822
823
1.85k
  void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
824
825
public:
826
10.2k
  SourceRange getSourceRange() const override { return Location; }
827
7.25k
  unsigned getNumArgs() const override { return 0; }
828
829
  RuntimeDefinition getRuntimeDefinition() const override;
830
831
  /// Returns the value of the implicit 'this' object.
832
  SVal getCXXThisVal() const override;
833
834
  /// Returns true if this is a call to a base class destructor.
835
2.45k
  bool isBaseDestructor() const {
836
2.45k
    return DtorDataTy::getFromOpaqueValue(Data).getInt();
837
2.45k
  }
838
839
16.3k
  Kind getKind() const override { return CE_CXXDestructor; }
840
841
69.4k
  static bool classof(const CallEvent *CA) {
842
69.4k
    return CA->getKind() == CE_CXXDestructor;
843
69.4k
  }
844
};
845
846
/// Represents a call to a C++ constructor.
847
///
848
/// Example: \c T(1)
849
class CXXConstructorCall : public AnyFunctionCall {
850
  friend class CallEventManager;
851
852
protected:
853
  /// Creates a constructor call.
854
  ///
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
24.1k
      : AnyFunctionCall(CE, St, LCtx) {
863
24.1k
    Data = Target;
864
24.1k
  }
865
866
34.7k
  CXXConstructorCall(const CXXConstructorCall &Other) = default;
867
868
34.7k
  void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
869
870
  void getExtraInvalidatedValues(ValueList &Values,
871
         RegionAndSymbolInvalidationTraits *ETraits) const override;
872
873
public:
874
345k
  virtual const CXXConstructExpr *getOriginExpr() const {
875
345k
    return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
876
345k
  }
877
878
143k
  const CXXConstructorDecl *getDecl() const override {
879
143k
    return getOriginExpr()->getConstructor();
880
143k
  }
881
882
85.8k
  unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
883
884
82.7k
  const Expr *getArgExpr(unsigned Index) const override {
885
82.7k
    return getOriginExpr()->getArg(Index);
886
82.7k
  }
887
888
  /// Returns the value of the implicit 'this' object.
889
  SVal getCXXThisVal() const;
890
891
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
892
                                    BindingsTy &Bindings) const override;
893
894
208k
  Kind getKind() const override { return CE_CXXConstructor; }
895
896
164k
  static bool classof(const CallEvent *CA) {
897
164k
    return CA->getKind() == CE_CXXConstructor;
898
164k
  }
899
};
900
901
/// Represents the memory allocation call in a C++ new-expression.
902
///
903
/// This is a call to "operator new".
904
class CXXAllocatorCall : public AnyFunctionCall {
905
  friend class CallEventManager;
906
907
protected:
908
  CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
909
                   const LocationContext *LCtx)
910
2.63k
      : AnyFunctionCall(E, St, LCtx) {}
911
1.64k
  CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
912
913
1.64k
  void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
914
915
public:
916
39.9k
  virtual const CXXNewExpr *getOriginExpr() const {
917
39.9k
    return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
918
39.9k
  }
919
920
15.8k
  const FunctionDecl *getDecl() const override {
921
15.8k
    return getOriginExpr()->getOperatorNew();
922
15.8k
  }
923
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
15.7k
  unsigned getNumImplicitArgs() const {
928
15.7k
    return getOriginExpr()->passAlignment() ? 
219
:
115.7k
;
929
15.7k
  }
930
931
6.69k
  unsigned getNumArgs() const override {
932
6.69k
    return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
933
6.69k
  }
934
935
7.42k
  const Expr *getArgExpr(unsigned Index) const override {
936
7.42k
    // The first argument of an allocator call is the size of the allocation.
937
7.42k
    if (Index < getNumImplicitArgs())
938
5.75k
      return nullptr;
939
1.67k
    return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs());
940
1.67k
  }
941
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
0
  const Expr *getPlacementArgExpr(unsigned Index) const {
947
0
    return getOriginExpr()->getPlacementArg(Index);
948
0
  }
949
950
15.5k
  Kind getKind() const override { return CE_CXXAllocator; }
951
952
0
  static bool classof(const CallEvent *CE) {
953
0
    return CE->getKind() == CE_CXXAllocator;
954
0
  }
955
};
956
957
/// Represents the ways an Objective-C message send can occur.
958
//
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 {
962
  OCM_PropertyAccess,
963
  OCM_Subscript,
964
  OCM_Message
965
};
966
967
/// Represents any expression that calls an Objective-C method.
968
///
969
/// This includes all of the kinds listed in ObjCMessageKind.
970
class ObjCMethodCall : public CallEvent {
971
  friend class CallEventManager;
972
973
  const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
974
975
protected:
976
  ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
977
                 const LocationContext *LCtx)
978
4.98k
      : CallEvent(Msg, St, LCtx) {
979
4.98k
    Data = nullptr;
980
4.98k
  }
981
982
26.3k
  ObjCMethodCall(const ObjCMethodCall &Other) = default;
983
984
26.3k
  void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
985
986
  void getExtraInvalidatedValues(ValueList &Values,
987
         RegionAndSymbolInvalidationTraits *ETraits) const override;
988
989
  /// Check if the selector may have multiple definitions (may have overrides).
990
  virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
991
                                        Selector Sel) const;
992
993
public:
994
180k
  virtual const ObjCMessageExpr *getOriginExpr() const {
995
180k
    return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
996
180k
  }
997
998
62.1k
  const ObjCMethodDecl *getDecl() const override {
999
62.1k
    return getOriginExpr()->getMethodDecl();
1000
62.1k
  }
1001
1002
23.5k
  unsigned getNumArgs() const override {
1003
23.5k
    return getOriginExpr()->getNumArgs();
1004
23.5k
  }
1005
1006
5.96k
  const Expr *getArgExpr(unsigned Index) const override {
1007
5.96k
    return getOriginExpr()->getArg(Index);
1008
5.96k
  }
1009
1010
40.0k
  bool isInstanceMessage() const {
1011
40.0k
    return getOriginExpr()->isInstanceMessage();
1012
40.0k
  }
1013
1014
6.47k
  ObjCMethodFamily getMethodFamily() const {
1015
6.47k
    return getOriginExpr()->getMethodFamily();
1016
6.47k
  }
1017
1018
3.90k
  Selector getSelector() const {
1019
3.90k
    return getOriginExpr()->getSelector();
1020
3.90k
  }
1021
1022
  SourceRange getSourceRange() const override;
1023
1024
  /// Returns the value of the receiver at the time of this call.
1025
  SVal getReceiverSVal() const;
1026
1027
  /// Return the value of 'self' if available.
1028
  SVal getSelfSVal() const;
1029
1030
  /// Get the interface for the receiver.
1031
  ///
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
4.49k
  const ObjCInterfaceDecl *getReceiverInterface() const {
1035
4.49k
    return getOriginExpr()->getReceiverInterface();
1036
4.49k
  }
1037
1038
  /// Checks if the receiver refers to 'self' or 'super'.
1039
  bool isReceiverSelfOrSuper() const;
1040
1041
  /// Returns how the message was written in the source (property access,
1042
  /// subscript, or explicit message send).
1043
  ObjCMessageKind getMessageKind() const;
1044
1045
  /// Returns true if this property access or subscript is a setter (has the
1046
  /// form of an assignment).
1047
6
  bool isSetter() const {
1048
6
    switch (getMessageKind()) {
1049
6
    case OCM_Message:
1050
0
      llvm_unreachable("This is not a pseudo-object access!");
1051
6
    case OCM_PropertyAccess:
1052
0
      return getNumArgs() > 0;
1053
6
    case OCM_Subscript:
1054
6
      return getNumArgs() > 1;
1055
0
    }
1056
0
    llvm_unreachable("Unknown message kind");
1057
0
  }
1058
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;
1063
1064
  RuntimeDefinition getRuntimeDefinition() const override;
1065
1066
  bool argumentsMayEscape() const override;
1067
1068
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1069
                                    BindingsTy &Bindings) const override;
1070
1071
  ArrayRef<ParmVarDecl*> parameters() const override;
1072
1073
39.0k
  Kind getKind() const override { return CE_ObjCMessage; }
1074
1075
190k
  static bool classof(const CallEvent *CA) {
1076
190k
    return CA->getKind() == CE_ObjCMessage;
1077
190k
  }
1078
};
1079
1080
/// Manages the lifetime of CallEvent objects.
1081
///
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;
1089
1090
  llvm::BumpPtrAllocator &Alloc;
1091
  SmallVector<void *, 8> Cache;
1092
1093
  using CallEventTemplateTy = SimpleFunctionCall;
1094
1095
263k
  void reclaim(const void *Memory) {
1096
263k
    Cache.push_back(const_cast<void *>(Memory));
1097
263k
  }
1098
1099
  /// Returns memory that can be initialized as a CallEvent.
1100
263k
  void *allocate() {
1101
263k
    if (Cache.empty())
1102
15.1k
      return Alloc.Allocate<CallEventTemplateTy>();
1103
248k
    else
1104
248k
      return Cache.pop_back_val();
1105
263k
  }
1106
1107
  template <typename T, typename Arg>
1108
105k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
105k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
105k
                  "CallEvent subclasses are not all the same size");
1111
105k
    return new (allocate()) T(A, St, LCtx);
1112
105k
  }
clang::ento::ObjCMethodCall* clang::ento::CallEventManager::create<clang::ento::ObjCMethodCall, clang::ObjCMessageExpr const*>(clang::ObjCMessageExpr const*, llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::LocationContext const*)
Line
Count
Source
1108
4.98k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
4.98k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
4.98k
                  "CallEvent subclasses are not all the same size");
1111
4.98k
    return new (allocate()) T(A, St, LCtx);
1112
4.98k
  }
clang::ento::CXXAllocatorCall* clang::ento::CallEventManager::create<clang::ento::CXXAllocatorCall, clang::CXXNewExpr const*>(clang::CXXNewExpr const*, llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::LocationContext const*)
Line
Count
Source
1108
2.63k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
2.63k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
2.63k
                  "CallEvent subclasses are not all the same size");
1111
2.63k
    return new (allocate()) T(A, St, LCtx);
1112
2.63k
  }
clang::ento::CXXMemberCall* clang::ento::CallEventManager::create<clang::ento::CXXMemberCall, clang::CXXMemberCallExpr const*>(clang::CXXMemberCallExpr const*, llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::LocationContext const*)
Line
Count
Source
1108
10.3k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
10.3k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
10.3k
                  "CallEvent subclasses are not all the same size");
1111
10.3k
    return new (allocate()) T(A, St, LCtx);
1112
10.3k
  }
clang::ento::CXXMemberOperatorCall* clang::ento::CallEventManager::create<clang::ento::CXXMemberOperatorCall, clang::CXXOperatorCallExpr const*>(clang::CXXOperatorCallExpr const*, llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::LocationContext const*)
Line
Count
Source
1108
3.00k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
3.00k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
3.00k
                  "CallEvent subclasses are not all the same size");
1111
3.00k
    return new (allocate()) T(A, St, LCtx);
1112
3.00k
  }
clang::ento::BlockCall* clang::ento::CallEventManager::create<clang::ento::BlockCall, clang::CallExpr const*>(clang::CallExpr const*, llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::LocationContext const*)
Line
Count
Source
1108
539
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
539
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
539
                  "CallEvent subclasses are not all the same size");
1111
539
    return new (allocate()) T(A, St, LCtx);
1112
539
  }
clang::ento::SimpleFunctionCall* clang::ento::CallEventManager::create<clang::ento::SimpleFunctionCall, clang::CallExpr const*>(clang::CallExpr const*, llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::LocationContext const*)
Line
Count
Source
1108
84.4k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1109
84.4k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1110
84.4k
                  "CallEvent subclasses are not all the same size");
1111
84.4k
    return new (allocate()) T(A, St, LCtx);
1112
84.4k
  }
1113
1114
  template <typename T, typename Arg1, typename Arg2>
1115
24.1k
  T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1116
24.1k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1117
24.1k
                  "CallEvent subclasses are not all the same size");
1118
24.1k
    return new (allocate()) T(A1, A2, St, LCtx);
1119
24.1k
  }
1120
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);
1127
  }
1128
1129
  template <typename T, typename Arg1, typename Arg2, typename Arg3,
1130
            typename Arg4>
1131
  T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1132
2.63k
            const LocationContext *LCtx) {
1133
2.63k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1134
2.63k
                  "CallEvent subclasses are not all the same size");
1135
2.63k
    return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1136
2.63k
  }
1137
1138
public:
1139
9.80k
  CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1140
1141
  CallEventRef<>
1142
  getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1143
1144
  CallEventRef<>
1145
  getSimpleCall(const CallExpr *E, ProgramStateRef State,
1146
                const LocationContext *LCtx);
1147
1148
  CallEventRef<ObjCMethodCall>
1149
  getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1150
4.98k
                    const LocationContext *LCtx) {
1151
4.98k
    return create<ObjCMethodCall>(E, State, LCtx);
1152
4.98k
  }
1153
1154
  CallEventRef<CXXConstructorCall>
1155
  getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1156
24.1k
                        ProgramStateRef State, const LocationContext *LCtx) {
1157
24.1k
    return create<CXXConstructorCall>(E, Target, State, LCtx);
1158
24.1k
  }
1159
1160
  CallEventRef<CXXDestructorCall>
1161
  getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1162
                       const MemRegion *Target, bool IsBase,
1163
2.63k
                       ProgramStateRef State, const LocationContext *LCtx) {
1164
2.63k
    return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1165
2.63k
  }
1166
1167
  CallEventRef<CXXAllocatorCall>
1168
  getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1169
2.63k
                      const LocationContext *LCtx) {
1170
2.63k
    return create<CXXAllocatorCall>(E, State, LCtx);
1171
2.63k
  }
1172
};
1173
1174
template <typename T>
1175
504k
CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1176
504k
  assert(isa<T>(*this) && "Cloning to unrelated type");
1177
504k
  static_assert(sizeof(T) == sizeof(CallEvent),
1178
504k
                "Subclasses may not add fields");
1179
504k
1180
504k
  if (NewState == State)
1181
374k
    return cast<T>(this);
1182
130k
1183
130k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1184
130k
  T *Copy = static_cast<T *>(Mgr.allocate());
1185
130k
  cloneTo(Copy);
1186
130k
  assert(Copy->getKind() == this->getKind() && "Bad copy");
1187
130k
1188
130k
  Copy->State = NewState;
1189
130k
  return Copy;
1190
130k
}
clang::ento::CallEventRef<clang::ento::ObjCMethodCall> clang::ento::CallEvent::cloneWithState<clang::ento::ObjCMethodCall>(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
1175
19.1k
CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1176
19.1k
  assert(isa<T>(*this) && "Cloning to unrelated type");
1177
19.1k
  static_assert(sizeof(T) == sizeof(CallEvent),
1178
19.1k
                "Subclasses may not add fields");
1179
19.1k
1180
19.1k
  if (NewState == State)
1181
6.58k
    return cast<T>(this);
1182
12.5k
1183
12.5k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1184
12.5k
  T *Copy = static_cast<T *>(Mgr.allocate());
1185
12.5k
  cloneTo(Copy);
1186
12.5k
  assert(Copy->getKind() == this->getKind() && "Bad copy");
1187
12.5k
1188
12.5k
  Copy->State = NewState;
1189
12.5k
  return Copy;
1190
12.5k
}
clang::ento::CallEventRef<clang::ento::CallEvent> clang::ento::CallEvent::cloneWithState<clang::ento::CallEvent>(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
1175
485k
CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1176
485k
  assert(isa<T>(*this) && "Cloning to unrelated type");
1177
485k
  static_assert(sizeof(T) == sizeof(CallEvent),
1178
485k
                "Subclasses may not add fields");
1179
485k
1180
485k
  if (NewState == State)
1181
367k
    return cast<T>(this);
1182
117k
1183
117k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1184
117k
  T *Copy = static_cast<T *>(Mgr.allocate());
1185
117k
  cloneTo(Copy);
1186
117k
  assert(Copy->getKind() == this->getKind() && "Bad copy");
1187
117k
1188
117k
  Copy->State = NewState;
1189
117k
  return Copy;
1190
117k
}
1191
1192
696k
inline void CallEvent::Release() const {
1193
696k
  assert(RefCount > 0 && "Reference count is already zero.");
1194
696k
  --RefCount;
1195
696k
1196
696k
  if (RefCount > 0)
1197
433k
    return;
1198
263k
1199
263k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1200
263k
  Mgr.reclaim(this);
1201
263k
1202
263k
  this->~CallEvent();
1203
263k
}
1204
1205
} // namespace ento
1206
1207
} // namespace clang
1208
1209
namespace llvm {
1210
1211
// Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1212
template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1213
  using SimpleType = const T *;
1214
1215
  static SimpleType
1216
27.7k
  getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1217
27.7k
    return Val.get();
1218
27.7k
  }
1219
};
1220
1221
} // namespace llvm
1222
1223
#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H