Coverage Report

Created: 2019-02-20 07:29

/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
// 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/Support/Allocator.h"
43
#include "llvm/Support/Casting.h"
44
#include "llvm/Support/ErrorHandling.h"
45
#include <cassert>
46
#include <limits>
47
#include <utility>
48
49
namespace clang {
50
51
class LocationContext;
52
class ProgramPoint;
53
class ProgramPointTag;
54
class StackFrameContext;
55
56
namespace ento {
57
58
enum CallEventKind {
59
  CE_Function,
60
  CE_CXXMember,
61
  CE_CXXMemberOperator,
62
  CE_CXXDestructor,
63
  CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
64
  CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
65
  CE_CXXConstructor,
66
  CE_CXXAllocator,
67
  CE_BEG_FUNCTION_CALLS = CE_Function,
68
  CE_END_FUNCTION_CALLS = CE_CXXAllocator,
69
  CE_Block,
70
  CE_ObjCMessage
71
};
72
73
class CallEvent;
74
75
/// This class represents a description of a function call using the number of
76
/// arguments and the name of the function.
77
class CallDescription {
78
  friend CallEvent;
79
80
  mutable IdentifierInfo *II = nullptr;
81
  mutable bool IsLookupDone = false;
82
  // The list of the qualified names used to identify the specified CallEvent,
83
  // e.g. "{a, b}" represent the qualified names, like "a::b".
84
  std::vector<const char *> QualifiedName;
85
  unsigned RequiredArgs;
86
87
public:
88
  const static unsigned NoArgRequirement = std::numeric_limits<unsigned>::max();
89
90
  /// Constructs a CallDescription object.
91
  ///
92
  /// @param QualifiedName The list of the name qualifiers of the function that
93
  /// will be matched. The user is allowed to skip any of the qualifiers.
94
  /// For example, {"std", "basic_string", "c_str"} would match both
95
  /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
96
  ///
97
  /// @param RequiredArgs The number of arguments that is expected to match a
98
  /// call. Omit this parameter to match every occurrence of call with a given
99
  /// name regardless the number of arguments.
100
  CallDescription(ArrayRef<const char *> QualifiedName,
101
                  unsigned RequiredArgs = NoArgRequirement)
102
952k
      : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
103
104
  /// Get the name of the function that this object matches.
105
511
  StringRef getFunctionName() const { return QualifiedName.back(); }
106
};
107
108
template<typename T = CallEvent>
109
class CallEventRef : public IntrusiveRefCntPtr<const T> {
110
public:
111
774k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::ObjCMethodCall>::CallEventRef(clang::ento::ObjCMethodCall const*)
Line
Count
Source
111
27.2k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CallEvent>::CallEventRef(clang::ento::CallEvent const*)
Line
Count
Source
111
710k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CXXConstructorCall>::CallEventRef(clang::ento::CXXConstructorCall const*)
Line
Count
Source
111
31.2k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CXXDestructorCall>::CallEventRef(clang::ento::CXXDestructorCall const*)
Line
Count
Source
111
2.68k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
clang::ento::CallEventRef<clang::ento::CXXAllocatorCall>::CallEventRef(clang::ento::CXXAllocatorCall const*)
Line
Count
Source
111
2.70k
  CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
112
59.6k
  CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
113
114
37.1k
  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
115
37.1k
    return this->get()->template cloneWithState<T>(State);
116
37.1k
  }
clang::ento::CallEventRef<clang::ento::CallEvent>::cloneWithState(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
114
33.2k
  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
115
33.2k
    return this->get()->template cloneWithState<T>(State);
116
33.2k
  }
clang::ento::CallEventRef<clang::ento::ObjCMethodCall>::cloneWithState(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
114
3.89k
  CallEventRef<T> cloneWithState(ProgramStateRef State) const {
115
3.89k
    return this->get()->template cloneWithState<T>(State);
116
3.89k
  }
117
118
  // Allow implicit conversions to a superclass type, since CallEventRef
119
  // behaves like a pointer-to-const.
120
  template <typename SuperT>
121
16.4k
  operator CallEventRef<SuperT> () const {
122
16.4k
    return this->get();
123
16.4k
  }
clang::ento::CallEventRef<clang::ento::CXXConstructorCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
121
12.9k
  operator CallEventRef<SuperT> () const {
122
12.9k
    return this->get();
123
12.9k
  }
clang::ento::CallEventRef<clang::ento::CXXDestructorCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
121
1.38k
  operator CallEventRef<SuperT> () const {
122
1.38k
    return this->get();
123
1.38k
  }
clang::ento::CallEventRef<clang::ento::CXXAllocatorCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
121
681
  operator CallEventRef<SuperT> () const {
122
681
    return this->get();
123
681
  }
clang::ento::CallEventRef<clang::ento::ObjCMethodCall>::operator clang::ento::CallEventRef<clang::ento::CallEvent><clang::ento::CallEvent>() const
Line
Count
Source
121
1.46k
  operator CallEventRef<SuperT> () const {
122
1.46k
    return this->get();
123
1.46k
  }
124
};
125
126
/// \class RuntimeDefinition
127
/// Defines the runtime definition of the called function.
128
///
129
/// Encapsulates the information we have about which Decl will be used
130
/// when the call is executed on the given path. When dealing with dynamic
131
/// dispatch, the information is based on DynamicTypeInfo and might not be
132
/// precise.
133
class RuntimeDefinition {
134
  /// The Declaration of the function which could be called at runtime.
135
  /// NULL if not available.
136
  const Decl *D = nullptr;
137
138
  /// The region representing an object (ObjC/C++) on which the method is
139
  /// called. With dynamic dispatch, the method definition depends on the
140
  /// runtime type of this object. NULL when the DynamicTypeInfo is
141
  /// precise.
142
  const MemRegion *R = nullptr;
143
144
public:
145
31.1k
  RuntimeDefinition() = default;
146
30.4k
  RuntimeDefinition(const Decl *InD): D(InD) {}
147
2.68k
  RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
148
149
66.0k
  const Decl *getDecl() { return D; }
150
151
  /// Check if the definition we have is precise.
152
  /// If not, it is possible that the call dispatches to another definition at
153
  /// execution time.
154
28.3k
  bool mayHaveOtherDefinitions() { return R != nullptr; }
155
156
  /// When other definitions are possible, returns the region whose runtime type
157
  /// determines the method definition.
158
15
  const MemRegion *getDispatchRegion() { return R; }
159
};
160
161
/// Represents an abstract call to a function or method along a
162
/// particular path.
163
///
164
/// CallEvents are created through the factory methods of CallEventManager.
165
///
166
/// CallEvents should always be cheap to create and destroy. In order for
167
/// CallEventManager to be able to re-use CallEvent-sized memory blocks,
168
/// subclasses of CallEvent may not add any data members to the base class.
169
/// Use the "Data" and "Location" fields instead.
170
class CallEvent {
171
public:
172
  using Kind = CallEventKind;
173
174
private:
175
  ProgramStateRef State;
176
  const LocationContext *LCtx;
177
  llvm::PointerUnion<const Expr *, const Decl *> Origin;
178
179
protected:
180
  // This is user data for subclasses.
181
  const void *Data;
182
183
  // This is user data for subclasses.
184
  // This should come right before RefCount, so that the two fields can be
185
  // packed together on LP64 platforms.
186
  SourceLocation Location;
187
188
private:
189
  template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
190
191
  mutable unsigned RefCount = 0;
192
193
821k
  void Retain() const { ++RefCount; }
194
  void Release() const;
195
196
protected:
197
  friend class CallEventManager;
198
199
  CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
200
155k
      : State(std::move(state)), LCtx(lctx), Origin(E) {}
201
202
  CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
203
2.68k
      : State(std::move(state)), LCtx(lctx), Origin(D) {}
204
205
  // DO NOT MAKE PUBLIC
206
  CallEvent(const CallEvent &Original)
207
      : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
208
159k
        Data(Original.Data), Location(Original.Location) {}
209
210
  /// Copies this CallEvent, with vtable intact, into a new block of memory.
211
  virtual void cloneTo(void *Dest) const = 0;
212
213
  /// Get the value of arbitrary expressions at this point in the path.
214
288k
  SVal getSVal(const Stmt *S) const {
215
288k
    return getState()->getSVal(S, getLocationContext());
216
288k
  }
217
218
  using ValueList = SmallVectorImpl<SVal>;
219
220
  /// Used to specify non-argument regions that will be invalidated as a
221
  /// result of this call.
222
  virtual void getExtraInvalidatedValues(ValueList &Values,
223
18.9k
                 RegionAndSymbolInvalidationTraits *ETraits) const {}
224
225
public:
226
  CallEvent &operator=(const CallEvent &) = delete;
227
317k
  virtual ~CallEvent() = default;
228
229
  /// Returns the kind of call this is.
230
  virtual Kind getKind() const = 0;
231
232
  /// Returns the declaration of the function or method that will be
233
  /// called. May be null.
234
31.6k
  virtual const Decl *getDecl() const {
235
31.6k
    return Origin.dyn_cast<const Decl *>();
236
31.6k
  }
237
238
  /// The state in which the call is being evaluated.
239
465k
  const ProgramStateRef &getState() const {
240
465k
    return State;
241
465k
  }
242
243
  /// The context in which the call is being evaluated.
244
1.02M
  const LocationContext *getLocationContext() const {
245
1.02M
    return LCtx;
246
1.02M
  }
247
248
  /// Returns the definition of the function or method that will be
249
  /// called.
250
  virtual RuntimeDefinition getRuntimeDefinition() const = 0;
251
252
  /// Returns the expression whose value will be the result of this call.
253
  /// May be null.
254
2.92M
  const Expr *getOriginExpr() const {
255
2.92M
    return Origin.dyn_cast<const Expr *>();
256
2.92M
  }
257
258
  /// Returns the number of arguments (explicit and implicit).
259
  ///
260
  /// Note that this may be greater than the number of parameters in the
261
  /// callee's declaration, and that it may include arguments not written in
262
  /// the source.
263
  virtual unsigned getNumArgs() const = 0;
264
265
  /// Returns true if the callee is known to be from a system header.
266
30.6k
  bool isInSystemHeader() const {
267
30.6k
    const Decl *D = getDecl();
268
30.6k
    if (!D)
269
73
      return false;
270
30.6k
271
30.6k
    SourceLocation Loc = D->getLocation();
272
30.6k
    if (Loc.isValid()) {
273
29.9k
      const SourceManager &SM =
274
29.9k
        getState()->getStateManager().getContext().getSourceManager();
275
29.9k
      return SM.isInSystemHeader(D->getLocation());
276
29.9k
    }
277
678
278
678
    // Special case for implicitly-declared global operator new/delete.
279
678
    // These should be considered system functions.
280
678
    if (const auto *FD = dyn_cast<FunctionDecl>(D))
281
678
      return FD->isOverloadedOperator() && 
FD->isImplicit()677
&&
FD->isGlobal()677
;
282
0
283
0
    return false;
284
0
  }
285
286
  /// Returns true if the CallEvent is a call to a function that matches
287
  /// the CallDescription.
288
  ///
289
  /// Note that this function is not intended to be used to match Obj-C method
290
  /// calls.
291
  bool isCalled(const CallDescription &CD) const;
292
293
  /// Returns a source range for the entire call, suitable for
294
  /// outputting in diagnostics.
295
68
  virtual SourceRange getSourceRange() const {
296
68
    return getOriginExpr()->getSourceRange();
297
68
  }
298
299
  /// Returns the value of a given argument at the time of the call.
300
  virtual SVal getArgSVal(unsigned Index) const;
301
302
  /// Returns the expression associated with a given argument.
303
  /// May be null if this expression does not appear in the source.
304
0
  virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
305
306
  /// Returns the source range for errors associated with this argument.
307
  ///
308
  /// May be invalid if the argument is not written in the source.
309
  virtual SourceRange getArgSourceRange(unsigned Index) const;
310
311
  /// Returns the result type, adjusted for references.
312
  QualType getResultType() const;
313
314
  /// Returns the return value of the call.
315
  ///
316
  /// This should only be called if the CallEvent was created using a state in
317
  /// which the return value has already been bound to the origin expression.
318
  SVal getReturnValue() const;
319
320
  /// Returns true if the type of any of the non-null arguments satisfies
321
  /// the condition.
322
  bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
323
324
  /// Returns true if any of the arguments appear to represent callbacks.
325
  bool hasNonZeroCallbackArg() const;
326
327
  /// Returns true if any of the arguments is void*.
328
  bool hasVoidPointerToNonConstArg() const;
329
330
  /// Returns true if any of the arguments are known to escape to long-
331
  /// term storage, even if this method will not modify them.
332
  // NOTE: The exact semantics of this are still being defined!
333
  // We don't really want a list of hardcoded exceptions in the long run,
334
  // but we don't want duplicated lists of known APIs in the short term either.
335
26.1k
  virtual bool argumentsMayEscape() const {
336
26.1k
    return hasNonZeroCallbackArg();
337
26.1k
  }
338
339
  /// Returns true if the callee is an externally-visible function in the
340
  /// top-level namespace, such as \c malloc.
341
  ///
342
  /// You can use this call to determine that a particular function really is
343
  /// a library function and not, say, a C++ member function with the same name.
344
  ///
345
  /// If a name is provided, the function must additionally match the given
346
  /// name.
347
  ///
348
  /// Note that this deliberately excludes C++ library functions in the \c std
349
  /// namespace, but will include C library functions accessed through the
350
  /// \c std namespace. This also does not check if the function is declared
351
  /// as 'extern "C"', or if it uses C++ name mangling.
352
  // FIXME: Add a helper for checking namespaces.
353
  // FIXME: Move this down to AnyFunctionCall once checkers have more
354
  // precise callbacks.
355
  bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
356
357
  /// Returns the name of the callee, if its name is a simple identifier.
358
  ///
359
  /// Note that this will fail for Objective-C methods, blocks, and C++
360
  /// overloaded operators. The former is named by a Selector rather than a
361
  /// simple identifier, and the latter two do not have names.
362
  // FIXME: Move this down to AnyFunctionCall once checkers have more
363
  // precise callbacks.
364
51.5k
  const IdentifierInfo *getCalleeIdentifier() const {
365
51.5k
    const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
366
51.5k
    if (!ND)
367
2
      return nullptr;
368
51.5k
    return ND->getIdentifier();
369
51.5k
  }
370
371
  /// Returns an appropriate ProgramPoint for this call.
372
  ProgramPoint getProgramPoint(bool IsPreVisit = false,
373
                               const ProgramPointTag *Tag = nullptr) const;
374
375
  /// Returns a new state with all argument regions invalidated.
376
  ///
377
  /// This accepts an alternate state in case some processing has already
378
  /// occurred.
379
  ProgramStateRef invalidateRegions(unsigned BlockCount,
380
                                    ProgramStateRef Orig = nullptr) const;
381
382
  using FrameBindingTy = std::pair<Loc, SVal>;
383
  using BindingsTy = SmallVectorImpl<FrameBindingTy>;
384
385
  /// Populates the given SmallVector with the bindings in the callee's stack
386
  /// frame at the start of this call.
387
  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
388
                                            BindingsTy &Bindings) const = 0;
389
390
  /// Returns a copy of this CallEvent, but using the given state.
391
  template <typename T>
392
  CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
393
394
  /// Returns a copy of this CallEvent, but using the given state.
395
531k
  CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
396
531k
    return cloneWithState<CallEvent>(NewState);
397
531k
  }
398
399
  /// Returns true if this is a statement is a function or method call
400
  /// of some kind.
401
  static bool isCallStmt(const Stmt *S);
402
403
  /// Returns the result type of a function or method declaration.
404
  ///
405
  /// This will return a null QualType if the result type cannot be determined.
406
  static QualType getDeclaredResultType(const Decl *D);
407
408
  /// Returns true if the given decl is known to be variadic.
409
  ///
410
  /// \p D must not be null.
411
  static bool isVariadic(const Decl *D);
412
413
  /// Returns AnalysisDeclContext for the callee stack frame.
414
  /// Currently may fail; returns null on failure.
415
  AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
416
417
  /// Returns the callee stack frame. That stack frame will only be entered
418
  /// during analysis if the call is inlined, but it may still be useful
419
  /// in intermediate calculations even if the call isn't inlined.
420
  /// May fail; returns null on failure.
421
  const StackFrameContext *getCalleeStackFrame() const;
422
423
  /// Returns memory location for a parameter variable within the callee stack
424
  /// frame. May fail; returns null on failure.
425
  const VarRegion *getParameterLocation(unsigned Index) const;
426
427
  /// Returns true if on the current path, the argument was constructed by
428
  /// calling a C++ constructor over it. This is an internal detail of the
429
  /// analysis which doesn't necessarily represent the program semantics:
430
  /// if we are supposed to construct an argument directly, we may still
431
  /// not do that because we don't know how (i.e., construction context is
432
  /// unavailable in the CFG or not supported by the analyzer).
433
40.9k
  bool isArgumentConstructedDirectly(unsigned Index) const {
434
40.9k
    // This assumes that the object was not yet removed from the state.
435
40.9k
    return ExprEngine::getObjectUnderConstruction(
436
40.9k
        getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue();
437
40.9k
  }
438
439
  /// Some calls have parameter numbering mismatched from argument numbering.
440
  /// This function converts an argument index to the corresponding
441
  /// parameter index. Returns None is the argument doesn't correspond
442
  /// to any parameter variable.
443
  virtual Optional<unsigned>
444
813
  getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
445
813
    return ASTArgumentIndex;
446
813
  }
447
448
  /// Some call event sub-classes conveniently adjust mismatching AST indices
449
  /// to match parameter indices. This function converts an argument index
450
  /// as understood by CallEvent to the argument index as understood by the AST.
451
66.6k
  virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
452
66.6k
    return CallArgumentIndex;
453
66.6k
  }
