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