MemRegion.cpp 47 KB

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