blob: c61094c20cd813f3b764ed36d54040dc1ed1caa7 [file] [log] [blame]
Zhongxing Xu17892752008-10-08 02:50:44 +00001//== 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/Analysis/PathSensitive/MemRegion.h"
18#include "clang/Analysis/PathSensitive/GRState.h"
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Zhongxing Xu17892752008-10-08 02:50:44 +000020#include "clang/Analysis/Analyses/LiveVariables.h"
21
22#include "llvm/ADT/ImmutableMap.h"
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000023#include "llvm/ADT/ImmutableList.h"
Zhongxing Xua071eb02008-10-24 06:01:33 +000024#include "llvm/Support/raw_ostream.h"
Zhongxing Xu17892752008-10-08 02:50:44 +000025#include "llvm/Support/Compiler.h"
26
27using namespace clang;
28
Zhongxing Xubaf03a72008-11-24 09:44:56 +000029// Actual Store type.
Zhongxing Xu1c96b242008-10-17 05:57:07 +000030typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy;
Zhongxing Xubaf03a72008-11-24 09:44:56 +000031
Ted Kremenek50dc1b32008-12-24 01:05:03 +000032//===----------------------------------------------------------------------===//
33// Region "Views"
34//===----------------------------------------------------------------------===//
35//
36// MemRegions can be layered on top of each other. This GDM entry tracks
37// what are the MemRegions that layer a given MemRegion.
38//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000039typedef llvm::ImmutableSet<const MemRegion*> RegionViews;
Ted Kremenek50dc1b32008-12-24 01:05:03 +000040namespace { class VISIBILITY_HIDDEN RegionViewMap {}; }
41static int RegionViewMapIndex = 0;
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000042namespace clang {
Ted Kremenek50dc1b32008-12-24 01:05:03 +000043 template<> struct GRStateTrait<RegionViewMap>
44 : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*,
45 RegionViews> > {
46
47 static void* GDMIndex() { return &RegionViewMapIndex; }
48 };
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000049}
Zhongxing Xu17892752008-10-08 02:50:44 +000050
Ted Kremenek50dc1b32008-12-24 01:05:03 +000051//===----------------------------------------------------------------------===//
52// Region "Extents"
53//===----------------------------------------------------------------------===//
54//
55// MemRegions represent chunks of memory with a size (their "extent"). This
56// GDM entry tracks the extents for regions. Extents are in bytes.
Ted Kremenekd6cfbe42009-01-07 22:18:50 +000057//
Ted Kremenek50dc1b32008-12-24 01:05:03 +000058namespace { class VISIBILITY_HIDDEN RegionExtents {}; }
59static int RegionExtentsIndex = 0;
Zhongxing Xubaf03a72008-11-24 09:44:56 +000060namespace clang {
Ted Kremenek50dc1b32008-12-24 01:05:03 +000061 template<> struct GRStateTrait<RegionExtents>
62 : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, SVal> > {
63 static void* GDMIndex() { return &RegionExtentsIndex; }
64 };
Zhongxing Xubaf03a72008-11-24 09:44:56 +000065}
66
Ted Kremenek50dc1b32008-12-24 01:05:03 +000067//===----------------------------------------------------------------------===//
68// Region "killsets".
69//===----------------------------------------------------------------------===//
70//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000071// RegionStore lazily adds value bindings to regions when the analyzer handles
72// assignment statements. Killsets track which default values have been
73// killed, thus distinguishing between "unknown" values and default
74// values. Regions are added to killset only when they are assigned "unknown"
75// directly, otherwise we should have their value in the region bindings.
Ted Kremenek50dc1b32008-12-24 01:05:03 +000076//
77namespace { class VISIBILITY_HIDDEN RegionKills {}; }
Ted Kremenek2ed14be2008-12-05 00:47:52 +000078static int RegionKillsIndex = 0;
Ted Kremenekc48ea6e2008-12-04 02:08:27 +000079namespace clang {
Ted Kremenek2ed14be2008-12-05 00:47:52 +000080 template<> struct GRStateTrait<RegionKills>
Ted Kremenek50dc1b32008-12-24 01:05:03 +000081 : public GRStatePartialTrait< llvm::ImmutableSet<const MemRegion*> > {
Ted Kremenek2ed14be2008-12-05 00:47:52 +000082 static void* GDMIndex() { return &RegionKillsIndex; }
Ted Kremenekc48ea6e2008-12-04 02:08:27 +000083 };
84}
85
Ted Kremenek50dc1b32008-12-24 01:05:03 +000086//===----------------------------------------------------------------------===//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000087// Regions with default values.
Ted Kremenek50dc1b32008-12-24 01:05:03 +000088//===----------------------------------------------------------------------===//
89//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000090// This GDM entry tracks what regions have a default value if they have no bound
91// value and have not been killed.
Ted Kremenek50dc1b32008-12-24 01:05:03 +000092//
93namespace { class VISIBILITY_HIDDEN RegionDefaultValue {}; }
94static int RegionDefaultValueIndex = 0;
95namespace clang {
96 template<> struct GRStateTrait<RegionDefaultValue>
97 : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, SVal> > {
98 static void* GDMIndex() { return &RegionDefaultValueIndex; }
99 };
100}
101
102//===----------------------------------------------------------------------===//
103// Main RegionStore logic.
104//===----------------------------------------------------------------------===//
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000105
Zhongxing Xu17892752008-10-08 02:50:44 +0000106namespace {
107
108class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager {
109 RegionBindingsTy::Factory RBFactory;
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000110 RegionViews::Factory RVFactory;
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000111
Zhongxing Xu17892752008-10-08 02:50:44 +0000112 GRStateManager& StateMgr;
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000113 const MemRegion* SelfRegion;
114 const ImplicitParamDecl *SelfDecl;
Zhongxing Xu17892752008-10-08 02:50:44 +0000115
116public:
117 RegionStoreManager(GRStateManager& mgr)
Ted Kremenekd6cfbe42009-01-07 22:18:50 +0000118 : StoreManager(mgr.getAllocator()),
119 RBFactory(mgr.getAllocator()),
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000120 RVFactory(mgr.getAllocator()),
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000121 StateMgr(mgr), SelfRegion(0), SelfDecl(0) {
122 if (const ObjCMethodDecl* MD =
123 dyn_cast<ObjCMethodDecl>(&StateMgr.getCodeDecl()))
124 SelfDecl = MD->getSelfDecl();
125 }
Zhongxing Xu17892752008-10-08 02:50:44 +0000126
127 virtual ~RegionStoreManager() {}
128
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000129 MemRegionManager& getRegionManager() { return MRMgr; }
Ted Kremenek4f090272008-10-27 21:54:31 +0000130
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000131 const GRState* BindCompoundLiteral(const GRState* St,
132 const CompoundLiteralExpr* CL, SVal V);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000133
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000134 /// getLValueString - Returns an SVal representing the lvalue of a
135 /// StringLiteral. Within RegionStore a StringLiteral has an
136 /// associated StringRegion, and the lvalue of a StringLiteral is
137 /// the lvalue of that region.
Zhongxing Xu143bf822008-10-25 14:18:57 +0000138 SVal getLValueString(const GRState* St, const StringLiteral* S);
139
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000140 /// getLValueCompoundLiteral - Returns an SVal representing the
141 /// lvalue of a compound literal. Within RegionStore a compound
142 /// literal has an associated region, and the lvalue of the
143 /// compound literal is the lvalue of that region.
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000144 SVal getLValueCompoundLiteral(const GRState* St, const CompoundLiteralExpr*);
145
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000146 /// getLValueVar - Returns an SVal that represents the lvalue of a
147 /// variable. Within RegionStore a variable has an associated
148 /// VarRegion, and the lvalue of the variable is the lvalue of that region.
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000149 SVal getLValueVar(const GRState* St, const VarDecl* VD);
150
151 SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base);
152
153 SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D);
154
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000155 SVal getLValueElement(const GRState* St, SVal Base, SVal Offset);
156
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000157 SVal getSizeInElements(const GRState* St, const MemRegion* R);
158
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000159 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
160 /// type. 'Array' represents the lvalue of the array being decayed
161 /// to a pointer, and the returned SVal represents the decayed
162 /// version of that lvalue (i.e., a pointer to the first element of
163 /// the array). This is called by GRExprEngine when evaluating
164 /// casts from arrays to pointers.
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000165 SVal ArrayToPointer(SVal Array);
166
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000167 /// CastRegion - Used by GRExprEngine::VisitCast to handle casts from
168 /// a MemRegion* to a specific location type. 'R' is the region being
169 /// casted and 'CastToTy' the result type of the cast.
170 CastResult CastRegion(const GRState* state, const MemRegion* R,
171 QualType CastToTy);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000172
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000173 /// The high level logic for this method is this:
174 /// Retrieve (L)
175 /// if L has binding
176 /// return L's binding
177 /// else if L is in killset
178 /// return unknown
179 /// else
180 /// if L is on stack or heap
181 /// return undefined
182 /// else
183 /// return symbolic
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000184 SVal Retrieve(const GRState* state, Loc L, QualType T = QualType());
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000185
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000186 const GRState* Bind(const GRState* St, Loc LV, SVal V);
Zhongxing Xu17892752008-10-08 02:50:44 +0000187
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000188 Store Remove(Store store, Loc LV);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000189
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000190 Store getInitialStore() { return RBFactory.GetEmptyMap().getRoot(); }
Ted Kremenek9deb0e32008-10-24 20:32:16 +0000191
192 /// getSelfRegion - Returns the region for the 'self' (Objective-C) or
193 /// 'this' object (C++). When used when analyzing a normal function this
194 /// method returns NULL.
195 const MemRegion* getSelfRegion(Store) {
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000196 if (!SelfDecl)
197 return 0;
198
199 if (!SelfRegion) {
200 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(&StateMgr.getCodeDecl());
201 SelfRegion = MRMgr.getObjCObjectRegion(MD->getClassInterface(),
202 MRMgr.getHeapRegion());
203 }
204
205 return SelfRegion;
Ted Kremenek9deb0e32008-10-24 20:32:16 +0000206 }
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000207
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000208 /// RemoveDeadBindings - Scans the RegionStore of 'state' for dead values.
209 /// It returns a new Store with these values removed, and populates LSymbols
210 // and DSymbols with the known set of live and dead symbols respectively.
211 Store RemoveDeadBindings(const GRState* state, Stmt* Loc,
Ted Kremenek241677a2009-01-21 22:26:05 +0000212 SymbolReaper& SymReaper,
213 llvm::SmallVectorImpl<const MemRegion*>& RegionRoots);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000214
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000215 const GRState* BindDecl(const GRState* St, const VarDecl* VD, SVal InitVal);
216
217 const GRState* BindDeclWithNoInit(const GRState* St, const VarDecl* VD) {
218 return St;
219 }
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000220
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000221 const GRState* setExtent(const GRState* St, const MemRegion* R, SVal Extent);
222
Zhongxing Xu17892752008-10-08 02:50:44 +0000223 static inline RegionBindingsTy GetRegionBindings(Store store) {
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000224 return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store));
Zhongxing Xu17892752008-10-08 02:50:44 +0000225 }
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000226
Zhongxing Xu5b8b6f22008-10-24 04:33:15 +0000227 void print(Store store, std::ostream& Out, const char* nl, const char *sep);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000228
229 void iterBindings(Store store, BindingsHandler& f) {
230 // FIXME: Implement.
231 }
Zhongxing Xua82512a2008-10-24 08:42:28 +0000232
233private:
234 Loc getVarLoc(const VarDecl* VD) {
235 return loc::MemRegionVal(MRMgr.getVarRegion(VD));
236 }
237
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000238 const GRState* BindArray(const GRState* St, const TypedRegion* R, SVal V);
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000239
Zhongxing Xu0b242ec2008-12-04 01:12:41 +0000240 /// Retrieve the values in a struct and return a CompoundVal, used when doing
241 /// struct copy:
242 /// struct s x, y;
243 /// x = y;
244 /// y's value is retrieved by this method.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000245 SVal RetrieveStruct(const GRState* St, const TypedRegion* R);
Zhongxing Xu0b242ec2008-12-04 01:12:41 +0000246
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000247 const GRState* BindStruct(const GRState* St, const TypedRegion* R, SVal V);
Zhongxing Xu63123d82008-11-23 04:30:35 +0000248
Zhongxing Xu5834ed62009-01-13 01:49:57 +0000249 /// KillStruct - Set the entire struct to unknown.
250 const GRState* KillStruct(const GRState* St, const TypedRegion* R);
251
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000252 // Utility methods.
253 BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); }
254 ASTContext& getContext() { return StateMgr.getContext(); }
Zhongxing Xu63123d82008-11-23 04:30:35 +0000255 SymbolManager& getSymbolManager() { return StateMgr.getSymbolManager(); }
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000256
257 const GRState* AddRegionView(const GRState* St,
258 const MemRegion* View, const MemRegion* Base);
Zhongxing Xu5834ed62009-01-13 01:49:57 +0000259 const GRState* RemoveRegionView(const GRState* St,
260 const MemRegion* View, const MemRegion* Base);
Zhongxing Xu17892752008-10-08 02:50:44 +0000261};
262
263} // end anonymous namespace
264
Ted Kremenek95c7b002008-10-24 01:04:59 +0000265StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) {
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000266 return new RegionStoreManager(StMgr);
Ted Kremenek95c7b002008-10-24 01:04:59 +0000267}
268
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000269
270/// getLValueString - Returns an SVal representing the lvalue of a
271/// StringLiteral. Within RegionStore a StringLiteral has an
272/// associated StringRegion, and the lvalue of a StringLiteral is the
273/// lvalue of that region.
Zhongxing Xu143bf822008-10-25 14:18:57 +0000274SVal RegionStoreManager::getLValueString(const GRState* St,
275 const StringLiteral* S) {
276 return loc::MemRegionVal(MRMgr.getStringRegion(S));
277}
278
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000279/// getLValueVar - Returns an SVal that represents the lvalue of a
280/// variable. Within RegionStore a variable has an associated
281/// VarRegion, and the lvalue of the variable is the lvalue of that region.
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000282SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {
283 return loc::MemRegionVal(MRMgr.getVarRegion(VD));
284}
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000285
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000286/// getLValueCompoundLiteral - Returns an SVal representing the lvalue
287/// of a compound literal. Within RegionStore a compound literal
288/// has an associated region, and the lvalue of the compound literal
289/// is the lvalue of that region.
290SVal
291RegionStoreManager::getLValueCompoundLiteral(const GRState* St,
292 const CompoundLiteralExpr* CL) {
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000293 return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL));
294}
295
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000296SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,
297 SVal Base) {
298 return UnknownVal();
299}
300
301SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base,
302 const FieldDecl* D) {
303 if (Base.isUnknownOrUndef())
304 return Base;
305
306 Loc BaseL = cast<Loc>(Base);
307 const MemRegion* BaseR = 0;
308
309 switch (BaseL.getSubKind()) {
310 case loc::MemRegionKind:
311 BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
312 break;
313
314 case loc::SymbolValKind:
Zhongxing Xu026c6632009-02-05 06:57:29 +0000315 BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol(),
316 StateMgr.getSymbolManager());
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000317 break;
318
319 case loc::GotoLabelKind:
320 case loc::FuncValKind:
321 // These are anormal cases. Flag an undefined value.
322 return UndefinedVal();
323
324 case loc::ConcreteIntKind:
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000325 // While these seem funny, this can happen through casts.
326 // FIXME: What we should return is the field offset. For example,
327 // add the field offset to the integer value. That way funny things
328 // like this work properly: &(((struct foo *) 0xa)->f)
329 return Base;
330
331 default:
Zhongxing Xu13d1ee22008-11-07 08:57:30 +0000332 assert(0 && "Unhandled Base.");
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000333 return Base;
334 }
335
336 return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR));
337}
338
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000339SVal RegionStoreManager::getLValueElement(const GRState* St,
340 SVal Base, SVal Offset) {
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000341
Zhongxing Xua48f7372009-02-06 08:44:27 +0000342 if (Base.isUnknownOrUndef())
Zhongxing Xu4a1513e2008-10-27 12:23:17 +0000343 return Base;
344
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000345 // Only handle integer offsets... for now.
346 if (!isa<nonloc::ConcreteInt>(Offset))
Zhongxing Xue4d13932008-11-13 09:48:44 +0000347 return UnknownVal();
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000348
Zhongxing Xua48f7372009-02-06 08:44:27 +0000349 const TypedRegion* BaseRegion = 0;
350
351 if (isa<loc::SymbolVal>(Base))
352 BaseRegion = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(Base).getSymbol(),
353 StateMgr.getSymbolManager());
354 else
355 BaseRegion = cast<TypedRegion>(cast<loc::MemRegionVal>(Base).getRegion());
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000356
357 // Pointer of any type can be cast and used as array base.
358 const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
359
360 if (!ElemR) {
361 //
362 // If the base region is not an ElementRegion, create one.
363 // This can happen in the following example:
364 //
365 // char *p = __builtin_alloc(10);
366 // p[1] = 8;
367 //
368 // Observe that 'p' binds to an AnonTypedRegion<AllocaRegion>.
369 //
Zhongxing Xu5ea2ffc2009-02-19 08:37:16 +0000370
371 // Offset might be unsigned. We have to convert it to signed ConcreteInt.
372 if (nonloc::ConcreteInt* CI = dyn_cast<nonloc::ConcreteInt>(&Offset)) {
373 const llvm::APSInt& OffI = CI->getValue();
374 if (OffI.isUnsigned()) {
375 llvm::APSInt Tmp = OffI;
376 Tmp.setIsSigned(true);
377 Offset = NonLoc::MakeVal(getBasicVals(), Tmp);
378 }
379 }
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000380 return loc::MemRegionVal(MRMgr.getElementRegion(Offset, BaseRegion));
Zhongxing Xue4d13932008-11-13 09:48:44 +0000381 }
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000382
383 SVal BaseIdx = ElemR->getIndex();
384
385 if (!isa<nonloc::ConcreteInt>(BaseIdx))
386 return UnknownVal();
387
388 const llvm::APSInt& BaseIdxI = cast<nonloc::ConcreteInt>(BaseIdx).getValue();
389 const llvm::APSInt& OffI = cast<nonloc::ConcreteInt>(Offset).getValue();
390 assert(BaseIdxI.isSigned());
391
392 // FIXME: This appears to be the assumption of this code. We should review
393 // whether or not BaseIdxI.getBitWidth() < OffI.getBitWidth(). If it
394 // can't we need to put a comment here. If it can, we should handle it.
395 assert(BaseIdxI.getBitWidth() >= OffI.getBitWidth());
Zhongxing Xue4d13932008-11-13 09:48:44 +0000396
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000397 const TypedRegion *ArrayR = ElemR->getArrayRegion();
398 SVal NewIdx;
399
400 if (OffI.isUnsigned() || OffI.getBitWidth() < BaseIdxI.getBitWidth()) {
401 // 'Offset' might be unsigned. We have to convert it to signed and
402 // possibly extend it.
403 llvm::APSInt Tmp = OffI;
404
405 if (OffI.getBitWidth() < BaseIdxI.getBitWidth())
406 Tmp.extend(BaseIdxI.getBitWidth());
407
408 Tmp.setIsSigned(true);
409 Tmp += BaseIdxI; // Compute the new offset.
Zhongxing Xu5ea2ffc2009-02-19 08:37:16 +0000410 NewIdx = NonLoc::MakeVal(getBasicVals(), Tmp);
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000411 }
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000412 else
413 NewIdx = nonloc::ConcreteInt(getBasicVals().getValue(BaseIdxI + OffI));
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000414
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000415 return loc::MemRegionVal(MRMgr.getElementRegion(NewIdx, ArrayR));
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000416}
417
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000418SVal RegionStoreManager::getSizeInElements(const GRState* St,
419 const MemRegion* R) {
420 if (const VarRegion* VR = dyn_cast<VarRegion>(R)) {
421 // Get the type of the variable.
Ted Kremenek14553ab2009-01-30 00:08:43 +0000422 QualType T = VR->getDesugaredRValueType(getContext());
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000423
Ted Kremenek14553ab2009-01-30 00:08:43 +0000424 // FIXME: Handle variable-length arrays.
425 if (isa<VariableArrayType>(T))
426 return UnknownVal();
427
428 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(T)) {
429 // return the size as signed integer.
430 return NonLoc::MakeVal(getBasicVals(), CAT->getSize(), false);
431 }
432
433 // Clients can use ordinary variables as if they were arrays. These
434 // essentially are arrays of size 1.
435 return NonLoc::MakeIntVal(getBasicVals(), 1, false);
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000436 }
437
438 if (const StringRegion* SR = dyn_cast<StringRegion>(R)) {
Zhongxing Xu6613d082008-11-24 02:18:56 +0000439 const StringLiteral* Str = SR->getStringLiteral();
Zhongxing Xud0fd3b72008-11-24 02:30:48 +0000440 // We intentionally made the size value signed because it participates in
441 // operations with signed indices.
Ted Kremenek14553ab2009-01-30 00:08:43 +0000442 return NonLoc::MakeIntVal(getBasicVals(), Str->getByteLength()+1, false);
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000443 }
444
445 if (const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R)) {
Ted Kremenek2e842572009-01-22 23:56:56 +0000446#if 0
447 // FIXME: This logic doesn't really work, as we can have all sorts of
448 // weird cases. For example, this crashes on test case 'rdar-6442306-1.m'.
449 // The weird cases come in when arbitrary casting comes into play, violating
450 // any type-safe programming.
451
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000452 GRStateRef state(St, StateMgr);
453
454 // Get the size of the super region in bytes.
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000455 const SVal* Extent = state.get<RegionExtents>(ATR->getSuperRegion());
456 assert(Extent && "region extent not exist");
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000457
458 // Assume it's ConcreteInt for now.
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000459 llvm::APSInt SSize = cast<nonloc::ConcreteInt>(*Extent).getValue();
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000460
461 // Get the size of the element in bits.
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000462 QualType LvT = ATR->getLValueType(getContext());
463 QualType ElemTy = cast<PointerType>(LvT.getTypePtr())->getPointeeType();
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000464
465 uint64_t X = getContext().getTypeSize(ElemTy);
466
467 const llvm::APSInt& ESize = getBasicVals().getValue(X, SSize.getBitWidth(),
468 false);
469
470 // Calculate the number of elements.
471
472 // FIXME: What do we do with signed-ness problem? Shall we make all APSInts
473 // signed?
474 if (SSize.isUnsigned())
475 SSize.setIsSigned(true);
476
477 // FIXME: move this operation into BasicVals.
478 const llvm::APSInt S =
479 (SSize * getBasicVals().getValue(8, SSize.getBitWidth(), false)) / ESize;
480
481 return NonLoc::MakeVal(getBasicVals(), S);
Ted Kremenek2e842572009-01-22 23:56:56 +0000482#else
483 ATR = ATR;
484 return UnknownVal();
485#endif
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000486 }
487
488 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) {
489 // FIXME: Unsupported yet.
490 FR = 0;
491 return UnknownVal();
492 }
Zhongxing Xu369f4292008-11-22 13:23:00 +0000493
Zhongxing Xu02ebefb2009-02-06 08:51:30 +0000494 if (isa<SymbolicRegion>(R)) {
Zhongxing Xua48f7372009-02-06 08:44:27 +0000495 return UnknownVal();
496 }
497
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000498 assert(0 && "Other regions are not supported yet.");
Ted Kremeneka21362d2009-01-06 19:12:06 +0000499 return UnknownVal();
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000500}
501
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000502/// ArrayToPointer - Emulates the "decay" of an array to a pointer
503/// type. 'Array' represents the lvalue of the array being decayed
504/// to a pointer, and the returned SVal represents the decayed
505/// version of that lvalue (i.e., a pointer to the first element of
506/// the array). This is called by GRExprEngine when evaluating casts
507/// from arrays to pointers.
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000508SVal RegionStoreManager::ArrayToPointer(SVal Array) {
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000509 // FIXME: This should be factored into GRExprEngine. This allows
510 // us to pass a "loc" instead of an "SVal" for "Array".
Ted Kremenekabb042f2008-12-13 19:24:37 +0000511 if (Array.isUnknownOrUndef())
512 return Array;
513
514 if (!isa<loc::MemRegionVal>(Array))
515 return UnknownVal();
516
517 const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
518 const TypedRegion* ArrayR = dyn_cast<TypedRegion>(R);
519
Ted Kremenekbbee1a72009-01-13 01:03:27 +0000520 if (!ArrayR)
Ted Kremenekabb042f2008-12-13 19:24:37 +0000521 return UnknownVal();
522
Zhongxing Xu63123d82008-11-23 04:30:35 +0000523 nonloc::ConcreteInt Idx(getBasicVals().getZeroWithPtrWidth(false));
Zhongxing Xu0b7e6422008-10-26 02:23:57 +0000524 ElementRegion* ER = MRMgr.getElementRegion(Idx, ArrayR);
525
526 return loc::MemRegionVal(ER);
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000527}
528
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000529StoreManager::CastResult
530RegionStoreManager::CastRegion(const GRState* state, const MemRegion* R,
531 QualType CastToTy) {
532
533 // Return the same region if the region types are compatible.
534 if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) {
535 ASTContext& Ctx = StateMgr.getContext();
536 QualType Ta = Ctx.getCanonicalType(TR->getLValueType(Ctx));
537 QualType Tb = Ctx.getCanonicalType(CastToTy);
538
539 if (Ta == Tb)
540 return CastResult(state, R);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000541 }
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000542
543 // FIXME: We should handle the case when we are casting *back* to a
544 // previous type. For example:
545 //
546 // void* x = ...;
547 // char* y = (char*) x;
548 // void* z = (void*) y; // <-- we should get the same region that is
549 // bound to 'x'
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000550 const MemRegion* ViewR = MRMgr.getAnonTypedRegion(CastToTy, R);
551 return CastResult(AddRegionView(state, ViewR, R), ViewR);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000552}
553
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000554SVal RegionStoreManager::Retrieve(const GRState* St, Loc L, QualType T) {
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000555 assert(!isa<UnknownVal>(L) && "location unknown");
556 assert(!isa<UndefinedVal>(L) && "location undefined");
557
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000558 // FIXME: What does loc::SymbolVal represent? It represents the value
559 // of a location but that value is not known. In the future we should
560 // handle potential aliasing relationships; e.g. a loc::SymbolVal could
561 // be an alias for a particular region.
Zhongxing Xu779747c2009-02-20 05:19:30 +0000562 // Example:
563 // void foo(char* buf) {
564 // char c = *buf;
565 // }
566 if (isa<loc::SymbolVal>(L)) {
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000567 return UnknownVal();
Zhongxing Xu779747c2009-02-20 05:19:30 +0000568 }
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000569
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000570 // FIXME: Is this even possible? Shouldn't this be treated as a null
571 // dereference at a higher level?
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000572 if (isa<loc::ConcreteInt>(L))
573 return UndefinedVal();
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000574
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000575 // FIXME: Should this be refactored into GRExprEngine or GRStateManager?
576 // It seems that all StoreManagers would do the same thing here.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000577 if (isa<loc::FuncVal>(L))
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000578 return L;
579
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000580 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
581 // instead of 'Loc', and have the other Loc cases handled at a higher level.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000582 const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
583 assert(R && "bad region");
584
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000585 // FIXME: We should eventually handle funny addressing. e.g.:
586 //
587 // int x = ...;
588 // int *p = &x;
589 // char *q = (char*) p;
590 // char c = *q; // returns the first byte of 'x'.
591 //
592 // Such funny addressing will occur due to layering of regions.
593
Ted Kremenek265a3052009-02-24 02:23:11 +0000594 if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) {
595 QualType T =TR->getRValueType(getContext());
596 if (T->isStructureType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000597 return RetrieveStruct(St, TR);
Ted Kremenek265a3052009-02-24 02:23:11 +0000598 // FIXME: handle Vector types.
599 if (T->isVectorType())
600 return UnknownVal();
601 }
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000602
603 RegionBindingsTy B = GetRegionBindings(St->getStore());
604 RegionBindingsTy::data_type* V = B.lookup(R);
605
606 // Check if the region has a binding.
607 if (V)
608 return *V;
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000609
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000610 GRStateRef state(St, StateMgr);
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000611
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000612 // Check if the region is in killset.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000613 if (state.contains<RegionKills>(R))
614 return UnknownVal();
615
Zhongxing Xu562c4d92009-01-23 11:22:12 +0000616 // If the region is an element of field, it may have a default value.
617 if (isa<ElementRegion>(R) || isa<FieldRegion>(R)) {
618 const MemRegion* SuperR = cast<SubRegion>(R)->getSuperRegion();
619 GRStateTrait<RegionDefaultValue>::lookup_type D =
620 state.get<RegionDefaultValue>(SuperR);
621 if (D)
622 return *D;
623 }
624
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000625 // The location does not have a bound value. This means that it has
626 // the value it had upon its creation and/or entry to the analyzed
627 // function/method. These are either symbolic values or 'undefined'.
628
629 // We treat function parameters as symbolic values.
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000630 if (const VarRegion* VR = dyn_cast<VarRegion>(R)) {
631 const VarDecl *VD = VR->getDecl();
632
Zhongxing Xud8895f62009-02-19 09:56:08 +0000633 if (isa<ParmVarDecl>(VD) || VD->hasGlobalStorage()) {
634 QualType VTy = VD->getType();
635 if (Loc::IsLocType(VTy) || VTy->isIntegerType())
636 return SVal::GetRValueSymbolVal(getSymbolManager(), VR);
637 else
638 return UnknownVal();
639 }
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000640 else if (VD == SelfDecl)
641 return loc::MemRegionVal(getSelfRegion(0));
642 }
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000643
Ted Kremenek265a3052009-02-24 02:23:11 +0000644
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000645 if (MRMgr.onStack(R) || MRMgr.onHeap(R)) {
646 // All stack variables are considered to have undefined values
647 // upon creation. All heap allocated blocks are considered to
648 // have undefined values as well unless they are explicitly bound
649 // to specific values.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000650 return UndefinedVal();
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000651 }
652
653 // All other values are symbolic.
Ted Kremenek9ab6b9c2009-01-22 18:23:34 +0000654 return SVal::GetRValueSymbolVal(getSymbolManager(), R);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000655
656 // FIXME: consider default values for elements and fields.
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000657}
658
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000659SVal RegionStoreManager::RetrieveStruct(const GRState* St,const TypedRegion* R){
660
661 Store store = St->getStore();
662 GRStateRef state(St, StateMgr);
663
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000664 // FIXME: Verify we want getRValueType instead of getLValueType.
665 QualType T = R->getRValueType(getContext());
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000666 assert(T->isStructureType());
667
668 const RecordType* RT = cast<RecordType>(T.getTypePtr());
669 RecordDecl* RD = RT->getDecl();
670 assert(RD->isDefinition());
671
672 llvm::ImmutableList<SVal> StructVal = getBasicVals().getEmptySValList();
673
Douglas Gregore267ff32008-12-11 20:41:00 +0000674 std::vector<FieldDecl *> Fields(RD->field_begin(), RD->field_end());
Douglas Gregor44b43212008-12-11 16:49:14 +0000675
Douglas Gregore267ff32008-12-11 20:41:00 +0000676 for (std::vector<FieldDecl *>::reverse_iterator Field = Fields.rbegin(),
677 FieldEnd = Fields.rend();
678 Field != FieldEnd; ++Field) {
679 FieldRegion* FR = MRMgr.getFieldRegion(*Field, R);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000680 RegionBindingsTy B = GetRegionBindings(store);
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000681 RegionBindingsTy::data_type* data = B.lookup(FR);
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000682
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000683 SVal FieldValue;
684 if (data)
685 FieldValue = *data;
686 else if (state.contains<RegionKills>(FR))
687 FieldValue = UnknownVal();
688 else {
689 if (MRMgr.onStack(FR) || MRMgr.onHeap(FR))
690 FieldValue = UndefinedVal();
691 else
Ted Kremenek9ab6b9c2009-01-22 18:23:34 +0000692 FieldValue = SVal::GetRValueSymbolVal(getSymbolManager(), FR);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000693 }
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000694
695 StructVal = getBasicVals().consVals(FieldValue, StructVal);
696 }
697
698 return NonLoc::MakeCompoundVal(T, StructVal, getBasicVals());
699}
700
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000701const GRState* RegionStoreManager::Bind(const GRState* St, Loc L, SVal V) {
702 // Currently we don't bind value to symbolic location. But if the logic is
703 // made clear, we might change this decision.
704 if (isa<loc::SymbolVal>(L))
705 return St;
Zhongxing Xu8fe63af2008-10-27 09:24:07 +0000706
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000707 // If we get here, the location should be a region.
708 const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000709 assert(R);
710
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000711 // Check if the region is a struct region.
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000712 if (const TypedRegion* TR = dyn_cast<TypedRegion>(R))
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000713 // FIXME: Verify we want getRValueType().
714 if (TR->getRValueType(getContext())->isStructureType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000715 return BindStruct(St, TR, V);
Zhongxing Xu17892752008-10-08 02:50:44 +0000716
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000717 Store store = St->getStore();
Zhongxing Xu17892752008-10-08 02:50:44 +0000718 RegionBindingsTy B = GetRegionBindings(store);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000719
720 if (V.isUnknown()) {
721 // Remove the binding.
722 store = RBFactory.Remove(B, R).getRoot();
723
724 // Add the region to the killset.
725 GRStateRef state(St, StateMgr);
726 St = state.add<RegionKills>(R);
727 }
728 else
729 store = RBFactory.Add(B, R, V).getRoot();
730
731 return StateMgr.MakeStateWithStore(St, store);
Zhongxing Xu17892752008-10-08 02:50:44 +0000732}
733
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000734Store RegionStoreManager::Remove(Store store, Loc L) {
Ted Kremenek0964a062009-01-21 06:57:53 +0000735 const MemRegion* R = 0;
736
737 if (isa<loc::MemRegionVal>(L))
738 R = cast<loc::MemRegionVal>(L).getRegion();
739 else if (isa<loc::SymbolVal>(L))
Zhongxing Xu026c6632009-02-05 06:57:29 +0000740 R = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(L).getSymbol(),
741 StateMgr.getSymbolManager());
Ted Kremenek0964a062009-01-21 06:57:53 +0000742
743 if (R) {
744 RegionBindingsTy B = GetRegionBindings(store);
745 return RBFactory.Remove(B, R).getRoot();
746 }
747
748 return store;
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000749}
750
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000751const GRState* RegionStoreManager::BindDecl(const GRState* St,
752 const VarDecl* VD, SVal InitVal) {
Zhongxing Xua4f28ff2008-11-13 08:41:36 +0000753
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000754 QualType T = VD->getType();
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000755 VarRegion* VR = MRMgr.getVarRegion(VD);
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000756
Ted Kremenek0964a062009-01-21 06:57:53 +0000757 if (T->isArrayType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000758 return BindArray(St, VR, InitVal);
Ted Kremenek0964a062009-01-21 06:57:53 +0000759 if (T->isStructureType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000760 return BindStruct(St, VR, InitVal);
Zhongxing Xud463d442008-11-02 12:13:30 +0000761
Ted Kremenek0964a062009-01-21 06:57:53 +0000762 return Bind(St, Loc::MakeVal(VR), InitVal);
Zhongxing Xu17892752008-10-08 02:50:44 +0000763}
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000764
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000765// FIXME: this method should be merged into Bind().
766const GRState*
767RegionStoreManager::BindCompoundLiteral(const GRState* St,
768 const CompoundLiteralExpr* CL, SVal V) {
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000769 CompoundLiteralRegion* R = MRMgr.getCompoundLiteralRegion(CL);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000770 return Bind(St, loc::MemRegionVal(R), V);
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000771}
772
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000773const GRState* RegionStoreManager::setExtent(const GRState* St,
774 const MemRegion* R, SVal Extent) {
775 GRStateRef state(St, StateMgr);
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000776 return state.set<RegionExtents>(R, Extent);
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000777}
778
779
Ted Kremenek241677a2009-01-21 22:26:05 +0000780static void UpdateLiveSymbols(SVal X, SymbolReaper& SymReaper) {
781 for (SVal::symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end();SI!=SE;++SI)
782 SymReaper.markLive(*SI);
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000783}
784
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000785Store RegionStoreManager::RemoveDeadBindings(const GRState* state, Stmt* Loc,
Ted Kremenek241677a2009-01-21 22:26:05 +0000786 SymbolReaper& SymReaper,
787 llvm::SmallVectorImpl<const MemRegion*>& RegionRoots)
788{
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000789
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000790 Store store = state->getStore();
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000791 RegionBindingsTy B = GetRegionBindings(store);
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000792
793 // Lazily constructed backmap from MemRegions to SubRegions.
794 typedef llvm::ImmutableSet<const MemRegion*> SubRegionsTy;
795 typedef llvm::ImmutableMap<const MemRegion*, SubRegionsTy> SubRegionsMapTy;
796
797 // FIXME: As a future optimization we can modifiy BumpPtrAllocator to have
798 // the ability to reuse memory. This way we can keep TmpAlloc around as
799 // an instance variable of RegionStoreManager (avoiding repeated malloc
800 // overhead).
801 llvm::BumpPtrAllocator TmpAlloc;
802
803 // Factory objects.
804 SubRegionsMapTy::Factory SubRegMapF(TmpAlloc);
805 SubRegionsTy::Factory SubRegF(TmpAlloc);
806
807 // The backmap from regions to subregions.
808 SubRegionsMapTy SubRegMap = SubRegMapF.GetEmptyMap();
809
810 // Do a pass over the regions in the store. For VarRegions we check if
811 // the variable is still live and if so add it to the list of live roots.
812 // For other regions we populate our region backmap.
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000813 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000814 const MemRegion* R = I.getKey();
815 if (const VarRegion* VR = dyn_cast<VarRegion>(R)) {
Ted Kremenek241677a2009-01-21 22:26:05 +0000816 if (SymReaper.isLive(Loc, VR->getDecl()))
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000817 RegionRoots.push_back(VR); // This is a live "root".
818 }
819 else {
820 // Get the super region for R.
821 const MemRegion* SuperR = cast<SubRegion>(R)->getSuperRegion();
822 // Get the current set of subregions for SuperR.
823 const SubRegionsTy* SRptr = SubRegMap.lookup(SuperR);
824 SubRegionsTy SR = SRptr ? *SRptr : SubRegF.GetEmptySet();
825 // Add R to the subregions of SuperR.
826 SubRegMap = SubRegMapF.Add(SubRegMap, SuperR, SubRegF.Add(SR, R));
827
828 // Finally, check if SuperR is a VarRegion. We need to do this
829 // to also mark SuperR as a root (as it may not have a value directly
830 // bound to it in the store).
831 if (const VarRegion* VR = dyn_cast<VarRegion>(SuperR)) {
Ted Kremenek241677a2009-01-21 22:26:05 +0000832 if (SymReaper.isLive(Loc, VR->getDecl()))
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000833 RegionRoots.push_back(VR); // This is a live "root".
834 }
835 }
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000836 }
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000837
838 // Process the worklist of RegionRoots. This performs a "mark-and-sweep"
839 // of the store. We want to find all live symbols and dead regions.
840 llvm::SmallPtrSet<const MemRegion*, 10> Marked;
841
842 while (!RegionRoots.empty()) {
843 // Dequeue the next region on the worklist.
844 const MemRegion* R = RegionRoots.back();
845 RegionRoots.pop_back();
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000846
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000847 // Check if we have already processed this region.
848 if (Marked.count(R)) continue;
849
850 // Mark this region as processed. This is needed for termination in case
851 // a region is referenced more than once.
852 Marked.insert(R);
853
854 // Mark the symbol for any live SymbolicRegion as "live". This means we
855 // should continue to track that symbol.
856 if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(R))
Ted Kremenek241677a2009-01-21 22:26:05 +0000857 SymReaper.markLive(SymR->getSymbol());
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000858
859 // Get the data binding for R (if any).
860 RegionBindingsTy::data_type* Xptr = B.lookup(R);
861 if (Xptr) {
862 SVal X = *Xptr;
Ted Kremenek241677a2009-01-21 22:26:05 +0000863 UpdateLiveSymbols(X, SymReaper); // Update the set of live symbols.
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000864
865 // If X is a region, then add it the RegionRoots.
866 if (loc::MemRegionVal* RegionX = dyn_cast<loc::MemRegionVal>(&X))
867 RegionRoots.push_back(RegionX->getRegion());
868 }
869
870 // Get the subregions of R. These are RegionRoots as well since they
871 // represent values that are also bound to R.
872 const SubRegionsTy* SRptr = SubRegMap.lookup(R);
873 if (!SRptr) continue;
874 SubRegionsTy SR = *SRptr;
875
876 for (SubRegionsTy::iterator I=SR.begin(), E=SR.end(); I!=E; ++I)
877 RegionRoots.push_back(*I);
878 }
879
880 // We have now scanned the store, marking reachable regions and symbols
881 // as live. We now remove all the regions that are dead from the store
882 // as well as update DSymbols with the set symbols that are now dead.
883
884 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
885 const MemRegion* R = I.getKey();
886
887 // If this region live? Is so, none of its symbols are dead.
888 if (Marked.count(R))
889 continue;
890
891 // Remove this dead region from the store.
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000892 store = Remove(store, Loc::MakeVal(R));
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000893
894 // Mark all non-live symbols that this region references as dead.
Ted Kremenek241677a2009-01-21 22:26:05 +0000895 if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(R))
896 SymReaper.maybeDead(SymR->getSymbol());
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000897
898 SVal X = I.getData();
899 SVal::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
Ted Kremenek241677a2009-01-21 22:26:05 +0000900 for (; SI != SE; ++SI) SymReaper.maybeDead(*SI);
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000901 }
902
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000903 return store;
904}
905
Zhongxing Xua071eb02008-10-24 06:01:33 +0000906void RegionStoreManager::print(Store store, std::ostream& Out,
907 const char* nl, const char *sep) {
908 llvm::raw_os_ostream OS(Out);
909 RegionBindingsTy B = GetRegionBindings(store);
910 OS << "Store:" << nl;
911
912 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
913 OS << ' '; I.getKey()->print(OS); OS << " : ";
914 I.getData().print(OS); OS << nl;
915 }
Zhongxing Xu5b8b6f22008-10-24 04:33:15 +0000916}
Zhongxing Xua82512a2008-10-24 08:42:28 +0000917
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000918const GRState* RegionStoreManager::BindArray(const GRState* St,
919 const TypedRegion* R, SVal Init) {
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000920
921 // FIXME: Verify we should use getLValueType or getRValueType.
Zhongxing Xu2ef93722008-12-14 03:14:52 +0000922 QualType T = R->getRValueType(getContext());
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000923 assert(T->isArrayType());
924
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000925 // When we are binding the whole array, it always has default value 0.
926 GRStateRef state(St, StateMgr);
Ted Kremenek14553ab2009-01-30 00:08:43 +0000927 St = state.set<RegionDefaultValue>(R, NonLoc::MakeIntVal(getBasicVals(), 0,
928 false));
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000929
930 Store store = St->getStore();
931
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000932 ConstantArrayType* CAT = cast<ConstantArrayType>(T.getTypePtr());
933
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000934 llvm::APSInt Size(CAT->getSize(), false);
Sebastian Redl1be3da52009-01-26 19:54:12 +0000935 llvm::APSInt i = getBasicVals().getValue(0, Size.getBitWidth(),
936 Size.isUnsigned());
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000937
938 // Check if the init expr is a StringLiteral.
939 if (isa<loc::MemRegionVal>(Init)) {
940 const MemRegion* InitR = cast<loc::MemRegionVal>(Init).getRegion();
941 const StringLiteral* S = cast<StringRegion>(InitR)->getStringLiteral();
942 const char* str = S->getStrData();
943 unsigned len = S->getByteLength();
944 unsigned j = 0;
945
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000946 // Copy bytes from the string literal into the target array. Trailing bytes
947 // in the array that are not covered by the string literal are initialized
948 // to zero.
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000949 for (; i < Size; ++i, ++j) {
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000950 if (j >= len)
951 break;
952
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000953 SVal Idx = NonLoc::MakeVal(getBasicVals(), i);
954 ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
955
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000956 SVal V = NonLoc::MakeVal(getBasicVals(), str[j], sizeof(char)*8, true);
957 St = Bind(St, loc::MemRegionVal(ER), V);
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000958 }
959
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000960 return StateMgr.MakeStateWithStore(St, store);
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000961 }
962
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000963
964 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
965
966 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
967
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000968 for (; i < Size; ++i, ++VI) {
969 // The init list might be shorter than the array decl.
970 if (VI == VE)
971 break;
972
Zhongxing Xu6987c7b2008-11-30 05:49:49 +0000973 SVal Idx = NonLoc::MakeVal(getBasicVals(), i);
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000974 ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000975
976 if (CAT->getElementType()->isStructureType())
977 St = BindStruct(St, ER, *VI);
978 else
979 St = Bind(St, Loc::MakeVal(ER), *VI);
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000980 }
981
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000982 return StateMgr.MakeStateWithStore(St, store);
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000983}
984
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000985const GRState*
986RegionStoreManager::BindStruct(const GRState* St, const TypedRegion* R, SVal V){
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000987 // FIXME: Verify that we should use getRValueType or getLValueType.
988 QualType T = R->getRValueType(getContext());
Zhongxing Xuaf0a8442008-10-31 10:53:01 +0000989 assert(T->isStructureType());
990
991 RecordType* RT = cast<RecordType>(T.getTypePtr());
992 RecordDecl* RD = RT->getDecl();
993 assert(RD->isDefinition());
994
Zhongxing Xu5834ed62009-01-13 01:49:57 +0000995 if (V.isUnknown())
996 return KillStruct(St, R);
997
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000998 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
Zhongxing Xuaf0a8442008-10-31 10:53:01 +0000999 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1000 RecordDecl::field_iterator FI = RD->field_begin(), FE = RD->field_end();
1001
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001002 for (; FI != FE; ++FI, ++VI) {
1003
1004 // There may be fewer values than fields only when we are initializing a
1005 // struct decl. In this case, mark the region as having default value.
1006 if (VI == VE) {
Zhongxing Xu13020162008-12-24 07:29:24 +00001007 GRStateRef state(St, StateMgr);
Ted Kremenek14553ab2009-01-30 00:08:43 +00001008 const NonLoc& Idx = NonLoc::MakeIntVal(getBasicVals(), 0, false);
1009 St = state.set<RegionDefaultValue>(R, Idx);
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001010 break;
1011 }
1012
Zhongxing Xuaf0a8442008-10-31 10:53:01 +00001013 QualType FTy = (*FI)->getType();
1014 FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
1015
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001016 if (Loc::IsLocType(FTy) || FTy->isIntegerType())
1017 St = Bind(St, Loc::MakeVal(FR), *VI);
Zhongxing Xua82512a2008-10-24 08:42:28 +00001018
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001019 else if (FTy->isArrayType())
1020 St = BindArray(St, FR, *VI);
Zhongxing Xua82512a2008-10-24 08:42:28 +00001021
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001022 else if (FTy->isStructureType())
1023 St = BindStruct(St, FR, *VI);
Zhongxing Xua82512a2008-10-24 08:42:28 +00001024 }
1025
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001026 return St;
Zhongxing Xuc3a05992008-11-19 11:06:24 +00001027}
1028
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001029const GRState* RegionStoreManager::KillStruct(const GRState* St,
1030 const TypedRegion* R){
1031 GRStateRef state(St, StateMgr);
1032
1033 // Kill the struct region because it is assigned "unknown".
1034 St = state.add<RegionKills>(R);
1035
1036 // Set the default value of the struct region to "unknown".
1037 St = state.set<RegionDefaultValue>(R, UnknownVal());
1038
1039 Store store = St->getStore();
1040 RegionBindingsTy B = GetRegionBindings(store);
1041
1042 // Remove all bindings for the subregions of the struct.
1043 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1044 const MemRegion* r = I.getKey();
1045 if (const SubRegion* sr = dyn_cast<SubRegion>(r))
1046 if (sr->isSubRegionOf(R))
1047 store = Remove(store, Loc::MakeVal(sr));
Zhongxing Xu9c2a3db2009-01-13 03:07:41 +00001048 // FIXME: Maybe we should also remove the bindings for the "views" of the
1049 // subregions.
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001050 }
1051
1052 return StateMgr.MakeStateWithStore(St, store);
1053}
1054
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001055const GRState* RegionStoreManager::AddRegionView(const GRState* St,
1056 const MemRegion* View,
1057 const MemRegion* Base) {
1058 GRStateRef state(St, StateMgr);
1059
1060 // First, retrieve the region view of the base region.
Ted Kremenek50dc1b32008-12-24 01:05:03 +00001061 const RegionViews* d = state.get<RegionViewMap>(Base);
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001062 RegionViews L = d ? *d : RVFactory.GetEmptySet();
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001063
1064 // Now add View to the region view.
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001065 L = RVFactory.Add(L, View);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001066
1067 // Create a new state with the new region view.
Ted Kremenek50dc1b32008-12-24 01:05:03 +00001068 return state.set<RegionViewMap>(Base, L);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001069}
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001070
1071const GRState* RegionStoreManager::RemoveRegionView(const GRState* St,
1072 const MemRegion* View,
1073 const MemRegion* Base) {
1074 GRStateRef state(St, StateMgr);
1075
1076 // Retrieve the region view of the base region.
1077 const RegionViews* d = state.get<RegionViewMap>(Base);
1078
1079 // If the base region has no view, return.
1080 if (!d)
1081 return St;
1082
1083 // Remove the view.
1084 RegionViews V = *d;
1085 V = RVFactory.Remove(V, View);
1086
1087 return state.set<RegionViewMap>(Base, V);
1088}