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