454
455
  // Iterator access to formal parameters and their types.
456
private:
457
  struct GetTypeFn {
458
64.0k
    QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
459
  };
460
461
public:
462
  /// Return call's formal parameters.
463
  ///
464
  /// Remember that the number of formal parameters may not match the number
465
  /// of arguments for all calls. However, the first parameter will always
466
  /// correspond with the argument value returned by \c getArgSVal(0).
467
  virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
468
469
  using param_type_iterator =
470
      llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
471
472
  /// Returns an iterator over the types of the call's formal parameters.
473
  ///
474
  /// This uses the callee decl found by default name lookup rather than the
475
  /// definition because it represents a public interface, and probably has
476
  /// more annotations.
477
78.0k
  param_type_iterator param_type_begin() const {
478
78.0k
    return llvm::map_iterator(parameters().begin(), GetTypeFn());
479
78.0k
  }
480
  /// \sa param_type_begin()
481
78.0k
  param_type_iterator param_type_end() const {
482
78.0k
    return llvm::map_iterator(parameters().end(), GetTypeFn());
483
78.0k
  }
484
485
  // For debugging purposes only
486
  void dump(raw_ostream &Out) const;
487
  void dump() const;
488
};
489
490
/// Represents a call to any sort of function that might have a
491
/// FunctionDecl.
492
class AnyFunctionCall : public CallEvent {
493
protected:
494
  AnyFunctionCall(const Expr *E, ProgramStateRef St,
495
                  const LocationContext *LCtx)
496
149k
      : CallEvent(E, St, LCtx) {}
497
  AnyFunctionCall(const Decl *D, ProgramStateRef St,
498
                  const LocationContext *LCtx)
499
2.68k
      : CallEvent(D, St, LCtx) {}
500
129k
  AnyFunctionCall(const AnyFunctionCall &Other) = default;
501
502
public:
503
  // This function is overridden by subclasses, but they must return
504
  // a FunctionDecl.
505
31.6k
  const FunctionDecl *getDecl() const override {
506
31.6k
    return cast<FunctionDecl>(CallEvent::getDecl());
507
31.6k
  }
508
509
  RuntimeDefinition getRuntimeDefinition() const override;
510
511
  bool argumentsMayEscape() const override;
512
513
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
514
                                    BindingsTy &Bindings) const override;
