RegionStore.cpp 72 KB

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