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