515
516
  ArrayRef<ParmVarDecl *> parameters() const override;
517
518
71.5k
  static bool classof(const CallEvent *CA) {
519
71.5k
    return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
520
71.5k
           CA->getKind() <= CE_END_FUNCTION_CALLS;
521
71.5k
  }
522
};
523
524
/// Represents a C function or static C++ member function call.
525
///
526
/// Example: \c fun()
527
class SimpleFunctionCall : public AnyFunctionCall {
528
  friend class CallEventManager;
529
530
protected:
531
  SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
532
                     const LocationContext *LCtx)
533
98.6k
      : AnyFunctionCall(CE, St, LCtx) {}
534
68.4k
  SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
535
536
68.4k
  void cloneTo(void *Dest) const override {
537
68.4k
    new (Dest) SimpleFunctionCall(*this);
538
68.4k
  }
539
540
public:
541
1.09M
  virtual const CallExpr *getOriginExpr() const {
542
1.09M
    return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
543
1.09M
  }
544
545
  const FunctionDecl *getDecl() const override;
546
547
276k
  unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
548
549
209k
  const Expr *getArgExpr(unsigned Index) const override {
550
209k
    return getOriginExpr()->getArg(Index);
551
209k
  }
552
553
534k
  Kind getKind() const override { return CE_Function; }
