RegionStore.cpp 71 KB

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