1 //===- Calls.cpp - 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 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17 #include "clang/AST/ParentMap.h"
18 #include "clang/Analysis/ProgramPoint.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 using namespace clang;
26 using namespace ento;
27 
28 QualType CallEvent::getResultType() const {
29   const Expr *E = getOriginExpr();
30   assert(E && "Calls without origin expressions do not have results");
31   QualType ResultTy = E->getType();
32 
33   ASTContext &Ctx = getState()->getStateManager().getContext();
34 
35   // A function that returns a reference to 'int' will have a result type
36   // of simply 'int'. Check the origin expr's value kind to recover the
37   // proper type.
38   switch (E->getValueKind()) {
39   case VK_LValue:
40     ResultTy = Ctx.getLValueReferenceType(ResultTy);
41     break;
42   case VK_XValue:
43     ResultTy = Ctx.getRValueReferenceType(ResultTy);
44     break;
45   case VK_RValue:
46     // No adjustment is necessary.
47     break;
48   }
49 
50   return ResultTy;
51 }
52 
53 static bool isCallback(QualType T) {
54   // If a parameter is a block or a callback, assume it can modify pointer.
55   if (T->isBlockPointerType() ||
56       T->isFunctionPointerType() ||
57       T->isObjCSelType())
58     return true;
59 
60   // Check if a callback is passed inside a struct (for both, struct passed by
61   // reference and by value). Dig just one level into the struct for now.
62 
63   if (T->isAnyPointerType() || T->isReferenceType())
64     T = T->getPointeeType();
65 
66   if (const RecordType *RT = T->getAsStructureType()) {
67     const RecordDecl *RD = RT->getDecl();
68     for (const auto *I : RD->fields()) {
69       QualType FieldT = I->getType();
70       if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
71         return true;
72     }
73   }
74   return false;
75 }
76 
77 static bool isVoidPointerToNonConst(QualType T) {
78   if (const PointerType *PT = T->getAs<PointerType>()) {
79     QualType PointeeTy = PT->getPointeeType();
80     if (PointeeTy.isConstQualified())
81       return false;
82     return PointeeTy->isVoidType();
83   } else
84     return false;
85 }
86 
87 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
88   unsigned NumOfArgs = getNumArgs();
89 
90   // If calling using a function pointer, assume the function does not
91   // satisfy the callback.
92   // TODO: We could check the types of the arguments here.
93   if (!getDecl())
94     return false;
95 
96   unsigned Idx = 0;
97   for (CallEvent::param_type_iterator I = param_type_begin(),
98                                       E = param_type_end();
99        I != E && Idx < NumOfArgs; ++I, ++Idx) {
100     // If the parameter is 0, it's harmless.
101     if (getArgSVal(Idx).isZeroConstant())
102       continue;
103 
104     if (Condition(*I))
105       return true;
106   }
107   return false;
108 }
109 
110 bool CallEvent::hasNonZeroCallbackArg() const {
111   return hasNonNullArgumentsWithType(isCallback);
112 }
113 
114 bool CallEvent::hasVoidPointerToNonConstArg() const {
115   return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
116 }
117 
118 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
119   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
120   if (!FD)
121     return false;
122 
123   return CheckerContext::isCLibraryFunction(FD, FunctionName);
124 }
125 
126 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
127 /// with no further indirection.
128 static bool isPointerToConst(QualType Ty) {
129   QualType PointeeTy = Ty->getPointeeType();
130   if (PointeeTy == QualType())
131     return false;
132   if (!PointeeTy.isConstQualified())
133     return false;
134   if (PointeeTy->isAnyPointerType())
135     return false;
136   return true;
137 }
138 
139 // Try to retrieve the function declaration and find the function parameter
140 // types which are pointers/references to a non-pointer const.
141 // We will not invalidate the corresponding argument regions.
142 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
143                                  const CallEvent &Call) {
144   unsigned Idx = 0;
145   for (CallEvent::param_type_iterator I = Call.param_type_begin(),
146                                       E = Call.param_type_end();
147        I != E; ++I, ++Idx) {
148     if (isPointerToConst(*I))
149       PreserveArgs.insert(Idx);
150   }
151 }
152 
153 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
154                                              ProgramStateRef Orig) const {
155   ProgramStateRef Result = (Orig ? Orig : getState());
156 
157   // Don't invalidate anything if the callee is marked pure/const.
158   if (const Decl *callee = getDecl())
159     if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
160       return Result;
161 
162   SmallVector<SVal, 8> ValuesToInvalidate;
163   RegionAndSymbolInvalidationTraits ETraits;
164 
165   getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
166 
167   // Indexes of arguments whose values will be preserved by the call.
168   llvm::SmallSet<unsigned, 4> PreserveArgs;
169   if (!argumentsMayEscape())
170     findPtrToConstParams(PreserveArgs, *this);
171 
172   for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
173     // Mark this region for invalidation.  We batch invalidate regions
174     // below for efficiency.
175     if (PreserveArgs.count(Idx))
176       if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
177         ETraits.setTrait(MR->getBaseRegion(),
178                         RegionAndSymbolInvalidationTraits::TK_PreserveContents);
179         // TODO: Factor this out + handle the lower level const pointers.
180 
181     ValuesToInvalidate.push_back(getArgSVal(Idx));
182   }
183 
184   // Invalidate designated regions using the batch invalidation API.
185   // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
186   //  global variables.
187   return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
188                                    BlockCount, getLocationContext(),
189                                    /*CausedByPointerEscape*/ true,
190                                    /*Symbols=*/nullptr, this, &ETraits);
191 }
192 
193 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
194                                         const ProgramPointTag *Tag) const {
195   if (const Expr *E = getOriginExpr()) {
196     if (IsPreVisit)
197       return PreStmt(E, getLocationContext(), Tag);
198     return PostStmt(E, getLocationContext(), Tag);
199   }
200 
201   const Decl *D = getDecl();
202   assert(D && "Cannot get a program point without a statement or decl");
203 
204   SourceLocation Loc = getSourceRange().getBegin();
205   if (IsPreVisit)
206     return PreImplicitCall(D, Loc, getLocationContext(), Tag);
207   return PostImplicitCall(D, Loc, getLocationContext(), Tag);
208 }
209 
210 bool CallEvent::isCalled(const CallDescription &CD) const {
211   assert(getKind() != CE_ObjCMessage && "Obj-C methods are not supported");
212   if (!CD.IsLookupDone) {
213     CD.IsLookupDone = true;
214     CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
215   }
216   const IdentifierInfo *II = getCalleeIdentifier();
217   if (!II || II != CD.II)
218     return false;
219   return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
220           CD.RequiredArgs == getNumArgs());
221 }
222 
223 SVal CallEvent::getArgSVal(unsigned Index) const {
224   const Expr *ArgE = getArgExpr(Index);
225   if (!ArgE)
226     return UnknownVal();
227   return getSVal(ArgE);
228 }
229 
230 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
231   const Expr *ArgE = getArgExpr(Index);
232   if (!ArgE)
233     return SourceRange();
234   return ArgE->getSourceRange();
235 }
236 
237 SVal CallEvent::getReturnValue() const {
238   const Expr *E = getOriginExpr();
239   if (!E)
240     return UndefinedVal();
241   return getSVal(E);
242 }
243 
244 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
245 
246 void CallEvent::dump(raw_ostream &Out) const {
247   ASTContext &Ctx = getState()->getStateManager().getContext();
248   if (const Expr *E = getOriginExpr()) {
249     E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
250     Out << "\n";
251     return;
252   }
253 
254   if (const Decl *D = getDecl()) {
255     Out << "Call to ";
256     D->print(Out, Ctx.getPrintingPolicy());
257     return;
258   }
259 
260   // FIXME: a string representation of the kind would be nice.
261   Out << "Unknown call (type " << getKind() << ")";
262 }
263 
264 
265 bool CallEvent::isCallStmt(const Stmt *S) {
266   return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
267                           || isa<CXXConstructExpr>(S)
268                           || isa<CXXNewExpr>(S);
269 }
270 
271 QualType CallEvent::getDeclaredResultType(const Decl *D) {
272   assert(D);
273   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
274     return FD->getReturnType();
275   if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
276     return MD->getReturnType();
277   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
278     // Blocks are difficult because the return type may not be stored in the
279     // BlockDecl itself. The AST should probably be enhanced, but for now we
280     // just do what we can.
281     // If the block is declared without an explicit argument list, the
282     // signature-as-written just includes the return type, not the entire
283     // function type.
284     // FIXME: All blocks should have signatures-as-written, even if the return
285     // type is inferred. (That's signified with a dependent result type.)
286     if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
287       QualType Ty = TSI->getType();
288       if (const FunctionType *FT = Ty->getAs<FunctionType>())
289         Ty = FT->getReturnType();
290       if (!Ty->isDependentType())
291         return Ty;
292     }
293 
294     return QualType();
295   }
296 
297   llvm_unreachable("unknown callable kind");
298 }
299 
300 bool CallEvent::isVariadic(const Decl *D) {
301   assert(D);
302 
303   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
304     return FD->isVariadic();
305   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
306     return MD->isVariadic();
307   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
308     return BD->isVariadic();
309 
310   llvm_unreachable("unknown callable kind");
311 }
312 
313 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
314                                          CallEvent::BindingsTy &Bindings,
315                                          SValBuilder &SVB,
316                                          const CallEvent &Call,
317                                          ArrayRef<ParmVarDecl*> parameters) {
318   MemRegionManager &MRMgr = SVB.getRegionManager();
319 
320   // If the function has fewer parameters than the call has arguments, we simply
321   // do not bind any values to them.
322   unsigned NumArgs = Call.getNumArgs();
323   unsigned Idx = 0;
324   ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
325   for (; I != E && Idx < NumArgs; ++I, ++Idx) {
326     const ParmVarDecl *ParamDecl = *I;
327     assert(ParamDecl && "Formal parameter has no decl?");
328 
329     SVal ArgVal = Call.getArgSVal(Idx);
330     if (!ArgVal.isUnknown()) {
331       Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
332       Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
333     }
334   }
335 
336   // FIXME: Variadic arguments are not handled at all right now.
337 }
338 
339 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
340   const FunctionDecl *D = getDecl();
341   if (!D)
342     return None;
343   return D->parameters();
344 }
345 
346 
347 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
348   const FunctionDecl *FD = getDecl();
349   // Note that the AnalysisDeclContext will have the FunctionDecl with
350   // the definition (if one exists).
351   if (FD) {
352     AnalysisDeclContext *AD =
353       getLocationContext()->getAnalysisDeclContext()->
354       getManager()->getContext(FD);
355     if (AD->getBody())
356       return RuntimeDefinition(AD->getDecl());
357   }
358 
359   return RuntimeDefinition();
360 }
361 
362 void AnyFunctionCall::getInitialStackFrameContents(
363                                         const StackFrameContext *CalleeCtx,
364                                         BindingsTy &Bindings) const {
365   const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
366   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
367   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
368                                D->parameters());
369 }
370 
371 bool AnyFunctionCall::argumentsMayEscape() const {
372   if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
373     return true;
374 
375   const FunctionDecl *D = getDecl();
376   if (!D)
377     return true;
378 
379   const IdentifierInfo *II = D->getIdentifier();
380   if (!II)
381     return false;
382 
383   // This set of "escaping" APIs is
384 
385   // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
386   //   value into thread local storage. The value can later be retrieved with
387   //   'void *ptheread_getspecific(pthread_key)'. So even thought the
388   //   parameter is 'const void *', the region escapes through the call.
389   if (II->isStr("pthread_setspecific"))
390     return true;
391 
392   // - xpc_connection_set_context stores a value which can be retrieved later
393   //   with xpc_connection_get_context.
394   if (II->isStr("xpc_connection_set_context"))
395     return true;
396 
397   // - funopen - sets a buffer for future IO calls.
398   if (II->isStr("funopen"))
399     return true;
400 
401   // - __cxa_demangle - can reallocate memory and can return the pointer to
402   // the input buffer.
403   if (II->isStr("__cxa_demangle"))
404     return true;
405 
406   StringRef FName = II->getName();
407 
408   // - CoreFoundation functions that end with "NoCopy" can free a passed-in
409   //   buffer even if it is const.
410   if (FName.endswith("NoCopy"))
411     return true;
412 
413   // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
414   //   be deallocated by NSMapRemove.
415   if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
416     return true;
417 
418   // - Many CF containers allow objects to escape through custom
419   //   allocators/deallocators upon container construction. (PR12101)
420   if (FName.startswith("CF") || FName.startswith("CG")) {
421     return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
422            StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
423            StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
424            StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
425            StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
426            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
427   }
428 
429   return false;
430 }
431 
432 
433 const FunctionDecl *SimpleFunctionCall::getDecl() const {
434   const FunctionDecl *D = getOriginExpr()->getDirectCallee();
435   if (D)
436     return D;
437 
438   return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
439 }
440 
441 
442 const FunctionDecl *CXXInstanceCall::getDecl() const {
443   const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
444   if (!CE)
445     return AnyFunctionCall::getDecl();
446 
447   const FunctionDecl *D = CE->getDirectCallee();
448   if (D)
449     return D;
450 
451   return getSVal(CE->getCallee()).getAsFunctionDecl();
452 }
453 
454 void CXXInstanceCall::getExtraInvalidatedValues(
455     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
456   SVal ThisVal = getCXXThisVal();
457   Values.push_back(ThisVal);
458 
459   // Don't invalidate if the method is const and there are no mutable fields.
460   if (const CXXMethodDecl *D = cast_or_null<CXXMethodDecl>(getDecl())) {
461     if (!D->isConst())
462       return;
463     // Get the record decl for the class of 'This'. D->getParent() may return a
464     // base class decl, rather than the class of the instance which needs to be
465     // checked for mutable fields.
466     const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
467     const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl();
468     if (!ParentRecord || ParentRecord->hasMutableFields())
469       return;
470     // Preserve CXXThis.
471     const MemRegion *ThisRegion = ThisVal.getAsRegion();
472     if (!ThisRegion)
473       return;
474 
475     ETraits->setTrait(ThisRegion->getBaseRegion(),
476                       RegionAndSymbolInvalidationTraits::TK_PreserveContents);
477   }
478 }
479 
480 SVal CXXInstanceCall::getCXXThisVal() const {
481   const Expr *Base = getCXXThisExpr();
482   // FIXME: This doesn't handle an overloaded ->* operator.
483   if (!Base)
484     return UnknownVal();
485 
486   SVal ThisVal = getSVal(Base);
487   assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
488   return ThisVal;
489 }
490 
491 
492 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
493   // Do we have a decl at all?
494   const Decl *D = getDecl();
495   if (!D)
496     return RuntimeDefinition();
497 
498   // If the method is non-virtual, we know we can inline it.
499   const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
500   if (!MD->isVirtual())
501     return AnyFunctionCall::getRuntimeDefinition();
502 
503   // Do we know the implicit 'this' object being called?
504   const MemRegion *R = getCXXThisVal().getAsRegion();
505   if (!R)
506     return RuntimeDefinition();
507 
508   // Do we know anything about the type of 'this'?
509   DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
510   if (!DynType.isValid())
511     return RuntimeDefinition();
512 
513   // Is the type a C++ class? (This is mostly a defensive check.)
514   QualType RegionType = DynType.getType()->getPointeeType();
515   assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
516 
517   const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
518   if (!RD || !RD->hasDefinition())
519     return RuntimeDefinition();
520 
521   // Find the decl for this method in that class.
522   const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
523   if (!Result) {
524     // We might not even get the original statically-resolved method due to
525     // some particularly nasty casting (e.g. casts to sister classes).
526     // However, we should at least be able to search up and down our own class
527     // hierarchy, and some real bugs have been caught by checking this.
528     assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
529 
530     // FIXME: This is checking that our DynamicTypeInfo is at least as good as
531     // the static type. However, because we currently don't update
532     // DynamicTypeInfo when an object is cast, we can't actually be sure the
533     // DynamicTypeInfo is up to date. This assert should be re-enabled once
534     // this is fixed. <rdar://problem/12287087>
535     //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
536 
537     return RuntimeDefinition();
538   }
539 
540   // Does the decl that we found have an implementation?
541   const FunctionDecl *Definition;
542   if (!Result->hasBody(Definition))
543     return RuntimeDefinition();
544 
545   // We found a definition. If we're not sure that this devirtualization is
546   // actually what will happen at runtime, make sure to provide the region so
547   // that ExprEngine can decide what to do with it.
548   if (DynType.canBeASubClass())
549     return RuntimeDefinition(Definition, R->StripCasts());
550   return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
551 }
552 
553 void CXXInstanceCall::getInitialStackFrameContents(
554                                             const StackFrameContext *CalleeCtx,
555                                             BindingsTy &Bindings) const {
556   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
557 
558   // Handle the binding of 'this' in the new stack frame.
559   SVal ThisVal = getCXXThisVal();
560   if (!ThisVal.isUnknown()) {
561     ProgramStateManager &StateMgr = getState()->getStateManager();
562     SValBuilder &SVB = StateMgr.getSValBuilder();
563 
564     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
565     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
566 
567     // If we devirtualized to a different member function, we need to make sure
568     // we have the proper layering of CXXBaseObjectRegions.
569     if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
570       ASTContext &Ctx = SVB.getContext();
571       const CXXRecordDecl *Class = MD->getParent();
572       QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
573 
574       // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
575       bool Failed;
576       ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
577       assert(!Failed && "Calling an incorrectly devirtualized method");
578     }
579 
580     if (!ThisVal.isUnknown())
581       Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
582   }
583 }
584 
585 
586 
587 const Expr *CXXMemberCall::getCXXThisExpr() const {
588   return getOriginExpr()->getImplicitObjectArgument();
589 }
590 
591 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
592   // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
593   // id-expression in the class member access expression is a qualified-id,
594   // that function is called. Otherwise, its final overrider in the dynamic type
595   // of the object expression is called.
596   if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
597     if (ME->hasQualifier())
598       return AnyFunctionCall::getRuntimeDefinition();
599 
600   return CXXInstanceCall::getRuntimeDefinition();
601 }
602 
603 
604 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
605   return getOriginExpr()->getArg(0);
606 }
607 
608 
609 const BlockDataRegion *BlockCall::getBlockRegion() const {
610   const Expr *Callee = getOriginExpr()->getCallee();
611   const MemRegion *DataReg = getSVal(Callee).getAsRegion();
612 
613   return dyn_cast_or_null<BlockDataRegion>(DataReg);
614 }
615 
616 ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
617   const BlockDecl *D = getDecl();
618   if (!D)
619     return nullptr;
620   return D->parameters();
621 }
622 
623 void BlockCall::getExtraInvalidatedValues(ValueList &Values,
624                   RegionAndSymbolInvalidationTraits *ETraits) const {
625   // FIXME: This also needs to invalidate captured globals.
626   if (const MemRegion *R = getBlockRegion())
627     Values.push_back(loc::MemRegionVal(R));
628 }
629 
630 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
631                                              BindingsTy &Bindings) const {
632   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
633   ArrayRef<ParmVarDecl*> Params;
634   if (isConversionFromLambda()) {
635     auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
636     Params = LambdaOperatorDecl->parameters();
637 
638     // For blocks converted from a C++ lambda, the callee declaration is the
639     // operator() method on the lambda so we bind "this" to
640     // the lambda captured by the block.
641     const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
642     SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
643     Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
644     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
645   } else {
646     Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
647   }
648 
649   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
650                                Params);
651 }
652 
653 
654 SVal CXXConstructorCall::getCXXThisVal() const {
655   if (Data)
656     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
657   return UnknownVal();
658 }
659 
660 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
661                            RegionAndSymbolInvalidationTraits *ETraits) const {
662   if (Data)
663     Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
664 }
665 
666 void CXXConstructorCall::getInitialStackFrameContents(
667                                              const StackFrameContext *CalleeCtx,
668                                              BindingsTy &Bindings) const {
669   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
670 
671   SVal ThisVal = getCXXThisVal();
672   if (!ThisVal.isUnknown()) {
673     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
674     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
675     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
676     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
677   }
678 }
679 
680 SVal CXXDestructorCall::getCXXThisVal() const {
681   if (Data)
682     return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
683   return UnknownVal();
684 }
685 
686 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
687   // Base destructors are always called non-virtually.
688   // Skip CXXInstanceCall's devirtualization logic in this case.
689   if (isBaseDestructor())
690     return AnyFunctionCall::getRuntimeDefinition();
691 
692   return CXXInstanceCall::getRuntimeDefinition();
693 }
694 
695 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
696   const ObjCMethodDecl *D = getDecl();
697   if (!D)
698     return None;
699   return D->parameters();
700 }
701 
702 void ObjCMethodCall::getExtraInvalidatedValues(
703     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
704 
705   // If the method call is a setter for property known to be backed by
706   // an instance variable, don't invalidate the entire receiver, just
707   // the storage for that instance variable.
708   if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
709     if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
710       SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
711       if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
712         ETraits->setTrait(
713           IvarRegion,
714           RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
715         ETraits->setTrait(
716           IvarRegion,
717           RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
718         Values.push_back(IvarLVal);
719       }
720       return;
721     }
722   }
723 
724   Values.push_back(getReceiverSVal());
725 }
726 
727 SVal ObjCMethodCall::getSelfSVal() const {
728   const LocationContext *LCtx = getLocationContext();
729   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
730   if (!SelfDecl)
731     return SVal();
732   return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
733 }
734 
735 SVal ObjCMethodCall::getReceiverSVal() const {
736   // FIXME: Is this the best way to handle class receivers?
737   if (!isInstanceMessage())
738     return UnknownVal();
739 
740   if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
741     return getSVal(RecE);
742 
743   // An instance message with no expression means we are sending to super.
744   // In this case the object reference is the same as 'self'.
745   assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
746   SVal SelfVal = getSelfSVal();
747   assert(SelfVal.isValid() && "Calling super but not in ObjC method");
748   return SelfVal;
749 }
750 
751 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
752   if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
753       getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
754       return true;
755 
756   if (!isInstanceMessage())
757     return false;
758 
759   SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
760 
761   return (RecVal == getSelfSVal());
762 }
763 
764 SourceRange ObjCMethodCall::getSourceRange() const {
765   switch (getMessageKind()) {
766   case OCM_Message:
767     return getOriginExpr()->getSourceRange();
768   case OCM_PropertyAccess:
769   case OCM_Subscript:
770     return getContainingPseudoObjectExpr()->getSourceRange();
771   }
772   llvm_unreachable("unknown message kind");
773 }
774 
775 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
776 
777 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
778   assert(Data && "Lazy lookup not yet performed.");
779   assert(getMessageKind() != OCM_Message && "Explicit message send.");
780   return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
781 }
782 
783 static const Expr *
784 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
785   const Expr *Syntactic = POE->getSyntacticForm();
786 
787   // This handles the funny case of assigning to the result of a getter.
788   // This can happen if the getter returns a non-const reference.
789   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
790     Syntactic = BO->getLHS();
791 
792   return Syntactic;
793 }
794 
795 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
796   if (!Data) {
797 
798     // Find the parent, ignoring implicit casts.
799     ParentMap &PM = getLocationContext()->getParentMap();
800     const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
801 
802     // Check if parent is a PseudoObjectExpr.
803     if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
804       const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
805 
806       ObjCMessageKind K;
807       switch (Syntactic->getStmtClass()) {
808       case Stmt::ObjCPropertyRefExprClass:
809         K = OCM_PropertyAccess;
810         break;
811       case Stmt::ObjCSubscriptRefExprClass:
812         K = OCM_Subscript;
813         break;
814       default:
815         // FIXME: Can this ever happen?
816         K = OCM_Message;
817         break;
818       }
819 
820       if (K != OCM_Message) {
821         const_cast<ObjCMethodCall *>(this)->Data
822           = ObjCMessageDataTy(POE, K).getOpaqueValue();
823         assert(getMessageKind() == K);
824         return K;
825       }
826     }
827 
828     const_cast<ObjCMethodCall *>(this)->Data
829       = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
830     assert(getMessageKind() == OCM_Message);
831     return OCM_Message;
832   }
833 
834   ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
835   if (!Info.getPointer())
836     return OCM_Message;
837   return static_cast<ObjCMessageKind>(Info.getInt());
838 }
839 
840 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
841   // Look for properties accessed with property syntax (foo.bar = ...)
842   if ( getMessageKind() == OCM_PropertyAccess) {
843     const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
844     assert(POE && "Property access without PseudoObjectExpr?");
845 
846     const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
847     auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
848 
849     if (RefExpr->isExplicitProperty())
850       return RefExpr->getExplicitProperty();
851   }
852 
853   // Look for properties accessed with method syntax ([foo setBar:...]).
854   const ObjCMethodDecl *MD = getDecl();
855   if (!MD || !MD->isPropertyAccessor())
856     return nullptr;
857 
858   // Note: This is potentially quite slow.
859   return MD->findPropertyDecl();
860 }
861 
862 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
863                                              Selector Sel) const {
864   assert(IDecl);
865   const SourceManager &SM =
866     getState()->getStateManager().getContext().getSourceManager();
867 
868   // If the class interface is declared inside the main file, assume it is not
869   // subcassed.
870   // TODO: It could actually be subclassed if the subclass is private as well.
871   // This is probably very rare.
872   SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
873   if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
874     return false;
875 
876   // Assume that property accessors are not overridden.
877   if (getMessageKind() == OCM_PropertyAccess)
878     return false;
879 
880   // We assume that if the method is public (declared outside of main file) or
881   // has a parent which publicly declares the method, the method could be
882   // overridden in a subclass.
883 
884   // Find the first declaration in the class hierarchy that declares
885   // the selector.
886   ObjCMethodDecl *D = nullptr;
887   while (true) {
888     D = IDecl->lookupMethod(Sel, true);
889 
890     // Cannot find a public definition.
891     if (!D)
892       return false;
893 
894     // If outside the main file,
895     if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
896       return true;
897 
898     if (D->isOverriding()) {
899       // Search in the superclass on the next iteration.
900       IDecl = D->getClassInterface();
901       if (!IDecl)
902         return false;
903 
904       IDecl = IDecl->getSuperClass();
905       if (!IDecl)
906         return false;
907 
908       continue;
909     }
910 
911     return false;
912   };
913 
914   llvm_unreachable("The while loop should always terminate.");
915 }
916 
917 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
918   if (!MD)
919     return MD;
920 
921   // Find the redeclaration that defines the method.
922   if (!MD->hasBody()) {
923     for (auto I : MD->redecls())
924       if (I->hasBody())
925         MD = cast<ObjCMethodDecl>(I);
926   }
927   return MD;
928 }
929 
930 static bool isCallToSelfClass(const ObjCMessageExpr *ME) {
931   const Expr* InstRec = ME->getInstanceReceiver();
932   if (!InstRec)
933     return false;
934   const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts());
935 
936   // Check that receiver is called 'self'.
937   if (!InstRecIg || !InstRecIg->getFoundDecl() ||
938       !InstRecIg->getFoundDecl()->getName().equals("self"))
939     return false;
940 
941   // Check that the method name is 'class'.
942   if (ME->getSelector().getNumArgs() != 0 ||
943       !ME->getSelector().getNameForSlot(0).equals("class"))
944     return false;
945 
946   return true;
947 }
948 
949 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
950   const ObjCMessageExpr *E = getOriginExpr();
951   assert(E);
952   Selector Sel = E->getSelector();
953 
954   if (E->isInstanceMessage()) {
955 
956     // Find the receiver type.
957     const ObjCObjectPointerType *ReceiverT = nullptr;
958     bool CanBeSubClassed = false;
959     QualType SupersType = E->getSuperType();
960     const MemRegion *Receiver = nullptr;
961 
962     if (!SupersType.isNull()) {
963       // The receiver is guaranteed to be 'super' in this case.
964       // Super always means the type of immediate predecessor to the method
965       // where the call occurs.
966       ReceiverT = cast<ObjCObjectPointerType>(SupersType);
967     } else {
968       Receiver = getReceiverSVal().getAsRegion();
969       if (!Receiver)
970         return RuntimeDefinition();
971 
972       DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
973       if (!DTI.isValid()) {
974         assert(isa<AllocaRegion>(Receiver) &&
975                "Unhandled untyped region class!");
976         return RuntimeDefinition();
977       }
978 
979       QualType DynType = DTI.getType();
980       CanBeSubClassed = DTI.canBeASubClass();
981       ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
982 
983       if (ReceiverT && CanBeSubClassed)
984         if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
985           if (!canBeOverridenInSubclass(IDecl, Sel))
986             CanBeSubClassed = false;
987     }
988 
989     // Handle special cases of '[self classMethod]' and
990     // '[[self class] classMethod]', which are treated by the compiler as
991     // instance (not class) messages. We will statically dispatch to those.
992     if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) {
993       // For [self classMethod], return the compiler visible declaration.
994       if (PT->getObjectType()->isObjCClass() &&
995           Receiver == getSelfSVal().getAsRegion())
996         return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
997 
998       // Similarly, handle [[self class] classMethod].
999       // TODO: We are currently doing a syntactic match for this pattern with is
1000       // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m
1001       // shows. A better way would be to associate the meta type with the symbol
1002       // using the dynamic type info tracking and use it here. We can add a new
1003       // SVal for ObjC 'Class' values that know what interface declaration they
1004       // come from. Then 'self' in a class method would be filled in with
1005       // something meaningful in ObjCMethodCall::getReceiverSVal() and we could
1006       // do proper dynamic dispatch for class methods just like we do for
1007       // instance methods now.
1008       if (E->getInstanceReceiver())
1009         if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver()))
1010           if (isCallToSelfClass(M))
1011             return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1012     }
1013 
1014     // Lookup the instance method implementation.
1015     if (ReceiverT)
1016       if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
1017         // Repeatedly calling lookupPrivateMethod() is expensive, especially
1018         // when in many cases it returns null.  We cache the results so
1019         // that repeated queries on the same ObjCIntefaceDecl and Selector
1020         // don't incur the same cost.  On some test cases, we can see the
1021         // same query being issued thousands of times.
1022         //
1023         // NOTE: This cache is essentially a "global" variable, but it
1024         // only gets lazily created when we get here.  The value of the
1025         // cache probably comes from it being global across ExprEngines,
1026         // where the same queries may get issued.  If we are worried about
1027         // concurrency, or possibly loading/unloading ASTs, etc., we may
1028         // need to revisit this someday.  In terms of memory, this table
1029         // stays around until clang quits, which also may be bad if we
1030         // need to release memory.
1031         typedef std::pair<const ObjCInterfaceDecl*, Selector>
1032                 PrivateMethodKey;
1033         typedef llvm::DenseMap<PrivateMethodKey,
1034                                Optional<const ObjCMethodDecl *> >
1035                 PrivateMethodCache;
1036 
1037         static PrivateMethodCache PMC;
1038         Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
1039 
1040         // Query lookupPrivateMethod() if the cache does not hit.
1041         if (!Val.hasValue()) {
1042           Val = IDecl->lookupPrivateMethod(Sel);
1043 
1044           // If the method is a property accessor, we should try to "inline" it
1045           // even if we don't actually have an implementation.
1046           if (!*Val)
1047             if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
1048               if (CompileTimeMD->isPropertyAccessor()) {
1049                 if (!CompileTimeMD->getSelfDecl() &&
1050                     isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
1051                   // If the method is an accessor in a category, and it doesn't
1052                   // have a self declaration, first
1053                   // try to find the method in a class extension. This
1054                   // works around a bug in Sema where multiple accessors
1055                   // are synthesized for properties in class
1056                   // extensions that are redeclared in a category and the
1057                   // the implicit parameters are not filled in for
1058                   // the method on the category.
1059                   // This ensures we find the accessor in the extension, which
1060                   // has the implicit parameters filled in.
1061                   auto *ID = CompileTimeMD->getClassInterface();
1062                   for (auto *CatDecl : ID->visible_extensions()) {
1063                     Val = CatDecl->getMethod(Sel,
1064                                              CompileTimeMD->isInstanceMethod());
1065                     if (*Val)
1066                       break;
1067                   }
1068                 }
1069                 if (!*Val)
1070                   Val = IDecl->lookupInstanceMethod(Sel);
1071               }
1072         }
1073 
1074         const ObjCMethodDecl *MD = Val.getValue();
1075         if (CanBeSubClassed)
1076           return RuntimeDefinition(MD, Receiver);
1077         else
1078           return RuntimeDefinition(MD, nullptr);
1079       }
1080 
1081   } else {
1082     // This is a class method.
1083     // If we have type info for the receiver class, we are calling via
1084     // class name.
1085     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1086       // Find/Return the method implementation.
1087       return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1088     }
1089   }
1090 
1091   return RuntimeDefinition();
1092 }
1093 
1094 bool ObjCMethodCall::argumentsMayEscape() const {
1095   if (isInSystemHeader() && !isInstanceMessage()) {
1096     Selector Sel = getSelector();
1097     if (Sel.getNumArgs() == 1 &&
1098         Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1099       return true;
1100   }
1101 
1102   return CallEvent::argumentsMayEscape();
1103 }
1104 
1105 void ObjCMethodCall::getInitialStackFrameContents(
1106                                              const StackFrameContext *CalleeCtx,
1107                                              BindingsTy &Bindings) const {
1108   const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1109   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1110   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1111                                D->parameters());
1112 
1113   SVal SelfVal = getReceiverSVal();
1114   if (!SelfVal.isUnknown()) {
1115     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1116     MemRegionManager &MRMgr = SVB.getRegionManager();
1117     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1118     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1119   }
1120 }
1121 
1122 CallEventRef<>
1123 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1124                                 const LocationContext *LCtx) {
1125   if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1126     return create<CXXMemberCall>(MCE, State, LCtx);
1127 
1128   if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1129     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1130     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1131       if (MD->isInstance())
1132         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1133 
1134   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1135     return create<BlockCall>(CE, State, LCtx);
1136   }
1137 
1138   // Otherwise, it's a normal function call, static member function call, or
1139   // something we can't reason about.
1140   return create<SimpleFunctionCall>(CE, State, LCtx);
1141 }
1142 
1143 
1144 CallEventRef<>
1145 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1146                             ProgramStateRef State) {
1147   const LocationContext *ParentCtx = CalleeCtx->getParent();
1148   const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
1149   assert(CallerCtx && "This should not be used for top-level stack frames");
1150 
1151   const Stmt *CallSite = CalleeCtx->getCallSite();
1152 
1153   if (CallSite) {
1154     if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
1155       return getSimpleCall(CE, State, CallerCtx);
1156 
1157     switch (CallSite->getStmtClass()) {
1158     case Stmt::CXXConstructExprClass:
1159     case Stmt::CXXTemporaryObjectExprClass: {
1160       SValBuilder &SVB = State->getStateManager().getSValBuilder();
1161       const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1162       Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1163       SVal ThisVal = State->getSVal(ThisPtr);
1164 
1165       return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
1166                                    ThisVal.getAsRegion(), State, CallerCtx);
1167     }
1168     case Stmt::CXXNewExprClass:
1169       return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
1170     case Stmt::ObjCMessageExprClass:
1171       return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
1172                                State, CallerCtx);
1173     default:
1174       llvm_unreachable("This is not an inlineable statement.");
1175     }
1176   }
1177 
1178   // Fall back to the CFG. The only thing we haven't handled yet is
1179   // destructors, though this could change in the future.
1180   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1181   CFGElement E = (*B)[CalleeCtx->getIndex()];
1182   assert(E.getAs<CFGImplicitDtor>() &&
1183          "All other CFG elements should have exprs");
1184   assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
1185 
1186   SValBuilder &SVB = State->getStateManager().getSValBuilder();
1187   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1188   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1189   SVal ThisVal = State->getSVal(ThisPtr);
1190 
1191   const Stmt *Trigger;
1192   if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1193     Trigger = AutoDtor->getTriggerStmt();
1194   else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1195     Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
1196   else
1197     Trigger = Dtor->getBody();
1198 
1199   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1200                               E.getAs<CFGBaseDtor>().hasValue(), State,
1201                               CallerCtx);
1202 }
1203