RegionStore.cpp 85 KB

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