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