554
555
1.28k
  static bool classof(const CallEvent *CA) {
556
1.28k
    return CA->getKind() == CE_Function;
557
1.28k
  }
558
};
559
560
/// Represents a call to a block.
561
///
562
/// Example: <tt>^{ /* ... */ }()</tt>
563
class BlockCall : public CallEvent {
564
  friend class CallEventManager;
565
566
protected:
567
  BlockCall(const CallExpr *CE, ProgramStateRef St,
568
            const LocationContext *LCtx)
569
570
      : CallEvent(CE, St, LCtx) {}
570
242
  BlockCall(const BlockCall &Other) = default;
571
572
242
  void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
573
574
  void getExtraInvalidatedValues(ValueList &Values,
575
         RegionAndSymbolInvalidationTraits *ETraits) const override;
576
577
public:
578
3.93k
  virtual const CallExpr *getOriginExpr() const {
579
3.93k
    return cast<CallExpr>(CallEvent::getOriginExpr());
580
3.93k
  }
581
582
1.17k
  unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
583
584
343
  const Expr *getArgExpr(unsigned Index) const override {
585
343
    return getOriginExpr()->getArg(Index);
586
343
  }
587
588
  /// Returns the region associated with this instance of the block.
589
  ///
590
  /// This may be NULL if the block's origin is unknown.
591
  const BlockDataRegion *getBlockRegion() const;
592
593
2.22k
  const BlockDecl *getDecl() const override {
594
2.22k
    const BlockDataRegion *BR = getBlockRegion();
595
2.22k
    if (!BR)
596
92
      return nullptr;
597
2.13k
    return BR->getDecl();
598
2.13k
  }
599
600
540
  bool isConversionFromLambda() const {
601
540
    const BlockDecl *BD = getDecl();
602
540
    if (!BD)
603
10
      return false;
604
530
605
530
    return BD->isConversionFromLambda();
606
530
  }
607
608
  /// For a block converted from a C++ lambda, returns the block
609
  /// VarRegion for the variable holding the captured C++ lambda record.
610
14
  const VarRegion *getRegionStoringCapturedLambda() const {
611
14
    assert(isConversionFromLambda());
612
14
    const BlockDataRegion *BR = getBlockRegion();
613
14
    assert(BR && "Block converted from lambda must have a block region");
614
14
615
14
    auto I = BR->referenced_vars_begin();
616
14
    assert(I != BR->referenced_vars_end());
617
14
618
14
    return I.getCapturedRegion();
619
14
  }
620
621
194
  RuntimeDefinition getRuntimeDefinition() const override {
622
194
    if (!isConversionFromLambda())
623
187
      return RuntimeDefinition(getDecl());
624
7
625
7
    // Clang converts lambdas to blocks with an implicit user-defined
626
7
    // conversion operator method on the lambda record that looks (roughly)
627
7
    // like:
628
7
    //
629
7
    // typedef R(^block_type)(P1, P2, ...);
630
7
    // operator block_type() const {
631
7
    //   auto Lambda = *this;
632
7
    //   return ^(P1 p1, P2 p2, ...){
633
7
    //     /* return Lambda(p1, p2, ...); */
634
7
    //   };
635
7
    // }
636
7
    //
637
7
    // Here R is the return type of the lambda and P1, P2, ... are
638
7
    // its parameter types. 'Lambda' is a fake VarDecl captured by the block
639
7
    // that is initialized to a copy of the lambda.
640
7
    //
641
7
    // Sema leaves the body of a lambda-converted block empty (it is
642
7
    // produced by CodeGen), so we can't analyze it directly. Instead, we skip
643
7
    // the block body and analyze the operator() method on the captured lambda.
644
7
    const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
645
7
    const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
646
7
    CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
647
7
648
7
    return RuntimeDefinition(LambdaCallOperator);
649
7
  }
650
651
18
  bool argumentsMayEscape() const override {
652
18
    return true;
653
18
  }
654
655
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
656
                                    BindingsTy &Bindings) const override;
