RegionStore.cpp 73 KB

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