RegionStore.cpp 84 KB

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