657
658
  ArrayRef<ParmVarDecl*> parameters() const override;
659
660
2.41k
  Kind getKind() const override { return CE_Block; }
661
662
0
  static bool classof(const CallEvent *CA) {
663
0
    return CA->getKind() == CE_Block;
664
0
  }
665
};
666
667
/// Represents a non-static C++ member function call, no matter how
668
/// it is written.
669
class CXXInstanceCall : public AnyFunctionCall {
670
protected:
671
  CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
672
                  const LocationContext *LCtx)
673
17.0k
      : AnyFunctionCall(CE, St, LCtx) {}
674
  CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
675
                  const LocationContext *LCtx)
676
2.68k
      : AnyFunctionCall(D, St, LCtx) {}
677
15.2k
  CXXInstanceCall(const CXXInstanceCall &Other) = default;
678
679
  void getExtraInvalidatedValues(ValueList &Values,
680
         RegionAndSymbolInvalidationTraits *ETraits) const override;
681
682
public:
683
  /// Returns the expression representing the implicit 'this' object.
684
60
  virtual const Expr *getCXXThisExpr() const { return nullptr; }
685
686
  /// Returns the value of the implicit 'this' object.
687
  virtual SVal getCXXThisVal() const;
688
689
  const FunctionDecl *getDecl() const override;
690
691
  RuntimeDefinition getRuntimeDefinition() const override;
692
693
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
694
                                    BindingsTy &Bindings) const override;
695
696
190k
  static bool classof(const CallEvent *CA) {
697
190k
    return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
698
190k
           
CA->getKind() <= CE_END_CXX_INSTANCE_CALLS79.6k
;
699
190k
  }
700
};
701
702
/// Represents a non-static C++ member function call.
703
///
704
/// Example: \c obj.fun()
705
class CXXMemberCall : public CXXInstanceCall {
706
  friend class CallEventManager;
707
708
protected:
709
  CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
710
                const LocationContext *LCtx)
711
11.9k
      : CXXInstanceCall(CE, St, LCtx) {}
712
8.80k
  CXXMemberCall(const CXXMemberCall &Other) = default;
713
714
8.80k
  void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
715
716
public:
717
63.2k
  virtual const CXXMemberCallExpr *getOriginExpr() const {
718
63.2k
    return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
719
63.2k
  }
720
721
28.8k
  unsigned getNumArgs() const override {
722
28.8k
    if (const CallExpr *CE = getOriginExpr())
723
28.8k
      return CE->getNumArgs();
724
0
    return 0;
725
0
  }
726
727
10.5k
  const Expr *getArgExpr(unsigned Index) const override {
728
10.5k
    return getOriginExpr()->getArg(Index);
729
10.5k
  }
730
731
  const Expr *getCXXThisExpr() const override;
732
733
  RuntimeDefinition getRuntimeDefinition() const override;
734
735
85.9k
  Kind getKind() const override { return CE_CXXMember; }
736
737
1.79k
  static bool classof(const CallEvent *CA) {
738
1.79k
    return CA->getKind() == CE_CXXMember;
739
1.79k
  }
740
};
741
742
/// Represents a C++ overloaded operator call where the operator is
743
/// implemented as a non-static member function.
744
///
745
/// Example: <tt>iter + 1</tt>
746
class CXXMemberOperatorCall : public CXXInstanceCall {
747
  friend class CallEventManager;
748
749
protected:
750
  CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
751
                        const LocationContext *LCtx)
752
5.12k
      : CXXInstanceCall(CE, St, LCtx) {}
753
4.28k
  CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
754
755
4.28k
  void cloneTo(void *Dest) const override {
756
4.28k
    new (Dest) CXXMemberOperatorCall(*this);
757
4.28k
  }
758
759
public:
760
25.0k
  virtual const CXXOperatorCallExpr *getOriginExpr() const {
761
25.0k
    return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
762
25.0k
  }
763
764
9.00k
  unsigned getNumArgs() const override {
765
9.00k
    return getOriginExpr()->getNumArgs() - 1;
766
9.00k
  }
767
768
6.84k
  const Expr *getArgExpr(unsigned Index) const override {
769
6.84k
    return getOriginExpr()->getArg(Index + 1);
770
6.84k
  }
771
772
  const Expr *getCXXThisExpr() const override;
773
774
41.2k
  Kind getKind() const override { return CE_CXXMemberOperator; }
775
776
1.32k
  static bool classof(const CallEvent *CA) {
777
1.32k
    return CA->getKind() == CE_CXXMemberOperator;
778
1.32k
  }
779
780
  Optional<unsigned>
781
4
  getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
782
4
    // For member operator calls argument 0 on the expression corresponds
783
4
    // to implicit this-parameter on the declaration.
784
4
    return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1)
785
4
                                  : 
None0
;
786
4
  }
787
788
1.41k
  unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
789
1.41k
    // For member operator calls argument 0 on the expression corresponds
790
1.41k
    // to implicit this-parameter on the declaration.
791
1.41k
    return CallArgumentIndex + 1;
792
1.41k
  }
793
};
794
795
/// Represents an implicit call to a C++ destructor.
796
///
797
/// This can occur at the end of a scope (for automatic objects), at the end
798
/// of a full-expression (for temporaries), or as part of a delete.
799
class CXXDestructorCall : public CXXInstanceCall {
800
  friend class CallEventManager;
801
802
protected:
803
  using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
804
805
  /// Creates an implicit destructor.
806
  ///
807
  /// \param DD The destructor that will be called.
808
  /// \param Trigger The statement whose completion causes this destructor call.
809
  /// \param Target The object region to be destructed.
810
  /// \param St The path-sensitive state at this point in the program.
811
  /// \param LCtx The location context at this point in the program.
812
  CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
813
                    const MemRegion *Target, bool IsBaseDestructor,
814
                    ProgramStateRef St, const LocationContext *LCtx)
