xref: /freebsd-src/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/CallEvent.cpp (revision 8cc087a1eee9ec1ca9f7ac1e63ad51bdb5a682eb)
1 //===- CallEvent.cpp - Wrapper for all function and method calls ----------===//
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 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
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/ParentMap.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Analysis/AnalysisDeclContext.h"
29 #include "clang/Analysis/CFG.h"
30 #include "clang/Analysis/CFGStmtMap.h"
31 #include "clang/Analysis/PathDiagnostic.h"
32 #include "clang/Analysis/ProgramPoint.h"
33 #include "clang/Basic/IdentifierTable.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/CrossTU/CrossTranslationUnit.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/ImmutableList.h"
52 #include "llvm/ADT/None.h"
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/ADT/PointerIntPair.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include <cassert>
65 #include <utility>
66 
67 #define DEBUG_TYPE "static-analyzer-call-event"
68 
69 using namespace clang;
70 using namespace ento;
71 
72 QualType CallEvent::getResultType() const {
73   ASTContext &Ctx = getState()->getStateManager().getContext();
74   const Expr *E = getOriginExpr();
75   if (!E)
76     return Ctx.VoidTy;
77   return Ctx.getReferenceQualifiedType(E);
78 }
79 
80 static bool isCallback(QualType T) {
81   // If a parameter is a block or a callback, assume it can modify pointer.
82   if (T->isBlockPointerType() ||
83       T->isFunctionPointerType() ||
84       T->isObjCSelType())
85     return true;
86 
87   // Check if a callback is passed inside a struct (for both, struct passed by
88   // reference and by value). Dig just one level into the struct for now.
89 
90   if (T->isAnyPointerType() || T->isReferenceType())
91     T = T->getPointeeType();
92 
93   if (const RecordType *RT = T->getAsStructureType()) {
94     const RecordDecl *RD = RT->getDecl();
95     for (const auto *I : RD->fields()) {
96       QualType FieldT = I->getType();
97       if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
98         return true;
99     }
100   }
101   return false;
102 }
103 
104 static bool isVoidPointerToNonConst(QualType T) {
105   if (const auto *PT = T->getAs<PointerType>()) {
106     QualType PointeeTy = PT->getPointeeType();
107     if (PointeeTy.isConstQualified())
108       return false;
109     return PointeeTy->isVoidType();
110   } else
111     return false;
112 }
113 
114 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
115   unsigned NumOfArgs = getNumArgs();
116 
117   // If calling using a function pointer, assume the function does not
118   // satisfy the callback.
119   // TODO: We could check the types of the arguments here.
120   if (!getDecl())
121     return false;
122 
123   unsigned Idx = 0;
124   for (CallEvent::param_type_iterator I = param_type_begin(),
125                                       E = param_type_end();
126        I != E && Idx < NumOfArgs; ++I, ++Idx) {
127     // If the parameter is 0, it's harmless.
128     if (getArgSVal(Idx).isZeroConstant())
129       continue;
130 
131     if (Condition(*I))
132       return true;
133   }
134   return false;
135 }
136 
137 bool CallEvent::hasNonZeroCallbackArg() const {
138   return hasNonNullArgumentsWithType(isCallback);
139 }
140 
141 bool CallEvent::hasVoidPointerToNonConstArg() const {
142   return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
143 }
144 
145 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
146   const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
147   if (!FD)
148     return false;
149 
150   return CheckerContext::isCLibraryFunction(FD, FunctionName);
151 }
152 
153 AnalysisDeclContext *CallEvent::getCalleeAnalysisDeclContext() const {
154   const Decl *D = getDecl();
155   if (!D)
156     return nullptr;
157 
158   AnalysisDeclContext *ADC =
159       LCtx->getAnalysisDeclContext()->getManager()->getContext(D);
160 
161   return ADC;
162 }
163 
164 const StackFrameContext *
165 CallEvent::getCalleeStackFrame(unsigned BlockCount) const {
166   AnalysisDeclContext *ADC = getCalleeAnalysisDeclContext();
167   if (!ADC)
168     return nullptr;
169 
170   const Expr *E = getOriginExpr();
171   if (!E)
172     return nullptr;
173 
174   // Recover CFG block via reverse lookup.
175   // TODO: If we were to keep CFG element information as part of the CallEvent
176   // instead of doing this reverse lookup, we would be able to build the stack
177   // frame for non-expression-based calls, and also we wouldn't need the reverse
178   // lookup.
179   CFGStmtMap *Map = LCtx->getAnalysisDeclContext()->getCFGStmtMap();
180   const CFGBlock *B = Map->getBlock(E);
181   assert(B);
182 
183   // Also recover CFG index by scanning the CFG block.
184   unsigned Idx = 0, Sz = B->size();
185   for (; Idx < Sz; ++Idx)
186     if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>())
187       if (StmtElem->getStmt() == E)
188         break;
189   assert(Idx < Sz);
190 
191   return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, BlockCount, Idx);
192 }
193 
194 const ParamVarRegion
195 *CallEvent::getParameterLocation(unsigned Index, unsigned BlockCount) const {
196   const StackFrameContext *SFC = getCalleeStackFrame(BlockCount);
197   // We cannot construct a VarRegion without a stack frame.
198   if (!SFC)
199     return nullptr;
200 
201   const ParamVarRegion *PVR =
202     State->getStateManager().getRegionManager().getParamVarRegion(
203         getOriginExpr(), Index, SFC);
204   return PVR;
205 }
206 
207 /// Returns true if a type is a pointer-to-const or reference-to-const
208 /// with no further indirection.
209 static bool isPointerToConst(QualType Ty) {
210   QualType PointeeTy = Ty->getPointeeType();
211   if (PointeeTy == QualType())
212     return false;
213   if (!PointeeTy.isConstQualified())
214     return false;
215   if (PointeeTy->isAnyPointerType())
216     return false;
217   return true;
218 }
219 
220 // Try to retrieve the function declaration and find the function parameter
221 // types which are pointers/references to a non-pointer const.
222 // We will not invalidate the corresponding argument regions.
223 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
224                                  const CallEvent &Call) {
225   unsigned Idx = 0;
226   for (CallEvent::param_type_iterator I = Call.param_type_begin(),
227                                       E = Call.param_type_end();
228        I != E; ++I, ++Idx) {
229     if (isPointerToConst(*I))
230       PreserveArgs.insert(Idx);
231   }
232 }
233 
234 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
235                                              ProgramStateRef Orig) const {
236   ProgramStateRef Result = (Orig ? Orig : getState());
237 
238   // Don't invalidate anything if the callee is marked pure/const.
239   if (const Decl *callee = getDecl())
240     if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
241       return Result;
242 
243   SmallVector<SVal, 8> ValuesToInvalidate;
244   RegionAndSymbolInvalidationTraits ETraits;
245 
246   getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
247 
248   // Indexes of arguments whose values will be preserved by the call.
249   llvm::SmallSet<unsigned, 4> PreserveArgs;
250   if (!argumentsMayEscape())
251     findPtrToConstParams(PreserveArgs, *this);
252 
253   for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
254     // Mark this region for invalidation.  We batch invalidate regions
255     // below for efficiency.
256     if (PreserveArgs.count(Idx))
257       if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
258         ETraits.setTrait(MR->getBaseRegion(),
259                         RegionAndSymbolInvalidationTraits::TK_PreserveContents);
260         // TODO: Factor this out + handle the lower level const pointers.
261 
262     ValuesToInvalidate.push_back(getArgSVal(Idx));
263 
264     // If a function accepts an object by argument (which would of course be a
265     // temporary that isn't lifetime-extended), invalidate the object itself,
266     // not only other objects reachable from it. This is necessary because the
267     // destructor has access to the temporary object after the call.
268     // TODO: Support placement arguments once we start
269     // constructing them directly.
270     // TODO: This is unnecessary when there's no destructor, but that's
271     // currently hard to figure out.
272     if (getKind() != CE_CXXAllocator)
273       if (isArgumentConstructedDirectly(Idx))
274         if (auto AdjIdx = getAdjustedParameterIndex(Idx))
275           if (const TypedValueRegion *TVR =
276                   getParameterLocation(*AdjIdx, BlockCount))
277             ValuesToInvalidate.push_back(loc::MemRegionVal(TVR));
278   }
279 
280   // Invalidate designated regions using the batch invalidation API.
281   // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
282   //  global variables.
283   return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
284                                    BlockCount, getLocationContext(),
285                                    /*CausedByPointerEscape*/ true,
286                                    /*Symbols=*/nullptr, this, &ETraits);
287 }
288 
289 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
290                                         const ProgramPointTag *Tag) const {
291   if (const Expr *E = getOriginExpr()) {
292     if (IsPreVisit)
293       return PreStmt(E, getLocationContext(), Tag);
294     return PostStmt(E, getLocationContext(), Tag);
295   }
296 
297   const Decl *D = getDecl();
298   assert(D && "Cannot get a program point without a statement or decl");
299 
300   SourceLocation Loc = getSourceRange().getBegin();
301   if (IsPreVisit)
302     return PreImplicitCall(D, Loc, getLocationContext(), Tag);
303   return PostImplicitCall(D, Loc, getLocationContext(), Tag);
304 }
305 
306 SVal CallEvent::getArgSVal(unsigned Index) const {
307   const Expr *ArgE = getArgExpr(Index);
308   if (!ArgE)
309     return UnknownVal();
310   return getSVal(ArgE);
311 }
312 
313 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
314   const Expr *ArgE = getArgExpr(Index);
315   if (!ArgE)
316     return {};
317   return ArgE->getSourceRange();
318 }
319 
320 SVal CallEvent::getReturnValue() const {
321   const Expr *E = getOriginExpr();
322   if (!E)
323     return UndefinedVal();
324   return getSVal(E);
325 }
326 
327 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
328 
329 void CallEvent::dump(raw_ostream &Out) const {
330   ASTContext &Ctx = getState()->getStateManager().getContext();
331   if (const Expr *E = getOriginExpr()) {
332     E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
333     return;
334   }
335 
336   if (const Decl *D = getDecl()) {
337     Out << "Call to ";
338     D->print(Out, Ctx.getPrintingPolicy());
339     return;
340   }
341 
342   Out << "Unknown call (type " << getKindAsString() << ")";
343 }
344 
345 bool CallEvent::isCallStmt(const Stmt *S) {
346   return isa<CallExpr, ObjCMessageExpr, CXXConstructExpr, CXXNewExpr>(S);
347 }
348 
349 QualType CallEvent::getDeclaredResultType(const Decl *D) {
350   assert(D);
351   if (const auto *FD = dyn_cast<FunctionDecl>(D))
352     return FD->getReturnType();
353   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
354     return MD->getReturnType();
355   if (const auto *BD = dyn_cast<BlockDecl>(D)) {
356     // Blocks are difficult because the return type may not be stored in the
357     // BlockDecl itself. The AST should probably be enhanced, but for now we
358     // just do what we can.
359     // If the block is declared without an explicit argument list, the
360     // signature-as-written just includes the return type, not the entire
361     // function type.
362     // FIXME: All blocks should have signatures-as-written, even if the return
363     // type is inferred. (That's signified with a dependent result type.)
364     if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
365       QualType Ty = TSI->getType();
366       if (const FunctionType *FT = Ty->getAs<FunctionType>())
367         Ty = FT->getReturnType();
368       if (!Ty->isDependentType())
369         return Ty;
370     }
371 
372     return {};
373   }
374 
375   llvm_unreachable("unknown callable kind");
376 }
377 
378 bool CallEvent::isVariadic(const Decl *D) {
379   assert(D);
380 
381   if (const auto *FD = dyn_cast<FunctionDecl>(D))
382     return FD->isVariadic();
383   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
384     return MD->isVariadic();
385   if (const auto *BD = dyn_cast<BlockDecl>(D))
386     return BD->isVariadic();
387 
388   llvm_unreachable("unknown callable kind");
389 }
390 
391 static bool isTransparentUnion(QualType T) {
392   const RecordType *UT = T->getAsUnionType();
393   return UT && UT->getDecl()->hasAttr<TransparentUnionAttr>();
394 }
395 
396 // In some cases, symbolic cases should be transformed before we associate
397 // them with parameters.  This function incapsulates such cases.
398 static SVal processArgument(SVal Value, const Expr *ArgumentExpr,
399                             const ParmVarDecl *Parameter, SValBuilder &SVB) {
400   QualType ParamType = Parameter->getType();
401   QualType ArgumentType = ArgumentExpr->getType();
402 
403   // Transparent unions allow users to easily convert values of union field
404   // types into union-typed objects.
405   //
406   // Also, more importantly, they allow users to define functions with different
407   // different parameter types, substituting types matching transparent union
408   // field types with the union type itself.
409   //
410   // Here, we check specifically for latter cases and prevent binding
411   // field-typed values to union-typed regions.
412   if (isTransparentUnion(ParamType) &&
413       // Let's check that we indeed trying to bind different types.
414       !isTransparentUnion(ArgumentType)) {
415     BasicValueFactory &BVF = SVB.getBasicValueFactory();
416 
417     llvm::ImmutableList<SVal> CompoundSVals = BVF.getEmptySValList();
418     CompoundSVals = BVF.prependSVal(Value, CompoundSVals);
419 
420     // Wrap it with compound value.
421     return SVB.makeCompoundVal(ParamType, CompoundSVals);
422   }
423 
424   return Value;
425 }
426 
427 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
428                                          CallEvent::BindingsTy &Bindings,
429                                          SValBuilder &SVB,
430                                          const CallEvent &Call,
431                                          ArrayRef<ParmVarDecl*> parameters) {
432   MemRegionManager &MRMgr = SVB.getRegionManager();
433 
434   // If the function has fewer parameters than the call has arguments, we simply
435   // do not bind any values to them.
436   unsigned NumArgs = Call.getNumArgs();
437   unsigned Idx = 0;
438   ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
439   for (; I != E && Idx < NumArgs; ++I, ++Idx) {
440     assert(*I && "Formal parameter has no decl?");
441 
442     // TODO: Support allocator calls.
443     if (Call.getKind() != CE_CXXAllocator)
444       if (Call.isArgumentConstructedDirectly(Call.getASTArgumentIndex(Idx)))
445         continue;
446 
447     // TODO: Allocators should receive the correct size and possibly alignment,
448     // determined in compile-time but not represented as arg-expressions,
449     // which makes getArgSVal() fail and return UnknownVal.
450     SVal ArgVal = Call.getArgSVal(Idx);
451     const Expr *ArgExpr = Call.getArgExpr(Idx);
452     if (!ArgVal.isUnknown()) {
453       Loc ParamLoc = SVB.makeLoc(
454           MRMgr.getParamVarRegion(Call.getOriginExpr(), Idx, CalleeCtx));
455       Bindings.push_back(
456           std::make_pair(ParamLoc, processArgument(ArgVal, ArgExpr, *I, SVB)));
457     }
458   }
459 
460   // FIXME: Variadic arguments are not handled at all right now.
461 }
462 
463 const ConstructionContext *CallEvent::getConstructionContext() const {
464   const StackFrameContext *StackFrame = getCalleeStackFrame(0);
465   if (!StackFrame)
466     return nullptr;
467 
468   const CFGElement Element = StackFrame->getCallSiteCFGElement();
469   if (const auto Ctor = Element.getAs<CFGConstructor>()) {
470     return Ctor->getConstructionContext();
471   }
472 
473   if (const auto RecCall = Element.getAs<CFGCXXRecordTypedCall>()) {
474     return RecCall->getConstructionContext();
475   }
476 
477   return nullptr;
478 }
479 
480 Optional<SVal>
481 CallEvent::getReturnValueUnderConstruction() const {
482   const auto *CC = getConstructionContext();
483   if (!CC)
484     return None;
485 
486   EvalCallOptions CallOpts;
487   ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
488   SVal RetVal =
489     Engine.computeObjectUnderConstruction(getOriginExpr(), getState(),
490                                           getLocationContext(), CC, CallOpts);
491   return RetVal;
492 }
493 
494 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
495   const FunctionDecl *D = getDecl();
496   if (!D)
497     return None;
498   return D->parameters();
499 }
500 
501 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
502   const FunctionDecl *FD = getDecl();
503   if (!FD)
504     return {};
505 
506   // Note that the AnalysisDeclContext will have the FunctionDecl with
507   // the definition (if one exists).
508   AnalysisDeclContext *AD =
509     getLocationContext()->getAnalysisDeclContext()->
510     getManager()->getContext(FD);
511   bool IsAutosynthesized;
512   Stmt* Body = AD->getBody(IsAutosynthesized);
513   LLVM_DEBUG({
514     if (IsAutosynthesized)
515       llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
516                    << "\n";
517   });
518   if (Body) {
519     const Decl* Decl = AD->getDecl();
520     return RuntimeDefinition(Decl);
521   }
522 
523   ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
524   AnalyzerOptions &Opts = Engine.getAnalysisManager().options;
525 
526   // Try to get CTU definition only if CTUDir is provided.
527   if (!Opts.IsNaiveCTUEnabled)
528     return {};
529 
530   cross_tu::CrossTranslationUnitContext &CTUCtx =
531       *Engine.getCrossTranslationUnitContext();
532   llvm::Expected<const FunctionDecl *> CTUDeclOrError =
533       CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName,
534                                   Opts.DisplayCTUProgress);
535 
536   if (!CTUDeclOrError) {
537     handleAllErrors(CTUDeclOrError.takeError(),
538                     [&](const cross_tu::IndexError &IE) {
539                       CTUCtx.emitCrossTUDiagnostics(IE);
540                     });
541     return {};
542   }
543 
544   return RuntimeDefinition(*CTUDeclOrError);
545 }
546 
547 void AnyFunctionCall::getInitialStackFrameContents(
548                                         const StackFrameContext *CalleeCtx,
549                                         BindingsTy &Bindings) const {
550   const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl());
551   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
552   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
553                                D->parameters());
554 }
555 
556 bool AnyFunctionCall::argumentsMayEscape() const {
557   if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
558     return true;
559 
560   const FunctionDecl *D = getDecl();
561   if (!D)
562     return true;
563 
564   const IdentifierInfo *II = D->getIdentifier();
565   if (!II)
566     return false;
567 
568   // This set of "escaping" APIs is
569 
570   // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
571   //   value into thread local storage. The value can later be retrieved with
572   //   'void *ptheread_getspecific(pthread_key)'. So even thought the
573   //   parameter is 'const void *', the region escapes through the call.
574   if (II->isStr("pthread_setspecific"))
575     return true;
576 
577   // - xpc_connection_set_context stores a value which can be retrieved later
578   //   with xpc_connection_get_context.
579   if (II->isStr("xpc_connection_set_context"))
580     return true;
581 
582   // - funopen - sets a buffer for future IO calls.
583   if (II->isStr("funopen"))
584     return true;
585 
586   // - __cxa_demangle - can reallocate memory and can return the pointer to
587   // the input buffer.
588   if (II->isStr("__cxa_demangle"))
589     return true;
590 
591   StringRef FName = II->getName();
592 
593   // - CoreFoundation functions that end with "NoCopy" can free a passed-in
594   //   buffer even if it is const.
595   if (FName.endswith("NoCopy"))
596     return true;
597 
598   // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
599   //   be deallocated by NSMapRemove.
600   if (FName.startswith("NS") && FName.contains("Insert"))
601     return true;
602 
603   // - Many CF containers allow objects to escape through custom
604   //   allocators/deallocators upon container construction. (PR12101)
605   if (FName.startswith("CF") || FName.startswith("CG")) {
606     return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
607            StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
608            StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
609            StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
610            StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
611            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
612   }
613 
614   return false;
615 }
616 
617 const FunctionDecl *SimpleFunctionCall::getDecl() const {
618   const FunctionDecl *D = getOriginExpr()->getDirectCallee();
619   if (D)
620     return D;
621 
622   return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
623 }
624 
625 const FunctionDecl *CXXInstanceCall::getDecl() const {
626   const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
627   if (!CE)
628     return AnyFunctionCall::getDecl();
629 
630   const FunctionDecl *D = CE->getDirectCallee();
631   if (D)
632     return D;
633 
634   return getSVal(CE->getCallee()).getAsFunctionDecl();
635 }
636 
637 void CXXInstanceCall::getExtraInvalidatedValues(
638     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
639   SVal ThisVal = getCXXThisVal();
640   Values.push_back(ThisVal);
641 
642   // Don't invalidate if the method is const and there are no mutable fields.
643   if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) {
644     if (!D->isConst())
645       return;
646     // Get the record decl for the class of 'This'. D->getParent() may return a
647     // base class decl, rather than the class of the instance which needs to be
648     // checked for mutable fields.
649     // TODO: We might as well look at the dynamic type of the object.
650     const Expr *Ex = getCXXThisExpr()->IgnoreParenBaseCasts();
651     QualType T = Ex->getType();
652     if (T->isPointerType()) // Arrow or implicit-this syntax?
653       T = T->getPointeeType();
654     const CXXRecordDecl *ParentRecord = T->getAsCXXRecordDecl();
655     assert(ParentRecord);
656     if (ParentRecord->hasMutableFields())
657       return;
658     // Preserve CXXThis.
659     const MemRegion *ThisRegion = ThisVal.getAsRegion();
660     if (!ThisRegion)
661       return;
662 
663     ETraits->setTrait(ThisRegion->getBaseRegion(),
664                       RegionAndSymbolInvalidationTraits::TK_PreserveContents);
665   }
666 }
667 
668 SVal CXXInstanceCall::getCXXThisVal() const {
669   const Expr *Base = getCXXThisExpr();
670   // FIXME: This doesn't handle an overloaded ->* operator.
671   if (!Base)
672     return UnknownVal();
673 
674   SVal ThisVal = getSVal(Base);
675   assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
676   return ThisVal;
677 }
678 
679 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
680   // Do we have a decl at all?
681   const Decl *D = getDecl();
682   if (!D)
683     return {};
684 
685   // If the method is non-virtual, we know we can inline it.
686   const auto *MD = cast<CXXMethodDecl>(D);
687   if (!MD->isVirtual())
688     return AnyFunctionCall::getRuntimeDefinition();
689 
690   // Do we know the implicit 'this' object being called?
691   const MemRegion *R = getCXXThisVal().getAsRegion();
692   if (!R)
693     return {};
694 
695   // Do we know anything about the type of 'this'?
696   DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
697   if (!DynType.isValid())
698     return {};
699 
700   // Is the type a C++ class? (This is mostly a defensive check.)
701   QualType RegionType = DynType.getType()->getPointeeType();
702   assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
703 
704   const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
705   if (!RD || !RD->hasDefinition())
706     return {};
707 
708   // Find the decl for this method in that class.
709   const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
710   if (!Result) {
711     // We might not even get the original statically-resolved method due to
712     // some particularly nasty casting (e.g. casts to sister classes).
713     // However, we should at least be able to search up and down our own class
714     // hierarchy, and some real bugs have been caught by checking this.
715     assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
716 
717     // FIXME: This is checking that our DynamicTypeInfo is at least as good as
718     // the static type. However, because we currently don't update
719     // DynamicTypeInfo when an object is cast, we can't actually be sure the
720     // DynamicTypeInfo is up to date. This assert should be re-enabled once
721     // this is fixed. <rdar://problem/12287087>
722     //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
723 
724     return {};
725   }
726 
727   // Does the decl that we found have an implementation?
728   const FunctionDecl *Definition;
729   if (!Result->hasBody(Definition)) {
730     if (!DynType.canBeASubClass())
731       return AnyFunctionCall::getRuntimeDefinition();
732     return {};
733   }
734 
735   // We found a definition. If we're not sure that this devirtualization is
736   // actually what will happen at runtime, make sure to provide the region so
737   // that ExprEngine can decide what to do with it.
738   if (DynType.canBeASubClass())
739     return RuntimeDefinition(Definition, R->StripCasts());
740   return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
741 }
742 
743 void CXXInstanceCall::getInitialStackFrameContents(
744                                             const StackFrameContext *CalleeCtx,
745                                             BindingsTy &Bindings) const {
746   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
747 
748   // Handle the binding of 'this' in the new stack frame.
749   SVal ThisVal = getCXXThisVal();
750   if (!ThisVal.isUnknown()) {
751     ProgramStateManager &StateMgr = getState()->getStateManager();
752     SValBuilder &SVB = StateMgr.getSValBuilder();
753 
754     const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
755     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
756 
757     // If we devirtualized to a different member function, we need to make sure
758     // we have the proper layering of CXXBaseObjectRegions.
759     if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
760       ASTContext &Ctx = SVB.getContext();
761       const CXXRecordDecl *Class = MD->getParent();
762       QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
763 
764       // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
765       Optional<SVal> V =
766           StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty);
767       if (!V.hasValue()) {
768         // We might have suffered some sort of placement new earlier, so
769         // we're constructing in a completely unexpected storage.
770         // Fall back to a generic pointer cast for this-value.
771         const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
772         const CXXRecordDecl *StaticClass = StaticMD->getParent();
773         QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
774         ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
775       } else
776         ThisVal = *V;
777     }
778 
779     if (!ThisVal.isUnknown())
780       Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
781   }
782 }
783 
784 const Expr *CXXMemberCall::getCXXThisExpr() const {
785   return getOriginExpr()->getImplicitObjectArgument();
786 }
787 
788 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
789   // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
790   // id-expression in the class member access expression is a qualified-id,
791   // that function is called. Otherwise, its final overrider in the dynamic type
792   // of the object expression is called.
793   if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
794     if (ME->hasQualifier())
795       return AnyFunctionCall::getRuntimeDefinition();
796 
797   return CXXInstanceCall::getRuntimeDefinition();
798 }
799 
800 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
801   return getOriginExpr()->getArg(0);
802 }
803 
804 const BlockDataRegion *BlockCall::getBlockRegion() const {
805   const Expr *Callee = getOriginExpr()->getCallee();
806   const MemRegion *DataReg = getSVal(Callee).getAsRegion();
807 
808   return dyn_cast_or_null<BlockDataRegion>(DataReg);
809 }
810 
811 ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
812   const BlockDecl *D = getDecl();
813   if (!D)
814     return None;
815   return D->parameters();
816 }
817 
818 void BlockCall::getExtraInvalidatedValues(ValueList &Values,
819                   RegionAndSymbolInvalidationTraits *ETraits) const {
820   // FIXME: This also needs to invalidate captured globals.
821   if (const MemRegion *R = getBlockRegion())
822     Values.push_back(loc::MemRegionVal(R));
823 }
824 
825 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
826                                              BindingsTy &Bindings) const {
827   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
828   ArrayRef<ParmVarDecl*> Params;
829   if (isConversionFromLambda()) {
830     auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
831     Params = LambdaOperatorDecl->parameters();
832 
833     // For blocks converted from a C++ lambda, the callee declaration is the
834     // operator() method on the lambda so we bind "this" to
835     // the lambda captured by the block.
836     const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
837     SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
838     Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
839     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
840   } else {
841     Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
842   }
843 
844   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
845                                Params);
846 }
847 
848 SVal AnyCXXConstructorCall::getCXXThisVal() const {
849   if (Data)
850     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
851   return UnknownVal();
852 }
853 
854 void AnyCXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
855                            RegionAndSymbolInvalidationTraits *ETraits) const {
856   SVal V = getCXXThisVal();
857   if (SymbolRef Sym = V.getAsSymbol(true))
858     ETraits->setTrait(Sym,
859                       RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
860   Values.push_back(V);
861 }
862 
863 void AnyCXXConstructorCall::getInitialStackFrameContents(
864                                              const StackFrameContext *CalleeCtx,
865                                              BindingsTy &Bindings) const {
866   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
867 
868   SVal ThisVal = getCXXThisVal();
869   if (!ThisVal.isUnknown()) {
870     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
871     const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
872     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
873     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
874   }
875 }
876 
877 const StackFrameContext *
878 CXXInheritedConstructorCall::getInheritingStackFrame() const {
879   const StackFrameContext *SFC = getLocationContext()->getStackFrame();
880   while (isa<CXXInheritedCtorInitExpr>(SFC->getCallSite()))
881     SFC = SFC->getParent()->getStackFrame();
882   return SFC;
883 }
884 
885 SVal CXXDestructorCall::getCXXThisVal() const {
886   if (Data)
887     return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
888   return UnknownVal();
889 }
890 
891 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
892   // Base destructors are always called non-virtually.
893   // Skip CXXInstanceCall's devirtualization logic in this case.
894   if (isBaseDestructor())
895     return AnyFunctionCall::getRuntimeDefinition();
896 
897   return CXXInstanceCall::getRuntimeDefinition();
898 }
899 
900 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
901   const ObjCMethodDecl *D = getDecl();
902   if (!D)
903     return None;
904   return D->parameters();
905 }
906 
907 void ObjCMethodCall::getExtraInvalidatedValues(
908     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
909 
910   // If the method call is a setter for property known to be backed by
911   // an instance variable, don't invalidate the entire receiver, just
912   // the storage for that instance variable.
913   if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
914     if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
915       SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
916       if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
917         ETraits->setTrait(
918           IvarRegion,
919           RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
920         ETraits->setTrait(
921           IvarRegion,
922           RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
923         Values.push_back(IvarLVal);
924       }
925       return;
926     }
927   }
928 
929   Values.push_back(getReceiverSVal());
930 }
931 
932 SVal ObjCMethodCall::getReceiverSVal() const {
933   // FIXME: Is this the best way to handle class receivers?
934   if (!isInstanceMessage())
935     return UnknownVal();
936 
937   if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
938     return getSVal(RecE);
939 
940   // An instance message with no expression means we are sending to super.
941   // In this case the object reference is the same as 'self'.
942   assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
943   SVal SelfVal = getState()->getSelfSVal(getLocationContext());
944   assert(SelfVal.isValid() && "Calling super but not in ObjC method");
945   return SelfVal;
946 }
947 
948 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
949   if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
950       getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
951       return true;
952 
953   if (!isInstanceMessage())
954     return false;
955 
956   SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
957   SVal SelfVal = getState()->getSelfSVal(getLocationContext());
958 
959   return (RecVal == SelfVal);
960 }
961 
962 SourceRange ObjCMethodCall::getSourceRange() const {
963   switch (getMessageKind()) {
964   case OCM_Message:
965     return getOriginExpr()->getSourceRange();
966   case OCM_PropertyAccess:
967   case OCM_Subscript:
968     return getContainingPseudoObjectExpr()->getSourceRange();
969   }
970   llvm_unreachable("unknown message kind");
971 }
972 
973 using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
974 
975 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
976   assert(Data && "Lazy lookup not yet performed.");
977   assert(getMessageKind() != OCM_Message && "Explicit message send.");
978   return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
979 }
980 
981 static const Expr *
982 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
983   const Expr *Syntactic = POE->getSyntacticForm()->IgnoreParens();
984 
985   // This handles the funny case of assigning to the result of a getter.
986   // This can happen if the getter returns a non-const reference.
987   if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
988     Syntactic = BO->getLHS()->IgnoreParens();
989 
990   return Syntactic;
991 }
992 
993 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
994   if (!Data) {
995     // Find the parent, ignoring implicit casts.
996     const ParentMap &PM = getLocationContext()->getParentMap();
997     const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
998 
999     // Check if parent is a PseudoObjectExpr.
1000     if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
1001       const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1002 
1003       ObjCMessageKind K;
1004       switch (Syntactic->getStmtClass()) {
1005       case Stmt::ObjCPropertyRefExprClass:
1006         K = OCM_PropertyAccess;
1007         break;
1008       case Stmt::ObjCSubscriptRefExprClass:
1009         K = OCM_Subscript;
1010         break;
1011       default:
1012         // FIXME: Can this ever happen?
1013         K = OCM_Message;
1014         break;
1015       }
1016 
1017       if (K != OCM_Message) {
1018         const_cast<ObjCMethodCall *>(this)->Data
1019           = ObjCMessageDataTy(POE, K).getOpaqueValue();
1020         assert(getMessageKind() == K);
1021         return K;
1022       }
1023     }
1024 
1025     const_cast<ObjCMethodCall *>(this)->Data
1026       = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
1027     assert(getMessageKind() == OCM_Message);
1028     return OCM_Message;
1029   }
1030 
1031   ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
1032   if (!Info.getPointer())
1033     return OCM_Message;
1034   return static_cast<ObjCMessageKind>(Info.getInt());
1035 }
1036 
1037 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
1038   // Look for properties accessed with property syntax (foo.bar = ...)
1039   if (getMessageKind() == OCM_PropertyAccess) {
1040     const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
1041     assert(POE && "Property access without PseudoObjectExpr?");
1042 
1043     const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1044     auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
1045 
1046     if (RefExpr->isExplicitProperty())
1047       return RefExpr->getExplicitProperty();
1048   }
1049 
1050   // Look for properties accessed with method syntax ([foo setBar:...]).
1051   const ObjCMethodDecl *MD = getDecl();
1052   if (!MD || !MD->isPropertyAccessor())
1053     return nullptr;
1054 
1055   // Note: This is potentially quite slow.
1056   return MD->findPropertyDecl();
1057 }
1058 
1059 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
1060                                              Selector Sel) const {
1061   assert(IDecl);
1062   AnalysisManager &AMgr =
1063       getState()->getStateManager().getOwningEngine().getAnalysisManager();
1064   // If the class interface is declared inside the main file, assume it is not
1065   // subcassed.
1066   // TODO: It could actually be subclassed if the subclass is private as well.
1067   // This is probably very rare.
1068   SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
1069   if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc))
1070     return false;
1071 
1072   // Assume that property accessors are not overridden.
1073   if (getMessageKind() == OCM_PropertyAccess)
1074     return false;
1075 
1076   // We assume that if the method is public (declared outside of main file) or
1077   // has a parent which publicly declares the method, the method could be
1078   // overridden in a subclass.
1079 
1080   // Find the first declaration in the class hierarchy that declares
1081   // the selector.
1082   ObjCMethodDecl *D = nullptr;
1083   while (true) {
1084     D = IDecl->lookupMethod(Sel, true);
1085 
1086     // Cannot find a public definition.
1087     if (!D)
1088       return false;
1089 
1090     // If outside the main file,
1091     if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation()))
1092       return true;
1093 
1094     if (D->isOverriding()) {
1095       // Search in the superclass on the next iteration.
1096       IDecl = D->getClassInterface();
1097       if (!IDecl)
1098         return false;
1099 
1100       IDecl = IDecl->getSuperClass();
1101       if (!IDecl)
1102         return false;
1103 
1104       continue;
1105     }
1106 
1107     return false;
1108   };
1109 
1110   llvm_unreachable("The while loop should always terminate.");
1111 }
1112 
1113 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
1114   if (!MD)
1115     return MD;
1116 
1117   // Find the redeclaration that defines the method.
1118   if (!MD->hasBody()) {
1119     for (auto I : MD->redecls())
1120       if (I->hasBody())
1121         MD = cast<ObjCMethodDecl>(I);
1122   }
1123   return MD;
1124 }
1125 
1126 struct PrivateMethodKey {
1127   const ObjCInterfaceDecl *Interface;
1128   Selector LookupSelector;
1129   bool IsClassMethod;
1130 };
1131 
1132 namespace llvm {
1133 template <> struct DenseMapInfo<PrivateMethodKey> {
1134   using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>;
1135   using SelectorInfo = DenseMapInfo<Selector>;
1136 
1137   static inline PrivateMethodKey getEmptyKey() {
1138     return {InterfaceInfo::getEmptyKey(), SelectorInfo::getEmptyKey(), false};
1139   }
1140 
1141   static inline PrivateMethodKey getTombstoneKey() {
1142     return {InterfaceInfo::getTombstoneKey(), SelectorInfo::getTombstoneKey(),
1143             true};
1144   }
1145 
1146   static unsigned getHashValue(const PrivateMethodKey &Key) {
1147     return llvm::hash_combine(
1148         llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)),
1149         llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)),
1150         Key.IsClassMethod);
1151   }
1152 
1153   static bool isEqual(const PrivateMethodKey &LHS,
1154                       const PrivateMethodKey &RHS) {
1155     return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) &&
1156            SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) &&
1157            LHS.IsClassMethod == RHS.IsClassMethod;
1158   }
1159 };
1160 } // end namespace llvm
1161 
1162 static const ObjCMethodDecl *
1163 lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface,
1164                         Selector LookupSelector, bool InstanceMethod) {
1165   // Repeatedly calling lookupPrivateMethod() is expensive, especially
1166   // when in many cases it returns null.  We cache the results so
1167   // that repeated queries on the same ObjCIntefaceDecl and Selector
1168   // don't incur the same cost.  On some test cases, we can see the
1169   // same query being issued thousands of times.
1170   //
1171   // NOTE: This cache is essentially a "global" variable, but it
1172   // only gets lazily created when we get here.  The value of the
1173   // cache probably comes from it being global across ExprEngines,
1174   // where the same queries may get issued.  If we are worried about
1175   // concurrency, or possibly loading/unloading ASTs, etc., we may
1176   // need to revisit this someday.  In terms of memory, this table
1177   // stays around until clang quits, which also may be bad if we
1178   // need to release memory.
1179   using PrivateMethodCache =
1180       llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>;
1181 
1182   static PrivateMethodCache PMC;
1183   Optional<const ObjCMethodDecl *> &Val =
1184       PMC[{Interface, LookupSelector, InstanceMethod}];
1185 
1186   // Query lookupPrivateMethod() if the cache does not hit.
1187   if (!Val.hasValue()) {
1188     Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod);
1189 
1190     if (!*Val) {
1191       // Query 'lookupMethod' as a backup.
1192       Val = Interface->lookupMethod(LookupSelector, InstanceMethod);
1193     }
1194   }
1195 
1196   return Val.getValue();
1197 }
1198 
1199 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
1200   const ObjCMessageExpr *E = getOriginExpr();
1201   assert(E);
1202   Selector Sel = E->getSelector();
1203 
1204   if (E->isInstanceMessage()) {
1205     // Find the receiver type.
1206     const ObjCObjectType *ReceiverT = nullptr;
1207     bool CanBeSubClassed = false;
1208     bool LookingForInstanceMethod = true;
1209     QualType SupersType = E->getSuperType();
1210     const MemRegion *Receiver = nullptr;
1211 
1212     if (!SupersType.isNull()) {
1213       // The receiver is guaranteed to be 'super' in this case.
1214       // Super always means the type of immediate predecessor to the method
1215       // where the call occurs.
1216       ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType();
1217     } else {
1218       Receiver = getReceiverSVal().getAsRegion();
1219       if (!Receiver)
1220         return {};
1221 
1222       DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
1223       if (!DTI.isValid()) {
1224         assert(isa<AllocaRegion>(Receiver) &&
1225                "Unhandled untyped region class!");
1226         return {};
1227       }
1228 
1229       QualType DynType = DTI.getType();
1230       CanBeSubClassed = DTI.canBeASubClass();
1231 
1232       const auto *ReceiverDynT =
1233           dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
1234 
1235       if (ReceiverDynT) {
1236         ReceiverT = ReceiverDynT->getObjectType();
1237 
1238         // It can be actually class methods called with Class object as a
1239         // receiver. This type of messages is treated by the compiler as
1240         // instance (not class).
1241         if (ReceiverT->isObjCClass()) {
1242 
1243           SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1244           // For [self classMethod], return compiler visible declaration.
1245           if (Receiver == SelfVal.getAsRegion()) {
1246             return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1247           }
1248 
1249           // Otherwise, let's check if we know something about the type
1250           // inside of this class object.
1251           if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) {
1252             DynamicTypeInfo DTI =
1253                 getClassObjectDynamicTypeInfo(getState(), ReceiverSym);
1254             if (DTI.isValid()) {
1255               // Let's use this type for lookup.
1256               ReceiverT =
1257                   cast<ObjCObjectType>(DTI.getType().getCanonicalType());
1258 
1259               CanBeSubClassed = DTI.canBeASubClass();
1260               // And it should be a class method instead.
1261               LookingForInstanceMethod = false;
1262             }
1263           }
1264         }
1265 
1266         if (CanBeSubClassed)
1267           if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface())
1268             // Even if `DynamicTypeInfo` told us that it can be
1269             // not necessarily this type, but its descendants, we still want
1270             // to check again if this selector can be actually overridden.
1271             CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel);
1272       }
1273     }
1274 
1275     // Lookup the instance method implementation.
1276     if (ReceiverT)
1277       if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) {
1278         const ObjCMethodDecl *MD =
1279             lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod);
1280 
1281         if (MD && !MD->hasBody())
1282           MD = MD->getCanonicalDecl();
1283 
1284         if (CanBeSubClassed)
1285           return RuntimeDefinition(MD, Receiver);
1286         else
1287           return RuntimeDefinition(MD, nullptr);
1288       }
1289   } else {
1290     // This is a class method.
1291     // If we have type info for the receiver class, we are calling via
1292     // class name.
1293     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1294       // Find/Return the method implementation.
1295       return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1296     }
1297   }
1298 
1299   return {};
1300 }
1301 
1302 bool ObjCMethodCall::argumentsMayEscape() const {
1303   if (isInSystemHeader() && !isInstanceMessage()) {
1304     Selector Sel = getSelector();
1305     if (Sel.getNumArgs() == 1 &&
1306         Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1307       return true;
1308   }
1309 
1310   return CallEvent::argumentsMayEscape();
1311 }
1312 
1313 void ObjCMethodCall::getInitialStackFrameContents(
1314                                              const StackFrameContext *CalleeCtx,
1315                                              BindingsTy &Bindings) const {
1316   const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1317   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1318   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1319                                D->parameters());
1320 
1321   SVal SelfVal = getReceiverSVal();
1322   if (!SelfVal.isUnknown()) {
1323     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1324     MemRegionManager &MRMgr = SVB.getRegionManager();
1325     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1326     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1327   }
1328 }
1329 
1330 CallEventRef<>
1331 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1332                                 const LocationContext *LCtx) {
1333   if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1334     return create<CXXMemberCall>(MCE, State, LCtx);
1335 
1336   if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1337     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1338     if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1339       if (MD->isInstance())
1340         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1341 
1342   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1343     return create<BlockCall>(CE, State, LCtx);
1344   }
1345 
1346   // Otherwise, it's a normal function call, static member function call, or
1347   // something we can't reason about.
1348   return create<SimpleFunctionCall>(CE, State, LCtx);
1349 }
1350 
1351 CallEventRef<>
1352 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1353                             ProgramStateRef State) {
1354   const LocationContext *ParentCtx = CalleeCtx->getParent();
1355   const LocationContext *CallerCtx = ParentCtx->getStackFrame();
1356   assert(CallerCtx && "This should not be used for top-level stack frames");
1357 
1358   const Stmt *CallSite = CalleeCtx->getCallSite();
1359 
1360   if (CallSite) {
1361     if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx))
1362       return Out;
1363 
1364     SValBuilder &SVB = State->getStateManager().getSValBuilder();
1365     const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1366     Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1367     SVal ThisVal = State->getSVal(ThisPtr);
1368 
1369     if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite))
1370       return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerCtx);
1371     else if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite))
1372       return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State,
1373                                             CallerCtx);
1374     else {
1375       // All other cases are handled by getCall.
1376       llvm_unreachable("This is not an inlineable statement");
1377     }
1378   }
1379 
1380   // Fall back to the CFG. The only thing we haven't handled yet is
1381   // destructors, though this could change in the future.
1382   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1383   CFGElement E = (*B)[CalleeCtx->getIndex()];
1384   assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
1385          "All other CFG elements should have exprs");
1386 
1387   SValBuilder &SVB = State->getStateManager().getSValBuilder();
1388   const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1389   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1390   SVal ThisVal = State->getSVal(ThisPtr);
1391 
1392   const Stmt *Trigger;
1393   if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1394     Trigger = AutoDtor->getTriggerStmt();
1395   else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1396     Trigger = DeleteDtor->getDeleteExpr();
1397   else
1398     Trigger = Dtor->getBody();
1399 
1400   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1401                               E.getAs<CFGBaseDtor>().hasValue(), State,
1402                               CallerCtx);
1403 }
1404 
1405 CallEventRef<> CallEventManager::getCall(const Stmt *S, ProgramStateRef State,
1406                                          const LocationContext *LC) {
1407   if (const auto *CE = dyn_cast<CallExpr>(S)) {
1408     return getSimpleCall(CE, State, LC);
1409   } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) {
1410     return getCXXAllocatorCall(NE, State, LC);
1411   } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1412     return getObjCMethodCall(ME, State, LC);
1413   } else {
1414     return nullptr;
1415   }
1416 }
1417