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