815
2.68k
      : CXXInstanceCall(DD, St, LCtx) {
816
2.68k
    Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
817
2.68k
    Location = Trigger->getEndLoc();
818
2.68k
  }
819
820
2.13k
  CXXDestructorCall(const CXXDestructorCall &Other) = default;
821
822
2.13k
  void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
823
824
public:
825
11.4k
  SourceRange getSourceRange() const override { return Location; }
826
7.45k
  unsigned getNumArgs() const override { return 0; }
827
828
  RuntimeDefinition getRuntimeDefinition() const override;
829
830
  /// Returns the value of the implicit 'this' object.
831
  SVal getCXXThisVal() const override;
832
833
  /// Returns true if this is a call to a base class destructor.
834
2.50k
  bool isBaseDestructor() const {
835
2.50k
    return DtorDataTy::getFromOpaqueValue(Data).getInt();
836
2.50k
  }
837
838
20.1k
  Kind getKind() const override { return CE_CXXDestructor; }
839
840
75.3k
  static bool classof(const CallEvent *CA) {
841
75.3k
    return CA->getKind() == CE_CXXDestructor;
842
75.3k
  }
843
};
844
845
/// Represents a call to a C++ constructor.
846
///
847
/// Example: \c T(1)
848
class CXXConstructorCall : public AnyFunctionCall {
849
  friend class CallEventManager;
850
851
protected:
852
  /// Creates a constructor call.
853
  ///
854
  /// \param CE The constructor expression as written in the source.
855
  /// \param Target The region where the object should be constructed. If NULL,
856
  ///               a new symbolic region will be used.
857
  /// \param St The path-sensitive state at this point in the program.
858
  /// \param LCtx The location context at this point in the program.
859
  CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
860
                     ProgramStateRef St, const LocationContext *LCtx)
861
31.2k
      : AnyFunctionCall(CE, St, LCtx) {
862
31.2k
    Data = Target;
863
31.2k
  }
864
865
43.6k
  CXXConstructorCall(const CXXConstructorCall &Other) = default;
866
867
43.6k
  void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
868
869
  void getExtraInvalidatedValues(ValueList &Values,
870
         RegionAndSymbolInvalidationTraits *ETraits) const override;
871
872
public:
873
389k
  virtual const CXXConstructExpr *getOriginExpr() const {
874
389k
    return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
875
389k
  }
876
877
168k
  const CXXConstructorDecl *getDecl() const override {
878
168k
    return getOriginExpr()->getConstructor();
879
168k
  }
880
881
91.9k
  unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
882
883
94.2k
  const Expr *getArgExpr(unsigned Index) const override {
884
94.2k
    return getOriginExpr()->getArg(Index);
885
94.2k
  }
886
887
  /// Returns the value of the implicit 'this' object.
888
  SVal getCXXThisVal() const;
889
890
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
891
                                    BindingsTy &Bindings) const override;
892
893
259k
  Kind getKind() const override { return CE_CXXConstructor; }
894
895
194k
  static bool classof(const CallEvent *CA) {
896
194k
    return CA->getKind() == CE_CXXConstructor;
897
194k
  }
898
};
899
900
/// Represents the memory allocation call in a C++ new-expression.
901
///
902
/// This is a call to "operator new".
903
class CXXAllocatorCall : public AnyFunctionCall {
904
  friend class CallEventManager;
905
906
protected:
907
  CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
908
                   const LocationContext *LCtx)
909
2.70k
      : AnyFunctionCall(E, St, LCtx) {}
910
1.83k
  CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
911
912
1.83k
  void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
913
914
public:
915
42.5k
  virtual const CXXNewExpr *getOriginExpr() const {
916
42.5k
    return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
917
42.5k
  }
918
919
16.6k
  const FunctionDecl *getDecl() const override {
920
16.6k
    return getOriginExpr()->getOperatorNew();
921
16.6k
  }
922
923
  /// Number of non-placement arguments to the call. It is equal to 2 for
924
  /// C++17 aligned operator new() calls that have alignment implicitly
925
  /// passed as the second argument, and to 1 for other operator new() calls.
926
17.1k
  unsigned getNumImplicitArgs() const {
927
17.1k
    return getOriginExpr()->passAlignment() ? 
221
:
117.1k
;
928
17.1k
  }
929
930
7.03k
  unsigned getNumArgs() const override {
931
7.03k
    return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
932
7.03k
  }
933
934
8.43k
  const Expr *getArgExpr(unsigned Index) const override {
935
8.43k
    // The first argument of an allocator call is the size of the allocation.
936
8.43k
    if (Index < getNumImplicitArgs())
937
6.73k
      return nullptr;
938
1.69k
    return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs());
939
1.69k
  }
940
941
  /// Number of placement arguments to the operator new() call. For example,
942
  /// standard std::nothrow operator new and standard placement new both have
943
  /// 1 implicit argument (size) and 1 placement argument, while regular
944
  /// operator new() has 1 implicit argument and 0 placement arguments.
945
0
  const Expr *getPlacementArgExpr(unsigned Index) const {
946
0
    return getOriginExpr()->getPlacementArg(Index);
947
0
  }
948
949
16.6k
  Kind getKind() const override { return CE_CXXAllocator; }
950
951
0
  static bool classof(const CallEvent *CE) {
952
0
    return CE->getKind() == CE_CXXAllocator;
953
0
  }
954
};
955
956
/// Represents the ways an Objective-C message send can occur.
957
//
958
// Note to maintainers: OCM_Message should always be last, since it does not
959
// need to fit in the Data field's low bits.
960
enum ObjCMessageKind {
961
  OCM_PropertyAccess,
962
  OCM_Subscript,
963
  OCM_Message
964
};
965
966
/// Represents any expression that calls an Objective-C method.
967
///
968
/// This includes all of the kinds listed in ObjCMessageKind.
969
class ObjCMethodCall : public CallEvent {
970
  friend class CallEventManager;
971
972
  const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
973
974
protected:
975
  ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
976
                 const LocationContext *LCtx)
