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