RegionStore.cpp 74 KB

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