977
5.75k
      : CallEvent(Msg, St, LCtx) {
978
5.75k
    Data = nullptr;
979
5.75k
  }
980
981
29.8k
  ObjCMethodCall(const ObjCMethodCall &Other) = default;
982
983
29.8k
  void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
984
985
  void getExtraInvalidatedValues(ValueList &Values,
986
         RegionAndSymbolInvalidationTraits *ETraits) const override;
987
988
  /// Check if the selector may have multiple definitions (may have overrides).
989
  virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
990
                                        Selector Sel) const;
991
992
public:
993
199k
  virtual const ObjCMessageExpr *getOriginExpr() const {
994
199k
    return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
995
199k
  }
996
997
68.2k
  const ObjCMethodDecl *getDecl() const override {
998
68.2k
    return getOriginExpr()->getMethodDecl();
999
68.2k
  }
1000
1001
28.8k
  unsigned getNumArgs() const override {
1002
28.8k
    return getOriginExpr()->getNumArgs();
1003
28.8k
  }
1004
1005
8.13k
  const Expr *getArgExpr(unsigned Index) const override {
1006
8.13k
    return getOriginExpr()->getArg(Index);
1007
8.13k
  }
1008
1009
43.0k
  bool isInstanceMessage() const {
1010
43.0k
    return getOriginExpr()->isInstanceMessage();
1011
43.0k
  }
1012
1013
7.37k
  ObjCMethodFamily getMethodFamily() const {
1014
7.37k
    return getOriginExpr()->getMethodFamily();
1015
7.37k
  }
1016
1017
2.12k
  Selector getSelector() const {
1018
2.12k
    return getOriginExpr()->getSelector();
1019
2.12k
  }
1020
1021
  SourceRange getSourceRange() const override;
1022
1023
  /// Returns the value of the receiver at the time of this call.
1024
  SVal getReceiverSVal() const;
1025
1026
  /// Return the value of 'self' if available.
1027
  SVal getSelfSVal() const;
1028
1029
  /// Get the interface for the receiver.
1030
  ///
1031
  /// This works whether this is an instance message or a class message.
1032
  /// However, it currently just uses the static type of the receiver.
1033
3.77k
  const ObjCInterfaceDecl *getReceiverInterface() const {
1034
3.77k
    return getOriginExpr()->getReceiverInterface();
1035
3.77k
  }
1036
1037
  /// Checks if the receiver refers to 'self' or 'super'.
1038
  bool isReceiverSelfOrSuper() const;
1039
1040
  /// Returns how the message was written in the source (property access,
1041
  /// subscript, or explicit message send).
1042
  ObjCMessageKind getMessageKind() const;
1043
1044
  /// Returns true if this property access or subscript is a setter (has the
1045
  /// form of an assignment).
1046
6
  bool isSetter() const {
1047
6
    switch (getMessageKind()) {
1048
6
    case OCM_Message:
1049
0
      llvm_unreachable("This is not a pseudo-object access!");
1050
6
    case OCM_PropertyAccess:
1051
0
      return getNumArgs() > 0;
1052
6
    case OCM_Subscript:
1053
6
      return getNumArgs() > 1;
1054
0
    }
1055
0
    llvm_unreachable("Unknown message kind");
1056
0
  }
1057
1058
  // Returns the property accessed by this method, either explicitly via
1059
  // property syntax or implicitly via a getter or setter method. Returns
1060
  // nullptr if the call is not a prooperty access.
1061
  const ObjCPropertyDecl *getAccessedProperty() const;
1062
1063
  RuntimeDefinition getRuntimeDefinition() const override;
1064
1065
  bool argumentsMayEscape() const override;
1066
1067
  void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1068
                                    BindingsTy &Bindings) const override;
1069
1070
  ArrayRef<ParmVarDecl*> parameters() const override;
1071
1072
41.8k
  Kind getKind() const override { return CE_ObjCMessage; }
1073
1074
205k
  static bool classof(const CallEvent *CA) {
1075
205k
    return CA->getKind() == CE_ObjCMessage;
1076
205k
  }
1077
};
1078
1079
/// Manages the lifetime of CallEvent objects.
1080
///
1081
/// CallEventManager provides a way to create arbitrary CallEvents "on the
1082
/// stack" as if they were value objects by keeping a cache of CallEvent-sized
1083
/// memory blocks. The CallEvents created by CallEventManager are only valid
1084
/// for the lifetime of the OwnedCallEvent that holds them; right now these
1085
/// objects cannot be copied and ownership cannot be transferred.
1086
class CallEventManager {
1087
  friend class CallEvent;
1088
1089
  llvm::BumpPtrAllocator &Alloc;
1090
  SmallVector<void *, 8> Cache;
1091
1092
  using CallEventTemplateTy = SimpleFunctionCall;
1093
1094
317k
  void reclaim(const void *Memory) {
1095
317k
    Cache.push_back(const_cast<void *>(Memory));
1096
317k
  }
1097
1098
  /// Returns memory that can be initialized as a CallEvent.
1099
317k
  void *allocate() {
1100
317k
    if (Cache.empty())
1101
16.5k
      return Alloc.Allocate<CallEventTemplateTy>();
1102
301k
    else
1103
301k
      return Cache.pop_back_val();
1104
317k
  }
1105
1106
  template <typename T, typename Arg>
1107
124k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
124k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
124k
                  "CallEvent subclasses are not all the same size");
1110
124k
    return new (allocate()) T(A, St, LCtx);
1111
124k
  }
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
1107
5.75k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
5.75k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
5.75k
                  "CallEvent subclasses are not all the same size");
1110
5.75k
    return new (allocate()) T(A, St, LCtx);
1111
5.75k
  }
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
1107
2.70k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
2.70k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
2.70k
                  "CallEvent subclasses are not all the same size");
1110
2.70k
    return new (allocate()) T(A, St, LCtx);
1111
2.70k
  }
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
1107
11.9k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
11.9k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
11.9k
                  "CallEvent subclasses are not all the same size");
1110
11.9k
    return new (allocate()) T(A, St, LCtx);
1111
11.9k
  }
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
1107
5.12k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
5.12k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
5.12k
                  "CallEvent subclasses are not all the same size");
1110
5.12k
    return new (allocate()) T(A, St, LCtx);
