CallEvent.cpp revision ef15831780b705475e7b237ac16418e9b53cb7a6
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
22using namespace clang;
23using namespace ento;
24
25QualType CallEvent::getResultType() const {
26  QualType ResultTy = getDeclaredResultType();
27
28  if (ResultTy.isNull())
29    ResultTy = getOriginExpr()->getType();
30
31  return ResultTy;
32}
33
34static 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
64bool 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.
88static 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.
102static 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
113ProgramStateRef 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
179ProgramPoint 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
196SVal CallEvent::getArgSVal(unsigned Index) const {
197  const Expr *ArgE = getArgExpr(Index);
198  if (!ArgE)
199    return UnknownVal();
200  return getSVal(ArgE);
201}
202
203SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
204  const Expr *ArgE = getArgExpr(Index);
205  if (!ArgE)
206    return SourceRange();
207  return ArgE->getSourceRange();
208}
209
210void 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
229bool CallEvent::mayBeInlined(const Stmt *S) {
230  // FIXME: Kill this.
231  return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
232                          || isa<CXXConstructExpr>(S);
233}
234
235static 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
259CallEvent::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
267CallEvent::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
275void 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
284QualType AnyFunctionCall::getDeclaredResultType() const {
285  const FunctionDecl *D = getDecl();
286  if (!D)
287    return QualType();
288
289  return D->getResultType();
290}
291
292bool 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
349const 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
358void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
359  if (const MemRegion *R = getCXXThisVal().getAsRegion())
360    Regions.push_back(R);
361}
362
363static 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
385const 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  if (const CXXMethodDecl *Devirtualized = devirtualize(MD, getCXXThisVal()))
397    return Devirtualized;
398
399  return 0;
400}
401
402void CXXInstanceCall::getInitialStackFrameContents(
403                                            const StackFrameContext *CalleeCtx,
404                                            BindingsTy &Bindings) const {
405  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
406
407  SVal ThisVal = getCXXThisVal();
408  if (!ThisVal.isUnknown()) {
409    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
410    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
411    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
412    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
413  }
414}
415
416
417
418SVal CXXMemberCall::getCXXThisVal() const {
419  const Expr *Base = getOriginExpr()->getImplicitObjectArgument();
420
421  // FIXME: Will eventually need to cope with member pointers.  This is
422  // a limitation in getImplicitObjectArgument().
423  if (!Base)
424    return UnknownVal();
425
426  return getSVal(Base);
427}
428
429
430SVal CXXMemberOperatorCall::getCXXThisVal() const {
431  const Expr *Base = getOriginExpr()->getArg(0);
432  return getSVal(Base);
433}
434
435
436const BlockDataRegion *BlockCall::getBlockRegion() const {
437  const Expr *Callee = getOriginExpr()->getCallee();
438  const MemRegion *DataReg = getSVal(Callee).getAsRegion();
439
440  return dyn_cast_or_null<BlockDataRegion>(DataReg);
441}
442
443CallEvent::param_iterator BlockCall::param_begin() const {
444  const BlockDecl *D = getBlockDecl();
445  if (!D)
446    return 0;
447  return D->param_begin();
448}
449
450CallEvent::param_iterator BlockCall::param_end() const {
451  const BlockDecl *D = getBlockDecl();
452  if (!D)
453    return 0;
454  return D->param_end();
455}
456
457void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
458  // FIXME: This also needs to invalidate captured globals.
459  if (const MemRegion *R = getBlockRegion())
460    Regions.push_back(R);
461}
462
463void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
464                                             BindingsTy &Bindings) const {
465  const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
466  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
467  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
468                               D->param_begin(), D->param_end());
469}
470
471
472QualType BlockCall::getDeclaredResultType() const {
473  const BlockDataRegion *BR = getBlockRegion();
474  if (!BR)
475    return QualType();
476  QualType BlockTy = BR->getCodeRegion()->getLocationType();
477  return cast<FunctionType>(BlockTy->getPointeeType())->getResultType();
478}
479
480
481SVal CXXConstructorCall::getCXXThisVal() const {
482  if (Data)
483    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
484  return UnknownVal();
485}
486
487void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
488  if (Data)
489    Regions.push_back(static_cast<const MemRegion *>(Data));
490}
491
492void CXXConstructorCall::getInitialStackFrameContents(
493                                             const StackFrameContext *CalleeCtx,
494                                             BindingsTy &Bindings) const {
495  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
496
497  SVal ThisVal = getCXXThisVal();
498  if (!ThisVal.isUnknown()) {
499    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
500    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
501    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
502    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
503  }
504}
505
506
507
508SVal CXXDestructorCall::getCXXThisVal() const {
509  if (Data)
510    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
511  return UnknownVal();
512}
513
514void CXXDestructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
515  if (Data)
516    Regions.push_back(static_cast<const MemRegion *>(Data));
517}
518
519const Decl *CXXDestructorCall::getRuntimeDefinition() const {
520  const Decl *D = AnyFunctionCall::getRuntimeDefinition();
521  if (!D)
522    return 0;
523
524  const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
525  if (!MD->isVirtual())
526    return MD;
527
528  // If the method is virtual, see if we can find the actual implementation
529  // based on context-sensitivity.
530  if (const CXXMethodDecl *Devirtualized = devirtualize(MD, getCXXThisVal()))
531    return Devirtualized;
532
533  return 0;
534}
535
536void 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
551CallEvent::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
559CallEvent::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
567void
568ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
569  if (const MemRegion *R = getReceiverSVal().getAsRegion())
570    Regions.push_back(R);
571}
572
573QualType ObjCMethodCall::getDeclaredResultType() const {
574  const ObjCMethodDecl *D = getDecl();
575  if (!D)
576    return QualType();
577
578  return D->getResultType();
579}
580
581SVal 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
597SourceRange 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
608typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
609
610const 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
616ObjCMessageKind 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
662const 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      DynamicTypeInfo TI = getState()->getDynamicTypeInfo(Receiver);
677      ReceiverT = dyn_cast<ObjCObjectPointerType>(TI.getType().getTypePtr());
678    }
679
680    // Lookup the method implementation.
681    if (ReceiverT)
682      if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
683        return IDecl->lookupPrivateMethod(Sel);
684
685  } else {
686    // This is a class method.
687    // If we have type info for the receiver class, we are calling via
688    // class name.
689    if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
690      // Find/Return the method implementation.
691      return IDecl->lookupPrivateClassMethod(Sel);
692    }
693  }
694
695  return 0;
696}
697
698void ObjCMethodCall::getInitialStackFrameContents(
699                                             const StackFrameContext *CalleeCtx,
700                                             BindingsTy &Bindings) const {
701  const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
702  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
703  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
704                               D->param_begin(), D->param_end());
705
706  SVal SelfVal = getReceiverSVal();
707  if (!SelfVal.isUnknown()) {
708    const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
709    MemRegionManager &MRMgr = SVB.getRegionManager();
710    Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
711    Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
712  }
713}
714
715
716CallEventRef<SimpleCall>
717CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
718                                const LocationContext *LCtx) {
719  if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
720    return create<CXXMemberCall>(MCE, State, LCtx);
721
722  if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
723    const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
724    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
725      if (MD->isInstance())
726        return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
727
728  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
729    return create<BlockCall>(CE, State, LCtx);
730  }
731
732  // Otherwise, it's a normal function call, static member function call, or
733  // something we can't reason about.
734  return create<FunctionCall>(CE, State, LCtx);
735}
736
737
738CallEventRef<>
739CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
740                            ProgramStateRef State) {
741  const LocationContext *ParentCtx = CalleeCtx->getParent();
742  const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
743  assert(CallerCtx && "This should not be used for top-level stack frames");
744
745  const Stmt *CallSite = CalleeCtx->getCallSite();
746
747  if (CallSite) {
748    if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
749      return getSimpleCall(CE, State, CallerCtx);
750
751    switch (CallSite->getStmtClass()) {
752    case Stmt::CXXConstructExprClass: {
753      SValBuilder &SVB = State->getStateManager().getSValBuilder();
754      const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
755      Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
756      SVal ThisVal = State->getSVal(ThisPtr);
757
758      return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
759                                   ThisVal.getAsRegion(), State, CallerCtx);
760    }
761    case Stmt::CXXNewExprClass:
762      return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
763    case Stmt::ObjCMessageExprClass:
764      return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
765                               State, CallerCtx);
766    default:
767      llvm_unreachable("This is not an inlineable statement.");
768    }
769  }
770
771  // Fall back to the CFG. The only thing we haven't handled yet is
772  // destructors, though this could change in the future.
773  const CFGBlock *B = CalleeCtx->getCallSiteBlock();
774  CFGElement E = (*B)[CalleeCtx->getIndex()];
775  assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
776  assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
777
778  SValBuilder &SVB = State->getStateManager().getSValBuilder();
779  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
780  Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
781  SVal ThisVal = State->getSVal(ThisPtr);
782
783  const Stmt *Trigger;
784  if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
785    Trigger = AutoDtor->getTriggerStmt();
786  else
787    Trigger = Dtor->getBody();
788
789  return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
790                              State, CallerCtx);
791}
792
793