RegionStore.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  1. //== RegionStore.cpp - Field-sensitive store model --------------*- 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 a basic region store model. In this model, we do have field
  11. // sensitivity. But we assume nothing about the heap shape. So recursive data
  12. // structures are largely ignored. Basically we do 1-limiting analysis.
  13. // Parameter pointers are assumed with no aliasing. Pointee objects of
  14. // parameters are created lazily.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/Analysis/Analyses/LiveVariables.h"
  19. #include "clang/Analysis/AnalysisContext.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  25. #include "llvm/ADT/ImmutableList.h"
  26. #include "llvm/ADT/ImmutableMap.h"
  27. #include "llvm/ADT/Optional.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace clang;
  30. using namespace ento;
  31. using llvm::Optional;
  32. //===----------------------------------------------------------------------===//
  33. // Representation of binding keys.
  34. //===----------------------------------------------------------------------===//
  35. namespace {
  36. class BindingKey {
  37. public:
  38. enum Kind { Default = 0x0, Direct = 0x1 };
  39. private:
  40. enum { Symbolic = 0x2 };
  41. llvm::PointerIntPair<const MemRegion *, 2> P;
  42. uint64_t Data;
  43. explicit BindingKey(const MemRegion *r, const MemRegion *Base, Kind k)
  44. : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
  45. assert(r && Base && "Must have known regions.");
  46. assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
  47. }
  48. explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
  49. : P(r, k), Data(offset) {
  50. assert(r && "Must have known regions.");
  51. assert(getOffset() == offset && "Failed to store offset");
  52. assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base");
  53. }
  54. public:
  55. bool isDirect() const { return P.getInt() & Direct; }
  56. bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
  57. const MemRegion *getRegion() const { return P.getPointer(); }
  58. uint64_t getOffset() const {
  59. assert(!hasSymbolicOffset());
  60. return Data;
  61. }
  62. const MemRegion *getConcreteOffsetRegion() const {
  63. assert(hasSymbolicOffset());
  64. return reinterpret_cast<const MemRegion *>(static_cast<uintptr_t>(Data));
  65. }
  66. const MemRegion *getBaseRegion() const {
  67. if (hasSymbolicOffset())
  68. return getConcreteOffsetRegion()->getBaseRegion();
  69. return getRegion()->getBaseRegion();
  70. }
  71. void Profile(llvm::FoldingSetNodeID& ID) const {
  72. ID.AddPointer(P.getOpaqueValue());
  73. ID.AddInteger(Data);
  74. }
  75. static BindingKey Make(const MemRegion *R, Kind k);
  76. bool operator<(const BindingKey &X) const {
  77. if (P.getOpaqueValue() < X.P.getOpaqueValue())
  78. return true;
  79. if (P.getOpaqueValue() > X.P.getOpaqueValue())
  80. return false;
  81. return Data < X.Data;
  82. }
  83. bool operator==(const BindingKey &X) const {
  84. return P.getOpaqueValue() == X.P.getOpaqueValue() &&
  85. Data == X.Data;
  86. }
  87. LLVM_ATTRIBUTE_USED void dump() const;
  88. };
  89. } // end anonymous namespace
  90. BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
  91. const RegionOffset &RO = R->getAsOffset();
  92. if (RO.hasSymbolicOffset())
  93. return BindingKey(R, RO.getRegion(), k);
  94. return BindingKey(RO.getRegion(), RO.getOffset(), k);
  95. }
  96. namespace llvm {
  97. static inline
  98. raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
  99. os << '(' << K.getRegion();
  100. if (!K.hasSymbolicOffset())
  101. os << ',' << K.getOffset();
  102. os << ',' << (K.isDirect() ? "direct" : "default")
  103. << ')';
  104. return os;
  105. }
  106. } // end llvm namespace
  107. void BindingKey::dump() const {
  108. llvm::errs() << *this;
  109. }
  110. //===----------------------------------------------------------------------===//
  111. // Actual Store type.
  112. //===----------------------------------------------------------------------===//
  113. typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings;
  114. typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings> RegionBindings;
  115. //===----------------------------------------------------------------------===//
  116. // Fine-grained control of RegionStoreManager.
  117. //===----------------------------------------------------------------------===//
  118. namespace {
  119. struct minimal_features_tag {};
  120. struct maximal_features_tag {};
  121. class RegionStoreFeatures {
  122. bool SupportsFields;
  123. public:
  124. RegionStoreFeatures(minimal_features_tag) :
  125. SupportsFields(false) {}
  126. RegionStoreFeatures(maximal_features_tag) :
  127. SupportsFields(true) {}
  128. void enableFields(bool t) { SupportsFields = t; }
  129. bool supportsFields() const { return SupportsFields; }
  130. };
  131. }
  132. //===----------------------------------------------------------------------===//
  133. // Main RegionStore logic.
  134. //===----------------------------------------------------------------------===//
  135. namespace {
  136. class RegionStoreManager : public StoreManager {
  137. const RegionStoreFeatures Features;
  138. RegionBindings::Factory RBFactory;
  139. ClusterBindings::Factory CBFactory;
  140. public:
  141. RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
  142. : StoreManager(mgr), Features(f),
  143. RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()) {}
  144. Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R);
  145. /// getDefaultBinding - Returns an SVal* representing an optional default
  146. /// binding associated with a region and its subregions.
  147. Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R);
  148. /// setImplicitDefaultValue - Set the default binding for the provided
  149. /// MemRegion to the value implicitly defined for compound literals when
  150. /// the value is not specified.
  151. StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T);
  152. /// ArrayToPointer - Emulates the "decay" of an array to a pointer
  153. /// type. 'Array' represents the lvalue of the array being decayed
  154. /// to a pointer, and the returned SVal represents the decayed
  155. /// version of that lvalue (i.e., a pointer to the first element of
  156. /// the array). This is called by ExprEngine when evaluating
  157. /// casts from arrays to pointers.
  158. SVal ArrayToPointer(Loc Array);
  159. StoreRef getInitialStore(const LocationContext *InitLoc) {
  160. return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
  161. }
  162. //===-------------------------------------------------------------------===//
  163. // Binding values to regions.
  164. //===-------------------------------------------------------------------===//
  165. RegionBindings invalidateGlobalRegion(MemRegion::Kind K,
  166. const Expr *Ex,
  167. unsigned Count,
  168. const LocationContext *LCtx,
  169. RegionBindings B,
  170. InvalidatedRegions *Invalidated);
  171. StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions,
  172. const Expr *E, unsigned Count,
  173. const LocationContext *LCtx,
  174. InvalidatedSymbols &IS,
  175. const CallEvent *Call,
  176. InvalidatedRegions *Invalidated);
  177. bool scanReachableSymbols(Store S, const MemRegion *R,
  178. ScanReachableSymbols &Callbacks);
  179. public: // Made public for helper classes.
  180. RegionBindings removeSubRegionBindings(RegionBindings B, const SubRegion *R);
  181. RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V);
  182. RegionBindings addBinding(RegionBindings B, const MemRegion *R,
  183. BindingKey::Kind k, SVal V);
  184. const SVal *lookup(RegionBindings B, BindingKey K);
  185. const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k);
  186. RegionBindings removeBinding(RegionBindings B, BindingKey K);
  187. RegionBindings removeBinding(RegionBindings B, const MemRegion *R,
  188. BindingKey::Kind k);
  189. RegionBindings removeBinding(RegionBindings B, const MemRegion *R) {
  190. return removeBinding(removeBinding(B, R, BindingKey::Direct), R,
  191. BindingKey::Default);
  192. }
  193. RegionBindings removeCluster(RegionBindings B, const MemRegion *R);
  194. public: // Part of public interface to class.
  195. StoreRef Bind(Store store, Loc LV, SVal V);
  196. // BindDefault is only used to initialize a region with a default value.
  197. StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
  198. RegionBindings B = GetRegionBindings(store);
  199. assert(!lookup(B, R, BindingKey::Default));
  200. assert(!lookup(B, R, BindingKey::Direct));
  201. return StoreRef(addBinding(B, R, BindingKey::Default, V)
  202. .getRootWithoutRetain(), *this);
  203. }
  204. /// \brief Create a new store that binds a value to a compound literal.
  205. ///
  206. /// \param ST The original store whose bindings are the basis for the new
  207. /// store.
  208. ///
  209. /// \param CL The compound literal to bind (the binding key).
  210. ///
  211. /// \param LC The LocationContext for the binding.
  212. ///
  213. /// \param V The value to bind to the compound literal.
  214. StoreRef bindCompoundLiteral(Store ST,
  215. const CompoundLiteralExpr *CL,
  216. const LocationContext *LC, SVal V);
  217. /// BindStruct - Bind a compound value to a structure.
  218. StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V);
  219. /// BindVector - Bind a compound value to a vector.
  220. StoreRef BindVector(Store store, const TypedValueRegion* R, SVal V);
  221. StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V);
  222. /// Clears out all bindings in the given region and assigns a new value
  223. /// as a Default binding.
  224. StoreRef BindAggregate(Store store, const TypedRegion *R, SVal DefaultVal);
  225. /// \brief Create a new store with the specified binding removed.
  226. /// \param ST the original store, that is the basis for the new store.
  227. /// \param L the location whose binding should be removed.
  228. StoreRef killBinding(Store ST, Loc L);
  229. void incrementReferenceCount(Store store) {
  230. GetRegionBindings(store).manualRetain();
  231. }
  232. /// If the StoreManager supports it, decrement the reference count of
  233. /// the specified Store object. If the reference count hits 0, the memory
  234. /// associated with the object is recycled.
  235. void decrementReferenceCount(Store store) {
  236. GetRegionBindings(store).manualRelease();
  237. }
  238. bool includedInBindings(Store store, const MemRegion *region) const;
  239. /// \brief Return the value bound to specified location in a given state.
  240. ///
  241. /// The high level logic for this method is this:
  242. /// getBinding (L)
  243. /// if L has binding
  244. /// return L's binding
  245. /// else if L is in killset
  246. /// return unknown
  247. /// else
  248. /// if L is on stack or heap
  249. /// return undefined
  250. /// else
  251. /// return symbolic
  252. SVal getBinding(Store store, Loc L, QualType T = QualType());
  253. SVal getBindingForElement(Store store, const ElementRegion *R);
  254. SVal getBindingForField(Store store, const FieldRegion *R);
  255. SVal getBindingForObjCIvar(Store store, const ObjCIvarRegion *R);
  256. SVal getBindingForVar(Store store, const VarRegion *R);
  257. SVal getBindingForLazySymbol(const TypedValueRegion *R);
  258. SVal getBindingForFieldOrElementCommon(Store store, const TypedValueRegion *R,
  259. QualType Ty, const MemRegion *superR);
  260. SVal getLazyBinding(const MemRegion *lazyBindingRegion,
  261. Store lazyBindingStore);
  262. /// Get bindings for the values in a struct and return a CompoundVal, used
  263. /// when doing struct copy:
  264. /// struct s x, y;
  265. /// x = y;
  266. /// y's value is retrieved by this method.
  267. SVal getBindingForStruct(Store store, const TypedValueRegion* R);
  268. SVal getBindingForArray(Store store, const TypedValueRegion* R);
  269. /// Used to lazily generate derived symbols for bindings that are defined
  270. /// implicitly by default bindings in a super region.
  271. Optional<SVal> getBindingForDerivedDefaultValue(RegionBindings B,
  272. const MemRegion *superR,
  273. const TypedValueRegion *R,
  274. QualType Ty);
  275. /// Get the state and region whose binding this region R corresponds to.
  276. std::pair<Store, const MemRegion*>
  277. GetLazyBinding(RegionBindings B, const MemRegion *R,
  278. const MemRegion *originalRegion,
  279. bool includeSuffix = false);
  280. //===------------------------------------------------------------------===//
  281. // State pruning.
  282. //===------------------------------------------------------------------===//
  283. /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
  284. /// It returns a new Store with these values removed.
  285. StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
  286. SymbolReaper& SymReaper);
  287. //===------------------------------------------------------------------===//
  288. // Region "extents".
  289. //===------------------------------------------------------------------===//
  290. // FIXME: This method will soon be eliminated; see the note in Store.h.
  291. DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
  292. const MemRegion* R, QualType EleTy);
  293. //===------------------------------------------------------------------===//
  294. // Utility methods.
  295. //===------------------------------------------------------------------===//
  296. static inline RegionBindings GetRegionBindings(Store store) {
  297. return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store));
  298. }
  299. void print(Store store, raw_ostream &Out, const char* nl,
  300. const char *sep);
  301. void iterBindings(Store store, BindingsHandler& f) {
  302. RegionBindings B = GetRegionBindings(store);
  303. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  304. const ClusterBindings &Cluster = I.getData();
  305. for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
  306. CI != CE; ++CI) {
  307. const BindingKey &K = CI.getKey();
  308. if (!K.isDirect())
  309. continue;
  310. if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
  311. // FIXME: Possibly incorporate the offset?
  312. if (!f.HandleBinding(*this, store, R, CI.getData()))
  313. return;
  314. }
  315. }
  316. }
  317. }
  318. };
  319. } // end anonymous namespace
  320. //===----------------------------------------------------------------------===//
  321. // RegionStore creation.
  322. //===----------------------------------------------------------------------===//
  323. StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
  324. RegionStoreFeatures F = maximal_features_tag();
  325. return new RegionStoreManager(StMgr, F);
  326. }
  327. StoreManager *
  328. ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
  329. RegionStoreFeatures F = minimal_features_tag();
  330. F.enableFields(true);
  331. return new RegionStoreManager(StMgr, F);
  332. }
  333. //===----------------------------------------------------------------------===//
  334. // Region Cluster analysis.
  335. //===----------------------------------------------------------------------===//
  336. namespace {
  337. template <typename DERIVED>
  338. class ClusterAnalysis {
  339. protected:
  340. typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
  341. typedef SmallVector<const MemRegion *, 10> WorkList;
  342. llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
  343. WorkList WL;
  344. RegionStoreManager &RM;
  345. ASTContext &Ctx;
  346. SValBuilder &svalBuilder;
  347. RegionBindings B;
  348. const bool includeGlobals;
  349. const ClusterBindings *getCluster(const MemRegion *R) {
  350. return B.lookup(R);
  351. }
  352. public:
  353. ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
  354. RegionBindings b, const bool includeGlobals)
  355. : RM(rm), Ctx(StateMgr.getContext()),
  356. svalBuilder(StateMgr.getSValBuilder()),
  357. B(b), includeGlobals(includeGlobals) {}
  358. RegionBindings getRegionBindings() const { return B; }
  359. bool isVisited(const MemRegion *R) {
  360. return Visited.count(getCluster(R));
  361. }
  362. void GenerateClusters() {
  363. // Scan the entire set of bindings and record the region clusters.
  364. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
  365. const MemRegion *Base = RI.getKey();
  366. const ClusterBindings &Cluster = RI.getData();
  367. assert(!Cluster.isEmpty() && "Empty clusters should be removed");
  368. static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
  369. if (includeGlobals)
  370. if (isa<NonStaticGlobalSpaceRegion>(Base->getMemorySpace()))
  371. AddToWorkList(Base, &Cluster);
  372. }
  373. }
  374. bool AddToWorkList(const MemRegion *R, const ClusterBindings *C) {
  375. if (C && !Visited.insert(C))
  376. return false;
  377. WL.push_back(R);
  378. return true;
  379. }
  380. bool AddToWorkList(const MemRegion *R) {
  381. const MemRegion *baseR = R->getBaseRegion();
  382. return AddToWorkList(baseR, getCluster(baseR));
  383. }
  384. void RunWorkList() {
  385. while (!WL.empty()) {
  386. const MemRegion *baseR = WL.pop_back_val();
  387. // First visit the cluster.
  388. if (const ClusterBindings *Cluster = getCluster(baseR))
  389. static_cast<DERIVED*>(this)->VisitCluster(baseR, *Cluster);
  390. // Next, visit the base region.
  391. static_cast<DERIVED*>(this)->VisitBaseRegion(baseR);
  392. }
  393. }
  394. public:
  395. void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
  396. void VisitCluster(const MemRegion *baseR, const ClusterBindings &C) {}
  397. void VisitBaseRegion(const MemRegion *baseR) {}
  398. };
  399. }
  400. //===----------------------------------------------------------------------===//
  401. // Binding invalidation.
  402. //===----------------------------------------------------------------------===//
  403. bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
  404. ScanReachableSymbols &Callbacks) {
  405. assert(R == R->getBaseRegion() && "Should only be called for base regions");
  406. RegionBindings B = GetRegionBindings(S);
  407. const ClusterBindings *Cluster = B.lookup(R);
  408. if (!Cluster)
  409. return true;
  410. for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
  411. RI != RE; ++RI) {
  412. if (!Callbacks.scan(RI.getData()))
  413. return false;
  414. }
  415. return true;
  416. }
  417. RegionBindings RegionStoreManager::removeSubRegionBindings(RegionBindings B,
  418. const SubRegion *R) {
  419. BindingKey SRKey = BindingKey::Make(R, BindingKey::Default);
  420. const MemRegion *ClusterHead = SRKey.getBaseRegion();
  421. if (R == ClusterHead) {
  422. // We can remove an entire cluster's bindings all in one go.
  423. return RBFactory.remove(B, R);
  424. }
  425. if (SRKey.hasSymbolicOffset()) {
  426. const SubRegion *Base = cast<SubRegion>(SRKey.getConcreteOffsetRegion());
  427. B = removeSubRegionBindings(B, Base);
  428. return addBinding(B, Base, BindingKey::Default, UnknownVal());
  429. }
  430. // This assumes the region being invalidated is char-aligned. This isn't
  431. // true for bitfields, but since bitfields have no subregions they shouldn't
  432. // be using this function anyway.
  433. uint64_t Length = UINT64_MAX;
  434. SVal Extent = R->getExtent(svalBuilder);
  435. if (nonloc::ConcreteInt *ExtentCI = dyn_cast<nonloc::ConcreteInt>(&Extent)) {
  436. const llvm::APSInt &ExtentInt = ExtentCI->getValue();
  437. assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
  438. // Extents are in bytes but region offsets are in bits. Be careful!
  439. Length = ExtentInt.getLimitedValue() * Ctx.getCharWidth();
  440. }
  441. const ClusterBindings *Cluster = B.lookup(ClusterHead);
  442. if (!Cluster)
  443. return B;
  444. ClusterBindings Result = *Cluster;
  445. // It is safe to iterate over the bindings as they are being changed
  446. // because they are in an ImmutableMap.
  447. for (ClusterBindings::iterator I = Cluster->begin(), E = Cluster->end();
  448. I != E; ++I) {
  449. BindingKey NextKey = I.getKey();
  450. if (NextKey.getRegion() == SRKey.getRegion()) {
  451. if (NextKey.getOffset() > SRKey.getOffset() &&
  452. NextKey.getOffset() - SRKey.getOffset() < Length) {
  453. // Case 1: The next binding is inside the region we're invalidating.
  454. // Remove it.
  455. Result = CBFactory.remove(Result, NextKey);
  456. } else if (NextKey.getOffset() == SRKey.getOffset()) {
  457. // Case 2: The next binding is at the same offset as the region we're
  458. // invalidating. In this case, we need to leave default bindings alone,
  459. // since they may be providing a default value for a regions beyond what
  460. // we're invalidating.
  461. // FIXME: This is probably incorrect; consider invalidating an outer
  462. // struct whose first field is bound to a LazyCompoundVal.
  463. if (NextKey.isDirect())
  464. Result = CBFactory.remove(Result, NextKey);
  465. }
  466. } else if (NextKey.hasSymbolicOffset()) {
  467. const MemRegion *Base = NextKey.getConcreteOffsetRegion();
  468. if (R->isSubRegionOf(Base)) {
  469. // Case 3: The next key is symbolic and we just changed something within
  470. // its concrete region. We don't know if the binding is still valid, so
  471. // we'll be conservative and remove it.
  472. if (NextKey.isDirect())
  473. Result = CBFactory.remove(Result, NextKey);
  474. } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
  475. // Case 4: The next key is symbolic, but we changed a known
  476. // super-region. In this case the binding is certainly no longer valid.
  477. if (R == Base || BaseSR->isSubRegionOf(R))
  478. Result = CBFactory.remove(Result, NextKey);
  479. }
  480. }
  481. }
  482. if (Result.isEmpty())
  483. return RBFactory.remove(B, ClusterHead);
  484. return RBFactory.add(B, ClusterHead, Result);
  485. }
  486. namespace {
  487. class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
  488. {
  489. const Expr *Ex;
  490. unsigned Count;
  491. const LocationContext *LCtx;
  492. StoreManager::InvalidatedSymbols &IS;
  493. StoreManager::InvalidatedRegions *Regions;
  494. public:
  495. invalidateRegionsWorker(RegionStoreManager &rm,
  496. ProgramStateManager &stateMgr,
  497. RegionBindings b,
  498. const Expr *ex, unsigned count,
  499. const LocationContext *lctx,
  500. StoreManager::InvalidatedSymbols &is,
  501. StoreManager::InvalidatedRegions *r,
  502. bool includeGlobals)
  503. : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals),
  504. Ex(ex), Count(count), LCtx(lctx), IS(is), Regions(r) {}
  505. void VisitCluster(const MemRegion *baseR, const ClusterBindings &C);
  506. void VisitBaseRegion(const MemRegion *baseR);
  507. private:
  508. void VisitBinding(SVal V);
  509. };
  510. }
  511. void invalidateRegionsWorker::VisitBinding(SVal V) {
  512. // A symbol? Mark it touched by the invalidation.
  513. if (SymbolRef Sym = V.getAsSymbol())
  514. IS.insert(Sym);
  515. if (const MemRegion *R = V.getAsRegion()) {
  516. AddToWorkList(R);
  517. return;
  518. }
  519. // Is it a LazyCompoundVal? All references get invalidated as well.
  520. if (const nonloc::LazyCompoundVal *LCS =
  521. dyn_cast<nonloc::LazyCompoundVal>(&V)) {
  522. const MemRegion *LazyR = LCS->getRegion();
  523. RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
  524. // FIXME: This should not have to walk all bindings in the old store.
  525. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
  526. const ClusterBindings &Cluster = RI.getData();
  527. for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
  528. CI != CE; ++CI) {
  529. BindingKey K = CI.getKey();
  530. if (const SubRegion *BaseR = dyn_cast<SubRegion>(K.getRegion())) {
  531. if (BaseR == LazyR)
  532. VisitBinding(CI.getData());
  533. else if (K.hasSymbolicOffset() && BaseR->isSubRegionOf(LazyR))
  534. VisitBinding(CI.getData());
  535. }
  536. }
  537. }
  538. return;
  539. }
  540. }
  541. void invalidateRegionsWorker::VisitCluster(const MemRegion *BaseR,
  542. const ClusterBindings &C) {
  543. for (ClusterBindings::iterator I = C.begin(), E = C.end(); I != E; ++I)
  544. VisitBinding(I.getData());
  545. B = RM.removeCluster(B, BaseR);
  546. }
  547. void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) {
  548. // Symbolic region? Mark that symbol touched by the invalidation.
  549. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
  550. IS.insert(SR->getSymbol());
  551. // BlockDataRegion? If so, invalidate captured variables that are passed
  552. // by reference.
  553. if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
  554. for (BlockDataRegion::referenced_vars_iterator
  555. BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
  556. BI != BE; ++BI) {
  557. const VarRegion *VR = *BI;
  558. const VarDecl *VD = VR->getDecl();
  559. if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
  560. AddToWorkList(VR);
  561. }
  562. else if (Loc::isLocType(VR->getValueType())) {
  563. // Map the current bindings to a Store to retrieve the value
  564. // of the binding. If that binding itself is a region, we should
  565. // invalidate that region. This is because a block may capture
  566. // a pointer value, but the thing pointed by that pointer may
  567. // get invalidated.
  568. Store store = B.getRootWithoutRetain();
  569. SVal V = RM.getBinding(store, loc::MemRegionVal(VR));
  570. if (const Loc *L = dyn_cast<Loc>(&V)) {
  571. if (const MemRegion *LR = L->getAsRegion())
  572. AddToWorkList(LR);
  573. }
  574. }
  575. }
  576. return;
  577. }
  578. // Otherwise, we have a normal data region. Record that we touched the region.
  579. if (Regions)
  580. Regions->push_back(baseR);
  581. if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
  582. // Invalidate the region by setting its default value to
  583. // conjured symbol. The type of the symbol is irrelavant.
  584. DefinedOrUnknownSVal V =
  585. svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
  586. B = RM.addBinding(B, baseR, BindingKey::Default, V);
  587. return;
  588. }
  589. if (!baseR->isBoundable())
  590. return;
  591. const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
  592. QualType T = TR->getValueType();
  593. // Invalidate the binding.
  594. if (T->isStructureOrClassType()) {
  595. // Invalidate the region by setting its default value to
  596. // conjured symbol. The type of the symbol is irrelavant.
  597. DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
  598. Ctx.IntTy, Count);
  599. B = RM.addBinding(B, baseR, BindingKey::Default, V);
  600. return;
  601. }
  602. if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
  603. // Set the default value of the array to conjured symbol.
  604. DefinedOrUnknownSVal V =
  605. svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
  606. AT->getElementType(), Count);
  607. B = RM.addBinding(B, baseR, BindingKey::Default, V);
  608. return;
  609. }
  610. if (includeGlobals &&
  611. isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) {
  612. // If the region is a global and we are invalidating all globals,
  613. // just erase the entry. This causes all globals to be lazily
  614. // symbolicated from the same base symbol.
  615. B = RM.removeBinding(B, baseR);
  616. return;
  617. }
  618. DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
  619. T,Count);
  620. assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
  621. B = RM.addBinding(B, baseR, BindingKey::Direct, V);
  622. }
  623. RegionBindings RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
  624. const Expr *Ex,
  625. unsigned Count,
  626. const LocationContext *LCtx,
  627. RegionBindings B,
  628. InvalidatedRegions *Invalidated) {
  629. // Bind the globals memory space to a new symbol that we will use to derive
  630. // the bindings for all globals.
  631. const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
  632. SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx,
  633. /* type does not matter */ Ctx.IntTy,
  634. Count);
  635. B = removeBinding(B, GS);
  636. B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
  637. // Even if there are no bindings in the global scope, we still need to
  638. // record that we touched it.
  639. if (Invalidated)
  640. Invalidated->push_back(GS);
  641. return B;
  642. }
  643. StoreRef RegionStoreManager::invalidateRegions(Store store,
  644. ArrayRef<const MemRegion *> Regions,
  645. const Expr *Ex, unsigned Count,
  646. const LocationContext *LCtx,
  647. InvalidatedSymbols &IS,
  648. const CallEvent *Call,
  649. InvalidatedRegions *Invalidated) {
  650. invalidateRegionsWorker W(*this, StateMgr,
  651. RegionStoreManager::GetRegionBindings(store),
  652. Ex, Count, LCtx, IS, Invalidated, false);
  653. // Scan the bindings and generate the clusters.
  654. W.GenerateClusters();
  655. // Add the regions to the worklist.
  656. for (ArrayRef<const MemRegion *>::iterator
  657. I = Regions.begin(), E = Regions.end(); I != E; ++I)
  658. W.AddToWorkList(*I);
  659. W.RunWorkList();
  660. // Return the new bindings.
  661. RegionBindings B = W.getRegionBindings();
  662. // For all globals which are not static nor immutable: determine which global
  663. // regions should be invalidated and invalidate them.
  664. // TODO: This could possibly be more precise with modules.
  665. //
  666. // System calls invalidate only system globals.
  667. if (Call && Call->isInSystemHeader()) {
  668. B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
  669. Ex, Count, LCtx, B, Invalidated);
  670. // Internal calls might invalidate both system and internal globals.
  671. } else {
  672. B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
  673. Ex, Count, LCtx, B, Invalidated);
  674. B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
  675. Ex, Count, LCtx, B, Invalidated);
  676. }
  677. return StoreRef(B.getRootWithoutRetain(), *this);
  678. }
  679. //===----------------------------------------------------------------------===//
  680. // Extents for regions.
  681. //===----------------------------------------------------------------------===//
  682. DefinedOrUnknownSVal
  683. RegionStoreManager::getSizeInElements(ProgramStateRef state,
  684. const MemRegion *R,
  685. QualType EleTy) {
  686. SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
  687. const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
  688. if (!SizeInt)
  689. return UnknownVal();
  690. CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
  691. if (Ctx.getAsVariableArrayType(EleTy)) {
  692. // FIXME: We need to track extra state to properly record the size
  693. // of VLAs. Returning UnknownVal here, however, is a stop-gap so that
  694. // we don't have a divide-by-zero below.
  695. return UnknownVal();
  696. }
  697. CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
  698. // If a variable is reinterpreted as a type that doesn't fit into a larger
  699. // type evenly, round it down.
  700. // This is a signed value, since it's used in arithmetic with signed indices.
  701. return svalBuilder.makeIntVal(RegionSize / EleSize, false);
  702. }
  703. //===----------------------------------------------------------------------===//
  704. // Location and region casting.
  705. //===----------------------------------------------------------------------===//
  706. /// ArrayToPointer - Emulates the "decay" of an array to a pointer
  707. /// type. 'Array' represents the lvalue of the array being decayed
  708. /// to a pointer, and the returned SVal represents the decayed
  709. /// version of that lvalue (i.e., a pointer to the first element of
  710. /// the array). This is called by ExprEngine when evaluating casts
  711. /// from arrays to pointers.
  712. SVal RegionStoreManager::ArrayToPointer(Loc Array) {
  713. if (!isa<loc::MemRegionVal>(Array))
  714. return UnknownVal();
  715. const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
  716. const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
  717. if (!ArrayR)
  718. return UnknownVal();
  719. // Strip off typedefs from the ArrayRegion's ValueType.
  720. QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
  721. const ArrayType *AT = cast<ArrayType>(T);
  722. T = AT->getElementType();
  723. NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
  724. return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
  725. }
  726. //===----------------------------------------------------------------------===//
  727. // Loading values from regions.
  728. //===----------------------------------------------------------------------===//
  729. Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B,
  730. const MemRegion *R) {
  731. if (const SVal *V = lookup(B, R, BindingKey::Direct))
  732. return *V;
  733. return Optional<SVal>();
  734. }
  735. Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B,
  736. const MemRegion *R) {
  737. if (R->isBoundable())
  738. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
  739. if (TR->getValueType()->isUnionType())
  740. return UnknownVal();
  741. if (const SVal *V = lookup(B, R, BindingKey::Default))
  742. return *V;
  743. return Optional<SVal>();
  744. }
  745. SVal RegionStoreManager::getBinding(Store store, Loc L, QualType T) {
  746. assert(!isa<UnknownVal>(L) && "location unknown");
  747. assert(!isa<UndefinedVal>(L) && "location undefined");
  748. // For access to concrete addresses, return UnknownVal. Checks
  749. // for null dereferences (and similar errors) are done by checkers, not
  750. // the Store.
  751. // FIXME: We can consider lazily symbolicating such memory, but we really
  752. // should defer this when we can reason easily about symbolicating arrays
  753. // of bytes.
  754. if (isa<loc::ConcreteInt>(L)) {
  755. return UnknownVal();
  756. }
  757. if (!isa<loc::MemRegionVal>(L)) {
  758. return UnknownVal();
  759. }
  760. const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion();
  761. if (isa<AllocaRegion>(MR) ||
  762. isa<SymbolicRegion>(MR) ||
  763. isa<CodeTextRegion>(MR)) {
  764. if (T.isNull()) {
  765. if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
  766. T = TR->getLocationType();
  767. else {
  768. const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
  769. T = SR->getSymbol()->getType();
  770. }
  771. }
  772. MR = GetElementZeroRegion(MR, T);
  773. }
  774. // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
  775. // instead of 'Loc', and have the other Loc cases handled at a higher level.
  776. const TypedValueRegion *R = cast<TypedValueRegion>(MR);
  777. QualType RTy = R->getValueType();
  778. // FIXME: We should eventually handle funny addressing. e.g.:
  779. //
  780. // int x = ...;
  781. // int *p = &x;
  782. // char *q = (char*) p;
  783. // char c = *q; // returns the first byte of 'x'.
  784. //
  785. // Such funny addressing will occur due to layering of regions.
  786. if (RTy->isStructureOrClassType())
  787. return getBindingForStruct(store, R);
  788. // FIXME: Handle unions.
  789. if (RTy->isUnionType())
  790. return UnknownVal();
  791. if (RTy->isArrayType()) {
  792. if (RTy->isConstantArrayType())
  793. return getBindingForArray(store, R);
  794. else
  795. return UnknownVal();
  796. }
  797. // FIXME: handle Vector types.
  798. if (RTy->isVectorType())
  799. return UnknownVal();
  800. if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
  801. return CastRetrievedVal(getBindingForField(store, FR), FR, T, false);
  802. if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
  803. // FIXME: Here we actually perform an implicit conversion from the loaded
  804. // value to the element type. Eventually we want to compose these values
  805. // more intelligently. For example, an 'element' can encompass multiple
  806. // bound regions (e.g., several bound bytes), or could be a subset of
  807. // a larger value.
  808. return CastRetrievedVal(getBindingForElement(store, ER), ER, T, false);
  809. }
  810. if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
  811. // FIXME: Here we actually perform an implicit conversion from the loaded
  812. // value to the ivar type. What we should model is stores to ivars
  813. // that blow past the extent of the ivar. If the address of the ivar is
  814. // reinterpretted, it is possible we stored a different value that could
  815. // fit within the ivar. Either we need to cast these when storing them
  816. // or reinterpret them lazily (as we do here).
  817. return CastRetrievedVal(getBindingForObjCIvar(store, IVR), IVR, T, false);
  818. }
  819. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  820. // FIXME: Here we actually perform an implicit conversion from the loaded
  821. // value to the variable type. What we should model is stores to variables
  822. // that blow past the extent of the variable. If the address of the
  823. // variable is reinterpretted, it is possible we stored a different value
  824. // that could fit within the variable. Either we need to cast these when
  825. // storing them or reinterpret them lazily (as we do here).
  826. return CastRetrievedVal(getBindingForVar(store, VR), VR, T, false);
  827. }
  828. RegionBindings B = GetRegionBindings(store);
  829. const SVal *V = lookup(B, R, BindingKey::Direct);
  830. // Check if the region has a binding.
  831. if (V)
  832. return *V;
  833. // The location does not have a bound value. This means that it has
  834. // the value it had upon its creation and/or entry to the analyzed
  835. // function/method. These are either symbolic values or 'undefined'.
  836. if (R->hasStackNonParametersStorage()) {
  837. // All stack variables are considered to have undefined values
  838. // upon creation. All heap allocated blocks are considered to
  839. // have undefined values as well unless they are explicitly bound
  840. // to specific values.
  841. return UndefinedVal();
  842. }
  843. // All other values are symbolic.
  844. return svalBuilder.getRegionValueSymbolVal(R);
  845. }
  846. std::pair<Store, const MemRegion *>
  847. RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R,
  848. const MemRegion *originalRegion,
  849. bool includeSuffix) {
  850. if (originalRegion != R) {
  851. if (Optional<SVal> OV = getDefaultBinding(B, R)) {
  852. if (const nonloc::LazyCompoundVal *V =
  853. dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer()))
  854. return std::make_pair(V->getStore(), V->getRegion());
  855. }
  856. }
  857. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  858. const std::pair<Store, const MemRegion *> &X =
  859. GetLazyBinding(B, ER->getSuperRegion(), originalRegion);
  860. if (X.second)
  861. return std::make_pair(X.first,
  862. MRMgr.getElementRegionWithSuper(ER, X.second));
  863. }
  864. else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
  865. const std::pair<Store, const MemRegion *> &X =
  866. GetLazyBinding(B, FR->getSuperRegion(), originalRegion);
  867. if (X.second) {
  868. if (includeSuffix)
  869. return std::make_pair(X.first,
  870. MRMgr.getFieldRegionWithSuper(FR, X.second));
  871. return X;
  872. }
  873. }
  874. // C++ base object region is another kind of region that we should blast
  875. // through to look for lazy compound value. It is like a field region.
  876. else if (const CXXBaseObjectRegion *baseReg =
  877. dyn_cast<CXXBaseObjectRegion>(R)) {
  878. const std::pair<Store, const MemRegion *> &X =
  879. GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion);
  880. if (X.second) {
  881. if (includeSuffix)
  882. return std::make_pair(X.first,
  883. MRMgr.getCXXBaseObjectRegionWithSuper(baseReg,
  884. X.second));
  885. return X;
  886. }
  887. }
  888. // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is
  889. // possible for a valid lazy binding.
  890. return std::make_pair((Store) 0, (const MemRegion *) 0);
  891. }
  892. SVal RegionStoreManager::getBindingForElement(Store store,
  893. const ElementRegion* R) {
  894. // We do not currently model bindings of the CompoundLiteralregion.
  895. if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
  896. return UnknownVal();
  897. // Check if the region has a binding.
  898. RegionBindings B = GetRegionBindings(store);
  899. if (const Optional<SVal> &V = getDirectBinding(B, R))
  900. return *V;
  901. const MemRegion* superR = R->getSuperRegion();
  902. // Check if the region is an element region of a string literal.
  903. if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
  904. // FIXME: Handle loads from strings where the literal is treated as
  905. // an integer, e.g., *((unsigned int*)"hello")
  906. QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
  907. if (T != Ctx.getCanonicalType(R->getElementType()))
  908. return UnknownVal();
  909. const StringLiteral *Str = StrR->getStringLiteral();
  910. SVal Idx = R->getIndex();
  911. if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) {
  912. int64_t i = CI->getValue().getSExtValue();
  913. // Abort on string underrun. This can be possible by arbitrary
  914. // clients of getBindingForElement().
  915. if (i < 0)
  916. return UndefinedVal();
  917. int64_t length = Str->getLength();
  918. // Technically, only i == length is guaranteed to be null.
  919. // However, such overflows should be caught before reaching this point;
  920. // the only time such an access would be made is if a string literal was
  921. // used to initialize a larger array.
  922. char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
  923. return svalBuilder.makeIntVal(c, T);
  924. }
  925. }
  926. // Check for loads from a code text region. For such loads, just give up.
  927. if (isa<CodeTextRegion>(superR))
  928. return UnknownVal();
  929. // Handle the case where we are indexing into a larger scalar object.
  930. // For example, this handles:
  931. // int x = ...
  932. // char *y = &x;
  933. // return *y;
  934. // FIXME: This is a hack, and doesn't do anything really intelligent yet.
  935. const RegionRawOffset &O = R->getAsArrayOffset();
  936. // If we cannot reason about the offset, return an unknown value.
  937. if (!O.getRegion())
  938. return UnknownVal();
  939. if (const TypedValueRegion *baseR =
  940. dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
  941. QualType baseT = baseR->getValueType();
  942. if (baseT->isScalarType()) {
  943. QualType elemT = R->getElementType();
  944. if (elemT->isScalarType()) {
  945. if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
  946. if (const Optional<SVal> &V = getDirectBinding(B, superR)) {
  947. if (SymbolRef parentSym = V->getAsSymbol())
  948. return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
  949. if (V->isUnknownOrUndef())
  950. return *V;
  951. // Other cases: give up. We are indexing into a larger object
  952. // that has some value, but we don't know how to handle that yet.
  953. return UnknownVal();
  954. }
  955. }
  956. }
  957. }
  958. }
  959. return getBindingForFieldOrElementCommon(store, R, R->getElementType(),
  960. superR);
  961. }
  962. SVal RegionStoreManager::getBindingForField(Store store,
  963. const FieldRegion* R) {
  964. // Check if the region has a binding.
  965. RegionBindings B = GetRegionBindings(store);
  966. if (const Optional<SVal> &V = getDirectBinding(B, R))
  967. return *V;
  968. QualType Ty = R->getValueType();
  969. return getBindingForFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
  970. }
  971. Optional<SVal>
  972. RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindings B,
  973. const MemRegion *superR,
  974. const TypedValueRegion *R,
  975. QualType Ty) {
  976. if (const Optional<SVal> &D = getDefaultBinding(B, superR)) {
  977. const SVal &val = D.getValue();
  978. if (SymbolRef parentSym = val.getAsSymbol())
  979. return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
  980. if (val.isZeroConstant())
  981. return svalBuilder.makeZeroVal(Ty);
  982. if (val.isUnknownOrUndef())
  983. return val;
  984. // Lazy bindings are handled later.
  985. if (isa<nonloc::LazyCompoundVal>(val))
  986. return Optional<SVal>();
  987. llvm_unreachable("Unknown default value");
  988. }
  989. return Optional<SVal>();
  990. }
  991. SVal RegionStoreManager::getLazyBinding(const MemRegion *lazyBindingRegion,
  992. Store lazyBindingStore) {
  993. if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion))
  994. return getBindingForElement(lazyBindingStore, ER);
  995. return getBindingForField(lazyBindingStore,
  996. cast<FieldRegion>(lazyBindingRegion));
  997. }
  998. SVal RegionStoreManager::getBindingForFieldOrElementCommon(Store store,
  999. const TypedValueRegion *R,
  1000. QualType Ty,
  1001. const MemRegion *superR) {
  1002. // At this point we have already checked in either getBindingForElement or
  1003. // getBindingForField if 'R' has a direct binding.
  1004. RegionBindings B = GetRegionBindings(store);
  1005. // Lazy binding?
  1006. Store lazyBindingStore = NULL;
  1007. const MemRegion *lazyBindingRegion = NULL;
  1008. llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R,
  1009. true);
  1010. if (lazyBindingRegion)
  1011. return getLazyBinding(lazyBindingRegion, lazyBindingStore);
  1012. // Record whether or not we see a symbolic index. That can completely
  1013. // be out of scope of our lookup.
  1014. bool hasSymbolicIndex = false;
  1015. while (superR) {
  1016. if (const Optional<SVal> &D =
  1017. getBindingForDerivedDefaultValue(B, superR, R, Ty))
  1018. return *D;
  1019. if (const ElementRegion *ER = dyn_cast<ElementRegion>(superR)) {
  1020. NonLoc index = ER->getIndex();
  1021. if (!index.isConstant())
  1022. hasSymbolicIndex = true;
  1023. }
  1024. // If our super region is a field or element itself, walk up the region
  1025. // hierarchy to see if there is a default value installed in an ancestor.
  1026. if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) {
  1027. superR = SR->getSuperRegion();
  1028. continue;
  1029. }
  1030. break;
  1031. }
  1032. if (R->hasStackNonParametersStorage()) {
  1033. if (isa<ElementRegion>(R)) {
  1034. // Currently we don't reason specially about Clang-style vectors. Check
  1035. // if superR is a vector and if so return Unknown.
  1036. if (const TypedValueRegion *typedSuperR =
  1037. dyn_cast<TypedValueRegion>(superR)) {
  1038. if (typedSuperR->getValueType()->isVectorType())
  1039. return UnknownVal();
  1040. }
  1041. }
  1042. // FIXME: We also need to take ElementRegions with symbolic indexes into
  1043. // account. This case handles both directly accessing an ElementRegion
  1044. // with a symbolic offset, but also fields within an element with
  1045. // a symbolic offset.
  1046. if (hasSymbolicIndex)
  1047. return UnknownVal();
  1048. return UndefinedVal();
  1049. }
  1050. // All other values are symbolic.
  1051. return svalBuilder.getRegionValueSymbolVal(R);
  1052. }
  1053. SVal RegionStoreManager::getBindingForObjCIvar(Store store,
  1054. const ObjCIvarRegion* R) {
  1055. // Check if the region has a binding.
  1056. RegionBindings B = GetRegionBindings(store);
  1057. if (const Optional<SVal> &V = getDirectBinding(B, R))
  1058. return *V;
  1059. const MemRegion *superR = R->getSuperRegion();
  1060. // Check if the super region has a default binding.
  1061. if (const Optional<SVal> &V = getDefaultBinding(B, superR)) {
  1062. if (SymbolRef parentSym = V->getAsSymbol())
  1063. return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
  1064. // Other cases: give up.
  1065. return UnknownVal();
  1066. }
  1067. return getBindingForLazySymbol(R);
  1068. }
  1069. SVal RegionStoreManager::getBindingForVar(Store store, const VarRegion *R) {
  1070. // Check if the region has a binding.
  1071. RegionBindings B = GetRegionBindings(store);
  1072. if (const Optional<SVal> &V = getDirectBinding(B, R))
  1073. return *V;
  1074. // Lazily derive a value for the VarRegion.
  1075. const VarDecl *VD = R->getDecl();
  1076. QualType T = VD->getType();
  1077. const MemSpaceRegion *MS = R->getMemorySpace();
  1078. if (isa<UnknownSpaceRegion>(MS) ||
  1079. isa<StackArgumentsSpaceRegion>(MS))
  1080. return svalBuilder.getRegionValueSymbolVal(R);
  1081. if (isa<GlobalsSpaceRegion>(MS)) {
  1082. if (isa<NonStaticGlobalSpaceRegion>(MS)) {
  1083. // Is 'VD' declared constant? If so, retrieve the constant value.
  1084. QualType CT = Ctx.getCanonicalType(T);
  1085. if (CT.isConstQualified()) {
  1086. const Expr *Init = VD->getInit();
  1087. // Do the null check first, as we want to call 'IgnoreParenCasts'.
  1088. if (Init)
  1089. if (const IntegerLiteral *IL =
  1090. dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) {
  1091. const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL);
  1092. return svalBuilder.evalCast(V, Init->getType(), IL->getType());
  1093. }
  1094. }
  1095. if (const Optional<SVal> &V
  1096. = getBindingForDerivedDefaultValue(B, MS, R, CT))
  1097. return V.getValue();
  1098. return svalBuilder.getRegionValueSymbolVal(R);
  1099. }
  1100. if (T->isIntegerType())
  1101. return svalBuilder.makeIntVal(0, T);
  1102. if (T->isPointerType())
  1103. return svalBuilder.makeNull();
  1104. return UnknownVal();
  1105. }
  1106. return UndefinedVal();
  1107. }
  1108. SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
  1109. // All other values are symbolic.
  1110. return svalBuilder.getRegionValueSymbolVal(R);
  1111. }
  1112. static bool mayHaveLazyBinding(QualType Ty) {
  1113. return Ty->isArrayType() || Ty->isStructureOrClassType();
  1114. }
  1115. SVal RegionStoreManager::getBindingForStruct(Store store,
  1116. const TypedValueRegion* R) {
  1117. const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
  1118. if (RD->field_empty())
  1119. return UnknownVal();
  1120. // If we already have a lazy binding, don't create a new one,
  1121. // unless the first field might have a lazy binding of its own.
  1122. // (Right now we can't tell the difference.)
  1123. QualType FirstFieldType = RD->field_begin()->getType();
  1124. if (!mayHaveLazyBinding(FirstFieldType)) {
  1125. RegionBindings B = GetRegionBindings(store);
  1126. BindingKey K = BindingKey::Make(R, BindingKey::Default);
  1127. if (const nonloc::LazyCompoundVal *V =
  1128. dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) {
  1129. return *V;
  1130. }
  1131. }
  1132. return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
  1133. }
  1134. SVal RegionStoreManager::getBindingForArray(Store store,
  1135. const TypedValueRegion * R) {
  1136. const ConstantArrayType *Ty = Ctx.getAsConstantArrayType(R->getValueType());
  1137. assert(Ty && "Only constant array types can have compound bindings.");
  1138. // If we already have a lazy binding, don't create a new one,
  1139. // unless the first element might have a lazy binding of its own.
  1140. // (Right now we can't tell the difference.)
  1141. if (!mayHaveLazyBinding(Ty->getElementType())) {
  1142. RegionBindings B = GetRegionBindings(store);
  1143. BindingKey K = BindingKey::Make(R, BindingKey::Default);
  1144. if (const nonloc::LazyCompoundVal *V =
  1145. dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) {
  1146. return *V;
  1147. }
  1148. }
  1149. return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
  1150. }
  1151. bool RegionStoreManager::includedInBindings(Store store,
  1152. const MemRegion *region) const {
  1153. RegionBindings B = GetRegionBindings(store);
  1154. region = region->getBaseRegion();
  1155. // Quick path: if the base is the head of a cluster, the region is live.
  1156. if (B.lookup(region))
  1157. return true;
  1158. // Slow path: if the region is the VALUE of any binding, it is live.
  1159. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
  1160. const ClusterBindings &Cluster = RI.getData();
  1161. for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
  1162. CI != CE; ++CI) {
  1163. const SVal &D = CI.getData();
  1164. if (const MemRegion *R = D.getAsRegion())
  1165. if (R->getBaseRegion() == region)
  1166. return true;
  1167. }
  1168. }
  1169. return false;
  1170. }
  1171. //===----------------------------------------------------------------------===//
  1172. // Binding values to regions.
  1173. //===----------------------------------------------------------------------===//
  1174. StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
  1175. if (isa<loc::MemRegionVal>(L))
  1176. if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion())
  1177. return StoreRef(removeBinding(GetRegionBindings(ST),
  1178. R).getRootWithoutRetain(),
  1179. *this);
  1180. return StoreRef(ST, *this);
  1181. }
  1182. StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) {
  1183. if (isa<loc::ConcreteInt>(L))
  1184. return StoreRef(store, *this);
  1185. // If we get here, the location should be a region.
  1186. const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion();
  1187. // Check if the region is a struct region.
  1188. if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
  1189. QualType Ty = TR->getValueType();
  1190. if (Ty->isArrayType())
  1191. return BindArray(store, TR, V);
  1192. if (Ty->isStructureOrClassType())
  1193. return BindStruct(store, TR, V);
  1194. if (Ty->isVectorType())
  1195. return BindVector(store, TR, V);
  1196. }
  1197. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
  1198. // Binding directly to a symbolic region should be treated as binding
  1199. // to element 0.
  1200. QualType T = SR->getSymbol()->getType();
  1201. if (T->isAnyPointerType() || T->isReferenceType())
  1202. T = T->getPointeeType();
  1203. R = GetElementZeroRegion(SR, T);
  1204. }
  1205. // Clear out bindings that may overlap with this binding.
  1206. // Perform the binding.
  1207. RegionBindings B = GetRegionBindings(store);
  1208. B = removeSubRegionBindings(B, cast<SubRegion>(R));
  1209. BindingKey Key = BindingKey::Make(R, BindingKey::Direct);
  1210. return StoreRef(addBinding(B, Key, V).getRootWithoutRetain(), *this);
  1211. }
  1212. // FIXME: this method should be merged into Bind().
  1213. StoreRef RegionStoreManager::bindCompoundLiteral(Store ST,
  1214. const CompoundLiteralExpr *CL,
  1215. const LocationContext *LC,
  1216. SVal V) {
  1217. return Bind(ST, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)), V);
  1218. }
  1219. StoreRef RegionStoreManager::setImplicitDefaultValue(Store store,
  1220. const MemRegion *R,
  1221. QualType T) {
  1222. RegionBindings B = GetRegionBindings(store);
  1223. SVal V;
  1224. if (Loc::isLocType(T))
  1225. V = svalBuilder.makeNull();
  1226. else if (T->isIntegerType())
  1227. V = svalBuilder.makeZeroVal(T);
  1228. else if (T->isStructureOrClassType() || T->isArrayType()) {
  1229. // Set the default value to a zero constant when it is a structure
  1230. // or array. The type doesn't really matter.
  1231. V = svalBuilder.makeZeroVal(Ctx.IntTy);
  1232. }
  1233. else {
  1234. // We can't represent values of this type, but we still need to set a value
  1235. // to record that the region has been initialized.
  1236. // If this assertion ever fires, a new case should be added above -- we
  1237. // should know how to default-initialize any value we can symbolicate.
  1238. assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
  1239. V = UnknownVal();
  1240. }
  1241. return StoreRef(addBinding(B, R, BindingKey::Default,
  1242. V).getRootWithoutRetain(), *this);
  1243. }
  1244. StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R,
  1245. SVal Init) {
  1246. const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
  1247. QualType ElementTy = AT->getElementType();
  1248. Optional<uint64_t> Size;
  1249. if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
  1250. Size = CAT->getSize().getZExtValue();
  1251. // Check if the init expr is a string literal.
  1252. if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) {
  1253. const StringRegion *S = cast<StringRegion>(MRV->getRegion());
  1254. // Treat the string as a lazy compound value.
  1255. nonloc::LazyCompoundVal LCV =
  1256. cast<nonloc::LazyCompoundVal>(svalBuilder.
  1257. makeLazyCompoundVal(StoreRef(store, *this), S));
  1258. return BindAggregate(store, R, LCV);
  1259. }
  1260. // Handle lazy compound values.
  1261. if (isa<nonloc::LazyCompoundVal>(Init))
  1262. return BindAggregate(store, R, Init);
  1263. // Remaining case: explicit compound values.
  1264. if (Init.isUnknown())
  1265. return setImplicitDefaultValue(store, R, ElementTy);
  1266. nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
  1267. nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
  1268. uint64_t i = 0;
  1269. StoreRef newStore(store, *this);
  1270. for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
  1271. // The init list might be shorter than the array length.
  1272. if (VI == VE)
  1273. break;
  1274. const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
  1275. const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
  1276. if (ElementTy->isStructureOrClassType())
  1277. newStore = BindStruct(newStore.getStore(), ER, *VI);
  1278. else if (ElementTy->isArrayType())
  1279. newStore = BindArray(newStore.getStore(), ER, *VI);
  1280. else
  1281. newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
  1282. }
  1283. // If the init list is shorter than the array length, set the
  1284. // array default value.
  1285. if (Size.hasValue() && i < Size.getValue())
  1286. newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy);
  1287. return newStore;
  1288. }
  1289. StoreRef RegionStoreManager::BindVector(Store store, const TypedValueRegion* R,
  1290. SVal V) {
  1291. QualType T = R->getValueType();
  1292. assert(T->isVectorType());
  1293. const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
  1294. // Handle lazy compound values and symbolic values.
  1295. if (isa<nonloc::LazyCompoundVal>(V) || isa<nonloc::SymbolVal>(V))
  1296. return BindAggregate(store, R, V);
  1297. // We may get non-CompoundVal accidentally due to imprecise cast logic or
  1298. // that we are binding symbolic struct value. Kill the field values, and if
  1299. // the value is symbolic go and bind it as a "default" binding.
  1300. if (!isa<nonloc::CompoundVal>(V)) {
  1301. return BindAggregate(store, R, UnknownVal());
  1302. }
  1303. QualType ElemType = VT->getElementType();
  1304. nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
  1305. nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
  1306. unsigned index = 0, numElements = VT->getNumElements();
  1307. StoreRef newStore(store, *this);
  1308. for ( ; index != numElements ; ++index) {
  1309. if (VI == VE)
  1310. break;
  1311. NonLoc Idx = svalBuilder.makeArrayIndex(index);
  1312. const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
  1313. if (ElemType->isArrayType())
  1314. newStore = BindArray(newStore.getStore(), ER, *VI);
  1315. else if (ElemType->isStructureOrClassType())
  1316. newStore = BindStruct(newStore.getStore(), ER, *VI);
  1317. else
  1318. newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
  1319. }
  1320. return newStore;
  1321. }
  1322. StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R,
  1323. SVal V) {
  1324. if (!Features.supportsFields())
  1325. return StoreRef(store, *this);
  1326. QualType T = R->getValueType();
  1327. assert(T->isStructureOrClassType());
  1328. const RecordType* RT = T->getAs<RecordType>();
  1329. RecordDecl *RD = RT->getDecl();
  1330. if (!RD->isCompleteDefinition())
  1331. return StoreRef(store, *this);
  1332. // Handle lazy compound values and symbolic values.
  1333. if (isa<nonloc::LazyCompoundVal>(V) || isa<nonloc::SymbolVal>(V))
  1334. return BindAggregate(store, R, V);
  1335. // We may get non-CompoundVal accidentally due to imprecise cast logic or
  1336. // that we are binding symbolic struct value. Kill the field values, and if
  1337. // the value is symbolic go and bind it as a "default" binding.
  1338. if (V.isUnknown() || !isa<nonloc::CompoundVal>(V))
  1339. return BindAggregate(store, R, UnknownVal());
  1340. nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
  1341. nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
  1342. RecordDecl::field_iterator FI, FE;
  1343. StoreRef newStore(store, *this);
  1344. for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
  1345. if (VI == VE)
  1346. break;
  1347. // Skip any unnamed bitfields to stay in sync with the initializers.
  1348. if (FI->isUnnamedBitfield())
  1349. continue;
  1350. QualType FTy = FI->getType();
  1351. const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
  1352. if (FTy->isArrayType())
  1353. newStore = BindArray(newStore.getStore(), FR, *VI);
  1354. else if (FTy->isStructureOrClassType())
  1355. newStore = BindStruct(newStore.getStore(), FR, *VI);
  1356. else
  1357. newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
  1358. ++VI;
  1359. }
  1360. // There may be fewer values in the initialize list than the fields of struct.
  1361. if (FI != FE) {
  1362. RegionBindings B = GetRegionBindings(newStore.getStore());
  1363. B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false));
  1364. newStore = StoreRef(B.getRootWithoutRetain(), *this);
  1365. }
  1366. return newStore;
  1367. }
  1368. StoreRef RegionStoreManager::BindAggregate(Store store, const TypedRegion *R,
  1369. SVal Val) {
  1370. // Remove the old bindings, using 'R' as the root of all regions
  1371. // we will invalidate. Then add the new binding.
  1372. RegionBindings B = GetRegionBindings(store);
  1373. B = removeSubRegionBindings(B, R);
  1374. B = addBinding(B, R, BindingKey::Default, Val);
  1375. return StoreRef(B.getRootWithoutRetain(), *this);
  1376. }
  1377. //===----------------------------------------------------------------------===//
  1378. // "Raw" retrievals and bindings.
  1379. //===----------------------------------------------------------------------===//
  1380. RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K,
  1381. SVal V) {
  1382. const MemRegion *Base = K.getBaseRegion();
  1383. const ClusterBindings *ExistingCluster = B.lookup(Base);
  1384. ClusterBindings Cluster = (ExistingCluster ? *ExistingCluster
  1385. : CBFactory.getEmptyMap());
  1386. ClusterBindings NewCluster = CBFactory.add(Cluster, K, V);
  1387. return RBFactory.add(B, Base, NewCluster);
  1388. }
  1389. RegionBindings RegionStoreManager::addBinding(RegionBindings B,
  1390. const MemRegion *R,
  1391. BindingKey::Kind k, SVal V) {
  1392. return addBinding(B, BindingKey::Make(R, k), V);
  1393. }
  1394. const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) {
  1395. const ClusterBindings *Cluster = B.lookup(K.getBaseRegion());
  1396. if (!Cluster)
  1397. return 0;
  1398. return Cluster->lookup(K);
  1399. }
  1400. const SVal *RegionStoreManager::lookup(RegionBindings B,
  1401. const MemRegion *R,
  1402. BindingKey::Kind k) {
  1403. return lookup(B, BindingKey::Make(R, k));
  1404. }
  1405. RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
  1406. BindingKey K) {
  1407. const MemRegion *Base = K.getBaseRegion();
  1408. const ClusterBindings *Cluster = B.lookup(Base);
  1409. if (!Cluster)
  1410. return B;
  1411. ClusterBindings NewCluster = CBFactory.remove(*Cluster, K);
  1412. if (NewCluster.isEmpty())
  1413. return RBFactory.remove(B, Base);
  1414. return RBFactory.add(B, Base, NewCluster);
  1415. }
  1416. RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
  1417. const MemRegion *R,
  1418. BindingKey::Kind k){
  1419. return removeBinding(B, BindingKey::Make(R, k));
  1420. }
  1421. RegionBindings RegionStoreManager::removeCluster(RegionBindings B,
  1422. const MemRegion *Base) {
  1423. return RBFactory.remove(B, Base);
  1424. }
  1425. //===----------------------------------------------------------------------===//
  1426. // State pruning.
  1427. //===----------------------------------------------------------------------===//
  1428. namespace {
  1429. class removeDeadBindingsWorker :
  1430. public ClusterAnalysis<removeDeadBindingsWorker> {
  1431. SmallVector<const SymbolicRegion*, 12> Postponed;
  1432. SymbolReaper &SymReaper;
  1433. const StackFrameContext *CurrentLCtx;
  1434. public:
  1435. removeDeadBindingsWorker(RegionStoreManager &rm,
  1436. ProgramStateManager &stateMgr,
  1437. RegionBindings b, SymbolReaper &symReaper,
  1438. const StackFrameContext *LCtx)
  1439. : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
  1440. /* includeGlobals = */ false),
  1441. SymReaper(symReaper), CurrentLCtx(LCtx) {}
  1442. // Called by ClusterAnalysis.
  1443. void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
  1444. void VisitCluster(const MemRegion *baseR, const ClusterBindings &C);
  1445. bool UpdatePostponed();
  1446. void VisitBinding(SVal V);
  1447. };
  1448. }
  1449. void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
  1450. const ClusterBindings &C) {
  1451. if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
  1452. if (SymReaper.isLive(VR))
  1453. AddToWorkList(baseR, &C);
  1454. return;
  1455. }
  1456. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
  1457. if (SymReaper.isLive(SR->getSymbol()))
  1458. AddToWorkList(SR, &C);
  1459. else
  1460. Postponed.push_back(SR);
  1461. return;
  1462. }
  1463. if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
  1464. AddToWorkList(baseR, &C);
  1465. return;
  1466. }
  1467. // CXXThisRegion in the current or parent location context is live.
  1468. if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
  1469. const StackArgumentsSpaceRegion *StackReg =
  1470. cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
  1471. const StackFrameContext *RegCtx = StackReg->getStackFrame();
  1472. if (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))
  1473. AddToWorkList(TR, &C);
  1474. }
  1475. }
  1476. void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
  1477. const ClusterBindings &C) {
  1478. // Mark the symbol for any SymbolicRegion with live bindings as live itself.
  1479. // This means we should continue to track that symbol.
  1480. if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
  1481. SymReaper.markLive(SymR->getSymbol());
  1482. for (ClusterBindings::iterator I = C.begin(), E = C.end(); I != E; ++I)
  1483. VisitBinding(I.getData());
  1484. }
  1485. void removeDeadBindingsWorker::VisitBinding(SVal V) {
  1486. // Is it a LazyCompoundVal? All referenced regions are live as well.
  1487. if (const nonloc::LazyCompoundVal *LCS =
  1488. dyn_cast<nonloc::LazyCompoundVal>(&V)) {
  1489. const MemRegion *LazyR = LCS->getRegion();
  1490. RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
  1491. // FIXME: This should not have to walk all bindings in the old store.
  1492. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
  1493. const ClusterBindings &Cluster = RI.getData();
  1494. for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
  1495. CI != CE; ++CI) {
  1496. BindingKey K = CI.getKey();
  1497. if (const SubRegion *BaseR = dyn_cast<SubRegion>(K.getRegion())) {
  1498. if (BaseR == LazyR)
  1499. VisitBinding(CI.getData());
  1500. else if (K.hasSymbolicOffset() && BaseR->isSubRegionOf(LazyR))
  1501. VisitBinding(CI.getData());
  1502. }
  1503. }
  1504. }
  1505. return;
  1506. }
  1507. // If V is a region, then add it to the worklist.
  1508. if (const MemRegion *R = V.getAsRegion()) {
  1509. AddToWorkList(R);
  1510. // All regions captured by a block are also live.
  1511. if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
  1512. BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
  1513. E = BR->referenced_vars_end();
  1514. for ( ; I != E; ++I)
  1515. AddToWorkList(I.getCapturedRegion());
  1516. }
  1517. }
  1518. // Update the set of live symbols.
  1519. for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
  1520. SI!=SE; ++SI)
  1521. SymReaper.markLive(*SI);
  1522. }
  1523. bool removeDeadBindingsWorker::UpdatePostponed() {
  1524. // See if any postponed SymbolicRegions are actually live now, after
  1525. // having done a scan.
  1526. bool changed = false;
  1527. for (SmallVectorImpl<const SymbolicRegion*>::iterator
  1528. I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
  1529. if (const SymbolicRegion *SR = *I) {
  1530. if (SymReaper.isLive(SR->getSymbol())) {
  1531. changed |= AddToWorkList(SR);
  1532. *I = NULL;
  1533. }
  1534. }
  1535. }
  1536. return changed;
  1537. }
  1538. StoreRef RegionStoreManager::removeDeadBindings(Store store,
  1539. const StackFrameContext *LCtx,
  1540. SymbolReaper& SymReaper) {
  1541. RegionBindings B = GetRegionBindings(store);
  1542. removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
  1543. W.GenerateClusters();
  1544. // Enqueue the region roots onto the worklist.
  1545. for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
  1546. E = SymReaper.region_end(); I != E; ++I) {
  1547. W.AddToWorkList(*I);
  1548. }
  1549. do W.RunWorkList(); while (W.UpdatePostponed());
  1550. // We have now scanned the store, marking reachable regions and symbols
  1551. // as live. We now remove all the regions that are dead from the store
  1552. // as well as update DSymbols with the set symbols that are now dead.
  1553. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  1554. const MemRegion *Base = I.getKey();
  1555. // If the cluster has been visited, we know the region has been marked.
  1556. if (W.isVisited(Base))
  1557. continue;
  1558. // Remove the dead entry.
  1559. B = removeCluster(B, Base);
  1560. if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base))
  1561. SymReaper.maybeDead(SymR->getSymbol());
  1562. // Mark all non-live symbols that this binding references as dead.
  1563. const ClusterBindings &Cluster = I.getData();
  1564. for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
  1565. CI != CE; ++CI) {
  1566. SVal X = CI.getData();
  1567. SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
  1568. for (; SI != SE; ++SI)
  1569. SymReaper.maybeDead(*SI);
  1570. }
  1571. }
  1572. return StoreRef(B.getRootWithoutRetain(), *this);
  1573. }
  1574. //===----------------------------------------------------------------------===//
  1575. // Utility methods.
  1576. //===----------------------------------------------------------------------===//
  1577. void RegionStoreManager::print(Store store, raw_ostream &OS,
  1578. const char* nl, const char *sep) {
  1579. RegionBindings B = GetRegionBindings(store);
  1580. OS << "Store (direct and default bindings), "
  1581. << (void*) B.getRootWithoutRetain()
  1582. << " :" << nl;
  1583. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  1584. const ClusterBindings &Cluster = I.getData();
  1585. for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
  1586. CI != CE; ++CI) {
  1587. OS << ' ' << CI.getKey() << " : " << CI.getData() << nl;
  1588. }
  1589. OS << nl;
  1590. }
  1591. }