1111
5.12k
  }
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
1107
570
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
570
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
570
                  "CallEvent subclasses are not all the same size");
1110
570
    return new (allocate()) T(A, St, LCtx);
1111
570
  }
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
1107
98.6k
  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108
98.6k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109
98.6k
                  "CallEvent subclasses are not all the same size");
1110
98.6k
    return new (allocate()) T(A, St, LCtx);
1111
98.6k
  }
1112
1113
  template <typename T, typename Arg1, typename Arg2>
1114
31.2k
  T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1115
31.2k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1116
31.2k
                  "CallEvent subclasses are not all the same size");
1117
31.2k
    return new (allocate()) T(A1, A2, St, LCtx);
1118
31.2k
  }
1119
1120
  template <typename T, typename Arg1, typename Arg2, typename Arg3>
1121
  T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1122
            const LocationContext *LCtx) {
1123
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1124
                  "CallEvent subclasses are not all the same size");
1125
    return new (allocate()) T(A1, A2, A3, St, LCtx);
1126
  }
1127
1128
  template <typename T, typename Arg1, typename Arg2, typename Arg3,
1129
            typename Arg4>
1130
  T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1131
2.68k
            const LocationContext *LCtx) {
1132
2.68k
    static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1133
2.68k
                  "CallEvent subclasses are not all the same size");
1134
2.68k
    return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1135
2.68k
  }
1136
1137
public:
1138
10.5k
  CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1139
1140
  /// Gets an outside caller given a callee context.
1141
  CallEventRef<>
1142
  getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1143
1144
  /// Gets a call event for a function call, Objective-C method call,
1145
  /// or a 'new' call.
1146
  CallEventRef<>
1147
  getCall(const Stmt *S, ProgramStateRef State,
1148
          const LocationContext *LC);
1149
1150
  CallEventRef<>
1151
  getSimpleCall(const CallExpr *E, ProgramStateRef State,
1152
                const LocationContext *LCtx);
1153
1154
  CallEventRef<ObjCMethodCall>
1155
  getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1156
5.75k
                    const LocationContext *LCtx) {
1157
5.75k
    return create<ObjCMethodCall>(E, State, LCtx);
1158
5.75k
  }
1159
1160
  CallEventRef<CXXConstructorCall>
1161
  getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1162
31.2k
                        ProgramStateRef State, const LocationContext *LCtx) {
1163
31.2k
    return create<CXXConstructorCall>(E, Target, State, LCtx);
1164
31.2k
  }
1165
1166
  CallEventRef<CXXDestructorCall>
1167
  getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1168
                       const MemRegion *Target, bool IsBase,
1169
2.68k
                       ProgramStateRef State, const LocationContext *LCtx) {
1170
2.68k
    return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1171
2.68k
  }
1172
1173
  CallEventRef<CXXAllocatorCall>
1174
  getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1175
2.70k
                      const LocationContext *LCtx) {
1176
2.70k
    return create<CXXAllocatorCall>(E, State, LCtx);
1177
2.70k
  }
1178
};
1179
1180
template <typename T>
1181
586k
CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1182
586k
  assert(isa<T>(*this) && "Cloning to unrelated type");
1183
586k
  static_assert(sizeof(T) == sizeof(CallEvent),
1184
586k
                "Subclasses may not add fields");
1185
586k
1186
586k
  if (NewState == State)
1187
427k
    return cast<T>(this);
1188
159k
1189
159k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1190
159k
  T *Copy = static_cast<T *>(Mgr.allocate());
1191
159k
  cloneTo(Copy);
1192
159k
  assert(Copy->getKind() == this->getKind() && "Bad copy");
1193
159k
1194
159k
  Copy->State = NewState;
1195
159k
  return Copy;
1196
159k
}
clang::ento::CallEventRef<clang::ento::ObjCMethodCall> clang::ento::CallEvent::cloneWithState<clang::ento::ObjCMethodCall>(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
1181
21.5k
CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1182
21.5k
  assert(isa<T>(*this) && "Cloning to unrelated type");
1183
21.5k
  static_assert(sizeof(T) == sizeof(CallEvent),
1184
21.5k
                "Subclasses may not add fields");
1185
21.5k
1186
21.5k
  if (NewState == State)
1187
7.39k
    return cast<T>(this);
1188
14.1k
1189
14.1k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1190
14.1k
  T *Copy = static_cast<T *>(Mgr.allocate());
1191
14.1k
  cloneTo(Copy);
1192
14.1k
  assert(Copy->getKind() == this->getKind() && "Bad copy");
1193
14.1k
1194
14.1k
  Copy->State = NewState;
1195
14.1k
  return Copy;
1196
14.1k
}
clang::ento::CallEventRef<clang::ento::CallEvent> clang::ento::CallEvent::cloneWithState<clang::ento::CallEvent>(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>) const
Line
Count
Source
1181
565k
CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1182
565k
  assert(isa<T>(*this) && "Cloning to unrelated type");
1183
565k
  static_assert(sizeof(T) == sizeof(CallEvent),
1184
565k
                "Subclasses may not add fields");
1185
565k
1186
565k
  if (NewState == State)
1187
420k
    return cast<T>(this);
1188
145k
1189
145k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1190
145k
  T *Copy = static_cast<T *>(Mgr.allocate());
1191
145k
  cloneTo(Copy);
1192
145k
  assert(Copy->getKind() == this->getKind() && "Bad copy");
1193
145k
1194
145k
  Copy->State = NewState;
1195
145k
  return Copy;
1196
145k
}
1197
1198
821k
inline void CallEvent::Release() const {
1199
821k
  assert(RefCount > 0 && "Reference count is already zero.");
1200
821k
  --RefCount;
1201
821k
1202
821k
  if (RefCount > 0)
1203
503k
    return;
1204
317k
1205
317k
  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1206
317k
  Mgr.reclaim(this);
1207
317k
1208
317k
  this->~CallEvent();
1209
317k
}
1210
1211
} // namespace ento
1212
1213
} // namespace clang
1214
1215
namespace llvm {
1216
1217
// Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1218
template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1219
  using SimpleType = const T *;
1220
1221
  static SimpleType
1222
35.0k
  getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1223
35.0k
    return Val.get();
1224
35.0k
  }
1225
};
1226
1227
} // namespace llvm
1228
1229
#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H