RegionStore.cpp 75 KB

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