RegionStore.cpp 85 KB

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