1 //===- MemRegion.cpp - Abstract memory regions for static analysis --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines MemRegion and its subclasses. MemRegion defines a
11 // partially-typed abstraction of memory useful for path-sensitive dataflow
14 //===----------------------------------------------------------------------===//
16 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Analysis/AnalysisDeclContext.h"
28 #include "clang/Analysis/Support/BumpVector.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
35 #include "llvm/ADT/APInt.h"
36 #include "llvm/ADT/FoldingSet.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/PointerUnion.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/Support/Allocator.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CheckedArithmetic.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/raw_ostream.h"
57 using namespace clang;
60 #define DEBUG_TYPE "MemRegion"
62 //===----------------------------------------------------------------------===//
63 // MemRegion Construction.
64 //===----------------------------------------------------------------------===//
66 template <typename RegionTy, typename SuperTy, typename Arg1Ty>
67 RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
68 const SuperTy *superRegion) {
69 llvm::FoldingSetNodeID ID;
70 RegionTy::ProfileRegion(ID, arg1, superRegion);
72 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
75 R = A.Allocate<RegionTy>();
76 new (R) RegionTy(arg1, superRegion);
77 Regions.InsertNode(R, InsertPos);
83 template <typename RegionTy, typename SuperTy, typename Arg1Ty, typename Arg2Ty>
84 RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
85 const SuperTy *superRegion) {
86 llvm::FoldingSetNodeID ID;
87 RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
89 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
92 R = A.Allocate<RegionTy>();
93 new (R) RegionTy(arg1, arg2, superRegion);
94 Regions.InsertNode(R, InsertPos);
100 template <typename RegionTy, typename SuperTy,
101 typename Arg1Ty, typename Arg2Ty, typename Arg3Ty>
102 RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
104 const SuperTy *superRegion) {
105 llvm::FoldingSetNodeID ID;
106 RegionTy::ProfileRegion(ID, arg1, arg2, arg3, superRegion);
108 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
111 R = A.Allocate<RegionTy>();
112 new (R) RegionTy(arg1, arg2, arg3, superRegion);
113 Regions.InsertNode(R, InsertPos);
119 //===----------------------------------------------------------------------===//
120 // Object destruction.
121 //===----------------------------------------------------------------------===//
123 MemRegion::~MemRegion() = default;
125 // All regions and their data are BumpPtrAllocated. No need to call their
127 MemRegionManager::~MemRegionManager() = default;
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
133 bool SubRegion::isSubRegionOf(const MemRegion* R) const {
134 const MemRegion* r = this;
138 if (const auto *sr = dyn_cast<SubRegion>(r))
139 r = sr->getSuperRegion();
142 } while (r != nullptr);
146 MemRegionManager* SubRegion::getMemRegionManager() const {
147 const SubRegion* r = this;
149 const MemRegion *superRegion = r->getSuperRegion();
150 if (const auto *sr = dyn_cast<SubRegion>(superRegion)) {
154 return superRegion->getMemRegionManager();
158 const StackFrameContext *VarRegion::getStackFrame() const {
159 const auto *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
160 return SSR ? SSR->getStackFrame() : nullptr;
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
167 DefinedOrUnknownSVal TypedValueRegion::getExtent(SValBuilder &svalBuilder) const {
168 ASTContext &Ctx = svalBuilder.getContext();
169 QualType T = getDesugaredValueType(Ctx);
171 if (isa<VariableArrayType>(T))
172 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
173 if (T->isIncompleteType())
176 CharUnits size = Ctx.getTypeSizeInChars(T);
177 QualType sizeTy = svalBuilder.getArrayIndexType();
178 return svalBuilder.makeIntVal(size.getQuantity(), sizeTy);
181 DefinedOrUnknownSVal FieldRegion::getExtent(SValBuilder &svalBuilder) const {
182 // Force callers to deal with bitfields explicitly.
183 if (getDecl()->isBitField())
186 DefinedOrUnknownSVal Extent = DeclRegion::getExtent(svalBuilder);
188 // A zero-length array at the end of a struct often stands for dynamically-
189 // allocated extra memory.
190 if (Extent.isZeroConstant()) {
191 QualType T = getDesugaredValueType(svalBuilder.getContext());
193 if (isa<ConstantArrayType>(T))
200 DefinedOrUnknownSVal AllocaRegion::getExtent(SValBuilder &svalBuilder) const {
201 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
204 DefinedOrUnknownSVal SymbolicRegion::getExtent(SValBuilder &svalBuilder) const {
205 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
208 DefinedOrUnknownSVal StringRegion::getExtent(SValBuilder &svalBuilder) const {
209 return svalBuilder.makeIntVal(getStringLiteral()->getByteLength()+1,
210 svalBuilder.getArrayIndexType());
213 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
214 : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {}
216 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const {
217 return cast<ObjCIvarDecl>(D);
220 QualType ObjCIvarRegion::getValueType() const {
221 return getDecl()->getType();
224 QualType CXXBaseObjectRegion::getValueType() const {
225 return QualType(getDecl()->getTypeForDecl(), 0);
228 QualType CXXDerivedObjectRegion::getValueType() const {
229 return QualType(getDecl()->getTypeForDecl(), 0);
232 //===----------------------------------------------------------------------===//
233 // FoldingSet profiling.
234 //===----------------------------------------------------------------------===//
236 void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
237 ID.AddInteger(static_cast<unsigned>(getKind()));
240 void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
241 ID.AddInteger(static_cast<unsigned>(getKind()));
242 ID.AddPointer(getStackFrame());
245 void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
246 ID.AddInteger(static_cast<unsigned>(getKind()));
247 ID.AddPointer(getCodeRegion());
250 void StringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
251 const StringLiteral *Str,
252 const MemRegion *superRegion) {
253 ID.AddInteger(static_cast<unsigned>(StringRegionKind));
255 ID.AddPointer(superRegion);
258 void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
259 const ObjCStringLiteral *Str,
260 const MemRegion *superRegion) {
261 ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind));
263 ID.AddPointer(superRegion);
266 void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
267 const Expr *Ex, unsigned cnt,
268 const MemRegion *superRegion) {
269 ID.AddInteger(static_cast<unsigned>(AllocaRegionKind));
272 ID.AddPointer(superRegion);
275 void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
276 ProfileRegion(ID, Ex, Cnt, superRegion);
279 void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
280 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
283 void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
284 const CompoundLiteralExpr *CL,
285 const MemRegion* superRegion) {
286 ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind));
288 ID.AddPointer(superRegion);
291 void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
292 const PointerType *PT,
293 const MemRegion *sRegion) {
294 ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind));
296 ID.AddPointer(sRegion);
299 void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
300 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
303 void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
304 const ObjCIvarDecl *ivd,
305 const MemRegion* superRegion) {
306 DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind);
309 void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D,
310 const MemRegion* superRegion, Kind k) {
311 ID.AddInteger(static_cast<unsigned>(k));
313 ID.AddPointer(superRegion);
316 void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const {
317 DeclRegion::ProfileRegion(ID, D, superRegion, getKind());
320 void VarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
321 VarRegion::ProfileRegion(ID, getDecl(), superRegion);
324 void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
325 const MemRegion *sreg) {
326 ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind));
331 void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
332 SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
335 void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
336 QualType ElementType, SVal Idx,
337 const MemRegion* superRegion) {
338 ID.AddInteger(MemRegion::ElementRegionKind);
340 ID.AddPointer(superRegion);
344 void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
345 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
348 void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
351 ID.AddInteger(MemRegion::FunctionCodeRegionKind);
355 void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
356 FunctionCodeRegion::ProfileRegion(ID, FD, superRegion);
359 void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
360 const BlockDecl *BD, CanQualType,
361 const AnalysisDeclContext *AC,
363 ID.AddInteger(MemRegion::BlockCodeRegionKind);
367 void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
368 BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
371 void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
372 const BlockCodeRegion *BC,
373 const LocationContext *LC,
375 const MemRegion *sReg) {
376 ID.AddInteger(MemRegion::BlockDataRegionKind);
379 ID.AddInteger(BlkCount);
383 void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
384 BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion());
387 void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
389 const MemRegion *sReg) {
394 void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
395 ProfileRegion(ID, Ex, getSuperRegion());
398 void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
399 const CXXRecordDecl *RD,
401 const MemRegion *SReg) {
403 ID.AddBoolean(IsVirtual);
407 void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
408 ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
411 void CXXDerivedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
412 const CXXRecordDecl *RD,
413 const MemRegion *SReg) {
418 void CXXDerivedObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
419 ProfileRegion(ID, getDecl(), superRegion);
422 //===----------------------------------------------------------------------===//
424 //===----------------------------------------------------------------------===//
426 void GlobalsSpaceRegion::anchor() {}
428 void NonStaticGlobalSpaceRegion::anchor() {}
430 void StackSpaceRegion::anchor() {}
432 void TypedRegion::anchor() {}
434 void TypedValueRegion::anchor() {}
436 void CodeTextRegion::anchor() {}
438 void SubRegion::anchor() {}
440 //===----------------------------------------------------------------------===//
441 // Region pretty-printing.
442 //===----------------------------------------------------------------------===//
444 LLVM_DUMP_METHOD void MemRegion::dump() const {
445 dumpToStream(llvm::errs());
448 std::string MemRegion::getString() const {
450 llvm::raw_string_ostream os(s);
455 void MemRegion::dumpToStream(raw_ostream &os) const {
456 os << "<Unknown Region>";
459 void AllocaRegion::dumpToStream(raw_ostream &os) const {
460 os << "alloca{S" << Ex->getID(getContext()) << ',' << Cnt << '}';
463 void FunctionCodeRegion::dumpToStream(raw_ostream &os) const {
464 os << "code{" << getDecl()->getDeclName().getAsString() << '}';
467 void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
468 os << "block_code{" << static_cast<const void *>(this) << '}';
471 void BlockDataRegion::dumpToStream(raw_ostream &os) const {
472 os << "block_data{" << BC;
474 for (BlockDataRegion::referenced_vars_iterator
475 I = referenced_vars_begin(),
476 E = referenced_vars_end(); I != E; ++I)
477 os << "(" << I.getCapturedRegion() << "<-" <<
478 I.getOriginalRegion() << ") ";
482 void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
483 // FIXME: More elaborate pretty-printing.
484 os << "{ S" << CL->getID(getContext()) << " }";
487 void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
488 os << "temp_object{" << getValueType().getAsString() << ", "
489 << "S" << Ex->getID(getContext()) << '}';
492 void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
493 os << "Base{" << superRegion << ',' << getDecl()->getName() << '}';
496 void CXXDerivedObjectRegion::dumpToStream(raw_ostream &os) const {
497 os << "Derived{" << superRegion << ',' << getDecl()->getName() << '}';
500 void CXXThisRegion::dumpToStream(raw_ostream &os) const {
504 void ElementRegion::dumpToStream(raw_ostream &os) const {
505 os << "Element{" << superRegion << ','
506 << Index << ',' << getElementType().getAsString() << '}';
509 void FieldRegion::dumpToStream(raw_ostream &os) const {
510 os << superRegion << "->" << *getDecl();
513 void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
514 os << "Ivar{" << superRegion << ',' << *getDecl() << '}';
517 void StringRegion::dumpToStream(raw_ostream &os) const {
518 assert(Str != nullptr && "Expecting non-null StringLiteral");
519 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
522 void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
523 assert(Str != nullptr && "Expecting non-null ObjCStringLiteral");
524 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
527 void SymbolicRegion::dumpToStream(raw_ostream &os) const {
528 if (isa<HeapSpaceRegion>(getSuperRegion()))
530 os << "SymRegion{" << sym << '}';
533 void VarRegion::dumpToStream(raw_ostream &os) const {
534 const auto *VD = cast<VarDecl>(D);
535 if (const IdentifierInfo *ID = VD->getIdentifier())
538 os << "VarRegion{D" << VD->getID() << '}';
541 LLVM_DUMP_METHOD void RegionRawOffset::dump() const {
542 dumpToStream(llvm::errs());
545 void RegionRawOffset::dumpToStream(raw_ostream &os) const {
546 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
549 void CodeSpaceRegion::dumpToStream(raw_ostream &os) const {
550 os << "CodeSpaceRegion";
553 void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
554 os << "StaticGlobalsMemSpace{" << CR << '}';
557 void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
558 os << "GlobalInternalSpaceRegion";
561 void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
562 os << "GlobalSystemSpaceRegion";
565 void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
566 os << "GlobalImmutableSpaceRegion";
569 void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
570 os << "HeapSpaceRegion";
573 void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
574 os << "UnknownSpaceRegion";
577 void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
578 os << "StackArgumentsSpaceRegion";
581 void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
582 os << "StackLocalsSpaceRegion";
585 bool MemRegion::canPrintPretty() const {
586 return canPrintPrettyAsExpr();
589 bool MemRegion::canPrintPrettyAsExpr() const {
593 void MemRegion::printPretty(raw_ostream &os) const {
594 assert(canPrintPretty() && "This region cannot be printed pretty.");
596 printPrettyAsExpr(os);
600 void MemRegion::printPrettyAsExpr(raw_ostream &) const {
601 llvm_unreachable("This region cannot be printed pretty.");
604 bool VarRegion::canPrintPrettyAsExpr() const {
608 void VarRegion::printPrettyAsExpr(raw_ostream &os) const {
609 os << getDecl()->getName();
612 bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
616 void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
617 os << getDecl()->getName();
620 bool FieldRegion::canPrintPretty() const {
624 bool FieldRegion::canPrintPrettyAsExpr() const {
625 return superRegion->canPrintPrettyAsExpr();
628 void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
629 assert(canPrintPrettyAsExpr());
630 superRegion->printPrettyAsExpr(os);
631 os << "." << getDecl()->getName();
634 void FieldRegion::printPretty(raw_ostream &os) const {
635 if (canPrintPrettyAsExpr()) {
637 printPrettyAsExpr(os);
640 os << "field " << "\'" << getDecl()->getName() << "'";
644 bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
645 return superRegion->canPrintPrettyAsExpr();
648 void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
649 superRegion->printPrettyAsExpr(os);
652 bool CXXDerivedObjectRegion::canPrintPrettyAsExpr() const {
653 return superRegion->canPrintPrettyAsExpr();
656 void CXXDerivedObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
657 superRegion->printPrettyAsExpr(os);
660 std::string MemRegion::getDescriptiveName(bool UseQuotes) const {
661 std::string VariableName;
662 std::string ArrayIndices;
663 const MemRegion *R = this;
665 llvm::raw_svector_ostream os(buf);
667 // Obtain array indices to add them to the variable name.
668 const ElementRegion *ER = nullptr;
669 while ((ER = R->getAs<ElementRegion>())) {
670 // Index is a ConcreteInt.
671 if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) {
672 llvm::SmallString<2> Idx;
673 CI->getValue().toString(Idx);
674 ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str();
676 // If not a ConcreteInt, try to obtain the variable
677 // name by calling 'getDescriptiveName' recursively.
679 std::string Idx = ER->getDescriptiveName(false);
681 ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str();
684 R = ER->getSuperRegion();
687 // Get variable name.
688 if (R && R->canPrintPrettyAsExpr()) {
689 R->printPrettyAsExpr(os);
691 return (llvm::Twine("'") + os.str() + ArrayIndices + "'").str();
693 return (llvm::Twine(os.str()) + ArrayIndices).str();
699 SourceRange MemRegion::sourceRange() const {
700 const auto *const VR = dyn_cast<VarRegion>(this->getBaseRegion());
701 const auto *const FR = dyn_cast<FieldRegion>(this);
703 // Check for more specific regions first.
706 return FR->getDecl()->getSourceRange();
710 return VR->getDecl()->getSourceRange();
712 // Return invalid source range (can be checked by client).
717 //===----------------------------------------------------------------------===//
718 // MemRegionManager methods.
719 //===----------------------------------------------------------------------===//
721 template <typename REG>
722 const REG *MemRegionManager::LazyAllocate(REG*& region) {
724 region = A.Allocate<REG>();
725 new (region) REG(this);
731 template <typename REG, typename ARG>
732 const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
734 region = A.Allocate<REG>();
735 new (region) REG(this, a);
741 const StackLocalsSpaceRegion*
742 MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
744 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
749 R = A.Allocate<StackLocalsSpaceRegion>();
750 new (R) StackLocalsSpaceRegion(this, STC);
754 const StackArgumentsSpaceRegion *
755 MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
757 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
762 R = A.Allocate<StackArgumentsSpaceRegion>();
763 new (R) StackArgumentsSpaceRegion(this, STC);
767 const GlobalsSpaceRegion
768 *MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
769 const CodeTextRegion *CR) {
771 if (K == MemRegion::GlobalSystemSpaceRegionKind)
772 return LazyAllocate(SystemGlobals);
773 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
774 return LazyAllocate(ImmutableGlobals);
775 assert(K == MemRegion::GlobalInternalSpaceRegionKind);
776 return LazyAllocate(InternalGlobals);
779 assert(K == MemRegion::StaticGlobalSpaceRegionKind);
780 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
784 R = A.Allocate<StaticGlobalSpaceRegion>();
785 new (R) StaticGlobalSpaceRegion(this, CR);
789 const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
790 return LazyAllocate(heap);
793 const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() {
794 return LazyAllocate(unknown);
797 const CodeSpaceRegion *MemRegionManager::getCodeRegion() {
798 return LazyAllocate(code);
801 //===----------------------------------------------------------------------===//
802 // Constructing regions.
803 //===----------------------------------------------------------------------===//
805 const StringRegion *MemRegionManager::getStringRegion(const StringLiteral *Str){
806 return getSubRegion<StringRegion>(
807 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
810 const ObjCStringRegion *
811 MemRegionManager::getObjCStringRegion(const ObjCStringLiteral *Str){
812 return getSubRegion<ObjCStringRegion>(
813 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
816 /// Look through a chain of LocationContexts to either find the
817 /// StackFrameContext that matches a DeclContext, or find a VarRegion
818 /// for a variable captured by a block.
819 static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
820 getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
821 const DeclContext *DC,
824 if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) {
825 if (cast<DeclContext>(SFC->getDecl()) == DC)
828 if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
830 static_cast<const BlockDataRegion *>(BC->getContextData());
831 // FIXME: This can be made more efficient.
832 for (BlockDataRegion::referenced_vars_iterator
833 I = BR->referenced_vars_begin(),
834 E = BR->referenced_vars_end(); I != E; ++I) {
835 const VarRegion *VR = I.getOriginalRegion();
836 if (VR->getDecl() == VD)
837 return cast<VarRegion>(I.getCapturedRegion());
841 LC = LC->getParent();
843 return (const StackFrameContext *)nullptr;
846 const VarRegion* MemRegionManager::getVarRegion(const VarDecl *D,
847 const LocationContext *LC) {
848 const MemRegion *sReg = nullptr;
850 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
852 // First handle the globals defined in system headers.
853 if (C.getSourceManager().isInSystemHeader(D->getLocation())) {
854 // Whitelist the system globals which often DO GET modified, assume the
855 // rest are immutable.
856 if (D->getName().find("errno") != StringRef::npos)
857 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
859 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
861 // Treat other globals as GlobalInternal unless they are constants.
863 QualType GQT = D->getType();
864 const Type *GT = GQT.getTypePtrOrNull();
865 // TODO: We could walk the complex types here and see if everything is
867 if (GT && GQT.isConstQualified() && GT->isArithmeticType())
868 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
870 sReg = getGlobalsRegion();
873 // Finally handle static locals.
875 // FIXME: Once we implement scope handling, we will need to properly lookup
876 // 'D' to the proper LocationContext.
877 const DeclContext *DC = D->getDeclContext();
878 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
879 getStackOrCaptureRegionForDeclContext(LC, DC, D);
881 if (V.is<const VarRegion*>())
882 return V.get<const VarRegion*>();
884 const auto *STC = V.get<const StackFrameContext *>();
887 // FIXME: Assign a more sensible memory space to static locals
888 // we see from within blocks that we analyze as top-level declarations.
889 sReg = getUnknownRegion();
891 if (D->hasLocalStorage()) {
892 sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
893 ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
894 : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
897 assert(D->isStaticLocal());
898 const Decl *STCD = STC->getDecl();
899 if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
900 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
901 getFunctionCodeRegion(cast<NamedDecl>(STCD)));
902 else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
903 // FIXME: The fallback type here is totally bogus -- though it should
904 // never be queried, it will prevent uniquing with the real
905 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
908 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
911 T = getContext().VoidTy;
912 if (!T->getAs<FunctionType>())
913 T = getContext().getFunctionNoProtoType(T);
914 T = getContext().getBlockPointerType(T);
916 const BlockCodeRegion *BTR =
917 getBlockCodeRegion(BD, C.getCanonicalType(T),
918 STC->getAnalysisDeclContext());
919 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
923 sReg = getGlobalsRegion();
929 return getSubRegion<VarRegion>(D, sReg);
932 const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
933 const MemRegion *superR) {
934 return getSubRegion<VarRegion>(D, superR);
937 const BlockDataRegion *
938 MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC,
939 const LocationContext *LC,
940 unsigned blockCount) {
941 const MemSpaceRegion *sReg = nullptr;
942 const BlockDecl *BD = BC->getDecl();
943 if (!BD->hasCaptures()) {
944 // This handles 'static' blocks.
945 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
949 // FIXME: Once we implement scope handling, we want the parent region
951 const StackFrameContext *STC = LC->getStackFrame();
953 sReg = getStackLocalsRegion(STC);
956 // We allow 'LC' to be NULL for cases where want BlockDataRegions
957 // without context-sensitivity.
958 sReg = getUnknownRegion();
962 return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
965 const CXXTempObjectRegion *
966 MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
967 return getSubRegion<CXXTempObjectRegion>(
968 Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
971 const CompoundLiteralRegion*
972 MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
973 const LocationContext *LC) {
974 const MemSpaceRegion *sReg = nullptr;
976 if (CL->isFileScope())
977 sReg = getGlobalsRegion();
979 const StackFrameContext *STC = LC->getStackFrame();
981 sReg = getStackLocalsRegion(STC);
984 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
988 MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
989 const SubRegion* superRegion,
991 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
993 llvm::FoldingSetNodeID ID;
994 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
997 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
998 auto *R = cast_or_null<ElementRegion>(data);
1001 R = A.Allocate<ElementRegion>();
1002 new (R) ElementRegion(T, Idx, superRegion);
1003 Regions.InsertNode(R, InsertPos);
1009 const FunctionCodeRegion *
1010 MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) {
1011 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1014 const BlockCodeRegion *
1015 MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy,
1016 AnalysisDeclContext *AC) {
1017 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1020 /// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
1021 const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
1022 return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
1025 const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
1026 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1030 MemRegionManager::getFieldRegion(const FieldDecl *d,
1031 const SubRegion* superRegion){
1032 return getSubRegion<FieldRegion>(d, superRegion);
1035 const ObjCIvarRegion*
1036 MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
1037 const SubRegion* superRegion) {
1038 return getSubRegion<ObjCIvarRegion>(d, superRegion);
1041 const CXXTempObjectRegion*
1042 MemRegionManager::getCXXTempObjectRegion(Expr const *E,
1043 LocationContext const *LC) {
1044 const StackFrameContext *SFC = LC->getStackFrame();
1046 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
1049 /// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1050 /// class of the type of \p Super.
1051 static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1052 const TypedValueRegion *Super,
1054 BaseClass = BaseClass->getCanonicalDecl();
1056 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1061 return Class->isVirtuallyDerivedFrom(BaseClass);
1063 for (const auto &I : Class->bases()) {
1064 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1071 const CXXBaseObjectRegion *
1072 MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
1073 const SubRegion *Super,
1075 if (isa<TypedValueRegion>(Super)) {
1076 assert(isValidBaseClass(RD, dyn_cast<TypedValueRegion>(Super), IsVirtual));
1077 (void)&isValidBaseClass;
1080 // Virtual base regions should not be layered, since the layout rules
1082 while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1083 Super = cast<SubRegion>(Base->getSuperRegion());
1084 assert(Super && !isa<MemSpaceRegion>(Super));
1088 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1091 const CXXDerivedObjectRegion *
1092 MemRegionManager::getCXXDerivedObjectRegion(const CXXRecordDecl *RD,
1093 const SubRegion *Super) {
1094 return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1097 const CXXThisRegion*
1098 MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1099 const LocationContext *LC) {
1100 const auto *PT = thisPointerTy->getAs<PointerType>();
1102 // Inside the body of the operator() of a lambda a this expr might refer to an
1103 // object in one of the parent location contexts.
1104 const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1105 // FIXME: when operator() of lambda is analyzed as a top level function and
1106 // 'this' refers to a this to the enclosing scope, there is no right region to
1108 while (!LC->inTopFrame() && (!D || D->isStatic() ||
1109 PT != D->getThisType()->getAs<PointerType>())) {
1110 LC = LC->getParent();
1111 D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1113 const StackFrameContext *STC = LC->getStackFrame();
1115 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1119 MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1120 const LocationContext *LC) {
1121 const StackFrameContext *STC = LC->getStackFrame();
1123 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1126 const MemSpaceRegion *MemRegion::getMemorySpace() const {
1127 const MemRegion *R = this;
1128 const auto *SR = dyn_cast<SubRegion>(this);
1131 R = SR->getSuperRegion();
1132 SR = dyn_cast<SubRegion>(R);
1135 return dyn_cast<MemSpaceRegion>(R);
1138 bool MemRegion::hasStackStorage() const {
1139 return isa<StackSpaceRegion>(getMemorySpace());
1142 bool MemRegion::hasStackNonParametersStorage() const {
1143 return isa<StackLocalsSpaceRegion>(getMemorySpace());
1146 bool MemRegion::hasStackParametersStorage() const {
1147 return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1150 bool MemRegion::hasGlobalsOrParametersStorage() const {
1151 const MemSpaceRegion *MS = getMemorySpace();
1152 return isa<StackArgumentsSpaceRegion>(MS) ||
1153 isa<GlobalsSpaceRegion>(MS);
1156 // getBaseRegion strips away all elements and fields, and get the base region
1158 const MemRegion *MemRegion::getBaseRegion() const {
1159 const MemRegion *R = this;
1161 switch (R->getKind()) {
1162 case MemRegion::ElementRegionKind:
1163 case MemRegion::FieldRegionKind:
1164 case MemRegion::ObjCIvarRegionKind:
1165 case MemRegion::CXXBaseObjectRegionKind:
1166 case MemRegion::CXXDerivedObjectRegionKind:
1167 R = cast<SubRegion>(R)->getSuperRegion();
1177 // getgetMostDerivedObjectRegion gets the region of the root class of a C++
1179 const MemRegion *MemRegion::getMostDerivedObjectRegion() const {
1180 const MemRegion *R = this;
1181 while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1182 R = BR->getSuperRegion();
1186 bool MemRegion::isSubRegionOf(const MemRegion *) const {
1190 //===----------------------------------------------------------------------===//
1192 //===----------------------------------------------------------------------===//
1194 const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1195 const MemRegion *R = this;
1197 switch (R->getKind()) {
1198 case ElementRegionKind: {
1199 const auto *ER = cast<ElementRegion>(R);
1200 if (!ER->getIndex().isZeroConstant())
1202 R = ER->getSuperRegion();
1205 case CXXBaseObjectRegionKind:
1206 case CXXDerivedObjectRegionKind:
1207 if (!StripBaseAndDerivedCasts)
1209 R = cast<TypedValueRegion>(R)->getSuperRegion();
1217 const SymbolicRegion *MemRegion::getSymbolicBase() const {
1218 const auto *SubR = dyn_cast<SubRegion>(this);
1221 if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1223 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1228 RegionRawOffset ElementRegion::getAsArrayOffset() const {
1230 const ElementRegion *ER = this;
1231 const MemRegion *superR = nullptr;
1232 ASTContext &C = getContext();
1234 // FIXME: Handle multi-dimensional arrays.
1237 superR = ER->getSuperRegion();
1239 // FIXME: generalize to symbolic offsets.
1240 SVal index = ER->getIndex();
1241 if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1242 // Update the offset.
1243 int64_t i = CI->getValue().getSExtValue();
1246 QualType elemType = ER->getElementType();
1248 // If we are pointing to an incomplete type, go no further.
1249 if (elemType->isIncompleteType()) {
1254 int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1255 if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1256 offset = *NewOffset;
1258 LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "
1259 << "offset overflowing, returning unknown\n");
1265 // Go to the next ElementRegion (if any).
1266 ER = dyn_cast<ElementRegion>(superR);
1273 assert(superR && "super region cannot be NULL");
1274 return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1277 /// Returns true if \p Base is an immediate base class of \p Child
1278 static bool isImmediateBase(const CXXRecordDecl *Child,
1279 const CXXRecordDecl *Base) {
1280 assert(Child && "Child must not be null");
1281 // Note that we do NOT canonicalize the base class here, because
1282 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1283 // so be it; at least we won't crash.
1284 for (const auto &I : Child->bases()) {
1285 if (I.getType()->getAsCXXRecordDecl() == Base)
1292 static RegionOffset calculateOffset(const MemRegion *R) {
1293 const MemRegion *SymbolicOffsetBase = nullptr;
1297 switch (R->getKind()) {
1298 case MemRegion::CodeSpaceRegionKind:
1299 case MemRegion::StackLocalsSpaceRegionKind:
1300 case MemRegion::StackArgumentsSpaceRegionKind:
1301 case MemRegion::HeapSpaceRegionKind:
1302 case MemRegion::UnknownSpaceRegionKind:
1303 case MemRegion::StaticGlobalSpaceRegionKind:
1304 case MemRegion::GlobalInternalSpaceRegionKind:
1305 case MemRegion::GlobalSystemSpaceRegionKind:
1306 case MemRegion::GlobalImmutableSpaceRegionKind:
1307 // Stores can bind directly to a region space to set a default value.
1308 assert(Offset == 0 && !SymbolicOffsetBase);
1311 case MemRegion::FunctionCodeRegionKind:
1312 case MemRegion::BlockCodeRegionKind:
1313 case MemRegion::BlockDataRegionKind:
1314 // These will never have bindings, but may end up having values requested
1315 // if the user does some strange casting.
1317 SymbolicOffsetBase = R;
1320 case MemRegion::SymbolicRegionKind:
1321 case MemRegion::AllocaRegionKind:
1322 case MemRegion::CompoundLiteralRegionKind:
1323 case MemRegion::CXXThisRegionKind:
1324 case MemRegion::StringRegionKind:
1325 case MemRegion::ObjCStringRegionKind:
1326 case MemRegion::VarRegionKind:
1327 case MemRegion::CXXTempObjectRegionKind:
1328 // Usual base regions.
1331 case MemRegion::ObjCIvarRegionKind:
1332 // This is a little strange, but it's a compromise between
1333 // ObjCIvarRegions having unknown compile-time offsets (when using the
1334 // non-fragile runtime) and yet still being distinct, non-overlapping
1335 // regions. Thus we treat them as "like" base regions for the purposes
1336 // of computing offsets.
1339 case MemRegion::CXXBaseObjectRegionKind: {
1340 const auto *BOR = cast<CXXBaseObjectRegion>(R);
1341 R = BOR->getSuperRegion();
1344 bool RootIsSymbolic = false;
1345 if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1346 Ty = TVR->getDesugaredValueType(R->getContext());
1347 } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1348 // If our base region is symbolic, we don't know what type it really is.
1349 // Pretend the type of the symbol is the true dynamic type.
1350 // (This will at least be self-consistent for the life of the symbol.)
1351 Ty = SR->getSymbol()->getType()->getPointeeType();
1352 RootIsSymbolic = true;
1355 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1357 // We cannot compute the offset of the base class.
1358 SymbolicOffsetBase = R;
1360 if (RootIsSymbolic) {
1361 // Base layers on symbolic regions may not be type-correct.
1362 // Double-check the inheritance here, and revert to a symbolic offset
1363 // if it's invalid (e.g. due to a reinterpret_cast).
1364 if (BOR->isVirtual()) {
1365 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1366 SymbolicOffsetBase = R;
1368 if (!isImmediateBase(Child, BOR->getDecl()))
1369 SymbolicOffsetBase = R;
1374 // Don't bother calculating precise offsets if we already have a
1375 // symbolic offset somewhere in the chain.
1376 if (SymbolicOffsetBase)
1379 CharUnits BaseOffset;
1380 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1381 if (BOR->isVirtual())
1382 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1384 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1386 // The base offset is in chars, not in bits.
1387 Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1391 case MemRegion::CXXDerivedObjectRegionKind: {
1392 // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1396 case MemRegion::ElementRegionKind: {
1397 const auto *ER = cast<ElementRegion>(R);
1398 R = ER->getSuperRegion();
1400 QualType EleTy = ER->getValueType();
1401 if (EleTy->isIncompleteType()) {
1402 // We cannot compute the offset of the base class.
1403 SymbolicOffsetBase = R;
1407 SVal Index = ER->getIndex();
1408 if (Optional<nonloc::ConcreteInt> CI =
1409 Index.getAs<nonloc::ConcreteInt>()) {
1410 // Don't bother calculating precise offsets if we already have a
1411 // symbolic offset somewhere in the chain.
1412 if (SymbolicOffsetBase)
1415 int64_t i = CI->getValue().getSExtValue();
1416 // This type size is in bits.
1417 Offset += i * R->getContext().getTypeSize(EleTy);
1419 // We cannot compute offset for non-concrete index.
1420 SymbolicOffsetBase = R;
1424 case MemRegion::FieldRegionKind: {
1425 const auto *FR = cast<FieldRegion>(R);
1426 R = FR->getSuperRegion();
1428 const RecordDecl *RD = FR->getDecl()->getParent();
1429 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1430 // We cannot compute offset for incomplete type.
1431 // For unions, we could treat everything as offset 0, but we'd rather
1432 // treat each field as a symbolic offset so they aren't stored on top
1433 // of each other, since we depend on things in typed regions actually
1434 // matching their types.
1435 SymbolicOffsetBase = R;
1438 // Don't bother calculating precise offsets if we already have a
1439 // symbolic offset somewhere in the chain.
1440 if (SymbolicOffsetBase)
1443 // Get the field number.
1445 for (RecordDecl::field_iterator FI = RD->field_begin(),
1446 FE = RD->field_end(); FI != FE; ++FI, ++idx) {
1447 if (FR->getDecl() == *FI)
1450 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1451 // This is offset in bits.
1452 Offset += Layout.getFieldOffset(idx);
1459 if (SymbolicOffsetBase)
1460 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1461 return RegionOffset(R, Offset);
1464 RegionOffset MemRegion::getAsOffset() const {
1466 cachedOffset = calculateOffset(this);
1467 return *cachedOffset;
1470 //===----------------------------------------------------------------------===//
1472 //===----------------------------------------------------------------------===//
1474 std::pair<const VarRegion *, const VarRegion *>
1475 BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1476 MemRegionManager &MemMgr = *getMemRegionManager();
1477 const VarRegion *VR = nullptr;
1478 const VarRegion *OriginalVR = nullptr;
1480 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1481 VR = MemMgr.getVarRegion(VD, this);
1482 OriginalVR = MemMgr.getVarRegion(VD, LC);
1486 VR = MemMgr.getVarRegion(VD, LC);
1490 VR = MemMgr.getVarRegion(VD, MemMgr.getUnknownRegion());
1491 OriginalVR = MemMgr.getVarRegion(VD, LC);
1494 return std::make_pair(VR, OriginalVR);
1497 void BlockDataRegion::LazyInitializeReferencedVars() {
1501 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1502 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1504 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1506 if (NumBlockVars == 0) {
1507 ReferencedVars = (void*) 0x1;
1511 MemRegionManager &MemMgr = *getMemRegionManager();
1512 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1513 BumpVectorContext BC(A);
1515 using VarVec = BumpVector<const MemRegion *>;
1517 auto *BV = A.Allocate<VarVec>();
1518 new (BV) VarVec(BC, NumBlockVars);
1519 auto *BVOriginal = A.Allocate<VarVec>();
1520 new (BVOriginal) VarVec(BC, NumBlockVars);
1522 for (const auto *VD : ReferencedBlockVars) {
1523 const VarRegion *VR = nullptr;
1524 const VarRegion *OriginalVR = nullptr;
1525 std::tie(VR, OriginalVR) = getCaptureRegions(VD);
1528 BV->push_back(VR, BC);
1529 BVOriginal->push_back(OriginalVR, BC);
1532 ReferencedVars = BV;
1533 OriginalVars = BVOriginal;
1536 BlockDataRegion::referenced_vars_iterator
1537 BlockDataRegion::referenced_vars_begin() const {
1538 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1540 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1542 if (Vec == (void*) 0x1)
1543 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1546 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1548 return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1549 VecOriginal->begin());
1552 BlockDataRegion::referenced_vars_iterator
1553 BlockDataRegion::referenced_vars_end() const {
1554 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1556 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1558 if (Vec == (void*) 0x1)
1559 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1562 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1564 return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1565 VecOriginal->end());
1568 const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1569 for (referenced_vars_iterator I = referenced_vars_begin(),
1570 E = referenced_vars_end();
1572 if (I.getCapturedRegion() == R)
1573 return I.getOriginalRegion();
1578 //===----------------------------------------------------------------------===//
1579 // RegionAndSymbolInvalidationTraits
1580 //===----------------------------------------------------------------------===//
1582 void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1583 InvalidationKinds IK) {
1584 SymTraitsMap[Sym] |= IK;
1587 void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1588 InvalidationKinds IK) {
1590 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1591 setTrait(SR->getSymbol(), IK);
1593 MRTraitsMap[MR] |= IK;
1596 bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1597 InvalidationKinds IK) const {
1598 const_symbol_iterator I = SymTraitsMap.find(Sym);
1599 if (I != SymTraitsMap.end())
1600 return I->second & IK;
1605 bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1606 InvalidationKinds IK) const {
1610 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1611 return hasTrait(SR->getSymbol(), IK);
1613 const_region_iterator I = MRTraitsMap.find(MR);
1614 if (I != MRTraitsMap.end())
1615 return I->second & IK;