CallEvent.cpp revision 827eeb63614309bafac9d77a5a3a7ca81f1e4751
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() const {
211  dump(llvm::errs());
212}
213
214void CallEvent::dump(raw_ostream &Out) const {
215  ASTContext &Ctx = getState()->getStateManager().getContext();
216  if (const Expr *E = getOriginExpr()) {
217    E->printPretty(Out, 0, Ctx.getPrintingPolicy());
218    Out << "\n";
219    return;
220  }
221
222  if (const Decl *D = getDecl()) {
223    Out << "Call to ";
224    D->print(Out, Ctx.getPrintingPolicy());
225    return;
226  }
227
228  // FIXME: a string representation of the kind would be nice.
229  Out << "Unknown call (type " << getKind() << ")";
230}
231
232
233bool CallEvent::isCallStmt(const Stmt *S) {
234  return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
235                          || isa<CXXConstructExpr>(S)
236                          || isa<CXXNewExpr>(S);
237}
238
239static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
240                                         CallEvent::BindingsTy &Bindings,
241                                         SValBuilder &SVB,
242                                         const CallEvent &Call,
243                                         CallEvent::param_iterator I,
244                                         CallEvent::param_iterator E) {
245  MemRegionManager &MRMgr = SVB.getRegionManager();
246
247  unsigned Idx = 0;
248  for (; I != E; ++I, ++Idx) {
249    const ParmVarDecl *ParamDecl = *I;
250    assert(ParamDecl && "Formal parameter has no decl?");
251
252    SVal ArgVal = Call.getArgSVal(Idx);
253    if (!ArgVal.isUnknown()) {
254      Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
255      Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
256    }
257  }
258
259  // FIXME: Variadic arguments are not handled at all right now.
260}
261
262
263CallEvent::param_iterator AnyFunctionCall::param_begin() const {
264  const FunctionDecl *D = getDecl();
265  if (!D)
266    return 0;
267
268  return D->param_begin();
269}
270
271CallEvent::param_iterator AnyFunctionCall::param_end() const {
272  const FunctionDecl *D = getDecl();
273  if (!D)
274    return 0;
275
276  return D->param_end();
277}
278
279void AnyFunctionCall::getInitialStackFrameContents(
280                                        const StackFrameContext *CalleeCtx,
281                                        BindingsTy &Bindings) const {
282  const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
283  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
284  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
285                               D->param_begin(), D->param_end());
286}
287
288QualType AnyFunctionCall::getDeclaredResultType() const {
289  const FunctionDecl *D = getDecl();
290  if (!D)
291    return QualType();
292
293  return D->getResultType();
294}
295
296bool AnyFunctionCall::argumentsMayEscape() const {
297  if (hasNonZeroCallbackArg())
298    return true;
299
300  const FunctionDecl *D = getDecl();
301  if (!D)
302    return true;
303
304  const IdentifierInfo *II = D->getIdentifier();
305  if (!II)
306    return true;
307
308  // This set of "escaping" APIs is
309
310  // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
311  //   value into thread local storage. The value can later be retrieved with
312  //   'void *ptheread_getspecific(pthread_key)'. So even thought the
313  //   parameter is 'const void *', the region escapes through the call.
314  if (II->isStr("pthread_setspecific"))
315    return true;
316
317  // - xpc_connection_set_context stores a value which can be retrieved later
318  //   with xpc_connection_get_context.
319  if (II->isStr("xpc_connection_set_context"))
320    return true;
321
322  // - funopen - sets a buffer for future IO calls.
323  if (II->isStr("funopen"))
324    return true;
325
326  StringRef FName = II->getName();
327
328  // - CoreFoundation functions that end with "NoCopy" can free a passed-in
329  //   buffer even if it is const.
330  if (FName.endswith("NoCopy"))
331    return true;
332
333  // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
334  //   be deallocated by NSMapRemove.
335  if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
336    return true;
337
338  // - Many CF containers allow objects to escape through custom
339  //   allocators/deallocators upon container construction. (PR12101)
340  if (FName.startswith("CF") || FName.startswith("CG")) {
341    return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
342           StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
343           StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
344           StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
345           StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
346           StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
347  }
348
349  return false;
350}
351
352
353const FunctionDecl *SimpleCall::getDecl() const {
354  const FunctionDecl *D = getOriginExpr()->getDirectCallee();
355  if (D)
356    return D;
357
358  return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
359}
360
361
362const FunctionDecl *CXXInstanceCall::getDecl() const {
363  const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
364  if (!CE)
365    return AnyFunctionCall::getDecl();
366
367  const FunctionDecl *D = CE->getDirectCallee();
368  if (D)
369    return D;
370
371  return getSVal(CE->getCallee()).getAsFunctionDecl();
372}
373
374void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
375  if (const MemRegion *R = getCXXThisVal().getAsRegion())
376    Regions.push_back(R);
377}
378
379
380RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
381  // Do we have a decl at all?
382  const Decl *D = getDecl();
383  if (!D)
384    return RuntimeDefinition();
385
386  // If the method is non-virtual, we know we can inline it.
387  const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
388  if (!MD->isVirtual())
389    return AnyFunctionCall::getRuntimeDefinition();
390
391  // Do we know the implicit 'this' object being called?
392  const MemRegion *R = getCXXThisVal().getAsRegion();
393  if (!R)
394    return RuntimeDefinition();
395
396  // Do we know anything about the type of 'this'?
397  DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
398  if (!DynType.isValid())
399    return RuntimeDefinition();
400
401  // Is the type a C++ class? (This is mostly a defensive check.)
402  QualType RegionType = DynType.getType()->getPointeeType();
403  const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
404  if (!RD || !RD->hasDefinition())
405    return RuntimeDefinition();
406
407  // Find the decl for this method in that class.
408  const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
409  assert(Result && "At the very least the static decl should show up.");
410
411  // Does the decl that we found have an implementation?
412  const FunctionDecl *Definition;
413  if (!Result->hasBody(Definition))
414    return RuntimeDefinition();
415
416  // We found a definition. If we're not sure that this devirtualization is
417  // actually what will happen at runtime, make sure to provide the region so
418  // that ExprEngine can decide what to do with it.
419  if (DynType.canBeASubClass())
420    return RuntimeDefinition(Definition, R->StripCasts());
421  return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
422}
423
424void CXXInstanceCall::getInitialStackFrameContents(
425                                            const StackFrameContext *CalleeCtx,
426                                            BindingsTy &Bindings) const {
427  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
428
429  // Handle the binding of 'this' in the new stack frame.
430  SVal ThisVal = getCXXThisVal();
431  if (!ThisVal.isUnknown()) {
432    ProgramStateManager &StateMgr = getState()->getStateManager();
433    SValBuilder &SVB = StateMgr.getSValBuilder();
434
435    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
436    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
437
438    // If we devirtualized to a different member function, we need to make sure
439    // we have the proper layering of CXXBaseObjectRegions.
440    if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
441      ASTContext &Ctx = SVB.getContext();
442      const CXXRecordDecl *Class = MD->getParent();
443      QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
444
445      // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
446      bool Failed;
447      ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
448      assert(!Failed && "Calling an incorrectly devirtualized method");
449    }
450
451    if (!ThisVal.isUnknown())
452      Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
453  }
454}
455
456
457
458const Expr *CXXMemberCall::getCXXThisExpr() const {
459  return getOriginExpr()->getImplicitObjectArgument();
460}
461
462
463const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
464  return getOriginExpr()->getArg(0);
465}
466
467
468const BlockDataRegion *BlockCall::getBlockRegion() const {
469  const Expr *Callee = getOriginExpr()->getCallee();
470  const MemRegion *DataReg = getSVal(Callee).getAsRegion();
471
472  return dyn_cast_or_null<BlockDataRegion>(DataReg);
473}
474
475CallEvent::param_iterator BlockCall::param_begin() const {
476  const BlockDecl *D = getBlockDecl();
477  if (!D)
478    return 0;
479  return D->param_begin();
480}
481
482CallEvent::param_iterator BlockCall::param_end() const {
483  const BlockDecl *D = getBlockDecl();
484  if (!D)
485    return 0;
486  return D->param_end();
487}
488
489void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
490  // FIXME: This also needs to invalidate captured globals.
491  if (const MemRegion *R = getBlockRegion())
492    Regions.push_back(R);
493}
494
495void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
496                                             BindingsTy &Bindings) const {
497  const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
498  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
499  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
500                               D->param_begin(), D->param_end());
501}
502
503
504QualType BlockCall::getDeclaredResultType() const {
505  const BlockDataRegion *BR = getBlockRegion();
506  if (!BR)
507    return QualType();
508  QualType BlockTy = BR->getCodeRegion()->getLocationType();
509  return cast<FunctionType>(BlockTy->getPointeeType())->getResultType();
510}
511
512
513SVal CXXConstructorCall::getCXXThisVal() const {
514  if (Data)
515    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
516  return UnknownVal();
517}
518
519void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
520  if (Data)
521    Regions.push_back(static_cast<const MemRegion *>(Data));
522}
523
524void CXXConstructorCall::getInitialStackFrameContents(
525                                             const StackFrameContext *CalleeCtx,
526                                             BindingsTy &Bindings) const {
527  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
528
529  SVal ThisVal = getCXXThisVal();
530  if (!ThisVal.isUnknown()) {
531    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
532    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
533    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
534    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
535  }
536}
537
538
539
540SVal CXXDestructorCall::getCXXThisVal() const {
541  if (Data)
542    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
543  return UnknownVal();
544}
545
546
547CallEvent::param_iterator ObjCMethodCall::param_begin() const {
548  const ObjCMethodDecl *D = getDecl();
549  if (!D)
550    return 0;
551
552  return D->param_begin();
553}
554
555CallEvent::param_iterator ObjCMethodCall::param_end() const {
556  const ObjCMethodDecl *D = getDecl();
557  if (!D)
558    return 0;
559
560  return D->param_end();
561}
562
563void
564ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
565  if (const MemRegion *R = getReceiverSVal().getAsRegion())
566    Regions.push_back(R);
567}
568
569QualType ObjCMethodCall::getDeclaredResultType() const {
570  const ObjCMethodDecl *D = getDecl();
571  if (!D)
572    return QualType();
573
574  return D->getResultType();
575}
576
577SVal ObjCMethodCall::getSelfSVal() const {
578  const LocationContext *LCtx = getLocationContext();
579  const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
580  if (!SelfDecl)
581    return SVal();
582  return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
583}
584
585SVal ObjCMethodCall::getReceiverSVal() const {
586  // FIXME: Is this the best way to handle class receivers?
587  if (!isInstanceMessage())
588    return UnknownVal();
589
590  if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
591    return getSVal(RecE);
592
593  // An instance message with no expression means we are sending to super.
594  // In this case the object reference is the same as 'self'.
595  assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
596  SVal SelfVal = getSelfSVal();
597  assert(SelfVal.isValid() && "Calling super but not in ObjC method");
598  return SelfVal;
599}
600
601bool ObjCMethodCall::isReceiverSelfOrSuper() const {
602  if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
603      getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
604      return true;
605
606  if (!isInstanceMessage())
607    return false;
608
609  SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
610
611  return (RecVal == getSelfSVal());
612}
613
614SourceRange ObjCMethodCall::getSourceRange() const {
615  switch (getMessageKind()) {
616  case OCM_Message:
617    return getOriginExpr()->getSourceRange();
618  case OCM_PropertyAccess:
619  case OCM_Subscript:
620    return getContainingPseudoObjectExpr()->getSourceRange();
621  }
622  llvm_unreachable("unknown message kind");
623}
624
625typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
626
627const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
628  assert(Data != 0 && "Lazy lookup not yet performed.");
629  assert(getMessageKind() != OCM_Message && "Explicit message send.");
630  return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
631}
632
633ObjCMessageKind ObjCMethodCall::getMessageKind() const {
634  if (Data == 0) {
635    ParentMap &PM = getLocationContext()->getParentMap();
636    const Stmt *S = PM.getParent(getOriginExpr());
637    if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
638      const Expr *Syntactic = POE->getSyntacticForm();
639
640      // This handles the funny case of assigning to the result of a getter.
641      // This can happen if the getter returns a non-const reference.
642      if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
643        Syntactic = BO->getLHS();
644
645      ObjCMessageKind K;
646      switch (Syntactic->getStmtClass()) {
647      case Stmt::ObjCPropertyRefExprClass:
648        K = OCM_PropertyAccess;
649        break;
650      case Stmt::ObjCSubscriptRefExprClass:
651        K = OCM_Subscript;
652        break;
653      default:
654        // FIXME: Can this ever happen?
655        K = OCM_Message;
656        break;
657      }
658
659      if (K != OCM_Message) {
660        const_cast<ObjCMethodCall *>(this)->Data
661          = ObjCMessageDataTy(POE, K).getOpaqueValue();
662        assert(getMessageKind() == K);
663        return K;
664      }
665    }
666
667    const_cast<ObjCMethodCall *>(this)->Data
668      = ObjCMessageDataTy(0, 1).getOpaqueValue();
669    assert(getMessageKind() == OCM_Message);
670    return OCM_Message;
671  }
672
673  ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
674  if (!Info.getPointer())
675    return OCM_Message;
676  return static_cast<ObjCMessageKind>(Info.getInt());
677}
678
679
680bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
681                                             Selector Sel) const {
682  assert(IDecl);
683  const SourceManager &SM =
684    getState()->getStateManager().getContext().getSourceManager();
685
686  // If the class interface is declared inside the main file, assume it is not
687  // subcassed.
688  // TODO: It could actually be subclassed if the subclass is private as well.
689  // This is probably very rare.
690  SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
691  if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
692    return false;
693
694  // Assume that property accessors are not overridden.
695  if (getMessageKind() == OCM_PropertyAccess)
696    return false;
697
698  // We assume that if the method is public (declared outside of main file) or
699  // has a parent which publicly declares the method, the method could be
700  // overridden in a subclass.
701
702  // Find the first declaration in the class hierarchy that declares
703  // the selector.
704  ObjCMethodDecl *D = 0;
705  while (true) {
706    D = IDecl->lookupMethod(Sel, true);
707
708    // Cannot find a public definition.
709    if (!D)
710      return false;
711
712    // If outside the main file,
713    if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
714      return true;
715
716    if (D->isOverriding()) {
717      // Search in the superclass on the next iteration.
718      IDecl = D->getClassInterface();
719      if (!IDecl)
720        return false;
721
722      IDecl = IDecl->getSuperClass();
723      if (!IDecl)
724        return false;
725
726      continue;
727    }
728
729    return false;
730  };
731
732  llvm_unreachable("The while loop should always terminate.");
733}
734
735RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
736  const ObjCMessageExpr *E = getOriginExpr();
737  assert(E);
738  Selector Sel = E->getSelector();
739
740  if (E->isInstanceMessage()) {
741
742    // Find the the receiver type.
743    const ObjCObjectPointerType *ReceiverT = 0;
744    bool CanBeSubClassed = false;
745    QualType SupersType = E->getSuperType();
746    const MemRegion *Receiver = 0;
747
748    if (!SupersType.isNull()) {
749      // Super always means the type of immediate predecessor to the method
750      // where the call occurs.
751      ReceiverT = cast<ObjCObjectPointerType>(SupersType);
752    } else {
753      Receiver = getReceiverSVal().getAsRegion();
754      if (!Receiver)
755        return RuntimeDefinition();
756
757      DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
758      QualType DynType = DTI.getType();
759      CanBeSubClassed = DTI.canBeASubClass();
760      ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
761
762      if (ReceiverT && CanBeSubClassed)
763        if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
764          if (!canBeOverridenInSubclass(IDecl, Sel))
765            CanBeSubClassed = false;
766    }
767
768    // Lookup the method implementation.
769    if (ReceiverT)
770      if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
771        const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel);
772        if (CanBeSubClassed)
773          return RuntimeDefinition(MD, Receiver);
774        else
775          return RuntimeDefinition(MD, 0);
776      }
777
778  } else {
779    // This is a class method.
780    // If we have type info for the receiver class, we are calling via
781    // class name.
782    if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
783      // Find/Return the method implementation.
784      return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
785    }
786  }
787
788  return RuntimeDefinition();
789}
790
791void ObjCMethodCall::getInitialStackFrameContents(
792                                             const StackFrameContext *CalleeCtx,
793                                             BindingsTy &Bindings) const {
794  const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
795  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
796  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
797                               D->param_begin(), D->param_end());
798
799  SVal SelfVal = getReceiverSVal();
800  if (!SelfVal.isUnknown()) {
801    const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
802    MemRegionManager &MRMgr = SVB.getRegionManager();
803    Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
804    Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
805  }
806}
807
808CallEventRef<>
809CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
810                                const LocationContext *LCtx) {
811  if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
812    return create<CXXMemberCall>(MCE, State, LCtx);
813
814  if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
815    const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
816    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
817      if (MD->isInstance())
818        return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
819
820  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
821    return create<BlockCall>(CE, State, LCtx);
822  }
823
824  // Otherwise, it's a normal function call, static member function call, or
825  // something we can't reason about.
826  return create<FunctionCall>(CE, State, LCtx);
827}
828
829
830CallEventRef<>
831CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
832                            ProgramStateRef State) {
833  const LocationContext *ParentCtx = CalleeCtx->getParent();
834  const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
835  assert(CallerCtx && "This should not be used for top-level stack frames");
836
837  const Stmt *CallSite = CalleeCtx->getCallSite();
838
839  if (CallSite) {
840    if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
841      return getSimpleCall(CE, State, CallerCtx);
842
843    switch (CallSite->getStmtClass()) {
844    case Stmt::CXXConstructExprClass:
845    case Stmt::CXXTemporaryObjectExprClass: {
846      SValBuilder &SVB = State->getStateManager().getSValBuilder();
847      const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
848      Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
849      SVal ThisVal = State->getSVal(ThisPtr);
850
851      return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
852                                   ThisVal.getAsRegion(), State, CallerCtx);
853    }
854    case Stmt::CXXNewExprClass:
855      return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
856    case Stmt::ObjCMessageExprClass:
857      return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
858                               State, CallerCtx);
859    default:
860      llvm_unreachable("This is not an inlineable statement.");
861    }
862  }
863
864  // Fall back to the CFG. The only thing we haven't handled yet is
865  // destructors, though this could change in the future.
866  const CFGBlock *B = CalleeCtx->getCallSiteBlock();
867  CFGElement E = (*B)[CalleeCtx->getIndex()];
868  assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
869  assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
870
871  SValBuilder &SVB = State->getStateManager().getSValBuilder();
872  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
873  Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
874  SVal ThisVal = State->getSVal(ThisPtr);
875
876  const Stmt *Trigger;
877  if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
878    Trigger = AutoDtor->getTriggerStmt();
879  else
880    Trigger = Dtor->getBody();
881
882  return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
883                              State, CallerCtx);
884}
885