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/Analysis/ProgramPoint.h"
18 #include "clang/AST/ParentMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/StringExtras.h"
21 
22 using namespace clang;
23 using namespace ento;
24 
25 QualType CallEvent::getResultType() const {
26   QualType ResultTy = getDeclaredResultType();
27 
28   if (ResultTy.isNull())
29     ResultTy = getOriginExpr()->getType();
30 
31   return ResultTy;
32 }
33 
34 static bool isCallbackArg(SVal V, QualType T) {
35   // If the parameter is 0, it's harmless.
36   if (V.isZeroConstant())
37     return false;
38 
39   // If a parameter is a block or a callback, assume it can modify pointer.
40   if (T->isBlockPointerType() ||
41       T->isFunctionPointerType() ||
42       T->isObjCSelType())
43     return true;
44 
45   // Check if a callback is passed inside a struct (for both, struct passed by
46   // reference and by value). Dig just one level into the struct for now.
47 
48   if (isa<PointerType>(T) || isa<ReferenceType>(T))
49     T = T->getPointeeType();
50 
51   if (const RecordType *RT = T->getAsStructureType()) {
52     const RecordDecl *RD = RT->getDecl();
53     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
54          I != E; ++I) {
55       QualType FieldT = I->getType();
56       if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
57         return true;
58     }
59   }
60 
61   return false;
62 }
63 
64 bool CallEvent::hasNonZeroCallbackArg() const {
65   unsigned NumOfArgs = getNumArgs();
66 
67   // If calling using a function pointer, assume the function does not
68   // have a callback. TODO: We could check the types of the arguments here.
69   if (!getDecl())
70     return false;
71 
72   unsigned Idx = 0;
73   for (CallEvent::param_type_iterator I = param_type_begin(),
74                                        E = param_type_end();
75        I != E && Idx < NumOfArgs; ++I, ++Idx) {
76     if (NumOfArgs <= Idx)
77       break;
78 
79     if (isCallbackArg(getArgSVal(Idx), *I))
80       return true;
81   }
82 
83   return false;
84 }
85 
86 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
87 /// with no further indirection.
88 static bool isPointerToConst(QualType Ty) {
89   QualType PointeeTy = Ty->getPointeeType();
90   if (PointeeTy == QualType())
91     return false;
92   if (!PointeeTy.isConstQualified())
93     return false;
94   if (PointeeTy->isAnyPointerType())
95     return false;
96   return true;
97 }
98 
99 // Try to retrieve the function declaration and find the function parameter
100 // types which are pointers/references to a non-pointer const.
101 // We will not invalidate the corresponding argument regions.
102 static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
103                                  const CallEvent &Call) {
104   unsigned Idx = 0;
105   for (CallEvent::param_type_iterator I = Call.param_type_begin(),
106                                       E = Call.param_type_end();
107        I != E; ++I, ++Idx) {
108     if (isPointerToConst(*I))
109       PreserveArgs.insert(Idx);
110   }
111 }
112 
113 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
114                                               ProgramStateRef Orig) const {
115   ProgramStateRef Result = (Orig ? Orig : getState());
116 
117   SmallVector<const MemRegion *, 8> RegionsToInvalidate;
118   getExtraInvalidatedRegions(RegionsToInvalidate);
119 
120   // Indexes of arguments whose values will be preserved by the call.
121   llvm::SmallSet<unsigned, 1> PreserveArgs;
122   if (!argumentsMayEscape())
123     findPtrToConstParams(PreserveArgs, *this);
124 
125   for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
126     if (PreserveArgs.count(Idx))
127       continue;
128 
129     SVal V = getArgSVal(Idx);
130 
131     // If we are passing a location wrapped as an integer, unwrap it and
132     // invalidate the values referred by the location.
133     if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
134       V = Wrapped->getLoc();
135     else if (!isa<Loc>(V))
136       continue;
137 
138     if (const MemRegion *R = V.getAsRegion()) {
139       // Invalidate the value of the variable passed by reference.
140 
141       // Are we dealing with an ElementRegion?  If the element type is
142       // a basic integer type (e.g., char, int) and the underlying region
143       // is a variable region then strip off the ElementRegion.
144       // FIXME: We really need to think about this for the general case
145       //   as sometimes we are reasoning about arrays and other times
146       //   about (char*), etc., is just a form of passing raw bytes.
147       //   e.g., void *p = alloca(); foo((char*)p);
148       if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
149         // Checking for 'integral type' is probably too promiscuous, but
150         // we'll leave it in for now until we have a systematic way of
151         // handling all of these cases.  Eventually we need to come up
152         // with an interface to StoreManager so that this logic can be
153         // appropriately delegated to the respective StoreManagers while
154         // still allowing us to do checker-specific logic (e.g.,
155         // invalidating reference counts), probably via callbacks.
156         if (ER->getElementType()->isIntegralOrEnumerationType()) {
157           const MemRegion *superReg = ER->getSuperRegion();
158           if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
159               isa<ObjCIvarRegion>(superReg))
160             R = cast<TypedRegion>(superReg);
161         }
162         // FIXME: What about layers of ElementRegions?
163       }
164 
165       // Mark this region for invalidation.  We batch invalidate regions
166       // below for efficiency.
167       RegionsToInvalidate.push_back(R);
168     }
169   }
170 
171   // Invalidate designated regions using the batch invalidation API.
172   // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
173   //  global variables.
174   return Result->invalidateRegions(RegionsToInvalidate, getOriginExpr(),
175                                    BlockCount, getLocationContext(),
176                                    /*Symbols=*/0, this);
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 void CallEvent::dump(raw_ostream &Out) const {
211   ASTContext &Ctx = getState()->getStateManager().getContext();
212   if (const Expr *E = getOriginExpr()) {
213     E->printPretty(Out, Ctx, 0, Ctx.getPrintingPolicy());
214     Out << "\n";
215     return;
216   }
217 
218   if (const Decl *D = getDecl()) {
219     Out << "Call to ";
220     D->print(Out, Ctx.getPrintingPolicy());
221     return;
222   }
223 
224   // FIXME: a string representation of the kind would be nice.
225   Out << "Unknown call (type " << getKind() << ")";
226 }
227 
228 
229 bool CallEvent::mayBeInlined(const Stmt *S) {
230   // FIXME: Kill this.
231   return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
232                           || isa<CXXConstructExpr>(S);
233 }
234 
235 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
236                                          CallEvent::BindingsTy &Bindings,
237                                          SValBuilder &SVB,
238                                          const CallEvent &Call,
239                                          CallEvent::param_iterator I,
240                                          CallEvent::param_iterator E) {
241   MemRegionManager &MRMgr = SVB.getRegionManager();
242 
243   unsigned Idx = 0;
244   for (; I != E; ++I, ++Idx) {
245     const ParmVarDecl *ParamDecl = *I;
246     assert(ParamDecl && "Formal parameter has no decl?");
247 
248     SVal ArgVal = Call.getArgSVal(Idx);
249     if (!ArgVal.isUnknown()) {
250       Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
251       Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
252     }
253   }
254 
255   // FIXME: Variadic arguments are not handled at all right now.
256 }
257 
258 
259 CallEvent::param_iterator AnyFunctionCall::param_begin() const {
260   const FunctionDecl *D = getDecl();
261   if (!D)
262     return 0;
263 
264   return D->param_begin();
265 }
266 
267 CallEvent::param_iterator AnyFunctionCall::param_end() const {
268   const FunctionDecl *D = getDecl();
269   if (!D)
270     return 0;
271 
272   return D->param_end();
273 }
274 
275 void AnyFunctionCall::getInitialStackFrameContents(
276                                         const StackFrameContext *CalleeCtx,
277                                         BindingsTy &Bindings) const {
278   const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
279   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
280   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
281                                D->param_begin(), D->param_end());
282 }
283 
284 QualType AnyFunctionCall::getDeclaredResultType() const {
285   const FunctionDecl *D = getDecl();
286   if (!D)
287     return QualType();
288 
289   return D->getResultType();
290 }
291 
292 bool AnyFunctionCall::argumentsMayEscape() const {
293   if (hasNonZeroCallbackArg())
294     return true;
295 
296   const FunctionDecl *D = getDecl();
297   if (!D)
298     return true;
299 
300   const IdentifierInfo *II = D->getIdentifier();
301   if (!II)
302     return true;
303 
304   // This set of "escaping" APIs is
305 
306   // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
307   //   value into thread local storage. The value can later be retrieved with
308   //   'void *ptheread_getspecific(pthread_key)'. So even thought the
309   //   parameter is 'const void *', the region escapes through the call.
310   if (II->isStr("pthread_setspecific"))
311     return true;
312 
313   // - xpc_connection_set_context stores a value which can be retrieved later
314   //   with xpc_connection_get_context.
315   if (II->isStr("xpc_connection_set_context"))
316     return true;
317 
318   // - funopen - sets a buffer for future IO calls.
319   if (II->isStr("funopen"))
320     return true;
321 
322   StringRef FName = II->getName();
323 
324   // - CoreFoundation functions that end with "NoCopy" can free a passed-in
325   //   buffer even if it is const.
326   if (FName.endswith("NoCopy"))
327     return true;
328 
329   // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
330   //   be deallocated by NSMapRemove.
331   if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
332     return true;
333 
334   // - Many CF containers allow objects to escape through custom
335   //   allocators/deallocators upon container construction. (PR12101)
336   if (FName.startswith("CF") || FName.startswith("CG")) {
337     return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
338            StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
339            StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
340            StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
341            StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
342            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
343   }
344 
345   return false;
346 }
347 
348 
349 const FunctionDecl *SimpleCall::getDecl() const {
350   const FunctionDecl *D = getOriginExpr()->getDirectCallee();
351   if (D)
352     return D;
353 
354   return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
355 }
356 
357 
358 void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
359   if (const MemRegion *R = getCXXThisVal().getAsRegion())
360     Regions.push_back(R);
361 }
362 
363 static const CXXMethodDecl *devirtualize(const CXXMethodDecl *MD, SVal ThisVal){
364   const MemRegion *R = ThisVal.getAsRegion();
365   if (!R)
366     return 0;
367 
368   const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R->StripCasts());
369   if (!TR)
370     return 0;
371 
372   const CXXRecordDecl *RD = TR->getValueType()->getAsCXXRecordDecl();
373   if (!RD)
374     return 0;
375 
376   const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD);
377   const FunctionDecl *Definition;
378   if (!Result->hasBody(Definition))
379     return 0;
380 
381   return cast<CXXMethodDecl>(Definition);
382 }
383 
384 
385 const Decl *CXXInstanceCall::getRuntimeDefinition() const {
386   const Decl *D = SimpleCall::getRuntimeDefinition();
387   if (!D)
388     return 0;
389 
390   const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
391   if (!MD->isVirtual())
392     return MD;
393 
394   // If the method is virtual, see if we can find the actual implementation
395   // based on context-sensitivity.
396   // FIXME: Virtual method calls behave differently when an object is being
397   // constructed or destructed. It's not as simple as "no devirtualization"
398   // because a /partially/ constructed object can be referred to through a
399   // base pointer. We'll eventually want to use DynamicTypeInfo here.
400   if (const CXXMethodDecl *Devirtualized = devirtualize(MD, getCXXThisVal()))
401     return Devirtualized;
402 
403   return 0;
404 }
405 
406 void CXXInstanceCall::getInitialStackFrameContents(
407                                             const StackFrameContext *CalleeCtx,
408                                             BindingsTy &Bindings) const {
409   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
410 
411   SVal ThisVal = getCXXThisVal();
412   if (!ThisVal.isUnknown()) {
413     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
414     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
415     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
416     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
417   }
418 }
419 
420 
421 
422 const Expr *CXXMemberCall::getCXXThisExpr() const {
423   return getOriginExpr()->getImplicitObjectArgument();
424 }
425 
426 
427 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
428   return getOriginExpr()->getArg(0);
429 }
430 
431 
432 const BlockDataRegion *BlockCall::getBlockRegion() const {
433   const Expr *Callee = getOriginExpr()->getCallee();
434   const MemRegion *DataReg = getSVal(Callee).getAsRegion();
435 
436   return dyn_cast_or_null<BlockDataRegion>(DataReg);
437 }
438 
439 CallEvent::param_iterator BlockCall::param_begin() const {
440   const BlockDecl *D = getBlockDecl();
441   if (!D)
442     return 0;
443   return D->param_begin();
444 }
445 
446 CallEvent::param_iterator BlockCall::param_end() const {
447   const BlockDecl *D = getBlockDecl();
448   if (!D)
449     return 0;
450   return D->param_end();
451 }
452 
453 void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
454   // FIXME: This also needs to invalidate captured globals.
455   if (const MemRegion *R = getBlockRegion())
456     Regions.push_back(R);
457 }
458 
459 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
460                                              BindingsTy &Bindings) const {
461   const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
462   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
463   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
464                                D->param_begin(), D->param_end());
465 }
466 
467 
468 QualType BlockCall::getDeclaredResultType() const {
469   const BlockDataRegion *BR = getBlockRegion();
470   if (!BR)
471     return QualType();
472   QualType BlockTy = BR->getCodeRegion()->getLocationType();
473   return cast<FunctionType>(BlockTy->getPointeeType())->getResultType();
474 }
475 
476 
477 SVal CXXConstructorCall::getCXXThisVal() const {
478   if (Data)
479     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
480   return UnknownVal();
481 }
482 
483 void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
484   if (Data)
485     Regions.push_back(static_cast<const MemRegion *>(Data));
486 }
487 
488 void CXXConstructorCall::getInitialStackFrameContents(
489                                              const StackFrameContext *CalleeCtx,
490                                              BindingsTy &Bindings) const {
491   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
492 
493   SVal ThisVal = getCXXThisVal();
494   if (!ThisVal.isUnknown()) {
495     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
496     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
497     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
498     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
499   }
500 }
501 
502 
503 
504 SVal CXXDestructorCall::getCXXThisVal() const {
505   if (Data)
506     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
507   return UnknownVal();
508 }
509 
510 void CXXDestructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
511   if (Data)
512     Regions.push_back(static_cast<const MemRegion *>(Data));
513 }
514 
515 const Decl *CXXDestructorCall::getRuntimeDefinition() const {
516   const Decl *D = AnyFunctionCall::getRuntimeDefinition();
517   if (!D)
518     return 0;
519 
520   const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
521   if (!MD->isVirtual())
522     return MD;
523 
524   // If the method is virtual, see if we can find the actual implementation
525   // based on context-sensitivity.
526   // FIXME: Virtual method calls behave differently when an object is being
527   // constructed or destructed. It's not as simple as "no devirtualization"
528   // because a /partially/ constructed object can be referred to through a
529   // base pointer. We'll eventually want to use DynamicTypeInfo here.
530   if (const CXXMethodDecl *Devirtualized = devirtualize(MD, getCXXThisVal()))
531     return Devirtualized;
532 
533   return 0;
534 }
535 
536 void CXXDestructorCall::getInitialStackFrameContents(
537                                              const StackFrameContext *CalleeCtx,
538                                              BindingsTy &Bindings) const {
539   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
540 
541   SVal ThisVal = getCXXThisVal();
542   if (!ThisVal.isUnknown()) {
543     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
544     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
545     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
546     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
547   }
548 }
549 
550 
551 CallEvent::param_iterator ObjCMethodCall::param_begin() const {
552   const ObjCMethodDecl *D = getDecl();
553   if (!D)
554     return 0;
555 
556   return D->param_begin();
557 }
558 
559 CallEvent::param_iterator ObjCMethodCall::param_end() const {
560   const ObjCMethodDecl *D = getDecl();
561   if (!D)
562     return 0;
563 
564   return D->param_end();
565 }
566 
567 void
568 ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
569   if (const MemRegion *R = getReceiverSVal().getAsRegion())
570     Regions.push_back(R);
571 }
572 
573 QualType ObjCMethodCall::getDeclaredResultType() const {
574   const ObjCMethodDecl *D = getDecl();
575   if (!D)
576     return QualType();
577 
578   return D->getResultType();
579 }
580 
581 SVal ObjCMethodCall::getReceiverSVal() const {
582   // FIXME: Is this the best way to handle class receivers?
583   if (!isInstanceMessage())
584     return UnknownVal();
585 
586   if (const Expr *Base = getOriginExpr()->getInstanceReceiver())
587     return getSVal(Base);
588 
589   // An instance message with no expression means we are sending to super.
590   // In this case the object reference is the same as 'self'.
591   const LocationContext *LCtx = getLocationContext();
592   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
593   assert(SelfDecl && "No message receiver Expr, but not in an ObjC method");
594   return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
595 }
596 
597 SourceRange ObjCMethodCall::getSourceRange() const {
598   switch (getMessageKind()) {
599   case OCM_Message:
600     return getOriginExpr()->getSourceRange();
601   case OCM_PropertyAccess:
602   case OCM_Subscript:
603     return getContainingPseudoObjectExpr()->getSourceRange();
604   }
605   llvm_unreachable("unknown message kind");
606 }
607 
608 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
609 
610 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
611   assert(Data != 0 && "Lazy lookup not yet performed.");
612   assert(getMessageKind() != OCM_Message && "Explicit message send.");
613   return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
614 }
615 
616 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
617   if (Data == 0) {
618     ParentMap &PM = getLocationContext()->getParentMap();
619     const Stmt *S = PM.getParent(getOriginExpr());
620     if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
621       const Expr *Syntactic = POE->getSyntacticForm();
622 
623       // This handles the funny case of assigning to the result of a getter.
624       // This can happen if the getter returns a non-const reference.
625       if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
626         Syntactic = BO->getLHS();
627 
628       ObjCMessageKind K;
629       switch (Syntactic->getStmtClass()) {
630       case Stmt::ObjCPropertyRefExprClass:
631         K = OCM_PropertyAccess;
632         break;
633       case Stmt::ObjCSubscriptRefExprClass:
634         K = OCM_Subscript;
635         break;
636       default:
637         // FIXME: Can this ever happen?
638         K = OCM_Message;
639         break;
640       }
641 
642       if (K != OCM_Message) {
643         const_cast<ObjCMethodCall *>(this)->Data
644           = ObjCMessageDataTy(POE, K).getOpaqueValue();
645         assert(getMessageKind() == K);
646         return K;
647       }
648     }
649 
650     const_cast<ObjCMethodCall *>(this)->Data
651       = ObjCMessageDataTy(0, 1).getOpaqueValue();
652     assert(getMessageKind() == OCM_Message);
653     return OCM_Message;
654   }
655 
656   ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
657   if (!Info.getPointer())
658     return OCM_Message;
659   return static_cast<ObjCMessageKind>(Info.getInt());
660 }
661 
662 const Decl *ObjCMethodCall::getRuntimeDefinition() const {
663   const ObjCMessageExpr *E = getOriginExpr();
664   assert(E);
665   Selector Sel = E->getSelector();
666 
667   if (E->isInstanceMessage()) {
668 
669     // Find the the receiver type.
670     const ObjCObjectPointerType *ReceiverT = 0;
671     QualType SupersType = E->getSuperType();
672     if (!SupersType.isNull()) {
673       ReceiverT = cast<ObjCObjectPointerType>(SupersType.getTypePtr());
674     } else {
675       const MemRegion *Receiver = getReceiverSVal().getAsRegion();
676       if (!Receiver)
677         return 0;
678 
679       DynamicTypeInfo TI = getState()->getDynamicTypeInfo(Receiver);
680       ReceiverT = dyn_cast<ObjCObjectPointerType>(TI.getType().getTypePtr());
681     }
682 
683     // Lookup the method implementation.
684     if (ReceiverT)
685       if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
686         return IDecl->lookupPrivateMethod(Sel);
687 
688   } else {
689     // This is a class method.
690     // If we have type info for the receiver class, we are calling via
691     // class name.
692     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
693       // Find/Return the method implementation.
694       return IDecl->lookupPrivateClassMethod(Sel);
695     }
696   }
697 
698   return 0;
699 }
700 
701 void ObjCMethodCall::getInitialStackFrameContents(
702                                              const StackFrameContext *CalleeCtx,
703                                              BindingsTy &Bindings) const {
704   const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
705   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
706   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
707                                D->param_begin(), D->param_end());
708 
709   SVal SelfVal = getReceiverSVal();
710   if (!SelfVal.isUnknown()) {
711     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
712     MemRegionManager &MRMgr = SVB.getRegionManager();
713     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
714     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
715   }
716 }
717 
718 
719 CallEventRef<SimpleCall>
720 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
721                                 const LocationContext *LCtx) {
722   if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
723     return create<CXXMemberCall>(MCE, State, LCtx);
724 
725   if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
726     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
727     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
728       if (MD->isInstance())
729         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
730 
731   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
732     return create<BlockCall>(CE, State, LCtx);
733   }
734 
735   // Otherwise, it's a normal function call, static member function call, or
736   // something we can't reason about.
737   return create<FunctionCall>(CE, State, LCtx);
738 }
739 
740 
741 CallEventRef<>
742 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
743                             ProgramStateRef State) {
744   const LocationContext *ParentCtx = CalleeCtx->getParent();
745   const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
746   assert(CallerCtx && "This should not be used for top-level stack frames");
747 
748   const Stmt *CallSite = CalleeCtx->getCallSite();
749 
750   if (CallSite) {
751     if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
752       return getSimpleCall(CE, State, CallerCtx);
753 
754     switch (CallSite->getStmtClass()) {
755     case Stmt::CXXConstructExprClass: {
756       SValBuilder &SVB = State->getStateManager().getSValBuilder();
757       const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
758       Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
759       SVal ThisVal = State->getSVal(ThisPtr);
760 
761       return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
762                                    ThisVal.getAsRegion(), State, CallerCtx);
763     }
764     case Stmt::CXXNewExprClass:
765       return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
766     case Stmt::ObjCMessageExprClass:
767       return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
768                                State, CallerCtx);
769     default:
770       llvm_unreachable("This is not an inlineable statement.");
771     }
772   }
773 
774   // Fall back to the CFG. The only thing we haven't handled yet is
775   // destructors, though this could change in the future.
776   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
777   CFGElement E = (*B)[CalleeCtx->getIndex()];
778   assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
779   assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
780 
781   SValBuilder &SVB = State->getStateManager().getSValBuilder();
782   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
783   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
784   SVal ThisVal = State->getSVal(ThisPtr);
785 
786   const Stmt *Trigger;
787   if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
788     Trigger = AutoDtor->getTriggerStmt();
789   else
790     Trigger = Dtor->getBody();
791 
792   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
793                               State, CallerCtx);
794 }
795 
796