1 //===-- llvm/Value.h - Definition of the Value class ------------*- 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 declares the Value class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
16 
17 #include "llvm-c/Core.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Use.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Compiler.h"
23 
24 namespace llvm {
25 
26 class APInt;
27 class Argument;
28 class AssemblyAnnotationWriter;
29 class BasicBlock;
30 class Constant;
31 class DataLayout;
32 class Function;
33 class GlobalAlias;
34 class GlobalObject;
35 class GlobalValue;
36 class GlobalVariable;
37 class InlineAsm;
38 class Instruction;
39 class LLVMContext;
40 class Module;
41 class StringRef;
42 class Twine;
43 class Type;
44 class ValueHandleBase;
45 class ValueSymbolTable;
46 class raw_ostream;
47 
48 template<typename ValueTy> class StringMapEntry;
49 typedef StringMapEntry<Value*> ValueName;
50 
51 //===----------------------------------------------------------------------===//
52 //                                 Value Class
53 //===----------------------------------------------------------------------===//
54 
55 /// \brief LLVM Value Representation
56 ///
57 /// This is a very important LLVM class. It is the base class of all values
58 /// computed by a program that may be used as operands to other values. Value is
59 /// the super class of other important classes such as Instruction and Function.
60 /// All Values have a Type. Type is not a subclass of Value. Some values can
61 /// have a name and they belong to some Module.  Setting the name on the Value
62 /// automatically updates the module's symbol table.
63 ///
64 /// Every value has a "use list" that keeps track of which other Values are
65 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
66 /// objects that watch it and listen to RAUW and Destroy events.  See
67 /// llvm/IR/ValueHandle.h for details.
68 class Value {
69   Type *VTy;
70   Use *UseList;
71 
72   friend class ValueAsMetadata; // Allow access to NameAndIsUsedByMD.
73   friend class ValueHandleBase;
74   PointerIntPair<ValueName *, 1> NameAndIsUsedByMD;
75 
76   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
77   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
78 protected:
79   /// \brief Hold subclass data that can be dropped.
80   ///
81   /// This member is similar to SubclassData, however it is for holding
82   /// information which may be used to aid optimization, but which may be
83   /// cleared to zero without affecting conservative interpretation.
84   unsigned char SubclassOptionalData : 7;
85 
86 private:
87   /// \brief Hold arbitrary subclass data.
88   ///
89   /// This member is defined by this class, but is not used for anything.
90   /// Subclasses can use it to hold whatever state they find useful.  This
91   /// field is initialized to zero by the ctor.
92   unsigned short SubclassData;
93 
94 protected:
95   /// \brief The number of operands in the subclass.
96   ///
97   /// This member is defined by this class, but not used for anything.
98   /// Subclasses can use it to store their number of operands, if they have
99   /// any.
100   ///
101   /// This is stored here to save space in User on 64-bit hosts.  Since most
102   /// instances of Value have operands, 32-bit hosts aren't significantly
103   /// affected.
104   unsigned NumOperands;
105 
106 private:
107   template <typename UseT> // UseT == 'Use' or 'const Use'
108   class use_iterator_impl
109       : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
110     typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
111 
112     UseT *U;
use_iterator_impl(UseT * u)113     explicit use_iterator_impl(UseT *u) : U(u) {}
114     friend class Value;
115 
116   public:
117     typedef typename super::reference reference;
118     typedef typename super::pointer pointer;
119 
use_iterator_impl()120     use_iterator_impl() : U() {}
121 
122     bool operator==(const use_iterator_impl &x) const { return U == x.U; }
123     bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
124 
125     use_iterator_impl &operator++() { // Preincrement
126       assert(U && "Cannot increment end iterator!");
127       U = U->getNext();
128       return *this;
129     }
130     use_iterator_impl operator++(int) { // Postincrement
131       auto tmp = *this;
132       ++*this;
133       return tmp;
134     }
135 
136     UseT &operator*() const {
137       assert(U && "Cannot dereference end iterator!");
138       return *U;
139     }
140 
141     UseT *operator->() const { return &operator*(); }
142 
143     operator use_iterator_impl<const UseT>() const {
144       return use_iterator_impl<const UseT>(U);
145     }
146   };
147 
148   template <typename UserTy> // UserTy == 'User' or 'const User'
149   class user_iterator_impl
150       : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
151     typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
152 
153     use_iterator_impl<Use> UI;
user_iterator_impl(Use * U)154     explicit user_iterator_impl(Use *U) : UI(U) {}
155     friend class Value;
156 
157   public:
158     typedef typename super::reference reference;
159     typedef typename super::pointer pointer;
160 
user_iterator_impl()161     user_iterator_impl() {}
162 
163     bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
164     bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
165 
166     /// \brief Returns true if this iterator is equal to user_end() on the value.
atEnd()167     bool atEnd() const { return *this == user_iterator_impl(); }
168 
169     user_iterator_impl &operator++() { // Preincrement
170       ++UI;
171       return *this;
172     }
173     user_iterator_impl operator++(int) { // Postincrement
174       auto tmp = *this;
175       ++*this;
176       return tmp;
177     }
178 
179     // Retrieve a pointer to the current User.
180     UserTy *operator*() const {
181       return UI->getUser();
182     }
183 
184     UserTy *operator->() const { return operator*(); }
185 
186     operator user_iterator_impl<const UserTy>() const {
187       return user_iterator_impl<const UserTy>(*UI);
188     }
189 
getUse()190     Use &getUse() const { return *UI; }
191 
192     /// \brief Return the operand # of this use in its User.
193     ///
194     /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
getOperandNo()195     unsigned getOperandNo() const { return UI->getOperandNo(); }
196   };
197 
198   void operator=(const Value &) LLVM_DELETED_FUNCTION;
199   Value(const Value &) LLVM_DELETED_FUNCTION;
200 
201 protected:
202   Value(Type *Ty, unsigned scid);
203 public:
204   virtual ~Value();
205 
206   /// \brief Support for debugging, callable in GDB: V->dump()
207   void dump() const;
208 
209   /// \brief Implement operator<< on Value.
210   void print(raw_ostream &O) const;
211 
212   /// \brief Print the name of this Value out to the specified raw_ostream.
213   ///
214   /// This is useful when you just want to print 'int %reg126', not the
215   /// instruction that generated it. If you specify a Module for context, then
216   /// even constanst get pretty-printed; for example, the type of a null
217   /// pointer is printed symbolically.
218   void printAsOperand(raw_ostream &O, bool PrintType = true,
219                       const Module *M = nullptr) const;
220 
221   /// \brief All values are typed, get the type of this value.
getType()222   Type *getType() const { return VTy; }
223 
224   /// \brief All values hold a context through their type.
225   LLVMContext &getContext() const;
226 
227   // \brief All values can potentially be named.
hasName()228   bool hasName() const { return getValueName() != nullptr; }
getValueName()229   ValueName *getValueName() const { return NameAndIsUsedByMD.getPointer(); }
setValueName(ValueName * VN)230   void setValueName(ValueName *VN) { NameAndIsUsedByMD.setPointer(VN); }
231 
232 private:
233   void destroyValueName();
234 
235 public:
236   /// \brief Return a constant reference to the value's name.
237   ///
238   /// This is cheap and guaranteed to return the same reference as long as the
239   /// value is not modified.
240   StringRef getName() const;
241 
242   /// \brief Change the name of the value.
243   ///
244   /// Choose a new unique name if the provided name is taken.
245   ///
246   /// \param Name The new name; or "" if the value's name should be removed.
247   void setName(const Twine &Name);
248 
249 
250   /// \brief Transfer the name from V to this value.
251   ///
252   /// After taking V's name, sets V's name to empty.
253   ///
254   /// \note It is an error to call V->takeName(V).
255   void takeName(Value *V);
256 
257   /// \brief Change all uses of this to point to a new Value.
258   ///
259   /// Go through the uses list for this definition and make each use point to
260   /// "V" instead of "this".  After this completes, 'this's use list is
261   /// guaranteed to be empty.
262   void replaceAllUsesWith(Value *V);
263 
264   /// replaceUsesOutsideBlock - Go through the uses list for this definition and
265   /// make each use point to "V" instead of "this" when the use is outside the
266   /// block. 'This's use list is expected to have at least one element.
267   /// Unlike replaceAllUsesWith this function does not support basic block
268   /// values or constant users.
269   void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
270 
271   //----------------------------------------------------------------------
272   // Methods for handling the chain of uses of this Value.
273   //
use_empty()274   bool               use_empty() const { return UseList == nullptr; }
275 
276   typedef use_iterator_impl<Use>       use_iterator;
277   typedef use_iterator_impl<const Use> const_use_iterator;
use_begin()278   use_iterator       use_begin()       { return use_iterator(UseList); }
use_begin()279   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
use_end()280   use_iterator       use_end()         { return use_iterator();   }
use_end()281   const_use_iterator use_end()   const { return const_use_iterator();   }
uses()282   iterator_range<use_iterator> uses() {
283     return iterator_range<use_iterator>(use_begin(), use_end());
284   }
uses()285   iterator_range<const_use_iterator> uses() const {
286     return iterator_range<const_use_iterator>(use_begin(), use_end());
287   }
288 
user_empty()289   bool               user_empty() const { return UseList == nullptr; }
290 
291   typedef user_iterator_impl<User>       user_iterator;
292   typedef user_iterator_impl<const User> const_user_iterator;
user_begin()293   user_iterator       user_begin()       { return user_iterator(UseList); }
user_begin()294   const_user_iterator user_begin() const { return const_user_iterator(UseList); }
user_end()295   user_iterator       user_end()         { return user_iterator();   }
user_end()296   const_user_iterator user_end()   const { return const_user_iterator();   }
user_back()297   User               *user_back()        { return *user_begin(); }
user_back()298   const User         *user_back()  const { return *user_begin(); }
users()299   iterator_range<user_iterator> users() {
300     return iterator_range<user_iterator>(user_begin(), user_end());
301   }
users()302   iterator_range<const_user_iterator> users() const {
303     return iterator_range<const_user_iterator>(user_begin(), user_end());
304   }
305 
306   /// \brief Return true if there is exactly one user of this value.
307   ///
308   /// This is specialized because it is a common request and does not require
309   /// traversing the whole use list.
hasOneUse()310   bool hasOneUse() const {
311     const_use_iterator I = use_begin(), E = use_end();
312     if (I == E) return false;
313     return ++I == E;
314   }
315 
316   /// \brief Return true if this Value has exactly N users.
317   bool hasNUses(unsigned N) const;
318 
319   /// \brief Return true if this value has N users or more.
320   ///
321   /// This is logically equivalent to getNumUses() >= N.
322   bool hasNUsesOrMore(unsigned N) const;
323 
324   /// \brief Check if this value is used in the specified basic block.
325   bool isUsedInBasicBlock(const BasicBlock *BB) const;
326 
327   /// \brief This method computes the number of uses of this Value.
328   ///
329   /// This is a linear time operation.  Use hasOneUse, hasNUses, or
330   /// hasNUsesOrMore to check for specific values.
331   unsigned getNumUses() const;
332 
333   /// \brief This method should only be used by the Use class.
addUse(Use & U)334   void addUse(Use &U) { U.addToList(&UseList); }
335 
336   /// \brief Concrete subclass of this.
337   ///
338   /// An enumeration for keeping track of the concrete subclass of Value that
339   /// is actually instantiated. Values of this enumeration are kept in the
340   /// Value classes SubclassID field. They are used for concrete type
341   /// identification.
342   enum ValueTy {
343     ArgumentVal,              // This is an instance of Argument
344     BasicBlockVal,            // This is an instance of BasicBlock
345     FunctionVal,              // This is an instance of Function
346     GlobalAliasVal,           // This is an instance of GlobalAlias
347     GlobalVariableVal,        // This is an instance of GlobalVariable
348     UndefValueVal,            // This is an instance of UndefValue
349     BlockAddressVal,          // This is an instance of BlockAddress
350     ConstantExprVal,          // This is an instance of ConstantExpr
351     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
352     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
353     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
354     ConstantIntVal,           // This is an instance of ConstantInt
355     ConstantFPVal,            // This is an instance of ConstantFP
356     ConstantArrayVal,         // This is an instance of ConstantArray
357     ConstantStructVal,        // This is an instance of ConstantStruct
358     ConstantVectorVal,        // This is an instance of ConstantVector
359     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
360     MetadataAsValueVal,       // This is an instance of MetadataAsValue
361     InlineAsmVal,             // This is an instance of InlineAsm
362     InstructionVal,           // This is an instance of Instruction
363     // Enum values starting at InstructionVal are used for Instructions;
364     // don't add new values here!
365 
366     // Markers:
367     ConstantFirstVal = FunctionVal,
368     ConstantLastVal  = ConstantPointerNullVal
369   };
370 
371   /// \brief Return an ID for the concrete type of this object.
372   ///
373   /// This is used to implement the classof checks.  This should not be used
374   /// for any other purpose, as the values may change as LLVM evolves.  Also,
375   /// note that for instructions, the Instruction's opcode is added to
376   /// InstructionVal. So this means three things:
377   /// # there is no value with code InstructionVal (no opcode==0).
378   /// # there are more possible values for the value type than in ValueTy enum.
379   /// # the InstructionVal enumerator must be the highest valued enumerator in
380   ///   the ValueTy enum.
getValueID()381   unsigned getValueID() const {
382     return SubclassID;
383   }
384 
385   /// \brief Return the raw optional flags value contained in this value.
386   ///
387   /// This should only be used when testing two Values for equivalence.
getRawSubclassOptionalData()388   unsigned getRawSubclassOptionalData() const {
389     return SubclassOptionalData;
390   }
391 
392   /// \brief Clear the optional flags contained in this value.
clearSubclassOptionalData()393   void clearSubclassOptionalData() {
394     SubclassOptionalData = 0;
395   }
396 
397   /// \brief Check the optional flags for equality.
hasSameSubclassOptionalData(const Value * V)398   bool hasSameSubclassOptionalData(const Value *V) const {
399     return SubclassOptionalData == V->SubclassOptionalData;
400   }
401 
402   /// \brief Clear any optional flags not set in the given Value.
intersectOptionalDataWith(const Value * V)403   void intersectOptionalDataWith(const Value *V) {
404     SubclassOptionalData &= V->SubclassOptionalData;
405   }
406 
407   /// \brief Return true if there is a value handle associated with this value.
hasValueHandle()408   bool hasValueHandle() const { return HasValueHandle; }
409 
410   /// \brief Return true if there is metadata referencing this value.
isUsedByMetadata()411   bool isUsedByMetadata() const { return NameAndIsUsedByMD.getInt(); }
412 
413   /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
414   ///
415   /// Returns the original uncasted value.  If this is called on a non-pointer
416   /// value, it returns 'this'.
417   Value *stripPointerCasts();
stripPointerCasts()418   const Value *stripPointerCasts() const {
419     return const_cast<Value*>(this)->stripPointerCasts();
420   }
421 
422   /// \brief Strip off pointer casts and all-zero GEPs.
423   ///
424   /// Returns the original uncasted value.  If this is called on a non-pointer
425   /// value, it returns 'this'.
426   Value *stripPointerCastsNoFollowAliases();
stripPointerCastsNoFollowAliases()427   const Value *stripPointerCastsNoFollowAliases() const {
428     return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
429   }
430 
431   /// \brief Strip off pointer casts and all-constant inbounds GEPs.
432   ///
433   /// Returns the original pointer value.  If this is called on a non-pointer
434   /// value, it returns 'this'.
435   Value *stripInBoundsConstantOffsets();
stripInBoundsConstantOffsets()436   const Value *stripInBoundsConstantOffsets() const {
437     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
438   }
439 
440   /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
441   ///
442   /// Stores the resulting constant offset stripped into the APInt provided.
443   /// The provided APInt will be extended or truncated as needed to be the
444   /// correct bitwidth for an offset of this pointer type.
445   ///
446   /// If this is called on a non-pointer value, it returns 'this'.
447   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
448                                                    APInt &Offset);
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)449   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
450                                                          APInt &Offset) const {
451     return const_cast<Value *>(this)
452         ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
453   }
454 
455   /// \brief Strip off pointer casts and inbounds GEPs.
456   ///
457   /// Returns the original pointer value.  If this is called on a non-pointer
458   /// value, it returns 'this'.
459   Value *stripInBoundsOffsets();
stripInBoundsOffsets()460   const Value *stripInBoundsOffsets() const {
461     return const_cast<Value*>(this)->stripInBoundsOffsets();
462   }
463 
464   /// \brief Check if this is always a dereferenceable pointer.
465   ///
466   /// Test if this value is always a pointer to allocated and suitably aligned
467   /// memory for a simple load or store.
468   bool isDereferenceablePointer(const DataLayout *DL = nullptr) const;
469 
470   /// \brief Translate PHI node to its predecessor from the given basic block.
471   ///
472   /// If this value is a PHI node with CurBB as its parent, return the value in
473   /// the PHI node corresponding to PredBB.  If not, return ourself.  This is
474   /// useful if you want to know the value something has in a predecessor
475   /// block.
476   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
477 
DoPHITranslation(const BasicBlock * CurBB,const BasicBlock * PredBB)478   const Value *DoPHITranslation(const BasicBlock *CurBB,
479                                 const BasicBlock *PredBB) const{
480     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
481   }
482 
483   /// \brief The maximum alignment for instructions.
484   ///
485   /// This is the greatest alignment value supported by load, store, and alloca
486   /// instructions, and global values.
487   static const unsigned MaximumAlignment = 1u << 29;
488 
489   /// \brief Mutate the type of this Value to be of the specified type.
490   ///
491   /// Note that this is an extremely dangerous operation which can create
492   /// completely invalid IR very easily.  It is strongly recommended that you
493   /// recreate IR objects with the right types instead of mutating them in
494   /// place.
mutateType(Type * Ty)495   void mutateType(Type *Ty) {
496     VTy = Ty;
497   }
498 
499   /// \brief Sort the use-list.
500   ///
501   /// Sorts the Value's use-list by Cmp using a stable mergesort.  Cmp is
502   /// expected to compare two \a Use references.
503   template <class Compare> void sortUseList(Compare Cmp);
504 
505   /// \brief Reverse the use-list.
506   void reverseUseList();
507 
508 private:
509   /// \brief Merge two lists together.
510   ///
511   /// Merges \c L and \c R using \c Cmp.  To enable stable sorts, always pushes
512   /// "equal" items from L before items from R.
513   ///
514   /// \return the first element in the list.
515   ///
516   /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
517   template <class Compare>
mergeUseLists(Use * L,Use * R,Compare Cmp)518   static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
519     Use *Merged;
520     mergeUseListsImpl(L, R, &Merged, Cmp);
521     return Merged;
522   }
523 
524   /// \brief Tail-recursive helper for \a mergeUseLists().
525   ///
526   /// \param[out] Next the first element in the list.
527   template <class Compare>
528   static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
529 
530 protected:
getSubclassDataFromValue()531   unsigned short getSubclassDataFromValue() const { return SubclassData; }
setValueSubclassData(unsigned short D)532   void setValueSubclassData(unsigned short D) { SubclassData = D; }
533 };
534 
535 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
536   V.print(OS);
537   return OS;
538 }
539 
set(Value * V)540 void Use::set(Value *V) {
541   if (Val) removeFromList();
542   Val = V;
543   if (V) V->addUse(*this);
544 }
545 
sortUseList(Compare Cmp)546 template <class Compare> void Value::sortUseList(Compare Cmp) {
547   if (!UseList || !UseList->Next)
548     // No need to sort 0 or 1 uses.
549     return;
550 
551   // Note: this function completely ignores Prev pointers until the end when
552   // they're fixed en masse.
553 
554   // Create a binomial vector of sorted lists, visiting uses one at a time and
555   // merging lists as necessary.
556   const unsigned MaxSlots = 32;
557   Use *Slots[MaxSlots];
558 
559   // Collect the first use, turning it into a single-item list.
560   Use *Next = UseList->Next;
561   UseList->Next = nullptr;
562   unsigned NumSlots = 1;
563   Slots[0] = UseList;
564 
565   // Collect all but the last use.
566   while (Next->Next) {
567     Use *Current = Next;
568     Next = Current->Next;
569 
570     // Turn Current into a single-item list.
571     Current->Next = nullptr;
572 
573     // Save Current in the first available slot, merging on collisions.
574     unsigned I;
575     for (I = 0; I < NumSlots; ++I) {
576       if (!Slots[I])
577         break;
578 
579       // Merge two lists, doubling the size of Current and emptying slot I.
580       //
581       // Since the uses in Slots[I] originally preceded those in Current, send
582       // Slots[I] in as the left parameter to maintain a stable sort.
583       Current = mergeUseLists(Slots[I], Current, Cmp);
584       Slots[I] = nullptr;
585     }
586     // Check if this is a new slot.
587     if (I == NumSlots) {
588       ++NumSlots;
589       assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
590     }
591 
592     // Found an open slot.
593     Slots[I] = Current;
594   }
595 
596   // Merge all the lists together.
597   assert(Next && "Expected one more Use");
598   assert(!Next->Next && "Expected only one Use");
599   UseList = Next;
600   for (unsigned I = 0; I < NumSlots; ++I)
601     if (Slots[I])
602       // Since the uses in Slots[I] originally preceded those in UseList, send
603       // Slots[I] in as the left parameter to maintain a stable sort.
604       UseList = mergeUseLists(Slots[I], UseList, Cmp);
605 
606   // Fix the Prev pointers.
607   for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
608     I->setPrev(Prev);
609     Prev = &I->Next;
610   }
611 }
612 
613 template <class Compare>
mergeUseListsImpl(Use * L,Use * R,Use ** Next,Compare Cmp)614 void Value::mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp) {
615   if (!L) {
616     *Next = R;
617     return;
618   }
619   if (!R) {
620     *Next = L;
621     return;
622   }
623   if (Cmp(*R, *L)) {
624     *Next = R;
625     mergeUseListsImpl(L, R->Next, &R->Next, Cmp);
626     return;
627   }
628   *Next = L;
629   mergeUseListsImpl(L->Next, R, &L->Next, Cmp);
630 }
631 
632 // isa - Provide some specializations of isa so that we don't have to include
633 // the subtype header files to test to see if the value is a subclass...
634 //
635 template <> struct isa_impl<Constant, Value> {
636   static inline bool doit(const Value &Val) {
637     return Val.getValueID() >= Value::ConstantFirstVal &&
638       Val.getValueID() <= Value::ConstantLastVal;
639   }
640 };
641 
642 template <> struct isa_impl<Argument, Value> {
643   static inline bool doit (const Value &Val) {
644     return Val.getValueID() == Value::ArgumentVal;
645   }
646 };
647 
648 template <> struct isa_impl<InlineAsm, Value> {
649   static inline bool doit(const Value &Val) {
650     return Val.getValueID() == Value::InlineAsmVal;
651   }
652 };
653 
654 template <> struct isa_impl<Instruction, Value> {
655   static inline bool doit(const Value &Val) {
656     return Val.getValueID() >= Value::InstructionVal;
657   }
658 };
659 
660 template <> struct isa_impl<BasicBlock, Value> {
661   static inline bool doit(const Value &Val) {
662     return Val.getValueID() == Value::BasicBlockVal;
663   }
664 };
665 
666 template <> struct isa_impl<Function, Value> {
667   static inline bool doit(const Value &Val) {
668     return Val.getValueID() == Value::FunctionVal;
669   }
670 };
671 
672 template <> struct isa_impl<GlobalVariable, Value> {
673   static inline bool doit(const Value &Val) {
674     return Val.getValueID() == Value::GlobalVariableVal;
675   }
676 };
677 
678 template <> struct isa_impl<GlobalAlias, Value> {
679   static inline bool doit(const Value &Val) {
680     return Val.getValueID() == Value::GlobalAliasVal;
681   }
682 };
683 
684 template <> struct isa_impl<GlobalValue, Value> {
685   static inline bool doit(const Value &Val) {
686     return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
687   }
688 };
689 
690 template <> struct isa_impl<GlobalObject, Value> {
691   static inline bool doit(const Value &Val) {
692     return isa<GlobalVariable>(Val) || isa<Function>(Val);
693   }
694 };
695 
696 // Value* is only 4-byte aligned.
697 template<>
698 class PointerLikeTypeTraits<Value*> {
699   typedef Value* PT;
700 public:
701   static inline void *getAsVoidPointer(PT P) { return P; }
702   static inline PT getFromVoidPointer(void *P) {
703     return static_cast<PT>(P);
704   }
705   enum { NumLowBitsAvailable = 2 };
706 };
707 
708 // Create wrappers for C Binding types (see CBindingWrapping.h).
709 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
710 
711 /* Specialized opaque value conversions.
712  */
713 inline Value **unwrap(LLVMValueRef *Vals) {
714   return reinterpret_cast<Value**>(Vals);
715 }
716 
717 template<typename T>
718 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
719 #ifdef DEBUG
720   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
721     cast<T>(*I);
722 #endif
723   (void)Length;
724   return reinterpret_cast<T**>(Vals);
725 }
726 
727 inline LLVMValueRef *wrap(const Value **Vals) {
728   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
729 }
730 
731 } // End llvm namespace
732 
733 #endif
734