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