1 //== MemRegion.cpp - Abstract memory regions for static analysis --*- 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 // This file defines MemRegion and its subclasses. MemRegion defines a 11 // partially-typed abstraction of memory useful for path-sensitive dataflow 12 // analyses. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/RecordLayout.h" 21 #include "clang/Analysis/AnalysisContext.h" 22 #include "clang/Analysis/Support/BumpVector.h" 23 #include "clang/Basic/SourceManager.h" 24 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 25 #include "llvm/Support/raw_ostream.h" 26 27 using namespace clang; 28 using namespace ento; 29 30 //===----------------------------------------------------------------------===// 31 // MemRegion Construction. 32 //===----------------------------------------------------------------------===// 33 34 template <typename RegionTy, typename A1> 35 RegionTy* MemRegionManager::getSubRegion(const A1 a1, 36 const MemRegion *superRegion) { 37 llvm::FoldingSetNodeID ID; 38 RegionTy::ProfileRegion(ID, a1, superRegion); 39 void *InsertPos; 40 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, 41 InsertPos)); 42 43 if (!R) { 44 R = A.Allocate<RegionTy>(); 45 new (R) RegionTy(a1, superRegion); 46 Regions.InsertNode(R, InsertPos); 47 } 48 49 return R; 50 } 51 52 template <typename RegionTy, typename A1, typename A2> 53 RegionTy* MemRegionManager::getSubRegion(const A1 a1, const A2 a2, 54 const MemRegion *superRegion) { 55 llvm::FoldingSetNodeID ID; 56 RegionTy::ProfileRegion(ID, a1, a2, superRegion); 57 void *InsertPos; 58 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, 59 InsertPos)); 60 61 if (!R) { 62 R = A.Allocate<RegionTy>(); 63 new (R) RegionTy(a1, a2, superRegion); 64 Regions.InsertNode(R, InsertPos); 65 } 66 67 return R; 68 } 69 70 template <typename RegionTy, typename A1, typename A2, typename A3> 71 RegionTy* MemRegionManager::getSubRegion(const A1 a1, const A2 a2, const A3 a3, 72 const MemRegion *superRegion) { 73 llvm::FoldingSetNodeID ID; 74 RegionTy::ProfileRegion(ID, a1, a2, a3, superRegion); 75 void *InsertPos; 76 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, 77 InsertPos)); 78 79 if (!R) { 80 R = A.Allocate<RegionTy>(); 81 new (R) RegionTy(a1, a2, a3, superRegion); 82 Regions.InsertNode(R, InsertPos); 83 } 84 85 return R; 86 } 87 88 //===----------------------------------------------------------------------===// 89 // Object destruction. 90 //===----------------------------------------------------------------------===// 91 92 MemRegion::~MemRegion() {} 93 94 MemRegionManager::~MemRegionManager() { 95 // All regions and their data are BumpPtrAllocated. No need to call 96 // their destructors. 97 } 98 99 //===----------------------------------------------------------------------===// 100 // Basic methods. 101 //===----------------------------------------------------------------------===// 102 103 bool SubRegion::isSubRegionOf(const MemRegion* R) const { 104 const MemRegion* r = getSuperRegion(); 105 while (r != nullptr) { 106 if (r == R) 107 return true; 108 if (const SubRegion* sr = dyn_cast<SubRegion>(r)) 109 r = sr->getSuperRegion(); 110 else 111 break; 112 } 113 return false; 114 } 115 116 MemRegionManager* SubRegion::getMemRegionManager() const { 117 const SubRegion* r = this; 118 do { 119 const MemRegion *superRegion = r->getSuperRegion(); 120 if (const SubRegion *sr = dyn_cast<SubRegion>(superRegion)) { 121 r = sr; 122 continue; 123 } 124 return superRegion->getMemRegionManager(); 125 } while (1); 126 } 127 128 const StackFrameContext *VarRegion::getStackFrame() const { 129 const StackSpaceRegion *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace()); 130 return SSR ? SSR->getStackFrame() : nullptr; 131 } 132 133 //===----------------------------------------------------------------------===// 134 // Region extents. 135 //===----------------------------------------------------------------------===// 136 137 DefinedOrUnknownSVal TypedValueRegion::getExtent(SValBuilder &svalBuilder) const { 138 ASTContext &Ctx = svalBuilder.getContext(); 139 QualType T = getDesugaredValueType(Ctx); 140 141 if (isa<VariableArrayType>(T)) 142 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this)); 143 if (T->isIncompleteType()) 144 return UnknownVal(); 145 146 CharUnits size = Ctx.getTypeSizeInChars(T); 147 QualType sizeTy = svalBuilder.getArrayIndexType(); 148 return svalBuilder.makeIntVal(size.getQuantity(), sizeTy); 149 } 150 151 DefinedOrUnknownSVal FieldRegion::getExtent(SValBuilder &svalBuilder) const { 152 // Force callers to deal with bitfields explicitly. 153 if (getDecl()->isBitField()) 154 return UnknownVal(); 155 156 DefinedOrUnknownSVal Extent = DeclRegion::getExtent(svalBuilder); 157 158 // A zero-length array at the end of a struct often stands for dynamically- 159 // allocated extra memory. 160 if (Extent.isZeroConstant()) { 161 QualType T = getDesugaredValueType(svalBuilder.getContext()); 162 163 if (isa<ConstantArrayType>(T)) 164 return UnknownVal(); 165 } 166 167 return Extent; 168 } 169 170 DefinedOrUnknownSVal AllocaRegion::getExtent(SValBuilder &svalBuilder) const { 171 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this)); 172 } 173 174 DefinedOrUnknownSVal SymbolicRegion::getExtent(SValBuilder &svalBuilder) const { 175 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this)); 176 } 177 178 DefinedOrUnknownSVal StringRegion::getExtent(SValBuilder &svalBuilder) const { 179 return svalBuilder.makeIntVal(getStringLiteral()->getByteLength()+1, 180 svalBuilder.getArrayIndexType()); 181 } 182 183 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg) 184 : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {} 185 186 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { 187 return cast<ObjCIvarDecl>(D); 188 } 189 190 QualType ObjCIvarRegion::getValueType() const { 191 return getDecl()->getType(); 192 } 193 194 QualType CXXBaseObjectRegion::getValueType() const { 195 return QualType(getDecl()->getTypeForDecl(), 0); 196 } 197 198 //===----------------------------------------------------------------------===// 199 // FoldingSet profiling. 200 //===----------------------------------------------------------------------===// 201 202 void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const { 203 ID.AddInteger(static_cast<unsigned>(getKind())); 204 } 205 206 void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const { 207 ID.AddInteger(static_cast<unsigned>(getKind())); 208 ID.AddPointer(getStackFrame()); 209 } 210 211 void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const { 212 ID.AddInteger(static_cast<unsigned>(getKind())); 213 ID.AddPointer(getCodeRegion()); 214 } 215 216 void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 217 const StringLiteral* Str, 218 const MemRegion* superRegion) { 219 ID.AddInteger(static_cast<unsigned>(StringRegionKind)); 220 ID.AddPointer(Str); 221 ID.AddPointer(superRegion); 222 } 223 224 void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 225 const ObjCStringLiteral* Str, 226 const MemRegion* superRegion) { 227 ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind)); 228 ID.AddPointer(Str); 229 ID.AddPointer(superRegion); 230 } 231 232 void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 233 const Expr *Ex, unsigned cnt, 234 const MemRegion *superRegion) { 235 ID.AddInteger(static_cast<unsigned>(AllocaRegionKind)); 236 ID.AddPointer(Ex); 237 ID.AddInteger(cnt); 238 ID.AddPointer(superRegion); 239 } 240 241 void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const { 242 ProfileRegion(ID, Ex, Cnt, superRegion); 243 } 244 245 void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const { 246 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion); 247 } 248 249 void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 250 const CompoundLiteralExpr *CL, 251 const MemRegion* superRegion) { 252 ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind)); 253 ID.AddPointer(CL); 254 ID.AddPointer(superRegion); 255 } 256 257 void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, 258 const PointerType *PT, 259 const MemRegion *sRegion) { 260 ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind)); 261 ID.AddPointer(PT); 262 ID.AddPointer(sRegion); 263 } 264 265 void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const { 266 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion); 267 } 268 269 void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 270 const ObjCIvarDecl *ivd, 271 const MemRegion* superRegion) { 272 DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind); 273 } 274 275 void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D, 276 const MemRegion* superRegion, Kind k) { 277 ID.AddInteger(static_cast<unsigned>(k)); 278 ID.AddPointer(D); 279 ID.AddPointer(superRegion); 280 } 281 282 void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const { 283 DeclRegion::ProfileRegion(ID, D, superRegion, getKind()); 284 } 285 286 void VarRegion::Profile(llvm::FoldingSetNodeID &ID) const { 287 VarRegion::ProfileRegion(ID, getDecl(), superRegion); 288 } 289 290 void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym, 291 const MemRegion *sreg) { 292 ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind)); 293 ID.Add(sym); 294 ID.AddPointer(sreg); 295 } 296 297 void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const { 298 SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion()); 299 } 300 301 void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 302 QualType ElementType, SVal Idx, 303 const MemRegion* superRegion) { 304 ID.AddInteger(MemRegion::ElementRegionKind); 305 ID.Add(ElementType); 306 ID.AddPointer(superRegion); 307 Idx.Profile(ID); 308 } 309 310 void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const { 311 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion); 312 } 313 314 void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 315 const NamedDecl *FD, 316 const MemRegion*) { 317 ID.AddInteger(MemRegion::FunctionCodeRegionKind); 318 ID.AddPointer(FD); 319 } 320 321 void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const { 322 FunctionCodeRegion::ProfileRegion(ID, FD, superRegion); 323 } 324 325 void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 326 const BlockDecl *BD, CanQualType, 327 const AnalysisDeclContext *AC, 328 const MemRegion*) { 329 ID.AddInteger(MemRegion::BlockCodeRegionKind); 330 ID.AddPointer(BD); 331 } 332 333 void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const { 334 BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion); 335 } 336 337 void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, 338 const BlockCodeRegion *BC, 339 const LocationContext *LC, 340 unsigned BlkCount, 341 const MemRegion *sReg) { 342 ID.AddInteger(MemRegion::BlockDataRegionKind); 343 ID.AddPointer(BC); 344 ID.AddPointer(LC); 345 ID.AddInteger(BlkCount); 346 ID.AddPointer(sReg); 347 } 348 349 void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const { 350 BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion()); 351 } 352 353 void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, 354 Expr const *Ex, 355 const MemRegion *sReg) { 356 ID.AddPointer(Ex); 357 ID.AddPointer(sReg); 358 } 359 360 void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const { 361 ProfileRegion(ID, Ex, getSuperRegion()); 362 } 363 364 void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, 365 const CXXRecordDecl *RD, 366 bool IsVirtual, 367 const MemRegion *SReg) { 368 ID.AddPointer(RD); 369 ID.AddBoolean(IsVirtual); 370 ID.AddPointer(SReg); 371 } 372 373 void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const { 374 ProfileRegion(ID, getDecl(), isVirtual(), superRegion); 375 } 376 377 //===----------------------------------------------------------------------===// 378 // Region anchors. 379 //===----------------------------------------------------------------------===// 380 381 void GlobalsSpaceRegion::anchor() { } 382 void HeapSpaceRegion::anchor() { } 383 void UnknownSpaceRegion::anchor() { } 384 void StackLocalsSpaceRegion::anchor() { } 385 void StackArgumentsSpaceRegion::anchor() { } 386 void TypedRegion::anchor() { } 387 void TypedValueRegion::anchor() { } 388 void CodeTextRegion::anchor() { } 389 void SubRegion::anchor() { } 390 391 //===----------------------------------------------------------------------===// 392 // Region pretty-printing. 393 //===----------------------------------------------------------------------===// 394 395 LLVM_DUMP_METHOD void MemRegion::dump() const { 396 dumpToStream(llvm::errs()); 397 } 398 399 std::string MemRegion::getString() const { 400 std::string s; 401 llvm::raw_string_ostream os(s); 402 dumpToStream(os); 403 return os.str(); 404 } 405 406 void MemRegion::dumpToStream(raw_ostream &os) const { 407 os << "<Unknown Region>"; 408 } 409 410 void AllocaRegion::dumpToStream(raw_ostream &os) const { 411 os << "alloca{" << static_cast<const void*>(Ex) << ',' << Cnt << '}'; 412 } 413 414 void FunctionCodeRegion::dumpToStream(raw_ostream &os) const { 415 os << "code{" << getDecl()->getDeclName().getAsString() << '}'; 416 } 417 418 void BlockCodeRegion::dumpToStream(raw_ostream &os) const { 419 os << "block_code{" << static_cast<const void*>(this) << '}'; 420 } 421 422 void BlockDataRegion::dumpToStream(raw_ostream &os) const { 423 os << "block_data{" << BC; 424 os << "; "; 425 for (BlockDataRegion::referenced_vars_iterator 426 I = referenced_vars_begin(), 427 E = referenced_vars_end(); I != E; ++I) 428 os << "(" << I.getCapturedRegion() << "," << 429 I.getOriginalRegion() << ") "; 430 os << '}'; 431 } 432 433 void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const { 434 // FIXME: More elaborate pretty-printing. 435 os << "{ " << static_cast<const void*>(CL) << " }"; 436 } 437 438 void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const { 439 os << "temp_object{" << getValueType().getAsString() << ',' 440 << static_cast<const void*>(Ex) << '}'; 441 } 442 443 void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const { 444 os << "base{" << superRegion << ',' << getDecl()->getName() << '}'; 445 } 446 447 void CXXThisRegion::dumpToStream(raw_ostream &os) const { 448 os << "this"; 449 } 450 451 void ElementRegion::dumpToStream(raw_ostream &os) const { 452 os << "element{" << superRegion << ',' 453 << Index << ',' << getElementType().getAsString() << '}'; 454 } 455 456 void FieldRegion::dumpToStream(raw_ostream &os) const { 457 os << superRegion << "->" << *getDecl(); 458 } 459 460 void ObjCIvarRegion::dumpToStream(raw_ostream &os) const { 461 os << "ivar{" << superRegion << ',' << *getDecl() << '}'; 462 } 463 464 void StringRegion::dumpToStream(raw_ostream &os) const { 465 assert(Str != nullptr && "Expecting non-null StringLiteral"); 466 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts())); 467 } 468 469 void ObjCStringRegion::dumpToStream(raw_ostream &os) const { 470 assert(Str != nullptr && "Expecting non-null ObjCStringLiteral"); 471 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts())); 472 } 473 474 void SymbolicRegion::dumpToStream(raw_ostream &os) const { 475 os << "SymRegion{" << sym << '}'; 476 } 477 478 void VarRegion::dumpToStream(raw_ostream &os) const { 479 os << *cast<VarDecl>(D); 480 } 481 482 LLVM_DUMP_METHOD void RegionRawOffset::dump() const { 483 dumpToStream(llvm::errs()); 484 } 485 486 void RegionRawOffset::dumpToStream(raw_ostream &os) const { 487 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}'; 488 } 489 490 void CodeSpaceRegion::dumpToStream(raw_ostream &os) const { 491 os << "CodeSpaceRegion"; 492 } 493 494 void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const { 495 os << "StaticGlobalsMemSpace{" << CR << '}'; 496 } 497 498 void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const { 499 os << "GlobalInternalSpaceRegion"; 500 } 501 502 void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const { 503 os << "GlobalSystemSpaceRegion"; 504 } 505 506 void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const { 507 os << "GlobalImmutableSpaceRegion"; 508 } 509 510 void HeapSpaceRegion::dumpToStream(raw_ostream &os) const { 511 os << "HeapSpaceRegion"; 512 } 513 514 void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const { 515 os << "UnknownSpaceRegion"; 516 } 517 518 void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const { 519 os << "StackArgumentsSpaceRegion"; 520 } 521 522 void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const { 523 os << "StackLocalsSpaceRegion"; 524 } 525 526 bool MemRegion::canPrintPretty() const { 527 return canPrintPrettyAsExpr(); 528 } 529 530 bool MemRegion::canPrintPrettyAsExpr() const { 531 return false; 532 } 533 534 void MemRegion::printPretty(raw_ostream &os) const { 535 assert(canPrintPretty() && "This region cannot be printed pretty."); 536 os << "'"; 537 printPrettyAsExpr(os); 538 os << "'"; 539 } 540 541 void MemRegion::printPrettyAsExpr(raw_ostream &os) const { 542 llvm_unreachable("This region cannot be printed pretty."); 543 } 544 545 bool VarRegion::canPrintPrettyAsExpr() const { 546 return true; 547 } 548 549 void VarRegion::printPrettyAsExpr(raw_ostream &os) const { 550 os << getDecl()->getName(); 551 } 552 553 bool ObjCIvarRegion::canPrintPrettyAsExpr() const { 554 return true; 555 } 556 557 void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const { 558 os << getDecl()->getName(); 559 } 560 561 bool FieldRegion::canPrintPretty() const { 562 return true; 563 } 564 565 bool FieldRegion::canPrintPrettyAsExpr() const { 566 return superRegion->canPrintPrettyAsExpr(); 567 } 568 569 void FieldRegion::printPrettyAsExpr(raw_ostream &os) const { 570 assert(canPrintPrettyAsExpr()); 571 superRegion->printPrettyAsExpr(os); 572 os << "." << getDecl()->getName(); 573 } 574 575 void FieldRegion::printPretty(raw_ostream &os) const { 576 if (canPrintPrettyAsExpr()) { 577 os << "\'"; 578 printPrettyAsExpr(os); 579 os << "'"; 580 } else { 581 os << "field " << "\'" << getDecl()->getName() << "'"; 582 } 583 } 584 585 bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const { 586 return superRegion->canPrintPrettyAsExpr(); 587 } 588 589 void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const { 590 superRegion->printPrettyAsExpr(os); 591 } 592 593 std::string MemRegion::getDescriptiveName(bool UseQuotes) const { 594 std::string VariableName; 595 std::string ArrayIndices; 596 const MemRegion *R = this; 597 SmallString<50> buf; 598 llvm::raw_svector_ostream os(buf); 599 600 // Obtain array indices to add them to the variable name. 601 const ElementRegion *ER = nullptr; 602 while ((ER = R->getAs<ElementRegion>())) { 603 // Index is a ConcreteInt. 604 if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) { 605 llvm::SmallString<2> Idx; 606 CI->getValue().toString(Idx); 607 ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str(); 608 } 609 // If not a ConcreteInt, try to obtain the variable 610 // name by calling 'getDescriptiveName' recursively. 611 else { 612 std::string Idx = ER->getDescriptiveName(false); 613 if (!Idx.empty()) { 614 ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str(); 615 } 616 } 617 R = ER->getSuperRegion(); 618 } 619 620 // Get variable name. 621 if (R && R->canPrintPrettyAsExpr()) { 622 R->printPrettyAsExpr(os); 623 if (UseQuotes) { 624 return (llvm::Twine("'") + os.str() + ArrayIndices + "'").str(); 625 } else { 626 return (llvm::Twine(os.str()) + ArrayIndices).str(); 627 } 628 } 629 630 return VariableName; 631 } 632 633 SourceRange MemRegion::sourceRange() const { 634 const VarRegion *const VR = dyn_cast<VarRegion>(this->getBaseRegion()); 635 const FieldRegion *const FR = dyn_cast<FieldRegion>(this); 636 637 // Check for more specific regions first. 638 // FieldRegion 639 if (FR) { 640 return FR->getDecl()->getSourceRange(); 641 } 642 // VarRegion 643 else if (VR) { 644 return VR->getDecl()->getSourceRange(); 645 } 646 // Return invalid source range (can be checked by client). 647 else { 648 return SourceRange{}; 649 } 650 } 651 652 //===----------------------------------------------------------------------===// 653 // MemRegionManager methods. 654 //===----------------------------------------------------------------------===// 655 656 template <typename REG> 657 const REG *MemRegionManager::LazyAllocate(REG*& region) { 658 if (!region) { 659 region = A.Allocate<REG>(); 660 new (region) REG(this); 661 } 662 663 return region; 664 } 665 666 template <typename REG, typename ARG> 667 const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) { 668 if (!region) { 669 region = A.Allocate<REG>(); 670 new (region) REG(this, a); 671 } 672 673 return region; 674 } 675 676 const StackLocalsSpaceRegion* 677 MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) { 678 assert(STC); 679 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC]; 680 681 if (R) 682 return R; 683 684 R = A.Allocate<StackLocalsSpaceRegion>(); 685 new (R) StackLocalsSpaceRegion(this, STC); 686 return R; 687 } 688 689 const StackArgumentsSpaceRegion * 690 MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) { 691 assert(STC); 692 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC]; 693 694 if (R) 695 return R; 696 697 R = A.Allocate<StackArgumentsSpaceRegion>(); 698 new (R) StackArgumentsSpaceRegion(this, STC); 699 return R; 700 } 701 702 const GlobalsSpaceRegion 703 *MemRegionManager::getGlobalsRegion(MemRegion::Kind K, 704 const CodeTextRegion *CR) { 705 if (!CR) { 706 if (K == MemRegion::GlobalSystemSpaceRegionKind) 707 return LazyAllocate(SystemGlobals); 708 if (K == MemRegion::GlobalImmutableSpaceRegionKind) 709 return LazyAllocate(ImmutableGlobals); 710 assert(K == MemRegion::GlobalInternalSpaceRegionKind); 711 return LazyAllocate(InternalGlobals); 712 } 713 714 assert(K == MemRegion::StaticGlobalSpaceRegionKind); 715 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR]; 716 if (R) 717 return R; 718 719 R = A.Allocate<StaticGlobalSpaceRegion>(); 720 new (R) StaticGlobalSpaceRegion(this, CR); 721 return R; 722 } 723 724 const HeapSpaceRegion *MemRegionManager::getHeapRegion() { 725 return LazyAllocate(heap); 726 } 727 728 const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() { 729 return LazyAllocate(unknown); 730 } 731 732 const CodeSpaceRegion *MemRegionManager::getCodeRegion() { 733 return LazyAllocate(code); 734 } 735 736 //===----------------------------------------------------------------------===// 737 // Constructing regions. 738 //===----------------------------------------------------------------------===// 739 const StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str){ 740 return getSubRegion<StringRegion>(Str, getGlobalsRegion()); 741 } 742 743 const ObjCStringRegion * 744 MemRegionManager::getObjCStringRegion(const ObjCStringLiteral* Str){ 745 return getSubRegion<ObjCStringRegion>(Str, getGlobalsRegion()); 746 } 747 748 /// Look through a chain of LocationContexts to either find the 749 /// StackFrameContext that matches a DeclContext, or find a VarRegion 750 /// for a variable captured by a block. 751 static llvm::PointerUnion<const StackFrameContext *, const VarRegion *> 752 getStackOrCaptureRegionForDeclContext(const LocationContext *LC, 753 const DeclContext *DC, 754 const VarDecl *VD) { 755 while (LC) { 756 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) { 757 if (cast<DeclContext>(SFC->getDecl()) == DC) 758 return SFC; 759 } 760 if (const BlockInvocationContext *BC = 761 dyn_cast<BlockInvocationContext>(LC)) { 762 const BlockDataRegion *BR = 763 static_cast<const BlockDataRegion*>(BC->getContextData()); 764 // FIXME: This can be made more efficient. 765 for (BlockDataRegion::referenced_vars_iterator 766 I = BR->referenced_vars_begin(), 767 E = BR->referenced_vars_end(); I != E; ++I) { 768 if (const VarRegion *VR = dyn_cast<VarRegion>(I.getOriginalRegion())) 769 if (VR->getDecl() == VD) 770 return cast<VarRegion>(I.getCapturedRegion()); 771 } 772 } 773 774 LC = LC->getParent(); 775 } 776 return (const StackFrameContext *)nullptr; 777 } 778 779 const VarRegion* MemRegionManager::getVarRegion(const VarDecl *D, 780 const LocationContext *LC) { 781 const MemRegion *sReg = nullptr; 782 783 if (D->hasGlobalStorage() && !D->isStaticLocal()) { 784 785 // First handle the globals defined in system headers. 786 if (C.getSourceManager().isInSystemHeader(D->getLocation())) { 787 // Whitelist the system globals which often DO GET modified, assume the 788 // rest are immutable. 789 if (D->getName().find("errno") != StringRef::npos) 790 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind); 791 else 792 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind); 793 794 // Treat other globals as GlobalInternal unless they are constants. 795 } else { 796 QualType GQT = D->getType(); 797 const Type *GT = GQT.getTypePtrOrNull(); 798 // TODO: We could walk the complex types here and see if everything is 799 // constified. 800 if (GT && GQT.isConstQualified() && GT->isArithmeticType()) 801 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind); 802 else 803 sReg = getGlobalsRegion(); 804 } 805 806 // Finally handle static locals. 807 } else { 808 // FIXME: Once we implement scope handling, we will need to properly lookup 809 // 'D' to the proper LocationContext. 810 const DeclContext *DC = D->getDeclContext(); 811 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V = 812 getStackOrCaptureRegionForDeclContext(LC, DC, D); 813 814 if (V.is<const VarRegion*>()) 815 return V.get<const VarRegion*>(); 816 817 const StackFrameContext *STC = V.get<const StackFrameContext*>(); 818 819 if (!STC) { 820 // FIXME: Assign a more sensible memory space to static locals 821 // we see from within blocks that we analyze as top-level declarations. 822 sReg = getUnknownRegion(); 823 } else { 824 if (D->hasLocalStorage()) { 825 sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) 826 ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC)) 827 : static_cast<const MemRegion*>(getStackLocalsRegion(STC)); 828 } 829 else { 830 assert(D->isStaticLocal()); 831 const Decl *STCD = STC->getDecl(); 832 if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD)) 833 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind, 834 getFunctionCodeRegion(cast<NamedDecl>(STCD))); 835 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(STCD)) { 836 // FIXME: The fallback type here is totally bogus -- though it should 837 // never be queried, it will prevent uniquing with the real 838 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a 839 // signature. 840 QualType T; 841 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) 842 T = TSI->getType(); 843 if (T.isNull()) 844 T = getContext().VoidTy; 845 if (!T->getAs<FunctionType>()) 846 T = getContext().getFunctionNoProtoType(T); 847 T = getContext().getBlockPointerType(T); 848 849 const BlockCodeRegion *BTR = 850 getBlockCodeRegion(BD, C.getCanonicalType(T), 851 STC->getAnalysisDeclContext()); 852 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind, 853 BTR); 854 } 855 else { 856 sReg = getGlobalsRegion(); 857 } 858 } 859 } 860 } 861 862 return getSubRegion<VarRegion>(D, sReg); 863 } 864 865 const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D, 866 const MemRegion *superR) { 867 return getSubRegion<VarRegion>(D, superR); 868 } 869 870 const BlockDataRegion * 871 MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC, 872 const LocationContext *LC, 873 unsigned blockCount) { 874 const MemRegion *sReg = nullptr; 875 const BlockDecl *BD = BC->getDecl(); 876 if (!BD->hasCaptures()) { 877 // This handles 'static' blocks. 878 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind); 879 } 880 else { 881 if (LC) { 882 // FIXME: Once we implement scope handling, we want the parent region 883 // to be the scope. 884 const StackFrameContext *STC = LC->getCurrentStackFrame(); 885 assert(STC); 886 sReg = getStackLocalsRegion(STC); 887 } 888 else { 889 // We allow 'LC' to be NULL for cases where want BlockDataRegions 890 // without context-sensitivity. 891 sReg = getUnknownRegion(); 892 } 893 } 894 895 return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg); 896 } 897 898 const CXXTempObjectRegion * 899 MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) { 900 return getSubRegion<CXXTempObjectRegion>( 901 Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr)); 902 } 903 904 const CompoundLiteralRegion* 905 MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL, 906 const LocationContext *LC) { 907 const MemRegion *sReg = nullptr; 908 909 if (CL->isFileScope()) 910 sReg = getGlobalsRegion(); 911 else { 912 const StackFrameContext *STC = LC->getCurrentStackFrame(); 913 assert(STC); 914 sReg = getStackLocalsRegion(STC); 915 } 916 917 return getSubRegion<CompoundLiteralRegion>(CL, sReg); 918 } 919 920 const ElementRegion* 921 MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx, 922 const MemRegion* superRegion, 923 ASTContext &Ctx){ 924 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType(); 925 926 llvm::FoldingSetNodeID ID; 927 ElementRegion::ProfileRegion(ID, T, Idx, superRegion); 928 929 void *InsertPos; 930 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); 931 ElementRegion* R = cast_or_null<ElementRegion>(data); 932 933 if (!R) { 934 R = A.Allocate<ElementRegion>(); 935 new (R) ElementRegion(T, Idx, superRegion); 936 Regions.InsertNode(R, InsertPos); 937 } 938 939 return R; 940 } 941 942 const FunctionCodeRegion * 943 MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) { 944 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion()); 945 } 946 947 const BlockCodeRegion * 948 MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy, 949 AnalysisDeclContext *AC) { 950 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion()); 951 } 952 953 954 /// getSymbolicRegion - Retrieve or create a "symbolic" memory region. 955 const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) { 956 return getSubRegion<SymbolicRegion>(sym, getUnknownRegion()); 957 } 958 959 const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) { 960 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion()); 961 } 962 963 const FieldRegion* 964 MemRegionManager::getFieldRegion(const FieldDecl *d, 965 const MemRegion* superRegion){ 966 return getSubRegion<FieldRegion>(d, superRegion); 967 } 968 969 const ObjCIvarRegion* 970 MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d, 971 const MemRegion* superRegion) { 972 return getSubRegion<ObjCIvarRegion>(d, superRegion); 973 } 974 975 const CXXTempObjectRegion* 976 MemRegionManager::getCXXTempObjectRegion(Expr const *E, 977 LocationContext const *LC) { 978 const StackFrameContext *SFC = LC->getCurrentStackFrame(); 979 assert(SFC); 980 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC)); 981 } 982 983 /// Checks whether \p BaseClass is a valid virtual or direct non-virtual base 984 /// class of the type of \p Super. 985 static bool isValidBaseClass(const CXXRecordDecl *BaseClass, 986 const TypedValueRegion *Super, 987 bool IsVirtual) { 988 BaseClass = BaseClass->getCanonicalDecl(); 989 990 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl(); 991 if (!Class) 992 return true; 993 994 if (IsVirtual) 995 return Class->isVirtuallyDerivedFrom(BaseClass); 996 997 for (const auto &I : Class->bases()) { 998 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass) 999 return true; 1000 } 1001 1002 return false; 1003 } 1004 1005 const CXXBaseObjectRegion * 1006 MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD, 1007 const MemRegion *Super, 1008 bool IsVirtual) { 1009 if (isa<TypedValueRegion>(Super)) { 1010 assert(isValidBaseClass(RD, dyn_cast<TypedValueRegion>(Super), IsVirtual)); 1011 (void)&isValidBaseClass; 1012 1013 if (IsVirtual) { 1014 // Virtual base regions should not be layered, since the layout rules 1015 // are different. 1016 while (const CXXBaseObjectRegion *Base = 1017 dyn_cast<CXXBaseObjectRegion>(Super)) { 1018 Super = Base->getSuperRegion(); 1019 } 1020 assert(Super && !isa<MemSpaceRegion>(Super)); 1021 } 1022 } 1023 1024 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super); 1025 } 1026 1027 const CXXThisRegion* 1028 MemRegionManager::getCXXThisRegion(QualType thisPointerTy, 1029 const LocationContext *LC) { 1030 const PointerType *PT = thisPointerTy->getAs<PointerType>(); 1031 assert(PT); 1032 // Inside the body of the operator() of a lambda a this expr might refer to an 1033 // object in one of the parent location contexts. 1034 const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl()); 1035 // FIXME: when operator() of lambda is analyzed as a top level function and 1036 // 'this' refers to a this to the enclosing scope, there is no right region to 1037 // return. 1038 while (!LC->inTopFrame() && 1039 (!D || D->isStatic() || 1040 PT != D->getThisType(getContext())->getAs<PointerType>())) { 1041 LC = LC->getParent(); 1042 D = dyn_cast<CXXMethodDecl>(LC->getDecl()); 1043 } 1044 const StackFrameContext *STC = LC->getCurrentStackFrame(); 1045 assert(STC); 1046 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC)); 1047 } 1048 1049 const AllocaRegion* 1050 MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt, 1051 const LocationContext *LC) { 1052 const StackFrameContext *STC = LC->getCurrentStackFrame(); 1053 assert(STC); 1054 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC)); 1055 } 1056 1057 const MemSpaceRegion *MemRegion::getMemorySpace() const { 1058 const MemRegion *R = this; 1059 const SubRegion* SR = dyn_cast<SubRegion>(this); 1060 1061 while (SR) { 1062 R = SR->getSuperRegion(); 1063 SR = dyn_cast<SubRegion>(R); 1064 } 1065 1066 return dyn_cast<MemSpaceRegion>(R); 1067 } 1068 1069 bool MemRegion::hasStackStorage() const { 1070 return isa<StackSpaceRegion>(getMemorySpace()); 1071 } 1072 1073 bool MemRegion::hasStackNonParametersStorage() const { 1074 return isa<StackLocalsSpaceRegion>(getMemorySpace()); 1075 } 1076 1077 bool MemRegion::hasStackParametersStorage() const { 1078 return isa<StackArgumentsSpaceRegion>(getMemorySpace()); 1079 } 1080 1081 bool MemRegion::hasGlobalsOrParametersStorage() const { 1082 const MemSpaceRegion *MS = getMemorySpace(); 1083 return isa<StackArgumentsSpaceRegion>(MS) || 1084 isa<GlobalsSpaceRegion>(MS); 1085 } 1086 1087 // getBaseRegion strips away all elements and fields, and get the base region 1088 // of them. 1089 const MemRegion *MemRegion::getBaseRegion() const { 1090 const MemRegion *R = this; 1091 while (true) { 1092 switch (R->getKind()) { 1093 case MemRegion::ElementRegionKind: 1094 case MemRegion::FieldRegionKind: 1095 case MemRegion::ObjCIvarRegionKind: 1096 case MemRegion::CXXBaseObjectRegionKind: 1097 R = cast<SubRegion>(R)->getSuperRegion(); 1098 continue; 1099 default: 1100 break; 1101 } 1102 break; 1103 } 1104 return R; 1105 } 1106 1107 bool MemRegion::isSubRegionOf(const MemRegion *R) const { 1108 return false; 1109 } 1110 1111 //===----------------------------------------------------------------------===// 1112 // View handling. 1113 //===----------------------------------------------------------------------===// 1114 1115 const MemRegion *MemRegion::StripCasts(bool StripBaseCasts) const { 1116 const MemRegion *R = this; 1117 while (true) { 1118 switch (R->getKind()) { 1119 case ElementRegionKind: { 1120 const ElementRegion *ER = cast<ElementRegion>(R); 1121 if (!ER->getIndex().isZeroConstant()) 1122 return R; 1123 R = ER->getSuperRegion(); 1124 break; 1125 } 1126 case CXXBaseObjectRegionKind: 1127 if (!StripBaseCasts) 1128 return R; 1129 R = cast<CXXBaseObjectRegion>(R)->getSuperRegion(); 1130 break; 1131 default: 1132 return R; 1133 } 1134 } 1135 } 1136 1137 const SymbolicRegion *MemRegion::getSymbolicBase() const { 1138 const SubRegion *SubR = dyn_cast<SubRegion>(this); 1139 1140 while (SubR) { 1141 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(SubR)) 1142 return SymR; 1143 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion()); 1144 } 1145 return nullptr; 1146 } 1147 1148 RegionRawOffset ElementRegion::getAsArrayOffset() const { 1149 CharUnits offset = CharUnits::Zero(); 1150 const ElementRegion *ER = this; 1151 const MemRegion *superR = nullptr; 1152 ASTContext &C = getContext(); 1153 1154 // FIXME: Handle multi-dimensional arrays. 1155 1156 while (ER) { 1157 superR = ER->getSuperRegion(); 1158 1159 // FIXME: generalize to symbolic offsets. 1160 SVal index = ER->getIndex(); 1161 if (Optional<nonloc::ConcreteInt> CI = index.getAs<nonloc::ConcreteInt>()) { 1162 // Update the offset. 1163 int64_t i = CI->getValue().getSExtValue(); 1164 1165 if (i != 0) { 1166 QualType elemType = ER->getElementType(); 1167 1168 // If we are pointing to an incomplete type, go no further. 1169 if (elemType->isIncompleteType()) { 1170 superR = ER; 1171 break; 1172 } 1173 1174 CharUnits size = C.getTypeSizeInChars(elemType); 1175 offset += (i * size); 1176 } 1177 1178 // Go to the next ElementRegion (if any). 1179 ER = dyn_cast<ElementRegion>(superR); 1180 continue; 1181 } 1182 1183 return nullptr; 1184 } 1185 1186 assert(superR && "super region cannot be NULL"); 1187 return RegionRawOffset(superR, offset); 1188 } 1189 1190 1191 /// Returns true if \p Base is an immediate base class of \p Child 1192 static bool isImmediateBase(const CXXRecordDecl *Child, 1193 const CXXRecordDecl *Base) { 1194 assert(Child && "Child must not be null"); 1195 // Note that we do NOT canonicalize the base class here, because 1196 // ASTRecordLayout doesn't either. If that leads us down the wrong path, 1197 // so be it; at least we won't crash. 1198 for (const auto &I : Child->bases()) { 1199 if (I.getType()->getAsCXXRecordDecl() == Base) 1200 return true; 1201 } 1202 1203 return false; 1204 } 1205 1206 RegionOffset MemRegion::getAsOffset() const { 1207 const MemRegion *R = this; 1208 const MemRegion *SymbolicOffsetBase = nullptr; 1209 int64_t Offset = 0; 1210 1211 while (1) { 1212 switch (R->getKind()) { 1213 case CodeSpaceRegionKind: 1214 case StackLocalsSpaceRegionKind: 1215 case StackArgumentsSpaceRegionKind: 1216 case HeapSpaceRegionKind: 1217 case UnknownSpaceRegionKind: 1218 case StaticGlobalSpaceRegionKind: 1219 case GlobalInternalSpaceRegionKind: 1220 case GlobalSystemSpaceRegionKind: 1221 case GlobalImmutableSpaceRegionKind: 1222 // Stores can bind directly to a region space to set a default value. 1223 assert(Offset == 0 && !SymbolicOffsetBase); 1224 goto Finish; 1225 1226 case FunctionCodeRegionKind: 1227 case BlockCodeRegionKind: 1228 case BlockDataRegionKind: 1229 // These will never have bindings, but may end up having values requested 1230 // if the user does some strange casting. 1231 if (Offset != 0) 1232 SymbolicOffsetBase = R; 1233 goto Finish; 1234 1235 case SymbolicRegionKind: 1236 case AllocaRegionKind: 1237 case CompoundLiteralRegionKind: 1238 case CXXThisRegionKind: 1239 case StringRegionKind: 1240 case ObjCStringRegionKind: 1241 case VarRegionKind: 1242 case CXXTempObjectRegionKind: 1243 // Usual base regions. 1244 goto Finish; 1245 1246 case ObjCIvarRegionKind: 1247 // This is a little strange, but it's a compromise between 1248 // ObjCIvarRegions having unknown compile-time offsets (when using the 1249 // non-fragile runtime) and yet still being distinct, non-overlapping 1250 // regions. Thus we treat them as "like" base regions for the purposes 1251 // of computing offsets. 1252 goto Finish; 1253 1254 case CXXBaseObjectRegionKind: { 1255 const CXXBaseObjectRegion *BOR = cast<CXXBaseObjectRegion>(R); 1256 R = BOR->getSuperRegion(); 1257 1258 QualType Ty; 1259 bool RootIsSymbolic = false; 1260 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) { 1261 Ty = TVR->getDesugaredValueType(getContext()); 1262 } else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) { 1263 // If our base region is symbolic, we don't know what type it really is. 1264 // Pretend the type of the symbol is the true dynamic type. 1265 // (This will at least be self-consistent for the life of the symbol.) 1266 Ty = SR->getSymbol()->getType()->getPointeeType(); 1267 RootIsSymbolic = true; 1268 } 1269 1270 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl(); 1271 if (!Child) { 1272 // We cannot compute the offset of the base class. 1273 SymbolicOffsetBase = R; 1274 } else { 1275 if (RootIsSymbolic) { 1276 // Base layers on symbolic regions may not be type-correct. 1277 // Double-check the inheritance here, and revert to a symbolic offset 1278 // if it's invalid (e.g. due to a reinterpret_cast). 1279 if (BOR->isVirtual()) { 1280 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl())) 1281 SymbolicOffsetBase = R; 1282 } else { 1283 if (!isImmediateBase(Child, BOR->getDecl())) 1284 SymbolicOffsetBase = R; 1285 } 1286 } 1287 } 1288 1289 // Don't bother calculating precise offsets if we already have a 1290 // symbolic offset somewhere in the chain. 1291 if (SymbolicOffsetBase) 1292 continue; 1293 1294 CharUnits BaseOffset; 1295 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Child); 1296 if (BOR->isVirtual()) 1297 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl()); 1298 else 1299 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl()); 1300 1301 // The base offset is in chars, not in bits. 1302 Offset += BaseOffset.getQuantity() * getContext().getCharWidth(); 1303 break; 1304 } 1305 case ElementRegionKind: { 1306 const ElementRegion *ER = cast<ElementRegion>(R); 1307 R = ER->getSuperRegion(); 1308 1309 QualType EleTy = ER->getValueType(); 1310 if (EleTy->isIncompleteType()) { 1311 // We cannot compute the offset of the base class. 1312 SymbolicOffsetBase = R; 1313 continue; 1314 } 1315 1316 SVal Index = ER->getIndex(); 1317 if (Optional<nonloc::ConcreteInt> CI = 1318 Index.getAs<nonloc::ConcreteInt>()) { 1319 // Don't bother calculating precise offsets if we already have a 1320 // symbolic offset somewhere in the chain. 1321 if (SymbolicOffsetBase) 1322 continue; 1323 1324 int64_t i = CI->getValue().getSExtValue(); 1325 // This type size is in bits. 1326 Offset += i * getContext().getTypeSize(EleTy); 1327 } else { 1328 // We cannot compute offset for non-concrete index. 1329 SymbolicOffsetBase = R; 1330 } 1331 break; 1332 } 1333 case FieldRegionKind: { 1334 const FieldRegion *FR = cast<FieldRegion>(R); 1335 R = FR->getSuperRegion(); 1336 1337 const RecordDecl *RD = FR->getDecl()->getParent(); 1338 if (RD->isUnion() || !RD->isCompleteDefinition()) { 1339 // We cannot compute offset for incomplete type. 1340 // For unions, we could treat everything as offset 0, but we'd rather 1341 // treat each field as a symbolic offset so they aren't stored on top 1342 // of each other, since we depend on things in typed regions actually 1343 // matching their types. 1344 SymbolicOffsetBase = R; 1345 } 1346 1347 // Don't bother calculating precise offsets if we already have a 1348 // symbolic offset somewhere in the chain. 1349 if (SymbolicOffsetBase) 1350 continue; 1351 1352 // Get the field number. 1353 unsigned idx = 0; 1354 for (RecordDecl::field_iterator FI = RD->field_begin(), 1355 FE = RD->field_end(); FI != FE; ++FI, ++idx) { 1356 if (FR->getDecl() == *FI) 1357 break; 1358 } 1359 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1360 // This is offset in bits. 1361 Offset += Layout.getFieldOffset(idx); 1362 break; 1363 } 1364 } 1365 } 1366 1367 Finish: 1368 if (SymbolicOffsetBase) 1369 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic); 1370 return RegionOffset(R, Offset); 1371 } 1372 1373 //===----------------------------------------------------------------------===// 1374 // BlockDataRegion 1375 //===----------------------------------------------------------------------===// 1376 1377 std::pair<const VarRegion *, const VarRegion *> 1378 BlockDataRegion::getCaptureRegions(const VarDecl *VD) { 1379 MemRegionManager &MemMgr = *getMemRegionManager(); 1380 const VarRegion *VR = nullptr; 1381 const VarRegion *OriginalVR = nullptr; 1382 1383 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) { 1384 VR = MemMgr.getVarRegion(VD, this); 1385 OriginalVR = MemMgr.getVarRegion(VD, LC); 1386 } 1387 else { 1388 if (LC) { 1389 VR = MemMgr.getVarRegion(VD, LC); 1390 OriginalVR = VR; 1391 } 1392 else { 1393 VR = MemMgr.getVarRegion(VD, MemMgr.getUnknownRegion()); 1394 OriginalVR = MemMgr.getVarRegion(VD, LC); 1395 } 1396 } 1397 return std::make_pair(VR, OriginalVR); 1398 } 1399 1400 void BlockDataRegion::LazyInitializeReferencedVars() { 1401 if (ReferencedVars) 1402 return; 1403 1404 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext(); 1405 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl()); 1406 auto NumBlockVars = 1407 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end()); 1408 1409 if (NumBlockVars == 0) { 1410 ReferencedVars = (void*) 0x1; 1411 return; 1412 } 1413 1414 MemRegionManager &MemMgr = *getMemRegionManager(); 1415 llvm::BumpPtrAllocator &A = MemMgr.getAllocator(); 1416 BumpVectorContext BC(A); 1417 1418 typedef BumpVector<const MemRegion*> VarVec; 1419 VarVec *BV = A.Allocate<VarVec>(); 1420 new (BV) VarVec(BC, NumBlockVars); 1421 VarVec *BVOriginal = A.Allocate<VarVec>(); 1422 new (BVOriginal) VarVec(BC, NumBlockVars); 1423 1424 for (const VarDecl *VD : ReferencedBlockVars) { 1425 const VarRegion *VR = nullptr; 1426 const VarRegion *OriginalVR = nullptr; 1427 std::tie(VR, OriginalVR) = getCaptureRegions(VD); 1428 assert(VR); 1429 assert(OriginalVR); 1430 BV->push_back(VR, BC); 1431 BVOriginal->push_back(OriginalVR, BC); 1432 } 1433 1434 ReferencedVars = BV; 1435 OriginalVars = BVOriginal; 1436 } 1437 1438 BlockDataRegion::referenced_vars_iterator 1439 BlockDataRegion::referenced_vars_begin() const { 1440 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars(); 1441 1442 BumpVector<const MemRegion*> *Vec = 1443 static_cast<BumpVector<const MemRegion*>*>(ReferencedVars); 1444 1445 if (Vec == (void*) 0x1) 1446 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr); 1447 1448 BumpVector<const MemRegion*> *VecOriginal = 1449 static_cast<BumpVector<const MemRegion*>*>(OriginalVars); 1450 1451 return BlockDataRegion::referenced_vars_iterator(Vec->begin(), 1452 VecOriginal->begin()); 1453 } 1454 1455 BlockDataRegion::referenced_vars_iterator 1456 BlockDataRegion::referenced_vars_end() const { 1457 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars(); 1458 1459 BumpVector<const MemRegion*> *Vec = 1460 static_cast<BumpVector<const MemRegion*>*>(ReferencedVars); 1461 1462 if (Vec == (void*) 0x1) 1463 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr); 1464 1465 BumpVector<const MemRegion*> *VecOriginal = 1466 static_cast<BumpVector<const MemRegion*>*>(OriginalVars); 1467 1468 return BlockDataRegion::referenced_vars_iterator(Vec->end(), 1469 VecOriginal->end()); 1470 } 1471 1472 const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const { 1473 for (referenced_vars_iterator I = referenced_vars_begin(), 1474 E = referenced_vars_end(); 1475 I != E; ++I) { 1476 if (I.getCapturedRegion() == R) 1477 return I.getOriginalRegion(); 1478 } 1479 return nullptr; 1480 } 1481 1482 //===----------------------------------------------------------------------===// 1483 // RegionAndSymbolInvalidationTraits 1484 //===----------------------------------------------------------------------===// 1485 1486 void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym, 1487 InvalidationKinds IK) { 1488 SymTraitsMap[Sym] |= IK; 1489 } 1490 1491 void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR, 1492 InvalidationKinds IK) { 1493 assert(MR); 1494 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR)) 1495 setTrait(SR->getSymbol(), IK); 1496 else 1497 MRTraitsMap[MR] |= IK; 1498 } 1499 1500 bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym, 1501 InvalidationKinds IK) const { 1502 const_symbol_iterator I = SymTraitsMap.find(Sym); 1503 if (I != SymTraitsMap.end()) 1504 return I->second & IK; 1505 1506 return false; 1507 } 1508 1509 bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR, 1510 InvalidationKinds IK) const { 1511 if (!MR) 1512 return false; 1513 1514 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR)) 1515 return hasTrait(SR->getSymbol(), IK); 1516 1517 const_region_iterator I = MRTraitsMap.find(MR); 1518 if (I != MRTraitsMap.end()) 1519 return I->second & IK; 1520 1521 return false; 1522 } 1523