3dc0ec3de00c9167de47aa4a95c41b6718868c2a
[oota-llvm.git] / include / llvm / Constants.h
1 //===-- llvm/Constants.h - Constant class subclass definitions --*- 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 /// @file
11 /// This file contains the declarations for the subclasses of Constant, 
12 /// which represent the different flavors of constant values that live in LLVM.
13 /// Note that Constants are immutable (once created they never change) and are 
14 /// fully shared by structural equivalence.  This means that two structurally
15 /// equivalent constants will always have the same address.  Constant's are
16 /// created on demand as needed and never deleted: thus clients don't have to
17 /// worry about the lifetime of the objects.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_CONSTANTS_H
22 #define LLVM_CONSTANTS_H
23
24 #include "llvm/Constant.h"
25 #include "llvm/OperandTraits.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/ArrayRef.h"
29
30 namespace llvm {
31
32 class ArrayType;
33 class IntegerType;
34 class StructType;
35 class PointerType;
36 class VectorType;
37 class SequentialType;
38
39 template<class ConstantClass, class TypeClass, class ValType>
40 struct ConstantCreator;
41 template<class ConstantClass, class TypeClass>
42 struct ConvertConstantType;
43
44 //===----------------------------------------------------------------------===//
45 /// This is the shared class of boolean and integer constants. This class 
46 /// represents both boolean and integral constants.
47 /// @brief Class for constant integers.
48 class ConstantInt : public Constant {
49   virtual void anchor();
50   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
51   ConstantInt(const ConstantInt &);      // DO NOT IMPLEMENT
52   ConstantInt(IntegerType *Ty, const APInt& V);
53   APInt Val;
54 protected:
55   // allocate space for exactly zero operands
56   void *operator new(size_t s) {
57     return User::operator new(s, 0);
58   }
59 public:
60   static ConstantInt *getTrue(LLVMContext &Context);
61   static ConstantInt *getFalse(LLVMContext &Context);
62   static Constant *getTrue(Type *Ty);
63   static Constant *getFalse(Type *Ty);
64   
65   /// If Ty is a vector type, return a Constant with a splat of the given
66   /// value. Otherwise return a ConstantInt for the given value.
67   static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);
68                               
69   /// Return a ConstantInt with the specified integer value for the specified
70   /// type. If the type is wider than 64 bits, the value will be zero-extended
71   /// to fit the type, unless isSigned is true, in which case the value will
72   /// be interpreted as a 64-bit signed integer and sign-extended to fit
73   /// the type.
74   /// @brief Get a ConstantInt for a specific value.
75   static ConstantInt *get(IntegerType *Ty, uint64_t V,
76                           bool isSigned = false);
77
78   /// Return a ConstantInt with the specified value for the specified type. The
79   /// value V will be canonicalized to a an unsigned APInt. Accessing it with
80   /// either getSExtValue() or getZExtValue() will yield a correctly sized and
81   /// signed value for the type Ty.
82   /// @brief Get a ConstantInt for a specific signed value.
83   static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
84   static Constant *getSigned(Type *Ty, int64_t V);
85   
86   /// Return a ConstantInt with the specified value and an implied Type. The
87   /// type is the integer type that corresponds to the bit width of the value.
88   static ConstantInt *get(LLVMContext &Context, const APInt &V);
89
90   /// Return a ConstantInt constructed from the string strStart with the given
91   /// radix. 
92   static ConstantInt *get(IntegerType *Ty, StringRef Str,
93                           uint8_t radix);
94   
95   /// If Ty is a vector type, return a Constant with a splat of the given
96   /// value. Otherwise return a ConstantInt for the given value.
97   static Constant *get(Type* Ty, const APInt& V);
98   
99   /// Return the constant as an APInt value reference. This allows clients to
100   /// obtain a copy of the value, with all its precision in tact.
101   /// @brief Return the constant's value.
102   inline const APInt &getValue() const {
103     return Val;
104   }
105   
106   /// getBitWidth - Return the bitwidth of this constant.
107   unsigned getBitWidth() const { return Val.getBitWidth(); }
108
109   /// Return the constant as a 64-bit unsigned integer value after it
110   /// has been zero extended as appropriate for the type of this constant. Note
111   /// that this method can assert if the value does not fit in 64 bits.
112   /// @deprecated
113   /// @brief Return the zero extended value.
114   inline uint64_t getZExtValue() const {
115     return Val.getZExtValue();
116   }
117
118   /// Return the constant as a 64-bit integer value after it has been sign
119   /// extended as appropriate for the type of this constant. Note that
120   /// this method can assert if the value does not fit in 64 bits.
121   /// @deprecated
122   /// @brief Return the sign extended value.
123   inline int64_t getSExtValue() const {
124     return Val.getSExtValue();
125   }
126
127   /// A helper method that can be used to determine if the constant contained 
128   /// within is equal to a constant.  This only works for very small values, 
129   /// because this is all that can be represented with all types.
130   /// @brief Determine if this constant's value is same as an unsigned char.
131   bool equalsInt(uint64_t V) const {
132     return Val == V;
133   }
134
135   /// getType - Specialize the getType() method to always return an IntegerType,
136   /// which reduces the amount of casting needed in parts of the compiler.
137   ///
138   inline IntegerType *getType() const {
139     return reinterpret_cast<IntegerType*>(Value::getType());
140   }
141
142   /// This static method returns true if the type Ty is big enough to 
143   /// represent the value V. This can be used to avoid having the get method 
144   /// assert when V is larger than Ty can represent. Note that there are two
145   /// versions of this method, one for unsigned and one for signed integers.
146   /// Although ConstantInt canonicalizes everything to an unsigned integer, 
147   /// the signed version avoids callers having to convert a signed quantity
148   /// to the appropriate unsigned type before calling the method.
149   /// @returns true if V is a valid value for type Ty
150   /// @brief Determine if the value is in range for the given type.
151   static bool isValueValidForType(Type *Ty, uint64_t V);
152   static bool isValueValidForType(Type *Ty, int64_t V);
153
154   bool isNegative() const { return Val.isNegative(); }
155
156   /// This is just a convenience method to make client code smaller for a
157   /// common code. It also correctly performs the comparison without the
158   /// potential for an assertion from getZExtValue().
159   bool isZero() const {
160     return Val == 0;
161   }
162
163   /// This is just a convenience method to make client code smaller for a 
164   /// common case. It also correctly performs the comparison without the
165   /// potential for an assertion from getZExtValue().
166   /// @brief Determine if the value is one.
167   bool isOne() const {
168     return Val == 1;
169   }
170
171   /// This function will return true iff every bit in this constant is set
172   /// to true.
173   /// @returns true iff this constant's bits are all set to true.
174   /// @brief Determine if the value is all ones.
175   bool isMinusOne() const { 
176     return Val.isAllOnesValue();
177   }
178
179   /// This function will return true iff this constant represents the largest
180   /// value that may be represented by the constant's type.
181   /// @returns true iff this is the largest value that may be represented 
182   /// by this type.
183   /// @brief Determine if the value is maximal.
184   bool isMaxValue(bool isSigned) const {
185     if (isSigned) 
186       return Val.isMaxSignedValue();
187     else
188       return Val.isMaxValue();
189   }
190
191   /// This function will return true iff this constant represents the smallest
192   /// value that may be represented by this constant's type.
193   /// @returns true if this is the smallest value that may be represented by 
194   /// this type.
195   /// @brief Determine if the value is minimal.
196   bool isMinValue(bool isSigned) const {
197     if (isSigned) 
198       return Val.isMinSignedValue();
199     else
200       return Val.isMinValue();
201   }
202
203   /// This function will return true iff this constant represents a value with
204   /// active bits bigger than 64 bits or a value greater than the given uint64_t
205   /// value.
206   /// @returns true iff this constant is greater or equal to the given number.
207   /// @brief Determine if the value is greater or equal to the given number.
208   bool uge(uint64_t Num) const {
209     return Val.getActiveBits() > 64 || Val.getZExtValue() >= Num;
210   }
211
212   /// getLimitedValue - If the value is smaller than the specified limit,
213   /// return it, otherwise return the limit value.  This causes the value
214   /// to saturate to the limit.
215   /// @returns the min of the value of the constant and the specified value
216   /// @brief Get the constant's value with a saturation limit
217   uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
218     return Val.getLimitedValue(Limit);
219   }
220
221   /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
222   static inline bool classof(const ConstantInt *) { return true; }
223   static bool classof(const Value *V) {
224     return V->getValueID() == ConstantIntVal;
225   }
226 };
227
228
229 //===----------------------------------------------------------------------===//
230 /// ConstantFP - Floating Point Values [float, double]
231 ///
232 class ConstantFP : public Constant {
233   APFloat Val;
234   virtual void anchor();
235   void *operator new(size_t, unsigned);// DO NOT IMPLEMENT
236   ConstantFP(const ConstantFP &);      // DO NOT IMPLEMENT
237   friend class LLVMContextImpl;
238 protected:
239   ConstantFP(Type *Ty, const APFloat& V);
240 protected:
241   // allocate space for exactly zero operands
242   void *operator new(size_t s) {
243     return User::operator new(s, 0);
244   }
245 public:
246   /// Floating point negation must be implemented with f(x) = -0.0 - x. This
247   /// method returns the negative zero constant for floating point or vector
248   /// floating point types; for all other types, it returns the null value.
249   static Constant *getZeroValueForNegation(Type *Ty);
250   
251   /// get() - This returns a ConstantFP, or a vector containing a splat of a
252   /// ConstantFP, for the specified value in the specified type.  This should
253   /// only be used for simple constant values like 2.0/1.0 etc, that are
254   /// known-valid both as host double and as the target format.
255   static Constant *get(Type* Ty, double V);
256   static Constant *get(Type* Ty, StringRef Str);
257   static ConstantFP *get(LLVMContext &Context, const APFloat &V);
258   static ConstantFP *getNegativeZero(Type* Ty);
259   static ConstantFP *getInfinity(Type *Ty, bool Negative = false);
260   
261   /// isValueValidForType - return true if Ty is big enough to represent V.
262   static bool isValueValidForType(Type *Ty, const APFloat &V);
263   inline const APFloat &getValueAPF() const { return Val; }
264
265   /// isZero - Return true if the value is positive or negative zero.
266   bool isZero() const { return Val.isZero(); }
267
268   /// isNegative - Return true if the sign bit is set.
269   bool isNegative() const { return Val.isNegative(); }
270
271   /// isNaN - Return true if the value is a NaN.
272   bool isNaN() const { return Val.isNaN(); }
273
274   /// isExactlyValue - We don't rely on operator== working on double values, as
275   /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
276   /// As such, this method can be used to do an exact bit-for-bit comparison of
277   /// two floating point values.  The version with a double operand is retained
278   /// because it's so convenient to write isExactlyValue(2.0), but please use
279   /// it only for simple constants.
280   bool isExactlyValue(const APFloat &V) const;
281
282   bool isExactlyValue(double V) const {
283     bool ignored;
284     // convert is not supported on this type
285     if (&Val.getSemantics() == &APFloat::PPCDoubleDouble)
286       return false;
287     APFloat FV(V);
288     FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
289     return isExactlyValue(FV);
290   }
291   /// Methods for support type inquiry through isa, cast, and dyn_cast:
292   static inline bool classof(const ConstantFP *) { return true; }
293   static bool classof(const Value *V) {
294     return V->getValueID() == ConstantFPVal;
295   }
296 };
297
298 //===----------------------------------------------------------------------===//
299 /// ConstantAggregateZero - All zero aggregate value
300 ///
301 class ConstantAggregateZero : public Constant {
302   void *operator new(size_t, unsigned);                      // DO NOT IMPLEMENT
303   ConstantAggregateZero(const ConstantAggregateZero &);      // DO NOT IMPLEMENT
304 protected:
305   explicit ConstantAggregateZero(Type *ty)
306     : Constant(ty, ConstantAggregateZeroVal, 0, 0) {}
307 protected:
308   // allocate space for exactly zero operands
309   void *operator new(size_t s) {
310     return User::operator new(s, 0);
311   }
312 public:
313   static ConstantAggregateZero *get(Type *Ty);
314   
315   virtual void destroyConstant();
316
317   /// getSequentialElement - If this CAZ has array or vector type, return a zero
318   /// with the right element type.
319   Constant *getSequentialElement();
320
321   /// getStructElement - If this CAZ has struct type, return a zero with the
322   /// right element type for the specified element.
323   Constant *getStructElement(unsigned Elt);
324
325   /// getElementValue - Return a zero of the right value for the specified GEP
326   /// index.
327   Constant *getElementValue(Constant *C);
328
329   /// getElementValue - Return a zero of the right value for the specified GEP
330   /// index.
331   Constant *getElementValue(unsigned Idx);
332
333   /// Methods for support type inquiry through isa, cast, and dyn_cast:
334   ///
335   static bool classof(const ConstantAggregateZero *) { return true; }
336   static bool classof(const Value *V) {
337     return V->getValueID() == ConstantAggregateZeroVal;
338   }
339 };
340
341
342 //===----------------------------------------------------------------------===//
343 /// ConstantArray - Constant Array Declarations
344 ///
345 class ConstantArray : public Constant {
346   friend struct ConstantCreator<ConstantArray, ArrayType,
347                                     std::vector<Constant*> >;
348   ConstantArray(const ConstantArray &);      // DO NOT IMPLEMENT
349 protected:
350   ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
351 public:
352   // ConstantArray accessors
353   static Constant *get(ArrayType *T, ArrayRef<Constant*> V);
354                              
355   /// This method constructs a ConstantArray and initializes it with a text
356   /// string. The default behavior (AddNull==true) causes a null terminator to
357   /// be placed at the end of the array. This effectively increases the length
358   /// of the array by one (you've been warned).  However, in some situations 
359   /// this is not desired so if AddNull==false then the string is copied without
360   /// null termination.
361   static Constant *get(LLVMContext &Context, StringRef Initializer,
362                        bool AddNull = true);
363   
364   /// Transparently provide more efficient getOperand methods.
365   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
366
367   /// getType - Specialize the getType() method to always return an ArrayType,
368   /// which reduces the amount of casting needed in parts of the compiler.
369   ///
370   inline ArrayType *getType() const {
371     return reinterpret_cast<ArrayType*>(Value::getType());
372   }
373
374   // FIXME: String methods will eventually be removed.
375   
376   
377   /// isString - This method returns true if the array is an array of i8 and
378   /// the elements of the array are all ConstantInt's.
379   bool isString() const;
380
381   /// isCString - This method returns true if the array is a string (see
382   /// @verbatim
383   /// isString) and it ends in a null byte \0 and does not contains any other
384   /// @endverbatim
385   /// null bytes except its terminator.
386   bool isCString() const;
387
388   /// getAsString - If this array is isString(), then this method converts the
389   /// array to an std::string and returns it.  Otherwise, it asserts out.
390   ///
391   std::string getAsString() const;
392
393   /// getAsCString - If this array is isCString(), then this method converts the
394   /// array (without the trailing null byte) to an std::string and returns it.
395   /// Otherwise, it asserts out.
396   ///
397   std::string getAsCString() const;
398
399   virtual void destroyConstant();
400   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
401
402   /// Methods for support type inquiry through isa, cast, and dyn_cast:
403   static inline bool classof(const ConstantArray *) { return true; }
404   static bool classof(const Value *V) {
405     return V->getValueID() == ConstantArrayVal;
406   }
407 };
408
409 template <>
410 struct OperandTraits<ConstantArray> :
411   public VariadicOperandTraits<ConstantArray> {
412 };
413
414 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantArray, Constant)
415
416 //===----------------------------------------------------------------------===//
417 // ConstantStruct - Constant Struct Declarations
418 //
419 class ConstantStruct : public Constant {
420   friend struct ConstantCreator<ConstantStruct, StructType,
421                                     std::vector<Constant*> >;
422   ConstantStruct(const ConstantStruct &);      // DO NOT IMPLEMENT
423 protected:
424   ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
425 public:
426   // ConstantStruct accessors
427   static Constant *get(StructType *T, ArrayRef<Constant*> V);
428   static Constant *get(StructType *T, ...) END_WITH_NULL;
429
430   /// getAnon - Return an anonymous struct that has the specified
431   /// elements.  If the struct is possibly empty, then you must specify a
432   /// context.
433   static Constant *getAnon(ArrayRef<Constant*> V, bool Packed = false) {
434     return get(getTypeForElements(V, Packed), V);
435   }
436   static Constant *getAnon(LLVMContext &Ctx, 
437                            ArrayRef<Constant*> V, bool Packed = false) {
438     return get(getTypeForElements(Ctx, V, Packed), V);
439   }
440
441   /// getTypeForElements - Return an anonymous struct type to use for a constant
442   /// with the specified set of elements.  The list must not be empty.
443   static StructType *getTypeForElements(ArrayRef<Constant*> V,
444                                         bool Packed = false);
445   /// getTypeForElements - This version of the method allows an empty list.
446   static StructType *getTypeForElements(LLVMContext &Ctx,
447                                         ArrayRef<Constant*> V,
448                                         bool Packed = false);
449   
450   /// Transparently provide more efficient getOperand methods.
451   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
452
453   /// getType() specialization - Reduce amount of casting...
454   ///
455   inline StructType *getType() const {
456     return reinterpret_cast<StructType*>(Value::getType());
457   }
458
459   virtual void destroyConstant();
460   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
461
462   /// Methods for support type inquiry through isa, cast, and dyn_cast:
463   static inline bool classof(const ConstantStruct *) { return true; }
464   static bool classof(const Value *V) {
465     return V->getValueID() == ConstantStructVal;
466   }
467 };
468
469 template <>
470 struct OperandTraits<ConstantStruct> :
471   public VariadicOperandTraits<ConstantStruct> {
472 };
473
474 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantStruct, Constant)
475
476
477 //===----------------------------------------------------------------------===//
478 /// ConstantVector - Constant Vector Declarations
479 ///
480 class ConstantVector : public Constant {
481   friend struct ConstantCreator<ConstantVector, VectorType,
482                                     std::vector<Constant*> >;
483   ConstantVector(const ConstantVector &);      // DO NOT IMPLEMENT
484 protected:
485   ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
486 public:
487   // ConstantVector accessors
488   static Constant *get(ArrayRef<Constant*> V);
489   
490   /// Transparently provide more efficient getOperand methods.
491   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
492
493   /// getType - Specialize the getType() method to always return a VectorType,
494   /// which reduces the amount of casting needed in parts of the compiler.
495   ///
496   inline VectorType *getType() const {
497     return reinterpret_cast<VectorType*>(Value::getType());
498   }
499
500   /// getSplatValue - If this is a splat constant, meaning that all of the
501   /// elements have the same value, return that value. Otherwise return NULL.
502   Constant *getSplatValue() const;
503
504   virtual void destroyConstant();
505   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
506
507   /// Methods for support type inquiry through isa, cast, and dyn_cast:
508   static inline bool classof(const ConstantVector *) { return true; }
509   static bool classof(const Value *V) {
510     return V->getValueID() == ConstantVectorVal;
511   }
512 };
513
514 template <>
515 struct OperandTraits<ConstantVector> :
516   public VariadicOperandTraits<ConstantVector> {
517 };
518
519 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantVector, Constant)
520
521 //===----------------------------------------------------------------------===//
522 /// ConstantPointerNull - a constant pointer value that points to null
523 ///
524 class ConstantPointerNull : public Constant {
525   void *operator new(size_t, unsigned);                  // DO NOT IMPLEMENT
526   ConstantPointerNull(const ConstantPointerNull &);      // DO NOT IMPLEMENT
527 protected:
528   explicit ConstantPointerNull(PointerType *T)
529     : Constant(reinterpret_cast<Type*>(T),
530                Value::ConstantPointerNullVal, 0, 0) {}
531
532 protected:
533   // allocate space for exactly zero operands
534   void *operator new(size_t s) {
535     return User::operator new(s, 0);
536   }
537 public:
538   /// get() - Static factory methods - Return objects of the specified value
539   static ConstantPointerNull *get(PointerType *T);
540
541   virtual void destroyConstant();
542
543   /// getType - Specialize the getType() method to always return an PointerType,
544   /// which reduces the amount of casting needed in parts of the compiler.
545   ///
546   inline PointerType *getType() const {
547     return reinterpret_cast<PointerType*>(Value::getType());
548   }
549
550   /// Methods for support type inquiry through isa, cast, and dyn_cast:
551   static inline bool classof(const ConstantPointerNull *) { return true; }
552   static bool classof(const Value *V) {
553     return V->getValueID() == ConstantPointerNullVal;
554   }
555 };
556   
557 //===----------------------------------------------------------------------===//
558 /// ConstantDataSequential - A vector or array of data that contains no
559 /// relocations, and whose element type is a simple 1/2/4/8-byte integer or
560 /// float/double.  This is the common base class of ConstantDataArray and
561 /// ConstantDataVector.
562 ///
563 class ConstantDataSequential : public Constant {
564   friend class LLVMContextImpl;
565   /// DataElements - A pointer to the bytes underlying this constant (which is
566   /// owned by the uniquing StringMap).
567   const char *DataElements;
568   
569   /// Next - This forms a link list of ConstantDataSequential nodes that have
570   /// the same value but different type.  For example, 0,0,0,1 could be a 4
571   /// element array of i8, or a 1-element array of i32.  They'll both end up in
572   /// the same StringMap bucket, linked up.
573   ConstantDataSequential *Next;
574   void *operator new(size_t, unsigned);                      // DO NOT IMPLEMENT
575   ConstantDataSequential(const ConstantDataSequential &);    // DO NOT IMPLEMENT
576 protected:
577   explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
578     : Constant(ty, VT, 0, 0), DataElements(Data) {}
579   ~ConstantDataSequential() { delete Next; }
580   
581   static Constant *getImpl(StringRef Bytes, Type *Ty);
582
583 protected:
584   // allocate space for exactly zero operands.
585   void *operator new(size_t s) {
586     return User::operator new(s, 0);
587   }
588 public:
589   
590   /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
591   /// formed with a vector or array of the specified element type.
592   /// ConstantDataArray only works with normal float and int types that are
593   /// stored densely in memory, not with things like i42 or x86_f80.
594   static bool isElementTypeCompatible(const Type *Ty);
595   
596   /// getElementAsInteger - If this is a sequential container of integers (of
597   /// any size), return the specified element in the low bits of a uint64_t.
598   uint64_t getElementAsInteger(unsigned i) const;
599
600   /// getElementAsAPFloat - If this is a sequential container of floating point
601   /// type, return the specified element as an APFloat.
602   APFloat getElementAsAPFloat(unsigned i) const;
603
604   /// getElementAsFloat - If this is an sequential container of floats, return
605   /// the specified element as a float.
606   float getElementAsFloat(unsigned i) const;
607   
608   /// getElementAsDouble - If this is an sequential container of doubles, return
609   /// the specified element as a float.
610   double getElementAsDouble(unsigned i) const;
611   
612   /// getElementAsConstant - Return a Constant for a specified index's element.
613   /// Note that this has to compute a new constant to return, so it isn't as
614   /// efficient as getElementAsInteger/Float/Double.
615   Constant *getElementAsConstant(unsigned i) const;
616   
617   /// getType - Specialize the getType() method to always return a
618   /// SequentialType, which reduces the amount of casting needed in parts of the
619   /// compiler.
620   inline SequentialType *getType() const {
621     return reinterpret_cast<SequentialType*>(Value::getType());
622   }
623   
624   /// getElementType - Return the element type of the array/vector.
625   Type *getElementType() const;
626   
627   /// getNumElements - Return the number of elements in the array or vector.
628   unsigned getNumElements() const;
629
630   /// getElementByteSize - Return the size (in bytes) of each element in the
631   /// array/vector.  The size of the elements is known to be a multiple of one
632   /// byte.
633   uint64_t getElementByteSize() const;
634
635   
636   /// isString - This method returns true if this is an array of i8.
637   bool isString() const;
638   
639   /// isCString - This method returns true if the array "isString", ends with a
640   /// nul byte, and does not contains any other nul bytes.
641   bool isCString() const;
642   
643   /// getAsString - If this array is isString(), then this method returns the
644   /// array as a StringRef.  Otherwise, it asserts out.
645   ///
646   StringRef getAsString() const {
647     assert(isString() && "Not a string");
648     return getRawDataValues();
649   }
650   
651   /// getAsCString - If this array is isCString(), then this method returns the
652   /// array (without the trailing null byte) as a StringRef. Otherwise, it
653   /// asserts out.
654   ///
655   StringRef getAsCString() const {
656     assert(isCString() && "Isn't a C string");
657     StringRef Str = getAsString();
658     return Str.substr(0, Str.size()-1);
659   }
660   
661   /// getRawDataValues - Return the raw, underlying, bytes of this data.  Note
662   /// that this is an extremely tricky thing to work with, as it exposes the
663   /// host endianness of the data elements.
664   StringRef getRawDataValues() const;
665   
666   virtual void destroyConstant();
667   
668   /// Methods for support type inquiry through isa, cast, and dyn_cast:
669   ///
670   static bool classof(const ConstantDataSequential *) { return true; }
671   static bool classof(const Value *V) {
672     return V->getValueID() == ConstantDataArrayVal ||
673            V->getValueID() == ConstantDataVectorVal;
674   }
675 private:
676   const char *getElementPointer(unsigned Elt) const;
677 };
678
679 //===----------------------------------------------------------------------===//
680 /// ConstantDataArray - An array of data that contains no relocations, and whose
681 /// element type is a simple 1/2/4/8-byte integer or float/double.
682 ///
683 class ConstantDataArray : public ConstantDataSequential {
684   void *operator new(size_t, unsigned);            // DO NOT IMPLEMENT
685   ConstantDataArray(const ConstantDataArray &);    // DO NOT IMPLEMENT
686   virtual void anchor();
687   friend class ConstantDataSequential;
688   explicit ConstantDataArray(Type *ty, const char *Data)
689     : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
690 protected:
691   // allocate space for exactly zero operands.
692   void *operator new(size_t s) {
693     return User::operator new(s, 0);
694   }
695 public:
696   
697   /// get() constructors - Return a constant with array type with an element
698   /// count and element type matching the ArrayRef passed in.  Note that this
699   /// can return a ConstantAggregateZero object.
700   static Constant *get(ArrayRef<uint8_t> Elts, LLVMContext &Context);
701   static Constant *get(ArrayRef<uint16_t> Elts, LLVMContext &Context);
702   static Constant *get(ArrayRef<uint32_t> Elts, LLVMContext &Context);
703   static Constant *get(ArrayRef<uint64_t> Elts, LLVMContext &Context);
704   static Constant *get(ArrayRef<float> Elts, LLVMContext &Context);
705   static Constant *get(ArrayRef<double> Elts, LLVMContext &Context);
706   
707   /// getType - Specialize the getType() method to always return an ArrayType,
708   /// which reduces the amount of casting needed in parts of the compiler.
709   ///
710   inline ArrayType *getType() const {
711     return reinterpret_cast<ArrayType*>(Value::getType());
712   }
713   
714   /// Methods for support type inquiry through isa, cast, and dyn_cast:
715   ///
716   static bool classof(const ConstantDataArray *) { return true; }
717   static bool classof(const Value *V) {
718     return V->getValueID() == ConstantDataArrayVal;
719   }
720 };
721   
722 //===----------------------------------------------------------------------===//
723 /// ConstantDataVector - A vector of data that contains no relocations, and
724 /// whose element type is a simple 1/2/4/8-byte integer or float/double.
725 ///
726 class ConstantDataVector : public ConstantDataSequential {
727   void *operator new(size_t, unsigned);              // DO NOT IMPLEMENT
728   ConstantDataVector(const ConstantDataVector &);    // DO NOT IMPLEMENT
729   virtual void anchor();
730   friend class ConstantDataSequential;
731   explicit ConstantDataVector(Type *ty, const char *Data)
732   : ConstantDataSequential(ty, ConstantDataVectorVal, Data) {}
733 protected:
734   // allocate space for exactly zero operands.
735   void *operator new(size_t s) {
736     return User::operator new(s, 0);
737   }
738 public:
739   
740   /// get() constructors - Return a constant with vector type with an element
741   /// count and element type matching the ArrayRef passed in.  Note that this
742   /// can return a ConstantAggregateZero object.
743   static Constant *get(ArrayRef<uint8_t> Elts, LLVMContext &Context);
744   static Constant *get(ArrayRef<uint16_t> Elts, LLVMContext &Context);
745   static Constant *get(ArrayRef<uint32_t> Elts, LLVMContext &Context);
746   static Constant *get(ArrayRef<uint64_t> Elts, LLVMContext &Context);
747   static Constant *get(ArrayRef<float> Elts, LLVMContext &Context);
748   static Constant *get(ArrayRef<double> Elts, LLVMContext &Context);
749   
750   /// getType - Specialize the getType() method to always return a VectorType,
751   /// which reduces the amount of casting needed in parts of the compiler.
752   ///
753   inline VectorType *getType() const {
754     return reinterpret_cast<VectorType*>(Value::getType());
755   }
756   
757   /// Methods for support type inquiry through isa, cast, and dyn_cast:
758   ///
759   static bool classof(const ConstantDataVector *) { return true; }
760   static bool classof(const Value *V) {
761     return V->getValueID() == ConstantDataVectorVal;
762   }
763 };
764
765
766
767 /// BlockAddress - The address of a basic block.
768 ///
769 class BlockAddress : public Constant {
770   void *operator new(size_t, unsigned);                  // DO NOT IMPLEMENT
771   void *operator new(size_t s) { return User::operator new(s, 2); }
772   BlockAddress(Function *F, BasicBlock *BB);
773 public:
774   /// get - Return a BlockAddress for the specified function and basic block.
775   static BlockAddress *get(Function *F, BasicBlock *BB);
776   
777   /// get - Return a BlockAddress for the specified basic block.  The basic
778   /// block must be embedded into a function.
779   static BlockAddress *get(BasicBlock *BB);
780   
781   /// Transparently provide more efficient getOperand methods.
782   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
783   
784   Function *getFunction() const { return (Function*)Op<0>().get(); }
785   BasicBlock *getBasicBlock() const { return (BasicBlock*)Op<1>().get(); }
786   
787   virtual void destroyConstant();
788   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
789   
790   /// Methods for support type inquiry through isa, cast, and dyn_cast:
791   static inline bool classof(const BlockAddress *) { return true; }
792   static inline bool classof(const Value *V) {
793     return V->getValueID() == BlockAddressVal;
794   }
795 };
796
797 template <>
798 struct OperandTraits<BlockAddress> :
799   public FixedNumOperandTraits<BlockAddress, 2> {
800 };
801
802 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
803   
804
805 //===----------------------------------------------------------------------===//
806 /// ConstantExpr - a constant value that is initialized with an expression using
807 /// other constant values.
808 ///
809 /// This class uses the standard Instruction opcodes to define the various
810 /// constant expressions.  The Opcode field for the ConstantExpr class is
811 /// maintained in the Value::SubclassData field.
812 class ConstantExpr : public Constant {
813   friend struct ConstantCreator<ConstantExpr,Type,
814                             std::pair<unsigned, std::vector<Constant*> > >;
815   friend struct ConvertConstantType<ConstantExpr, Type>;
816
817 protected:
818   ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
819     : Constant(ty, ConstantExprVal, Ops, NumOps) {
820     // Operation type (an Instruction opcode) is stored as the SubclassData.
821     setValueSubclassData(Opcode);
822   }
823
824 public:
825   // Static methods to construct a ConstantExpr of different kinds.  Note that
826   // these methods may return a object that is not an instance of the
827   // ConstantExpr class, because they will attempt to fold the constant
828   // expression into something simpler if possible.
829
830   /// getAlignOf constant expr - computes the alignment of a type in a target
831   /// independent way (Note: the return type is an i64).
832   static Constant *getAlignOf(Type *Ty);
833   
834   /// getSizeOf constant expr - computes the (alloc) size of a type (in
835   /// address-units, not bits) in a target independent way (Note: the return
836   /// type is an i64).
837   ///
838   static Constant *getSizeOf(Type *Ty);
839
840   /// getOffsetOf constant expr - computes the offset of a struct field in a 
841   /// target independent way (Note: the return type is an i64).
842   ///
843   static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
844
845   /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
846   /// which supports any aggregate type, and any Constant index.
847   ///
848   static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
849   
850   static Constant *getNeg(Constant *C, bool HasNUW = false, bool HasNSW =false);
851   static Constant *getFNeg(Constant *C);
852   static Constant *getNot(Constant *C);
853   static Constant *getAdd(Constant *C1, Constant *C2,
854                           bool HasNUW = false, bool HasNSW = false);
855   static Constant *getFAdd(Constant *C1, Constant *C2);
856   static Constant *getSub(Constant *C1, Constant *C2,
857                           bool HasNUW = false, bool HasNSW = false);
858   static Constant *getFSub(Constant *C1, Constant *C2);
859   static Constant *getMul(Constant *C1, Constant *C2,
860                           bool HasNUW = false, bool HasNSW = false);
861   static Constant *getFMul(Constant *C1, Constant *C2);
862   static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
863   static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
864   static Constant *getFDiv(Constant *C1, Constant *C2);
865   static Constant *getURem(Constant *C1, Constant *C2);
866   static Constant *getSRem(Constant *C1, Constant *C2);
867   static Constant *getFRem(Constant *C1, Constant *C2);
868   static Constant *getAnd(Constant *C1, Constant *C2);
869   static Constant *getOr(Constant *C1, Constant *C2);
870   static Constant *getXor(Constant *C1, Constant *C2);
871   static Constant *getShl(Constant *C1, Constant *C2,
872                           bool HasNUW = false, bool HasNSW = false);
873   static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
874   static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
875   static Constant *getTrunc   (Constant *C, Type *Ty);
876   static Constant *getSExt    (Constant *C, Type *Ty);
877   static Constant *getZExt    (Constant *C, Type *Ty);
878   static Constant *getFPTrunc (Constant *C, Type *Ty);
879   static Constant *getFPExtend(Constant *C, Type *Ty);
880   static Constant *getUIToFP  (Constant *C, Type *Ty);
881   static Constant *getSIToFP  (Constant *C, Type *Ty);
882   static Constant *getFPToUI  (Constant *C, Type *Ty);
883   static Constant *getFPToSI  (Constant *C, Type *Ty);
884   static Constant *getPtrToInt(Constant *C, Type *Ty);
885   static Constant *getIntToPtr(Constant *C, Type *Ty);
886   static Constant *getBitCast (Constant *C, Type *Ty);
887
888   static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
889   static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
890   static Constant *getNSWAdd(Constant *C1, Constant *C2) {
891     return getAdd(C1, C2, false, true);
892   }
893   static Constant *getNUWAdd(Constant *C1, Constant *C2) {
894     return getAdd(C1, C2, true, false);
895   }
896   static Constant *getNSWSub(Constant *C1, Constant *C2) {
897     return getSub(C1, C2, false, true);
898   }
899   static Constant *getNUWSub(Constant *C1, Constant *C2) {
900     return getSub(C1, C2, true, false);
901   }
902   static Constant *getNSWMul(Constant *C1, Constant *C2) {
903     return getMul(C1, C2, false, true);
904   }
905   static Constant *getNUWMul(Constant *C1, Constant *C2) {
906     return getMul(C1, C2, true, false);
907   }
908   static Constant *getNSWShl(Constant *C1, Constant *C2) {
909     return getShl(C1, C2, false, true);
910   }
911   static Constant *getNUWShl(Constant *C1, Constant *C2) {
912     return getShl(C1, C2, true, false);
913   }
914   static Constant *getExactSDiv(Constant *C1, Constant *C2) {
915     return getSDiv(C1, C2, true);
916   }
917   static Constant *getExactUDiv(Constant *C1, Constant *C2) {
918     return getUDiv(C1, C2, true);
919   }
920   static Constant *getExactAShr(Constant *C1, Constant *C2) {
921     return getAShr(C1, C2, true);
922   }
923   static Constant *getExactLShr(Constant *C1, Constant *C2) {
924     return getLShr(C1, C2, true);
925   }
926
927   /// Transparently provide more efficient getOperand methods.
928   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
929
930   // @brief Convenience function for getting one of the casting operations
931   // using a CastOps opcode.
932   static Constant *getCast(
933     unsigned ops,  ///< The opcode for the conversion
934     Constant *C,   ///< The constant to be converted
935     Type *Ty ///< The type to which the constant is converted
936   );
937
938   // @brief Create a ZExt or BitCast cast constant expression
939   static Constant *getZExtOrBitCast(
940     Constant *C,   ///< The constant to zext or bitcast
941     Type *Ty ///< The type to zext or bitcast C to
942   );
943
944   // @brief Create a SExt or BitCast cast constant expression 
945   static Constant *getSExtOrBitCast(
946     Constant *C,   ///< The constant to sext or bitcast
947     Type *Ty ///< The type to sext or bitcast C to
948   );
949
950   // @brief Create a Trunc or BitCast cast constant expression
951   static Constant *getTruncOrBitCast(
952     Constant *C,   ///< The constant to trunc or bitcast
953     Type *Ty ///< The type to trunc or bitcast C to
954   );
955
956   /// @brief Create a BitCast or a PtrToInt cast constant expression
957   static Constant *getPointerCast(
958     Constant *C,   ///< The pointer value to be casted (operand 0)
959     Type *Ty ///< The type to which cast should be made
960   );
961
962   /// @brief Create a ZExt, Bitcast or Trunc for integer -> integer casts
963   static Constant *getIntegerCast(
964     Constant *C,    ///< The integer constant to be casted 
965     Type *Ty, ///< The integer type to cast to
966     bool isSigned   ///< Whether C should be treated as signed or not
967   );
968
969   /// @brief Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
970   static Constant *getFPCast(
971     Constant *C,    ///< The integer constant to be casted 
972     Type *Ty ///< The integer type to cast to
973   );
974
975   /// @brief Return true if this is a convert constant expression
976   bool isCast() const;
977
978   /// @brief Return true if this is a compare constant expression
979   bool isCompare() const;
980
981   /// @brief Return true if this is an insertvalue or extractvalue expression,
982   /// and the getIndices() method may be used.
983   bool hasIndices() const;
984
985   /// @brief Return true if this is a getelementptr expression and all
986   /// the index operands are compile-time known integers within the
987   /// corresponding notional static array extents. Note that this is
988   /// not equivalant to, a subset of, or a superset of the "inbounds"
989   /// property.
990   bool isGEPWithNoNotionalOverIndexing() const;
991
992   /// Select constant expr
993   ///
994   static Constant *getSelect(Constant *C, Constant *V1, Constant *V2);
995
996   /// get - Return a binary or shift operator constant expression,
997   /// folding if possible.
998   ///
999   static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1000                        unsigned Flags = 0);
1001
1002   /// @brief Return an ICmp or FCmp comparison operator constant expression.
1003   static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2);
1004
1005   /// get* - Return some common constants without having to
1006   /// specify the full Instruction::OPCODE identifier.
1007   ///
1008   static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS);
1009   static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS);
1010
1011   /// Getelementptr form.  Value* is only accepted for convenience;
1012   /// all elements must be Constant's.
1013   ///
1014   static Constant *getGetElementPtr(Constant *C,
1015                                     ArrayRef<Constant *> IdxList,
1016                                     bool InBounds = false) {
1017     return getGetElementPtr(C, makeArrayRef((Value * const *)IdxList.data(),
1018                                             IdxList.size()),
1019                             InBounds);
1020   }
1021   static Constant *getGetElementPtr(Constant *C,
1022                                     Constant *Idx,
1023                                     bool InBounds = false) {
1024     // This form of the function only exists to avoid ambiguous overload
1025     // warnings about whether to convert Idx to ArrayRef<Constant *> or
1026     // ArrayRef<Value *>.
1027     return getGetElementPtr(C, cast<Value>(Idx), InBounds);
1028   }
1029   static Constant *getGetElementPtr(Constant *C,
1030                                     ArrayRef<Value *> IdxList,
1031                                     bool InBounds = false);
1032
1033   /// Create an "inbounds" getelementptr. See the documentation for the
1034   /// "inbounds" flag in LangRef.html for details.
1035   static Constant *getInBoundsGetElementPtr(Constant *C,
1036                                             ArrayRef<Constant *> IdxList) {
1037     return getGetElementPtr(C, IdxList, true);
1038   }
1039   static Constant *getInBoundsGetElementPtr(Constant *C,
1040                                             Constant *Idx) {
1041     // This form of the function only exists to avoid ambiguous overload
1042     // warnings about whether to convert Idx to ArrayRef<Constant *> or
1043     // ArrayRef<Value *>.
1044     return getGetElementPtr(C, Idx, true);
1045   }
1046   static Constant *getInBoundsGetElementPtr(Constant *C,
1047                                             ArrayRef<Value *> IdxList) {
1048     return getGetElementPtr(C, IdxList, true);
1049   }
1050
1051   static Constant *getExtractElement(Constant *Vec, Constant *Idx);
1052   static Constant *getInsertElement(Constant *Vec, Constant *Elt,Constant *Idx);
1053   static Constant *getShuffleVector(Constant *V1, Constant *V2, Constant *Mask);
1054   static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs);
1055   static Constant *getInsertValue(Constant *Agg, Constant *Val,
1056                                   ArrayRef<unsigned> Idxs);
1057
1058   /// getOpcode - Return the opcode at the root of this constant expression
1059   unsigned getOpcode() const { return getSubclassDataFromValue(); }
1060
1061   /// getPredicate - Return the ICMP or FCMP predicate value. Assert if this is
1062   /// not an ICMP or FCMP constant expression.
1063   unsigned getPredicate() const;
1064
1065   /// getIndices - Assert that this is an insertvalue or exactvalue
1066   /// expression and return the list of indices.
1067   ArrayRef<unsigned> getIndices() const;
1068
1069   /// getOpcodeName - Return a string representation for an opcode.
1070   const char *getOpcodeName() const;
1071
1072   /// getWithOperandReplaced - Return a constant expression identical to this
1073   /// one, but with the specified operand set to the specified value.
1074   Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
1075   
1076   /// getWithOperands - This returns the current constant expression with the
1077   /// operands replaced with the specified values.  The specified array must
1078   /// have the same number of operands as our current one.
1079   Constant *getWithOperands(ArrayRef<Constant*> Ops) const {
1080     return getWithOperands(Ops, getType());
1081   }
1082
1083   /// getWithOperands - This returns the current constant expression with the
1084   /// operands replaced with the specified values and with the specified result
1085   /// type.  The specified array must have the same number of operands as our
1086   /// current one.
1087   Constant *getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const;
1088
1089   virtual void destroyConstant();
1090   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
1091
1092   /// Methods for support type inquiry through isa, cast, and dyn_cast:
1093   static inline bool classof(const ConstantExpr *) { return true; }
1094   static inline bool classof(const Value *V) {
1095     return V->getValueID() == ConstantExprVal;
1096   }
1097   
1098 private:
1099   // Shadow Value::setValueSubclassData with a private forwarding method so that
1100   // subclasses cannot accidentally use it.
1101   void setValueSubclassData(unsigned short D) {
1102     Value::setValueSubclassData(D);
1103   }
1104 };
1105
1106 template <>
1107 struct OperandTraits<ConstantExpr> :
1108   public VariadicOperandTraits<ConstantExpr, 1> {
1109 };
1110
1111 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
1112
1113 //===----------------------------------------------------------------------===//
1114 /// UndefValue - 'undef' values are things that do not have specified contents.
1115 /// These are used for a variety of purposes, including global variable
1116 /// initializers and operands to instructions.  'undef' values can occur with
1117 /// any first-class type.
1118 ///
1119 /// Undef values aren't exactly constants; if they have multiple uses, they
1120 /// can appear to have different bit patterns at each use. See
1121 /// LangRef.html#undefvalues for details.
1122 ///
1123 class UndefValue : public Constant {
1124   void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
1125   UndefValue(const UndefValue &);      // DO NOT IMPLEMENT
1126 protected:
1127   explicit UndefValue(Type *T) : Constant(T, UndefValueVal, 0, 0) {}
1128 protected:
1129   // allocate space for exactly zero operands
1130   void *operator new(size_t s) {
1131     return User::operator new(s, 0);
1132   }
1133 public:
1134   /// get() - Static factory methods - Return an 'undef' object of the specified
1135   /// type.
1136   ///
1137   static UndefValue *get(Type *T);
1138
1139   /// getSequentialElement - If this Undef has array or vector type, return a
1140   /// undef with the right element type.
1141   UndefValue *getSequentialElement();
1142   
1143   /// getStructElement - If this undef has struct type, return a undef with the
1144   /// right element type for the specified element.
1145   UndefValue *getStructElement(unsigned Elt);
1146   
1147   /// getElementValue - Return an undef of the right value for the specified GEP
1148   /// index.
1149   UndefValue *getElementValue(Constant *C);
1150
1151   /// getElementValue - Return an undef of the right value for the specified GEP
1152   /// index.
1153   UndefValue *getElementValue(unsigned Idx);
1154
1155   virtual void destroyConstant();
1156
1157   /// Methods for support type inquiry through isa, cast, and dyn_cast:
1158   static inline bool classof(const UndefValue *) { return true; }
1159   static bool classof(const Value *V) {
1160     return V->getValueID() == UndefValueVal;
1161   }
1162 };
1163
1164 } // End llvm namespace
1165
1166 #endif