1 //===-- llvm/User.h - User class definition ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class defines the interface that one who 'use's a Value must implement.
11 // Each instance of the Value class keeps track of what User's have handles
14 // * Instructions are the largest class of User's.
15 // * Constants may be users of other constants (think arrays and stuff)
17 //===----------------------------------------------------------------------===//
22 #include "llvm/Value.h"
26 /*==============================================================================
29 -----------------------------------------------------------------
30 --- Interaction and relationship between User and Use objects ---
31 -----------------------------------------------------------------
34 A subclass of User can choose between incorporating its Use objects
35 or refer to them out-of-line by means of a pointer. A mixed variant
36 (some Uses inline others hung off) is impractical and breaks the invariant
37 that the Use objects belonging to the same User form a contiguous array.
39 We have 2 different layouts in the User (sub)classes:
42 The Use object(s) are inside (resp. at fixed offset) of the User
43 object and there are a fixed number of them.
46 The Use object(s) are referenced by a pointer to an
47 array from the User object and there may be a variable
50 Initially each layout will possess a direct pointer to the
51 start of the array of Uses. Though not mandatory for layout a),
52 we stick to this redundancy for the sake of simplicity.
53 The User object will also store the number of Use objects it
54 has. (Theoretically this information can also be calculated
55 given the scheme presented below.)
57 Special forms of allocation operators (operator new)
58 will enforce the following memory layouts:
61 # Layout a) will be modelled by prepending the User object
64 # ...---.---.---.---.-------...
65 # | P | P | P | P | User
66 # '''---'---'---'---'-------'''
69 # Layout b) will be modelled by pointing at the Use[] array.
80 (In the above figures 'P' stands for the Use** that
81 is stored in each Use object in the member Use::Prev)
84 Since the Use objects will be deprived of the direct pointer to
85 their User objects, there must be a fast and exact method to
86 recover it. This is accomplished by the following scheme:
88 A bit-encoding in the 2 LSBits of the Use::Prev will allow to find the
89 start of the User object:
93 10 --> stop and calc (s)
96 Given a Use*, all we have to do is to walk till we get
97 a stop and we either have a User immediately behind or
98 we have to walk to the next stop picking up digits
99 and calculating the offset:
101 .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.----------------
102 | 1 | s | 1 | 0 | 1 | 0 | s | 1 | 1 | 0 | s | 1 | 1 | s | 1 | S | User (or User*)
103 '---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'----------------
104 |+15 |+10 |+6 |+3 |+1
107 | | |______________________>
108 | |______________________________________>
109 |__________________________________________________________>
112 Only the significant number of bits need to be stored between the
113 stops, so that the worst case is 20 memory accesses when there are
116 The following literate Haskell fragment demonstrates the concept:
118 > import Test.QuickCheck
120 > digits :: Int -> [Char] -> [Char]
121 > digits 0 acc = '0' : acc
122 > digits 1 acc = '1' : acc
123 > digits n acc = digits (n `div` 2) $ digits (n `mod` 2) acc
125 > dist :: Int -> [Char] -> [Char]
128 > dist 1 acc = let r = dist 0 acc in 's' : digits (length r) r
129 > dist n acc = dist (n - 1) $ dist 1 acc
131 > takeLast n ss = reverse $ take n $ reverse ss
133 > test = takeLast 40 $ dist 20 []
136 Printing <test> gives: "1s100000s11010s10100s1111s1010s110s11s1S"
138 The reverse algorithm computes the
139 length of the string just by examining
142 > pref :: [Char] -> Int
144 > pref ('s':'1':rest) = decode 2 1 rest
145 > pref (_:rest) = 1 + pref rest
147 > decode walk acc ('0':rest) = decode (walk + 1) (acc * 2) rest
148 > decode walk acc ('1':rest) = decode (walk + 1) (acc * 2 + 1) rest
149 > decode walk acc _ = walk + acc
152 Now, as expected, printing <pref test> gives 40.
154 We can quickCheck this with following property:
156 > testcase = dist 2000 []
157 > testcaseLength = length testcase
159 > identityProp n = n > 0 && n <= testcaseLength ==> length arr == pref arr
160 > where arr = takeLast n testcase
162 As expected <quickCheck identityProp> gives:
164 *Main> quickCheck identityProp
165 OK, passed 100 tests.
167 Let's be a bit more exhaustive:
170 > deepCheck p = check (defaultConfig { configMaxTest = 500 }) p
173 And here is the result of <deepCheck identityProp>:
175 *Main> deepCheck identityProp
176 OK, passed 500 tests.
179 To maintain the invariant that the 2 LSBits of each Use** in Use
180 never change after being set up, setters of Use::Prev must re-tag the
181 new Use** on every modification. Accordingly getters must strip the
184 For layout b) instead of the User we will find a pointer (User* with LSBit set).
185 Following this pointer brings us to the User. A portable trick will ensure
186 that the first bytes of User (if interpreted as a pointer) will never have
189 ==============================================================================*/
191 /// OperandTraits - Compile-time customization of
192 /// operand-related allocators and accessors
193 /// for use of the User class
195 struct OperandTraits;
199 /// OperandTraits<User> - specialization to User
201 struct OperandTraits<User> {
202 static inline Use *op_begin(User*);
203 static inline Use *op_end(User*);
204 static inline unsigned operands(const User*);
209 static inline void *allocate(unsigned);
212 class User : public Value {
213 User(const User &); // Do not implement
214 void *operator new(size_t); // Do not implement
216 friend struct HungoffOperandTraits;
218 /// OperandList - This is a pointer to the array of Users for this operand.
219 /// For nodes of fixed arity (e.g. a binary operator) this array will live
220 /// prefixed to the derived class. For nodes of resizable variable arity
221 /// (e.g. PHINodes, SwitchInst etc.), this memory will be dynamically
222 /// allocated and should be destroyed by the classes'
226 /// NumOperands - The number of values used by this User.
228 unsigned NumOperands;
230 void *operator new(size_t s, unsigned Us) {
231 void *Storage = ::operator new(s + sizeof(Use) * Us);
232 Use *Start = static_cast<Use*>(Storage);
233 Use *End = Start + Us;
234 User *Obj = reinterpret_cast<User*>(End);
235 Obj->OperandList = Start;
236 Obj->NumOperands = Us;
237 Use::initTags(Start, End);
240 User(const Type *Ty, unsigned vty, Use *OpList, unsigned NumOps)
241 : Value(Ty, vty), OperandList(OpList), NumOperands(NumOps) {}
242 Use *allocHungoffUses(unsigned) const;
243 void dropHungoffUses(Use *U) {
244 if (OperandList == U) {
248 Use::zap(U, U->getImpliedUser(), true);
252 Use::zap(OperandList, OperandList + NumOperands);
254 void operator delete(void *Usr) {
255 User *Start = static_cast<User*>(Usr);
256 Use *Storage = static_cast<Use*>(Usr) - Start->NumOperands;
257 ::operator delete(Storage == Start->OperandList
261 template <unsigned Idx> Use &Op() {
262 return OperandTraits<User>::op_begin(this)[Idx];
264 template <unsigned Idx> const Use &Op() const {
265 return OperandTraits<User>::op_begin(const_cast<User*>(this))[Idx];
267 Value *getOperand(unsigned i) const {
268 assert(i < NumOperands && "getOperand() out of range!");
269 return OperandList[i];
271 void setOperand(unsigned i, Value *Val) {
272 assert(i < NumOperands && "setOperand() out of range!");
273 OperandList[i] = Val;
275 unsigned getNumOperands() const { return NumOperands; }
277 // ---------------------------------------------------------------------------
278 // Operand Iterator interface...
280 typedef Use* op_iterator;
281 typedef const Use* const_op_iterator;
283 inline op_iterator op_begin() { return OperandList; }
284 inline const_op_iterator op_begin() const { return OperandList; }
285 inline op_iterator op_end() { return OperandList+NumOperands; }
286 inline const_op_iterator op_end() const { return OperandList+NumOperands; }
288 // dropAllReferences() - This function is in charge of "letting go" of all
289 // objects that this User refers to. This allows one to
290 // 'delete' a whole class at a time, even though there may be circular
291 // references... first all references are dropped, and all use counts go to
292 // zero. Then everything is delete'd for real. Note that no operations are
293 // valid on an object that has "dropped all references", except operator
296 void dropAllReferences() {
297 Use *OL = OperandList;
298 for (unsigned i = 0, e = NumOperands; i != e; ++i)
302 /// replaceUsesOfWith - Replaces all references to the "From" definition with
303 /// references to the "To" definition.
305 void replaceUsesOfWith(Value *From, Value *To);
307 // Methods for support type inquiry through isa, cast, and dyn_cast:
308 static inline bool classof(const User *) { return true; }
309 static inline bool classof(const Value *V) {
310 return isa<Instruction>(V) || isa<Constant>(V);
314 inline Use *OperandTraits<User>::op_begin(User *U) {
315 return U->op_begin();
318 inline Use *OperandTraits<User>::op_end(User *U) {
322 inline unsigned OperandTraits<User>::operands(const User *U) {
323 return U->getNumOperands();
326 template<> struct simplify_type<User::op_iterator> {
327 typedef Value* SimpleType;
329 static SimpleType getSimplifiedValue(const User::op_iterator &Val) {
330 return static_cast<SimpleType>(Val->get());
334 template<> struct simplify_type<const User::op_iterator>
335 : public simplify_type<User::op_iterator> {};
337 template<> struct simplify_type<User::const_op_iterator> {
338 typedef Value* SimpleType;
340 static SimpleType getSimplifiedValue(const User::const_op_iterator &Val) {
341 return static_cast<SimpleType>(Val->get());
345 template<> struct simplify_type<const User::const_op_iterator>
346 : public simplify_type<User::const_op_iterator> {};
349 // value_use_iterator::getOperandNo - Requires the definition of the User class.
350 template<typename UserTy>
351 unsigned value_use_iterator<UserTy>::getOperandNo() const {
352 return U - U->getUser()->op_begin();
355 } // End llvm namespace