add a version of ConstantFP::get that doesn't take a redundant Type* value,
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include <algorithm>
28 #include <map>
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 //                              Constant Class
33 //===----------------------------------------------------------------------===//
34
35 void Constant::destroyConstantImpl() {
36   // When a Constant is destroyed, there may be lingering
37   // references to the constant by other constants in the constant pool.  These
38   // constants are implicitly dependent on the module that is being deleted,
39   // but they don't know that.  Because we only find out when the CPV is
40   // deleted, we must now notify all of our users (that should only be
41   // Constants) that they are, in fact, invalid now and should be deleted.
42   //
43   while (!use_empty()) {
44     Value *V = use_back();
45 #ifndef NDEBUG      // Only in -g mode...
46     if (!isa<Constant>(V))
47       DOUT << "While deleting: " << *this
48            << "\n\nUse still stuck around after Def is destroyed: "
49            << *V << "\n\n";
50 #endif
51     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52     Constant *CV = cast<Constant>(V);
53     CV->destroyConstant();
54
55     // The constant should remove itself from our use list...
56     assert((use_empty() || use_back() != V) && "Constant not removed!");
57   }
58
59   // Value has no outstanding references it is safe to delete it now...
60   delete this;
61 }
62
63 /// canTrap - Return true if evaluation of this constant could trap.  This is
64 /// true for things like constant expressions that could divide by zero.
65 bool Constant::canTrap() const {
66   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67   // The only thing that could possibly trap are constant exprs.
68   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69   if (!CE) return false;
70   
71   // ConstantExpr traps if any operands can trap. 
72   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73     if (getOperand(i)->canTrap()) 
74       return true;
75
76   // Otherwise, only specific operations can trap.
77   switch (CE->getOpcode()) {
78   default:
79     return false;
80   case Instruction::UDiv:
81   case Instruction::SDiv:
82   case Instruction::FDiv:
83   case Instruction::URem:
84   case Instruction::SRem:
85   case Instruction::FRem:
86     // Div and rem can trap if the RHS is not known to be non-zero.
87     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88       return true;
89     return false;
90   }
91 }
92
93 /// ContaintsRelocations - Return true if the constant value contains
94 /// relocations which cannot be resolved at compile time.
95 bool Constant::ContainsRelocations() const {
96   if (isa<GlobalValue>(this))
97     return true;
98   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99     if (getOperand(i)->ContainsRelocations())
100       return true;
101   return false;
102 }
103
104 // Static constructor to create a '0' constant of arbitrary type...
105 Constant *Constant::getNullValue(const Type *Ty) {
106   static uint64_t zero[2] = {0, 0};
107   switch (Ty->getTypeID()) {
108   case Type::IntegerTyID:
109     return ConstantInt::get(Ty, 0);
110   case Type::FloatTyID:
111     return ConstantFP::get(APFloat(APInt(32, 0)));
112   case Type::DoubleTyID:
113     return ConstantFP::get(APFloat(APInt(64, 0)));
114   case Type::X86_FP80TyID:
115     return ConstantFP::get(APFloat(APInt(80, 2, zero)));
116   case Type::FP128TyID:
117     return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
118   case Type::PPC_FP128TyID:
119     return ConstantFP::get(APFloat(APInt(128, 2, zero)));
120   case Type::PointerTyID:
121     return ConstantPointerNull::get(cast<PointerType>(Ty));
122   case Type::StructTyID:
123   case Type::ArrayTyID:
124   case Type::VectorTyID:
125     return ConstantAggregateZero::get(Ty);
126   default:
127     // Function, Label, or Opaque type?
128     assert(!"Cannot create a null constant of that type!");
129     return 0;
130   }
131 }
132
133 Constant *Constant::getAllOnesValue(const Type *Ty) {
134   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135     return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136   return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
137 }
138
139 // Static constructor to create an integral constant with all bits set
140 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
141   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
142     return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
143   return 0;
144 }
145
146 /// @returns the value for a vector integer constant of the given type that
147 /// has all its bits set to true.
148 /// @brief Get the all ones value
149 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
150   std::vector<Constant*> Elts;
151   Elts.resize(Ty->getNumElements(),
152               ConstantInt::getAllOnesValue(Ty->getElementType()));
153   assert(Elts[0] && "Not a vector integer type!");
154   return cast<ConstantVector>(ConstantVector::get(Elts));
155 }
156
157
158 //===----------------------------------------------------------------------===//
159 //                                ConstantInt
160 //===----------------------------------------------------------------------===//
161
162 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
163   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
164   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
165 }
166
167 ConstantInt *ConstantInt::TheTrueVal = 0;
168 ConstantInt *ConstantInt::TheFalseVal = 0;
169
170 namespace llvm {
171   void CleanupTrueFalse(void *) {
172     ConstantInt::ResetTrueFalse();
173   }
174 }
175
176 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
177
178 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179   assert(TheTrueVal == 0 && TheFalseVal == 0);
180   TheTrueVal  = get(Type::Int1Ty, 1);
181   TheFalseVal = get(Type::Int1Ty, 0);
182   
183   // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184   TrueFalseCleanup.Register();
185   
186   return WhichOne ? TheTrueVal : TheFalseVal;
187 }
188
189
190 namespace {
191   struct DenseMapAPIntKeyInfo {
192     struct KeyTy {
193       APInt val;
194       const Type* type;
195       KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196       KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197       bool operator==(const KeyTy& that) const {
198         return type == that.type && this->val == that.val;
199       }
200       bool operator!=(const KeyTy& that) const {
201         return !this->operator==(that);
202       }
203     };
204     static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205     static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
206     static unsigned getHashValue(const KeyTy &Key) {
207       return DenseMapInfo<void*>::getHashValue(Key.type) ^ 
208         Key.val.getHashValue();
209     }
210     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211       return LHS == RHS;
212     }
213     static bool isPod() { return false; }
214   };
215 }
216
217
218 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*, 
219                  DenseMapAPIntKeyInfo> IntMapTy;
220 static ManagedStatic<IntMapTy> IntConstants;
221
222 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
223   const IntegerType *ITy = cast<IntegerType>(Ty);
224   return get(APInt(ITy->getBitWidth(), V, isSigned));
225 }
226
227 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
228 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
229 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
230 // compare APInt's of different widths, which would violate an APInt class
231 // invariant which generates an assertion.
232 ConstantInt *ConstantInt::get(const APInt& V) {
233   // Get the corresponding integer type for the bit width of the value.
234   const IntegerType *ITy = IntegerType::get(V.getBitWidth());
235   // get an existing value or the insertion position
236   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
237   ConstantInt *&Slot = (*IntConstants)[Key]; 
238   // if it exists, return it.
239   if (Slot)
240     return Slot;
241   // otherwise create a new one, insert it, and return it.
242   return Slot = new ConstantInt(ITy, V);
243 }
244
245 //===----------------------------------------------------------------------===//
246 //                                ConstantFP
247 //===----------------------------------------------------------------------===//
248
249 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
250   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
251   // temporary
252   if (Ty==Type::FloatTy)
253     assert(&V.getSemantics()==&APFloat::IEEEsingle);
254   else if (Ty==Type::DoubleTy)
255     assert(&V.getSemantics()==&APFloat::IEEEdouble);
256   else if (Ty==Type::X86_FP80Ty)
257     assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
258   else if (Ty==Type::FP128Ty)
259     assert(&V.getSemantics()==&APFloat::IEEEquad);
260   else if (Ty==Type::PPC_FP128Ty)
261     assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
262   else
263     assert(0);
264 }
265
266 bool ConstantFP::isNullValue() const {
267   return Val.isZero() && !Val.isNegative();
268 }
269
270 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
271   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
272   apf.changeSign();
273   return ConstantFP::get(apf);
274 }
275
276 bool ConstantFP::isExactlyValue(const APFloat& V) const {
277   return Val.bitwiseIsEqual(V);
278 }
279
280 namespace {
281   struct DenseMapAPFloatKeyInfo {
282     struct KeyTy {
283       APFloat val;
284       KeyTy(const APFloat& V) : val(V){}
285       KeyTy(const KeyTy& that) : val(that.val) {}
286       bool operator==(const KeyTy& that) const {
287         return this->val.bitwiseIsEqual(that.val);
288       }
289       bool operator!=(const KeyTy& that) const {
290         return !this->operator==(that);
291       }
292     };
293     static inline KeyTy getEmptyKey() { 
294       return KeyTy(APFloat(APFloat::Bogus,1));
295     }
296     static inline KeyTy getTombstoneKey() { 
297       return KeyTy(APFloat(APFloat::Bogus,2)); 
298     }
299     static unsigned getHashValue(const KeyTy &Key) {
300       return Key.val.getHashValue();
301     }
302     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
303       return LHS == RHS;
304     }
305     static bool isPod() { return false; }
306   };
307 }
308
309 //---- ConstantFP::get() implementation...
310 //
311 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*, 
312                  DenseMapAPFloatKeyInfo> FPMapTy;
313
314 static ManagedStatic<FPMapTy> FPConstants;
315
316 ConstantFP *ConstantFP::get(const APFloat &V) {
317   DenseMapAPFloatKeyInfo::KeyTy Key(V);
318   ConstantFP *&Slot = (*FPConstants)[Key];
319   if (Slot) return Slot;
320   
321   const Type *Ty;
322   if (&V.getSemantics() == &APFloat::IEEEsingle)
323     Ty = Type::FloatTy;
324   else if (&V.getSemantics() == &APFloat::IEEEdouble)
325     Ty = Type::DoubleTy;
326   else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
327     Ty = Type::X86_FP80Ty;
328   else if (&V.getSemantics() == &APFloat::IEEEquad)
329     Ty = Type::FP128Ty;
330   else {
331     assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
332     Ty = Type::PPC_FP128Ty;
333   }
334   
335   return Slot = new ConstantFP(Ty, V);
336 }
337
338 //===----------------------------------------------------------------------===//
339 //                            ConstantXXX Classes
340 //===----------------------------------------------------------------------===//
341
342
343 ConstantArray::ConstantArray(const ArrayType *T,
344                              const std::vector<Constant*> &V)
345   : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
346   assert(V.size() == T->getNumElements() &&
347          "Invalid initializer vector for constant array");
348   Use *OL = OperandList;
349   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
350        I != E; ++I, ++OL) {
351     Constant *C = *I;
352     assert((C->getType() == T->getElementType() ||
353             (T->isAbstract() &&
354              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
355            "Initializer for array element doesn't match array element type!");
356     OL->init(C, this);
357   }
358 }
359
360 ConstantArray::~ConstantArray() {
361   delete [] OperandList;
362 }
363
364 ConstantStruct::ConstantStruct(const StructType *T,
365                                const std::vector<Constant*> &V)
366   : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
367   assert(V.size() == T->getNumElements() &&
368          "Invalid initializer vector for constant structure");
369   Use *OL = OperandList;
370   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
371        I != E; ++I, ++OL) {
372     Constant *C = *I;
373     assert((C->getType() == T->getElementType(I-V.begin()) ||
374             ((T->getElementType(I-V.begin())->isAbstract() ||
375               C->getType()->isAbstract()) &&
376              T->getElementType(I-V.begin())->getTypeID() == 
377                    C->getType()->getTypeID())) &&
378            "Initializer for struct element doesn't match struct element type!");
379     OL->init(C, this);
380   }
381 }
382
383 ConstantStruct::~ConstantStruct() {
384   delete [] OperandList;
385 }
386
387
388 ConstantVector::ConstantVector(const VectorType *T,
389                                const std::vector<Constant*> &V)
390   : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
391   Use *OL = OperandList;
392     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
393          I != E; ++I, ++OL) {
394       Constant *C = *I;
395       assert((C->getType() == T->getElementType() ||
396             (T->isAbstract() &&
397              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
398            "Initializer for vector element doesn't match vector element type!");
399     OL->init(C, this);
400   }
401 }
402
403 ConstantVector::~ConstantVector() {
404   delete [] OperandList;
405 }
406
407 // We declare several classes private to this file, so use an anonymous
408 // namespace
409 namespace {
410
411 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
412 /// behind the scenes to implement unary constant exprs.
413 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
414   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
415   Use Op;
416 public:
417   // allocate space for exactly one operand
418   void *operator new(size_t s) {
419     return User::operator new(s, 1);
420   }
421   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
422     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
423 };
424
425 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
426 /// behind the scenes to implement binary constant exprs.
427 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
428   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
429   Use Ops[2];
430 public:
431   // allocate space for exactly two operands
432   void *operator new(size_t s) {
433     return User::operator new(s, 2);
434   }
435   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
436     : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
437     Ops[0].init(C1, this);
438     Ops[1].init(C2, this);
439   }
440 };
441
442 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
443 /// behind the scenes to implement select constant exprs.
444 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
445   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
446   Use Ops[3];
447 public:
448   // allocate space for exactly three operands
449   void *operator new(size_t s) {
450     return User::operator new(s, 3);
451   }
452   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
453     : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
454     Ops[0].init(C1, this);
455     Ops[1].init(C2, this);
456     Ops[2].init(C3, this);
457   }
458 };
459
460 /// ExtractElementConstantExpr - This class is private to
461 /// Constants.cpp, and is used behind the scenes to implement
462 /// extractelement constant exprs.
463 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
464   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
465   Use Ops[2];
466 public:
467   // allocate space for exactly two operands
468   void *operator new(size_t s) {
469     return User::operator new(s, 2);
470   }
471   ExtractElementConstantExpr(Constant *C1, Constant *C2)
472     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
473                    Instruction::ExtractElement, Ops, 2) {
474     Ops[0].init(C1, this);
475     Ops[1].init(C2, this);
476   }
477 };
478
479 /// InsertElementConstantExpr - This class is private to
480 /// Constants.cpp, and is used behind the scenes to implement
481 /// insertelement constant exprs.
482 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
483   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
484   Use Ops[3];
485 public:
486   // allocate space for exactly three operands
487   void *operator new(size_t s) {
488     return User::operator new(s, 3);
489   }
490   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
491     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
492                    Ops, 3) {
493     Ops[0].init(C1, this);
494     Ops[1].init(C2, this);
495     Ops[2].init(C3, this);
496   }
497 };
498
499 /// ShuffleVectorConstantExpr - This class is private to
500 /// Constants.cpp, and is used behind the scenes to implement
501 /// shufflevector constant exprs.
502 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
503   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
504   Use Ops[3];
505 public:
506   // allocate space for exactly three operands
507   void *operator new(size_t s) {
508     return User::operator new(s, 3);
509   }
510   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
511   : ConstantExpr(C1->getType(), Instruction::ShuffleVector, 
512                  Ops, 3) {
513     Ops[0].init(C1, this);
514     Ops[1].init(C2, this);
515     Ops[2].init(C3, this);
516   }
517 };
518
519 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
520 /// used behind the scenes to implement getelementpr constant exprs.
521 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
522   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
523                             const Type *DestTy)
524     : ConstantExpr(DestTy, Instruction::GetElementPtr,
525                    new Use[IdxList.size()+1], IdxList.size()+1) {
526     OperandList[0].init(C, this);
527     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
528       OperandList[i+1].init(IdxList[i], this);
529   }
530 public:
531   static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
532                                     const Type *DestTy) {
533     return new(IdxList.size() + 1/*FIXME*/) GetElementPtrConstantExpr(C, IdxList, DestTy);
534   }
535   ~GetElementPtrConstantExpr() {
536     delete [] OperandList;
537   }
538 };
539
540 // CompareConstantExpr - This class is private to Constants.cpp, and is used
541 // behind the scenes to implement ICmp and FCmp constant expressions. This is
542 // needed in order to store the predicate value for these instructions.
543 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
544   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
545   // allocate space for exactly two operands
546   void *operator new(size_t s) {
547     return User::operator new(s, 2);
548   }
549   unsigned short predicate;
550   Use Ops[2];
551   CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred, 
552                       Constant* LHS, Constant* RHS)
553     : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
554     OperandList[0].init(LHS, this);
555     OperandList[1].init(RHS, this);
556   }
557 };
558
559 } // end anonymous namespace
560
561
562 // Utility function for determining if a ConstantExpr is a CastOp or not. This
563 // can't be inline because we don't want to #include Instruction.h into
564 // Constant.h
565 bool ConstantExpr::isCast() const {
566   return Instruction::isCast(getOpcode());
567 }
568
569 bool ConstantExpr::isCompare() const {
570   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
571 }
572
573 /// ConstantExpr::get* - Return some common constants without having to
574 /// specify the full Instruction::OPCODE identifier.
575 ///
576 Constant *ConstantExpr::getNeg(Constant *C) {
577   return get(Instruction::Sub,
578              ConstantExpr::getZeroValueForNegationExpr(C->getType()),
579              C);
580 }
581 Constant *ConstantExpr::getNot(Constant *C) {
582   assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
583   return get(Instruction::Xor, C,
584              ConstantInt::getAllOnesValue(C->getType()));
585 }
586 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
587   return get(Instruction::Add, C1, C2);
588 }
589 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
590   return get(Instruction::Sub, C1, C2);
591 }
592 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
593   return get(Instruction::Mul, C1, C2);
594 }
595 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
596   return get(Instruction::UDiv, C1, C2);
597 }
598 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
599   return get(Instruction::SDiv, C1, C2);
600 }
601 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
602   return get(Instruction::FDiv, C1, C2);
603 }
604 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
605   return get(Instruction::URem, C1, C2);
606 }
607 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
608   return get(Instruction::SRem, C1, C2);
609 }
610 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
611   return get(Instruction::FRem, C1, C2);
612 }
613 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
614   return get(Instruction::And, C1, C2);
615 }
616 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
617   return get(Instruction::Or, C1, C2);
618 }
619 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
620   return get(Instruction::Xor, C1, C2);
621 }
622 unsigned ConstantExpr::getPredicate() const {
623   assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
624   return ((const CompareConstantExpr*)this)->predicate;
625 }
626 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
627   return get(Instruction::Shl, C1, C2);
628 }
629 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
630   return get(Instruction::LShr, C1, C2);
631 }
632 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
633   return get(Instruction::AShr, C1, C2);
634 }
635
636 /// getWithOperandReplaced - Return a constant expression identical to this
637 /// one, but with the specified operand set to the specified value.
638 Constant *
639 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
640   assert(OpNo < getNumOperands() && "Operand num is out of range!");
641   assert(Op->getType() == getOperand(OpNo)->getType() &&
642          "Replacing operand with value of different type!");
643   if (getOperand(OpNo) == Op)
644     return const_cast<ConstantExpr*>(this);
645   
646   Constant *Op0, *Op1, *Op2;
647   switch (getOpcode()) {
648   case Instruction::Trunc:
649   case Instruction::ZExt:
650   case Instruction::SExt:
651   case Instruction::FPTrunc:
652   case Instruction::FPExt:
653   case Instruction::UIToFP:
654   case Instruction::SIToFP:
655   case Instruction::FPToUI:
656   case Instruction::FPToSI:
657   case Instruction::PtrToInt:
658   case Instruction::IntToPtr:
659   case Instruction::BitCast:
660     return ConstantExpr::getCast(getOpcode(), Op, getType());
661   case Instruction::Select:
662     Op0 = (OpNo == 0) ? Op : getOperand(0);
663     Op1 = (OpNo == 1) ? Op : getOperand(1);
664     Op2 = (OpNo == 2) ? Op : getOperand(2);
665     return ConstantExpr::getSelect(Op0, Op1, Op2);
666   case Instruction::InsertElement:
667     Op0 = (OpNo == 0) ? Op : getOperand(0);
668     Op1 = (OpNo == 1) ? Op : getOperand(1);
669     Op2 = (OpNo == 2) ? Op : getOperand(2);
670     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
671   case Instruction::ExtractElement:
672     Op0 = (OpNo == 0) ? Op : getOperand(0);
673     Op1 = (OpNo == 1) ? Op : getOperand(1);
674     return ConstantExpr::getExtractElement(Op0, Op1);
675   case Instruction::ShuffleVector:
676     Op0 = (OpNo == 0) ? Op : getOperand(0);
677     Op1 = (OpNo == 1) ? Op : getOperand(1);
678     Op2 = (OpNo == 2) ? Op : getOperand(2);
679     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
680   case Instruction::GetElementPtr: {
681     SmallVector<Constant*, 8> Ops;
682     Ops.resize(getNumOperands());
683     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
684       Ops[i] = getOperand(i);
685     if (OpNo == 0)
686       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
687     Ops[OpNo-1] = Op;
688     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
689   }
690   default:
691     assert(getNumOperands() == 2 && "Must be binary operator?");
692     Op0 = (OpNo == 0) ? Op : getOperand(0);
693     Op1 = (OpNo == 1) ? Op : getOperand(1);
694     return ConstantExpr::get(getOpcode(), Op0, Op1);
695   }
696 }
697
698 /// getWithOperands - This returns the current constant expression with the
699 /// operands replaced with the specified values.  The specified operands must
700 /// match count and type with the existing ones.
701 Constant *ConstantExpr::
702 getWithOperands(const std::vector<Constant*> &Ops) const {
703   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
704   bool AnyChange = false;
705   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
706     assert(Ops[i]->getType() == getOperand(i)->getType() &&
707            "Operand type mismatch!");
708     AnyChange |= Ops[i] != getOperand(i);
709   }
710   if (!AnyChange)  // No operands changed, return self.
711     return const_cast<ConstantExpr*>(this);
712
713   switch (getOpcode()) {
714   case Instruction::Trunc:
715   case Instruction::ZExt:
716   case Instruction::SExt:
717   case Instruction::FPTrunc:
718   case Instruction::FPExt:
719   case Instruction::UIToFP:
720   case Instruction::SIToFP:
721   case Instruction::FPToUI:
722   case Instruction::FPToSI:
723   case Instruction::PtrToInt:
724   case Instruction::IntToPtr:
725   case Instruction::BitCast:
726     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
727   case Instruction::Select:
728     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
729   case Instruction::InsertElement:
730     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
731   case Instruction::ExtractElement:
732     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
733   case Instruction::ShuffleVector:
734     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
735   case Instruction::GetElementPtr:
736     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
737   case Instruction::ICmp:
738   case Instruction::FCmp:
739     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
740   default:
741     assert(getNumOperands() == 2 && "Must be binary operator?");
742     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
743   }
744 }
745
746
747 //===----------------------------------------------------------------------===//
748 //                      isValueValidForType implementations
749
750 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
751   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
752   if (Ty == Type::Int1Ty)
753     return Val == 0 || Val == 1;
754   if (NumBits >= 64)
755     return true; // always true, has to fit in largest type
756   uint64_t Max = (1ll << NumBits) - 1;
757   return Val <= Max;
758 }
759
760 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
761   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
762   if (Ty == Type::Int1Ty)
763     return Val == 0 || Val == 1 || Val == -1;
764   if (NumBits >= 64)
765     return true; // always true, has to fit in largest type
766   int64_t Min = -(1ll << (NumBits-1));
767   int64_t Max = (1ll << (NumBits-1)) - 1;
768   return (Val >= Min && Val <= Max);
769 }
770
771 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
772   // convert modifies in place, so make a copy.
773   APFloat Val2 = APFloat(Val);
774   switch (Ty->getTypeID()) {
775   default:
776     return false;         // These can't be represented as floating point!
777
778   // FIXME rounding mode needs to be more flexible
779   case Type::FloatTyID:
780     return &Val2.getSemantics() == &APFloat::IEEEsingle ||
781            Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) == 
782               APFloat::opOK;
783   case Type::DoubleTyID:
784     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
785            &Val2.getSemantics() == &APFloat::IEEEdouble ||
786            Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) == 
787              APFloat::opOK;
788   case Type::X86_FP80TyID:
789     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
790            &Val2.getSemantics() == &APFloat::IEEEdouble ||
791            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
792   case Type::FP128TyID:
793     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
794            &Val2.getSemantics() == &APFloat::IEEEdouble ||
795            &Val2.getSemantics() == &APFloat::IEEEquad;
796   case Type::PPC_FP128TyID:
797     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
798            &Val2.getSemantics() == &APFloat::IEEEdouble ||
799            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
800   }
801 }
802
803 //===----------------------------------------------------------------------===//
804 //                      Factory Function Implementation
805
806 // ConstantCreator - A class that is used to create constants by
807 // ValueMap*.  This class should be partially specialized if there is
808 // something strange that needs to be done to interface to the ctor for the
809 // constant.
810 //
811 namespace llvm {
812   template<class ConstantClass, class TypeClass, class ValType>
813   struct VISIBILITY_HIDDEN ConstantCreator {
814     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
815       unsigned FIXME = 0; // = traits<ValType>::uses(V)
816       return new(FIXME) ConstantClass(Ty, V);
817     }
818   };
819
820   template<class ConstantClass, class TypeClass>
821   struct VISIBILITY_HIDDEN ConvertConstantType {
822     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
823       assert(0 && "This type cannot be converted!\n");
824       abort();
825     }
826   };
827
828   template<class ValType, class TypeClass, class ConstantClass,
829            bool HasLargeKey = false  /*true for arrays and structs*/ >
830   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
831   public:
832     typedef std::pair<const Type*, ValType> MapKey;
833     typedef std::map<MapKey, Constant *> MapTy;
834     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
835     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
836   private:
837     /// Map - This is the main map from the element descriptor to the Constants.
838     /// This is the primary way we avoid creating two of the same shape
839     /// constant.
840     MapTy Map;
841     
842     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
843     /// from the constants to their element in Map.  This is important for
844     /// removal of constants from the array, which would otherwise have to scan
845     /// through the map with very large keys.
846     InverseMapTy InverseMap;
847
848     /// AbstractTypeMap - Map for abstract type constants.
849     ///
850     AbstractTypeMapTy AbstractTypeMap;
851
852   public:
853     typename MapTy::iterator map_end() { return Map.end(); }
854     
855     /// InsertOrGetItem - Return an iterator for the specified element.
856     /// If the element exists in the map, the returned iterator points to the
857     /// entry and Exists=true.  If not, the iterator points to the newly
858     /// inserted entry and returns Exists=false.  Newly inserted entries have
859     /// I->second == 0, and should be filled in.
860     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
861                                    &InsertVal,
862                                    bool &Exists) {
863       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
864       Exists = !IP.second;
865       return IP.first;
866     }
867     
868 private:
869     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
870       if (HasLargeKey) {
871         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
872         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
873                IMI->second->second == CP &&
874                "InverseMap corrupt!");
875         return IMI->second;
876       }
877       
878       typename MapTy::iterator I =
879         Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
880       if (I == Map.end() || I->second != CP) {
881         // FIXME: This should not use a linear scan.  If this gets to be a
882         // performance problem, someone should look at this.
883         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
884           /* empty */;
885       }
886       return I;
887     }
888 public:
889     
890     /// getOrCreate - Return the specified constant from the map, creating it if
891     /// necessary.
892     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
893       MapKey Lookup(Ty, V);
894       typename MapTy::iterator I = Map.lower_bound(Lookup);
895       // Is it in the map?      
896       if (I != Map.end() && I->first == Lookup)
897         return static_cast<ConstantClass *>(I->second);  
898
899       // If no preexisting value, create one now...
900       ConstantClass *Result =
901         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
902
903       /// FIXME: why does this assert fail when loading 176.gcc?
904       //assert(Result->getType() == Ty && "Type specified is not correct!");
905       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
906
907       if (HasLargeKey)  // Remember the reverse mapping if needed.
908         InverseMap.insert(std::make_pair(Result, I));
909       
910       // If the type of the constant is abstract, make sure that an entry exists
911       // for it in the AbstractTypeMap.
912       if (Ty->isAbstract()) {
913         typename AbstractTypeMapTy::iterator TI =
914           AbstractTypeMap.lower_bound(Ty);
915
916         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
917           // Add ourselves to the ATU list of the type.
918           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
919
920           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
921         }
922       }
923       return Result;
924     }
925
926     void remove(ConstantClass *CP) {
927       typename MapTy::iterator I = FindExistingElement(CP);
928       assert(I != Map.end() && "Constant not found in constant table!");
929       assert(I->second == CP && "Didn't find correct element?");
930
931       if (HasLargeKey)  // Remember the reverse mapping if needed.
932         InverseMap.erase(CP);
933       
934       // Now that we found the entry, make sure this isn't the entry that
935       // the AbstractTypeMap points to.
936       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
937       if (Ty->isAbstract()) {
938         assert(AbstractTypeMap.count(Ty) &&
939                "Abstract type not in AbstractTypeMap?");
940         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
941         if (ATMEntryIt == I) {
942           // Yes, we are removing the representative entry for this type.
943           // See if there are any other entries of the same type.
944           typename MapTy::iterator TmpIt = ATMEntryIt;
945
946           // First check the entry before this one...
947           if (TmpIt != Map.begin()) {
948             --TmpIt;
949             if (TmpIt->first.first != Ty) // Not the same type, move back...
950               ++TmpIt;
951           }
952
953           // If we didn't find the same type, try to move forward...
954           if (TmpIt == ATMEntryIt) {
955             ++TmpIt;
956             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
957               --TmpIt;   // No entry afterwards with the same type
958           }
959
960           // If there is another entry in the map of the same abstract type,
961           // update the AbstractTypeMap entry now.
962           if (TmpIt != ATMEntryIt) {
963             ATMEntryIt = TmpIt;
964           } else {
965             // Otherwise, we are removing the last instance of this type
966             // from the table.  Remove from the ATM, and from user list.
967             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
968             AbstractTypeMap.erase(Ty);
969           }
970         }
971       }
972
973       Map.erase(I);
974     }
975
976     
977     /// MoveConstantToNewSlot - If we are about to change C to be the element
978     /// specified by I, update our internal data structures to reflect this
979     /// fact.
980     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
981       // First, remove the old location of the specified constant in the map.
982       typename MapTy::iterator OldI = FindExistingElement(C);
983       assert(OldI != Map.end() && "Constant not found in constant table!");
984       assert(OldI->second == C && "Didn't find correct element?");
985       
986       // If this constant is the representative element for its abstract type,
987       // update the AbstractTypeMap so that the representative element is I.
988       if (C->getType()->isAbstract()) {
989         typename AbstractTypeMapTy::iterator ATI =
990             AbstractTypeMap.find(C->getType());
991         assert(ATI != AbstractTypeMap.end() &&
992                "Abstract type not in AbstractTypeMap?");
993         if (ATI->second == OldI)
994           ATI->second = I;
995       }
996       
997       // Remove the old entry from the map.
998       Map.erase(OldI);
999       
1000       // Update the inverse map so that we know that this constant is now
1001       // located at descriptor I.
1002       if (HasLargeKey) {
1003         assert(I->second == C && "Bad inversemap entry!");
1004         InverseMap[C] = I;
1005       }
1006     }
1007     
1008     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1009       typename AbstractTypeMapTy::iterator I =
1010         AbstractTypeMap.find(cast<Type>(OldTy));
1011
1012       assert(I != AbstractTypeMap.end() &&
1013              "Abstract type not in AbstractTypeMap?");
1014
1015       // Convert a constant at a time until the last one is gone.  The last one
1016       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1017       // eliminated eventually.
1018       do {
1019         ConvertConstantType<ConstantClass,
1020                             TypeClass>::convert(
1021                                 static_cast<ConstantClass *>(I->second->second),
1022                                                 cast<TypeClass>(NewTy));
1023
1024         I = AbstractTypeMap.find(cast<Type>(OldTy));
1025       } while (I != AbstractTypeMap.end());
1026     }
1027
1028     // If the type became concrete without being refined to any other existing
1029     // type, we just remove ourselves from the ATU list.
1030     void typeBecameConcrete(const DerivedType *AbsTy) {
1031       AbsTy->removeAbstractTypeUser(this);
1032     }
1033
1034     void dump() const {
1035       DOUT << "Constant.cpp: ValueMap\n";
1036     }
1037   };
1038 }
1039
1040
1041
1042 //---- ConstantAggregateZero::get() implementation...
1043 //
1044 namespace llvm {
1045   // ConstantAggregateZero does not take extra "value" argument...
1046   template<class ValType>
1047   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1048     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1049       return new ConstantAggregateZero(Ty);
1050     }
1051   };
1052
1053   template<>
1054   struct ConvertConstantType<ConstantAggregateZero, Type> {
1055     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1056       // Make everyone now use a constant of the new type...
1057       Constant *New = ConstantAggregateZero::get(NewTy);
1058       assert(New != OldC && "Didn't replace constant??");
1059       OldC->uncheckedReplaceAllUsesWith(New);
1060       OldC->destroyConstant();     // This constant is now dead, destroy it.
1061     }
1062   };
1063 }
1064
1065 static ManagedStatic<ValueMap<char, Type, 
1066                               ConstantAggregateZero> > AggZeroConstants;
1067
1068 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1069
1070 Constant *ConstantAggregateZero::get(const Type *Ty) {
1071   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1072          "Cannot create an aggregate zero of non-aggregate type!");
1073   return AggZeroConstants->getOrCreate(Ty, 0);
1074 }
1075
1076 // destroyConstant - Remove the constant from the constant table...
1077 //
1078 void ConstantAggregateZero::destroyConstant() {
1079   AggZeroConstants->remove(this);
1080   destroyConstantImpl();
1081 }
1082
1083 //---- ConstantArray::get() implementation...
1084 //
1085 namespace llvm {
1086   template<>
1087   struct ConvertConstantType<ConstantArray, ArrayType> {
1088     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1089       // Make everyone now use a constant of the new type...
1090       std::vector<Constant*> C;
1091       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1092         C.push_back(cast<Constant>(OldC->getOperand(i)));
1093       Constant *New = ConstantArray::get(NewTy, C);
1094       assert(New != OldC && "Didn't replace constant??");
1095       OldC->uncheckedReplaceAllUsesWith(New);
1096       OldC->destroyConstant();    // This constant is now dead, destroy it.
1097     }
1098   };
1099 }
1100
1101 static std::vector<Constant*> getValType(ConstantArray *CA) {
1102   std::vector<Constant*> Elements;
1103   Elements.reserve(CA->getNumOperands());
1104   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1105     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1106   return Elements;
1107 }
1108
1109 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1110                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1111 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1112
1113 Constant *ConstantArray::get(const ArrayType *Ty,
1114                              const std::vector<Constant*> &V) {
1115   // If this is an all-zero array, return a ConstantAggregateZero object
1116   if (!V.empty()) {
1117     Constant *C = V[0];
1118     if (!C->isNullValue())
1119       return ArrayConstants->getOrCreate(Ty, V);
1120     for (unsigned i = 1, e = V.size(); i != e; ++i)
1121       if (V[i] != C)
1122         return ArrayConstants->getOrCreate(Ty, V);
1123   }
1124   return ConstantAggregateZero::get(Ty);
1125 }
1126
1127 // destroyConstant - Remove the constant from the constant table...
1128 //
1129 void ConstantArray::destroyConstant() {
1130   ArrayConstants->remove(this);
1131   destroyConstantImpl();
1132 }
1133
1134 /// ConstantArray::get(const string&) - Return an array that is initialized to
1135 /// contain the specified string.  If length is zero then a null terminator is 
1136 /// added to the specified string so that it may be used in a natural way. 
1137 /// Otherwise, the length parameter specifies how much of the string to use 
1138 /// and it won't be null terminated.
1139 ///
1140 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1141   std::vector<Constant*> ElementVals;
1142   for (unsigned i = 0; i < Str.length(); ++i)
1143     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1144
1145   // Add a null terminator to the string...
1146   if (AddNull) {
1147     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1148   }
1149
1150   ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1151   return ConstantArray::get(ATy, ElementVals);
1152 }
1153
1154 /// isString - This method returns true if the array is an array of i8, and 
1155 /// if the elements of the array are all ConstantInt's.
1156 bool ConstantArray::isString() const {
1157   // Check the element type for i8...
1158   if (getType()->getElementType() != Type::Int8Ty)
1159     return false;
1160   // Check the elements to make sure they are all integers, not constant
1161   // expressions.
1162   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1163     if (!isa<ConstantInt>(getOperand(i)))
1164       return false;
1165   return true;
1166 }
1167
1168 /// isCString - This method returns true if the array is a string (see
1169 /// isString) and it ends in a null byte \0 and does not contains any other
1170 /// null bytes except its terminator.
1171 bool ConstantArray::isCString() const {
1172   // Check the element type for i8...
1173   if (getType()->getElementType() != Type::Int8Ty)
1174     return false;
1175   Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1176   // Last element must be a null.
1177   if (getOperand(getNumOperands()-1) != Zero)
1178     return false;
1179   // Other elements must be non-null integers.
1180   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1181     if (!isa<ConstantInt>(getOperand(i)))
1182       return false;
1183     if (getOperand(i) == Zero)
1184       return false;
1185   }
1186   return true;
1187 }
1188
1189
1190 // getAsString - If the sub-element type of this array is i8
1191 // then this method converts the array to an std::string and returns it.
1192 // Otherwise, it asserts out.
1193 //
1194 std::string ConstantArray::getAsString() const {
1195   assert(isString() && "Not a string!");
1196   std::string Result;
1197   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1198     Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1199   return Result;
1200 }
1201
1202
1203 //---- ConstantStruct::get() implementation...
1204 //
1205
1206 namespace llvm {
1207   template<>
1208   struct ConvertConstantType<ConstantStruct, StructType> {
1209     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1210       // Make everyone now use a constant of the new type...
1211       std::vector<Constant*> C;
1212       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1213         C.push_back(cast<Constant>(OldC->getOperand(i)));
1214       Constant *New = ConstantStruct::get(NewTy, C);
1215       assert(New != OldC && "Didn't replace constant??");
1216
1217       OldC->uncheckedReplaceAllUsesWith(New);
1218       OldC->destroyConstant();    // This constant is now dead, destroy it.
1219     }
1220   };
1221 }
1222
1223 typedef ValueMap<std::vector<Constant*>, StructType,
1224                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1225 static ManagedStatic<StructConstantsTy> StructConstants;
1226
1227 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1228   std::vector<Constant*> Elements;
1229   Elements.reserve(CS->getNumOperands());
1230   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1231     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1232   return Elements;
1233 }
1234
1235 Constant *ConstantStruct::get(const StructType *Ty,
1236                               const std::vector<Constant*> &V) {
1237   // Create a ConstantAggregateZero value if all elements are zeros...
1238   for (unsigned i = 0, e = V.size(); i != e; ++i)
1239     if (!V[i]->isNullValue())
1240       return StructConstants->getOrCreate(Ty, V);
1241
1242   return ConstantAggregateZero::get(Ty);
1243 }
1244
1245 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1246   std::vector<const Type*> StructEls;
1247   StructEls.reserve(V.size());
1248   for (unsigned i = 0, e = V.size(); i != e; ++i)
1249     StructEls.push_back(V[i]->getType());
1250   return get(StructType::get(StructEls, packed), V);
1251 }
1252
1253 // destroyConstant - Remove the constant from the constant table...
1254 //
1255 void ConstantStruct::destroyConstant() {
1256   StructConstants->remove(this);
1257   destroyConstantImpl();
1258 }
1259
1260 //---- ConstantVector::get() implementation...
1261 //
1262 namespace llvm {
1263   template<>
1264   struct ConvertConstantType<ConstantVector, VectorType> {
1265     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1266       // Make everyone now use a constant of the new type...
1267       std::vector<Constant*> C;
1268       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1269         C.push_back(cast<Constant>(OldC->getOperand(i)));
1270       Constant *New = ConstantVector::get(NewTy, C);
1271       assert(New != OldC && "Didn't replace constant??");
1272       OldC->uncheckedReplaceAllUsesWith(New);
1273       OldC->destroyConstant();    // This constant is now dead, destroy it.
1274     }
1275   };
1276 }
1277
1278 static std::vector<Constant*> getValType(ConstantVector *CP) {
1279   std::vector<Constant*> Elements;
1280   Elements.reserve(CP->getNumOperands());
1281   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1282     Elements.push_back(CP->getOperand(i));
1283   return Elements;
1284 }
1285
1286 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1287                               ConstantVector> > VectorConstants;
1288
1289 Constant *ConstantVector::get(const VectorType *Ty,
1290                               const std::vector<Constant*> &V) {
1291   // If this is an all-zero vector, return a ConstantAggregateZero object
1292   if (!V.empty()) {
1293     Constant *C = V[0];
1294     if (!C->isNullValue())
1295       return VectorConstants->getOrCreate(Ty, V);
1296     for (unsigned i = 1, e = V.size(); i != e; ++i)
1297       if (V[i] != C)
1298         return VectorConstants->getOrCreate(Ty, V);
1299   }
1300   return ConstantAggregateZero::get(Ty);
1301 }
1302
1303 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1304   assert(!V.empty() && "Cannot infer type if V is empty");
1305   return get(VectorType::get(V.front()->getType(),V.size()), V);
1306 }
1307
1308 // destroyConstant - Remove the constant from the constant table...
1309 //
1310 void ConstantVector::destroyConstant() {
1311   VectorConstants->remove(this);
1312   destroyConstantImpl();
1313 }
1314
1315 /// This function will return true iff every element in this vector constant
1316 /// is set to all ones.
1317 /// @returns true iff this constant's emements are all set to all ones.
1318 /// @brief Determine if the value is all ones.
1319 bool ConstantVector::isAllOnesValue() const {
1320   // Check out first element.
1321   const Constant *Elt = getOperand(0);
1322   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1323   if (!CI || !CI->isAllOnesValue()) return false;
1324   // Then make sure all remaining elements point to the same value.
1325   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1326     if (getOperand(I) != Elt) return false;
1327   }
1328   return true;
1329 }
1330
1331 /// getSplatValue - If this is a splat constant, where all of the
1332 /// elements have the same value, return that value. Otherwise return null.
1333 Constant *ConstantVector::getSplatValue() {
1334   // Check out first element.
1335   Constant *Elt = getOperand(0);
1336   // Then make sure all remaining elements point to the same value.
1337   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1338     if (getOperand(I) != Elt) return 0;
1339   return Elt;
1340 }
1341
1342 //---- ConstantPointerNull::get() implementation...
1343 //
1344
1345 namespace llvm {
1346   // ConstantPointerNull does not take extra "value" argument...
1347   template<class ValType>
1348   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1349     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1350       return new ConstantPointerNull(Ty);
1351     }
1352   };
1353
1354   template<>
1355   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1356     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1357       // Make everyone now use a constant of the new type...
1358       Constant *New = ConstantPointerNull::get(NewTy);
1359       assert(New != OldC && "Didn't replace constant??");
1360       OldC->uncheckedReplaceAllUsesWith(New);
1361       OldC->destroyConstant();     // This constant is now dead, destroy it.
1362     }
1363   };
1364 }
1365
1366 static ManagedStatic<ValueMap<char, PointerType, 
1367                               ConstantPointerNull> > NullPtrConstants;
1368
1369 static char getValType(ConstantPointerNull *) {
1370   return 0;
1371 }
1372
1373
1374 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1375   return NullPtrConstants->getOrCreate(Ty, 0);
1376 }
1377
1378 // destroyConstant - Remove the constant from the constant table...
1379 //
1380 void ConstantPointerNull::destroyConstant() {
1381   NullPtrConstants->remove(this);
1382   destroyConstantImpl();
1383 }
1384
1385
1386 //---- UndefValue::get() implementation...
1387 //
1388
1389 namespace llvm {
1390   // UndefValue does not take extra "value" argument...
1391   template<class ValType>
1392   struct ConstantCreator<UndefValue, Type, ValType> {
1393     static UndefValue *create(const Type *Ty, const ValType &V) {
1394       return new UndefValue(Ty);
1395     }
1396   };
1397
1398   template<>
1399   struct ConvertConstantType<UndefValue, Type> {
1400     static void convert(UndefValue *OldC, const Type *NewTy) {
1401       // Make everyone now use a constant of the new type.
1402       Constant *New = UndefValue::get(NewTy);
1403       assert(New != OldC && "Didn't replace constant??");
1404       OldC->uncheckedReplaceAllUsesWith(New);
1405       OldC->destroyConstant();     // This constant is now dead, destroy it.
1406     }
1407   };
1408 }
1409
1410 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1411
1412 static char getValType(UndefValue *) {
1413   return 0;
1414 }
1415
1416
1417 UndefValue *UndefValue::get(const Type *Ty) {
1418   return UndefValueConstants->getOrCreate(Ty, 0);
1419 }
1420
1421 // destroyConstant - Remove the constant from the constant table.
1422 //
1423 void UndefValue::destroyConstant() {
1424   UndefValueConstants->remove(this);
1425   destroyConstantImpl();
1426 }
1427
1428
1429 //---- ConstantExpr::get() implementations...
1430 //
1431
1432 struct ExprMapKeyType {
1433   explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1434       unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1435   uint16_t opcode;
1436   uint16_t predicate;
1437   std::vector<Constant*> operands;
1438   bool operator==(const ExprMapKeyType& that) const {
1439     return this->opcode == that.opcode &&
1440            this->predicate == that.predicate &&
1441            this->operands == that.operands;
1442   }
1443   bool operator<(const ExprMapKeyType & that) const {
1444     return this->opcode < that.opcode ||
1445       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1446       (this->opcode == that.opcode && this->predicate == that.predicate &&
1447        this->operands < that.operands);
1448   }
1449
1450   bool operator!=(const ExprMapKeyType& that) const {
1451     return !(*this == that);
1452   }
1453 };
1454
1455 namespace llvm {
1456   template<>
1457   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1458     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1459         unsigned short pred = 0) {
1460       if (Instruction::isCast(V.opcode))
1461         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1462       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1463            V.opcode < Instruction::BinaryOpsEnd))
1464         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1465       if (V.opcode == Instruction::Select)
1466         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1467                                       V.operands[2]);
1468       if (V.opcode == Instruction::ExtractElement)
1469         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1470       if (V.opcode == Instruction::InsertElement)
1471         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1472                                              V.operands[2]);
1473       if (V.opcode == Instruction::ShuffleVector)
1474         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1475                                              V.operands[2]);
1476       if (V.opcode == Instruction::GetElementPtr) {
1477         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1478         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1479       }
1480
1481       // The compare instructions are weird. We have to encode the predicate
1482       // value and it is combined with the instruction opcode by multiplying
1483       // the opcode by one hundred. We must decode this to get the predicate.
1484       if (V.opcode == Instruction::ICmp)
1485         return new CompareConstantExpr(Instruction::ICmp, V.predicate, 
1486                                        V.operands[0], V.operands[1]);
1487       if (V.opcode == Instruction::FCmp) 
1488         return new CompareConstantExpr(Instruction::FCmp, V.predicate, 
1489                                        V.operands[0], V.operands[1]);
1490       assert(0 && "Invalid ConstantExpr!");
1491       return 0;
1492     }
1493   };
1494
1495   template<>
1496   struct ConvertConstantType<ConstantExpr, Type> {
1497     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1498       Constant *New;
1499       switch (OldC->getOpcode()) {
1500       case Instruction::Trunc:
1501       case Instruction::ZExt:
1502       case Instruction::SExt:
1503       case Instruction::FPTrunc:
1504       case Instruction::FPExt:
1505       case Instruction::UIToFP:
1506       case Instruction::SIToFP:
1507       case Instruction::FPToUI:
1508       case Instruction::FPToSI:
1509       case Instruction::PtrToInt:
1510       case Instruction::IntToPtr:
1511       case Instruction::BitCast:
1512         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1513                                     NewTy);
1514         break;
1515       case Instruction::Select:
1516         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1517                                         OldC->getOperand(1),
1518                                         OldC->getOperand(2));
1519         break;
1520       default:
1521         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1522                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1523         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1524                                   OldC->getOperand(1));
1525         break;
1526       case Instruction::GetElementPtr:
1527         // Make everyone now use a constant of the new type...
1528         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1529         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1530                                                &Idx[0], Idx.size());
1531         break;
1532       }
1533
1534       assert(New != OldC && "Didn't replace constant??");
1535       OldC->uncheckedReplaceAllUsesWith(New);
1536       OldC->destroyConstant();    // This constant is now dead, destroy it.
1537     }
1538   };
1539 } // end namespace llvm
1540
1541
1542 static ExprMapKeyType getValType(ConstantExpr *CE) {
1543   std::vector<Constant*> Operands;
1544   Operands.reserve(CE->getNumOperands());
1545   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1546     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1547   return ExprMapKeyType(CE->getOpcode(), Operands, 
1548       CE->isCompare() ? CE->getPredicate() : 0);
1549 }
1550
1551 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1552                               ConstantExpr> > ExprConstants;
1553
1554 /// This is a utility function to handle folding of casts and lookup of the
1555 /// cast in the ExprConstants map. It is used by the various get* methods below.
1556 static inline Constant *getFoldedCast(
1557   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1558   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1559   // Fold a few common cases
1560   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1561     return FC;
1562
1563   // Look up the constant in the table first to ensure uniqueness
1564   std::vector<Constant*> argVec(1, C);
1565   ExprMapKeyType Key(opc, argVec);
1566   return ExprConstants->getOrCreate(Ty, Key);
1567 }
1568  
1569 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1570   Instruction::CastOps opc = Instruction::CastOps(oc);
1571   assert(Instruction::isCast(opc) && "opcode out of range");
1572   assert(C && Ty && "Null arguments to getCast");
1573   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1574
1575   switch (opc) {
1576     default:
1577       assert(0 && "Invalid cast opcode");
1578       break;
1579     case Instruction::Trunc:    return getTrunc(C, Ty);
1580     case Instruction::ZExt:     return getZExt(C, Ty);
1581     case Instruction::SExt:     return getSExt(C, Ty);
1582     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1583     case Instruction::FPExt:    return getFPExtend(C, Ty);
1584     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1585     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1586     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1587     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1588     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1589     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1590     case Instruction::BitCast:  return getBitCast(C, Ty);
1591   }
1592   return 0;
1593
1594
1595 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1596   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1597     return getCast(Instruction::BitCast, C, Ty);
1598   return getCast(Instruction::ZExt, C, Ty);
1599 }
1600
1601 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1602   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1603     return getCast(Instruction::BitCast, C, Ty);
1604   return getCast(Instruction::SExt, C, Ty);
1605 }
1606
1607 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1608   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1609     return getCast(Instruction::BitCast, C, Ty);
1610   return getCast(Instruction::Trunc, C, Ty);
1611 }
1612
1613 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1614   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1615   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1616
1617   if (Ty->isInteger())
1618     return getCast(Instruction::PtrToInt, S, Ty);
1619   return getCast(Instruction::BitCast, S, Ty);
1620 }
1621
1622 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1623                                        bool isSigned) {
1624   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1625   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1626   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1627   Instruction::CastOps opcode =
1628     (SrcBits == DstBits ? Instruction::BitCast :
1629      (SrcBits > DstBits ? Instruction::Trunc :
1630       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1631   return getCast(opcode, C, Ty);
1632 }
1633
1634 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1635   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1636          "Invalid cast");
1637   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1638   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1639   if (SrcBits == DstBits)
1640     return C; // Avoid a useless cast
1641   Instruction::CastOps opcode =
1642      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1643   return getCast(opcode, C, Ty);
1644 }
1645
1646 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1647   assert(C->getType()->isInteger() && "Trunc operand must be integer");
1648   assert(Ty->isInteger() && "Trunc produces only integral");
1649   assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1650          "SrcTy must be larger than DestTy for Trunc!");
1651
1652   return getFoldedCast(Instruction::Trunc, C, Ty);
1653 }
1654
1655 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1656   assert(C->getType()->isInteger() && "SEXt operand must be integral");
1657   assert(Ty->isInteger() && "SExt produces only integer");
1658   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1659          "SrcTy must be smaller than DestTy for SExt!");
1660
1661   return getFoldedCast(Instruction::SExt, C, Ty);
1662 }
1663
1664 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1665   assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1666   assert(Ty->isInteger() && "ZExt produces only integer");
1667   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1668          "SrcTy must be smaller than DestTy for ZExt!");
1669
1670   return getFoldedCast(Instruction::ZExt, C, Ty);
1671 }
1672
1673 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1674   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1675          C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1676          "This is an illegal floating point truncation!");
1677   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1678 }
1679
1680 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1681   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1682          C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1683          "This is an illegal floating point extension!");
1684   return getFoldedCast(Instruction::FPExt, C, Ty);
1685 }
1686
1687 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1688   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1689   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1690   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1691   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1692          "This is an illegal uint to floating point cast!");
1693   return getFoldedCast(Instruction::UIToFP, C, Ty);
1694 }
1695
1696 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1697   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1698   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1699   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1700   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1701          "This is an illegal sint to floating point cast!");
1702   return getFoldedCast(Instruction::SIToFP, C, Ty);
1703 }
1704
1705 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1706   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1707   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1708   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1709   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1710          "This is an illegal floating point to uint cast!");
1711   return getFoldedCast(Instruction::FPToUI, C, Ty);
1712 }
1713
1714 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1715   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1716   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1717   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1718   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1719          "This is an illegal floating point to sint cast!");
1720   return getFoldedCast(Instruction::FPToSI, C, Ty);
1721 }
1722
1723 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1724   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1725   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1726   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1727 }
1728
1729 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1730   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1731   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1732   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1733 }
1734
1735 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1736   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1737   // can't cast pointers to anything but pointers.
1738   const Type *SrcTy = C->getType();
1739   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1740          "BitCast cannot cast pointer to non-pointer and vice versa");
1741
1742   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1743   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1744   // destination bit widths are identical.
1745   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1746   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1747   assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1748   return getFoldedCast(Instruction::BitCast, C, DstTy);
1749 }
1750
1751 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1752   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1753   Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1754   Constant *GEP =
1755     getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1756   return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1757 }
1758
1759 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1760                               Constant *C1, Constant *C2) {
1761   // Check the operands for consistency first
1762   assert(Opcode >= Instruction::BinaryOpsBegin &&
1763          Opcode <  Instruction::BinaryOpsEnd   &&
1764          "Invalid opcode in binary constant expression");
1765   assert(C1->getType() == C2->getType() &&
1766          "Operand types in binary constant expression should match");
1767
1768   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1769     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1770       return FC;          // Fold a few common cases...
1771
1772   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1773   ExprMapKeyType Key(Opcode, argVec);
1774   return ExprConstants->getOrCreate(ReqTy, Key);
1775 }
1776
1777 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1778                                      Constant *C1, Constant *C2) {
1779   switch (predicate) {
1780     default: assert(0 && "Invalid CmpInst predicate");
1781     case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1782     case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1783     case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1784     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1785     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1786     case FCmpInst::FCMP_TRUE:
1787       return getFCmp(predicate, C1, C2);
1788     case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1789     case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1790     case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1791     case ICmpInst::ICMP_SLE:
1792       return getICmp(predicate, C1, C2);
1793   }
1794 }
1795
1796 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1797 #ifndef NDEBUG
1798   switch (Opcode) {
1799   case Instruction::Add: 
1800   case Instruction::Sub:
1801   case Instruction::Mul: 
1802     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1803     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1804             isa<VectorType>(C1->getType())) &&
1805            "Tried to create an arithmetic operation on a non-arithmetic type!");
1806     break;
1807   case Instruction::UDiv: 
1808   case Instruction::SDiv: 
1809     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1810     assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1811       cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1812            "Tried to create an arithmetic operation on a non-arithmetic type!");
1813     break;
1814   case Instruction::FDiv:
1815     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1816     assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1817       && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint())) 
1818       && "Tried to create an arithmetic operation on a non-arithmetic type!");
1819     break;
1820   case Instruction::URem: 
1821   case Instruction::SRem: 
1822     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1823     assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1824       cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1825            "Tried to create an arithmetic operation on a non-arithmetic type!");
1826     break;
1827   case Instruction::FRem:
1828     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1829     assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1830       && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint())) 
1831       && "Tried to create an arithmetic operation on a non-arithmetic type!");
1832     break;
1833   case Instruction::And:
1834   case Instruction::Or:
1835   case Instruction::Xor:
1836     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1837     assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1838            "Tried to create a logical operation on a non-integral type!");
1839     break;
1840   case Instruction::Shl:
1841   case Instruction::LShr:
1842   case Instruction::AShr:
1843     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1844     assert(C1->getType()->isInteger() &&
1845            "Tried to create a shift operation on a non-integer type!");
1846     break;
1847   default:
1848     break;
1849   }
1850 #endif
1851
1852   return getTy(C1->getType(), Opcode, C1, C2);
1853 }
1854
1855 Constant *ConstantExpr::getCompare(unsigned short pred, 
1856                             Constant *C1, Constant *C2) {
1857   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1858   return getCompareTy(pred, C1, C2);
1859 }
1860
1861 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1862                                     Constant *V1, Constant *V2) {
1863   assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1864   assert(V1->getType() == V2->getType() && "Select value types must match!");
1865   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1866
1867   if (ReqTy == V1->getType())
1868     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1869       return SC;        // Fold common cases
1870
1871   std::vector<Constant*> argVec(3, C);
1872   argVec[1] = V1;
1873   argVec[2] = V2;
1874   ExprMapKeyType Key(Instruction::Select, argVec);
1875   return ExprConstants->getOrCreate(ReqTy, Key);
1876 }
1877
1878 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1879                                            Value* const *Idxs,
1880                                            unsigned NumIdx) {
1881   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
1882          "GEP indices invalid!");
1883
1884   if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1885     return FC;          // Fold a few common cases...
1886
1887   assert(isa<PointerType>(C->getType()) &&
1888          "Non-pointer type for constant GetElementPtr expression");
1889   // Look up the constant in the table first to ensure uniqueness
1890   std::vector<Constant*> ArgVec;
1891   ArgVec.reserve(NumIdx+1);
1892   ArgVec.push_back(C);
1893   for (unsigned i = 0; i != NumIdx; ++i)
1894     ArgVec.push_back(cast<Constant>(Idxs[i]));
1895   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1896   return ExprConstants->getOrCreate(ReqTy, Key);
1897 }
1898
1899 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1900                                          unsigned NumIdx) {
1901   // Get the result type of the getelementptr!
1902   const Type *Ty = 
1903     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
1904   assert(Ty && "GEP indices invalid!");
1905   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1906   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1907 }
1908
1909 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1910                                          unsigned NumIdx) {
1911   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1912 }
1913
1914
1915 Constant *
1916 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1917   assert(LHS->getType() == RHS->getType());
1918   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1919          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1920
1921   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1922     return FC;          // Fold a few common cases...
1923
1924   // Look up the constant in the table first to ensure uniqueness
1925   std::vector<Constant*> ArgVec;
1926   ArgVec.push_back(LHS);
1927   ArgVec.push_back(RHS);
1928   // Get the key type with both the opcode and predicate
1929   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1930   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1931 }
1932
1933 Constant *
1934 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1935   assert(LHS->getType() == RHS->getType());
1936   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1937
1938   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1939     return FC;          // Fold a few common cases...
1940
1941   // Look up the constant in the table first to ensure uniqueness
1942   std::vector<Constant*> ArgVec;
1943   ArgVec.push_back(LHS);
1944   ArgVec.push_back(RHS);
1945   // Get the key type with both the opcode and predicate
1946   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1947   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1948 }
1949
1950 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1951                                             Constant *Idx) {
1952   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1953     return FC;          // Fold a few common cases...
1954   // Look up the constant in the table first to ensure uniqueness
1955   std::vector<Constant*> ArgVec(1, Val);
1956   ArgVec.push_back(Idx);
1957   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1958   return ExprConstants->getOrCreate(ReqTy, Key);
1959 }
1960
1961 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1962   assert(isa<VectorType>(Val->getType()) &&
1963          "Tried to create extractelement operation on non-vector type!");
1964   assert(Idx->getType() == Type::Int32Ty &&
1965          "Extractelement index must be i32 type!");
1966   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1967                              Val, Idx);
1968 }
1969
1970 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1971                                            Constant *Elt, Constant *Idx) {
1972   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1973     return FC;          // Fold a few common cases...
1974   // Look up the constant in the table first to ensure uniqueness
1975   std::vector<Constant*> ArgVec(1, Val);
1976   ArgVec.push_back(Elt);
1977   ArgVec.push_back(Idx);
1978   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1979   return ExprConstants->getOrCreate(ReqTy, Key);
1980 }
1981
1982 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1983                                          Constant *Idx) {
1984   assert(isa<VectorType>(Val->getType()) &&
1985          "Tried to create insertelement operation on non-vector type!");
1986   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1987          && "Insertelement types must match!");
1988   assert(Idx->getType() == Type::Int32Ty &&
1989          "Insertelement index must be i32 type!");
1990   return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1991                             Val, Elt, Idx);
1992 }
1993
1994 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1995                                            Constant *V2, Constant *Mask) {
1996   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1997     return FC;          // Fold a few common cases...
1998   // Look up the constant in the table first to ensure uniqueness
1999   std::vector<Constant*> ArgVec(1, V1);
2000   ArgVec.push_back(V2);
2001   ArgVec.push_back(Mask);
2002   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2003   return ExprConstants->getOrCreate(ReqTy, Key);
2004 }
2005
2006 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2007                                          Constant *Mask) {
2008   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2009          "Invalid shuffle vector constant expr operands!");
2010   return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2011 }
2012
2013 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2014   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2015     if (PTy->getElementType()->isFloatingPoint()) {
2016       std::vector<Constant*> zeros(PTy->getNumElements(),
2017                            ConstantFP::getNegativeZero(PTy->getElementType()));
2018       return ConstantVector::get(PTy, zeros);
2019     }
2020
2021   if (Ty->isFloatingPoint()) 
2022     return ConstantFP::getNegativeZero(Ty);
2023
2024   return Constant::getNullValue(Ty);
2025 }
2026
2027 // destroyConstant - Remove the constant from the constant table...
2028 //
2029 void ConstantExpr::destroyConstant() {
2030   ExprConstants->remove(this);
2031   destroyConstantImpl();
2032 }
2033
2034 const char *ConstantExpr::getOpcodeName() const {
2035   return Instruction::getOpcodeName(getOpcode());
2036 }
2037
2038 //===----------------------------------------------------------------------===//
2039 //                replaceUsesOfWithOnConstant implementations
2040
2041 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2042 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2043 /// etc.
2044 ///
2045 /// Note that we intentionally replace all uses of From with To here.  Consider
2046 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2047 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2048 /// single invocation handles all 1000 uses.  Handling them one at a time would
2049 /// work, but would be really slow because it would have to unique each updated
2050 /// array instance.
2051 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2052                                                 Use *U) {
2053   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2054   Constant *ToC = cast<Constant>(To);
2055
2056   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2057   Lookup.first.first = getType();
2058   Lookup.second = this;
2059
2060   std::vector<Constant*> &Values = Lookup.first.second;
2061   Values.reserve(getNumOperands());  // Build replacement array.
2062
2063   // Fill values with the modified operands of the constant array.  Also, 
2064   // compute whether this turns into an all-zeros array.
2065   bool isAllZeros = false;
2066   unsigned NumUpdated = 0;
2067   if (!ToC->isNullValue()) {
2068     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2069       Constant *Val = cast<Constant>(O->get());
2070       if (Val == From) {
2071         Val = ToC;
2072         ++NumUpdated;
2073       }
2074       Values.push_back(Val);
2075     }
2076   } else {
2077     isAllZeros = true;
2078     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2079       Constant *Val = cast<Constant>(O->get());
2080       if (Val == From) {
2081         Val = ToC;
2082         ++NumUpdated;
2083       }
2084       Values.push_back(Val);
2085       if (isAllZeros) isAllZeros = Val->isNullValue();
2086     }
2087   }
2088   
2089   Constant *Replacement = 0;
2090   if (isAllZeros) {
2091     Replacement = ConstantAggregateZero::get(getType());
2092   } else {
2093     // Check to see if we have this array type already.
2094     bool Exists;
2095     ArrayConstantsTy::MapTy::iterator I =
2096       ArrayConstants->InsertOrGetItem(Lookup, Exists);
2097     
2098     if (Exists) {
2099       Replacement = I->second;
2100     } else {
2101       // Okay, the new shape doesn't exist in the system yet.  Instead of
2102       // creating a new constant array, inserting it, replaceallusesof'ing the
2103       // old with the new, then deleting the old... just update the current one
2104       // in place!
2105       ArrayConstants->MoveConstantToNewSlot(this, I);
2106       
2107       // Update to the new value.  Optimize for the case when we have a single
2108       // operand that we're changing, but handle bulk updates efficiently.
2109       if (NumUpdated == 1) {
2110         unsigned OperandToUpdate = U-OperandList;
2111         assert(getOperand(OperandToUpdate) == From &&
2112                "ReplaceAllUsesWith broken!");
2113         setOperand(OperandToUpdate, ToC);
2114       } else {
2115         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2116           if (getOperand(i) == From)
2117             setOperand(i, ToC);
2118       }
2119       return;
2120     }
2121   }
2122  
2123   // Otherwise, I do need to replace this with an existing value.
2124   assert(Replacement != this && "I didn't contain From!");
2125   
2126   // Everyone using this now uses the replacement.
2127   uncheckedReplaceAllUsesWith(Replacement);
2128   
2129   // Delete the old constant!
2130   destroyConstant();
2131 }
2132
2133 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2134                                                  Use *U) {
2135   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2136   Constant *ToC = cast<Constant>(To);
2137
2138   unsigned OperandToUpdate = U-OperandList;
2139   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2140
2141   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2142   Lookup.first.first = getType();
2143   Lookup.second = this;
2144   std::vector<Constant*> &Values = Lookup.first.second;
2145   Values.reserve(getNumOperands());  // Build replacement struct.
2146   
2147   
2148   // Fill values with the modified operands of the constant struct.  Also, 
2149   // compute whether this turns into an all-zeros struct.
2150   bool isAllZeros = false;
2151   if (!ToC->isNullValue()) {
2152     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2153       Values.push_back(cast<Constant>(O->get()));
2154   } else {
2155     isAllZeros = true;
2156     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2157       Constant *Val = cast<Constant>(O->get());
2158       Values.push_back(Val);
2159       if (isAllZeros) isAllZeros = Val->isNullValue();
2160     }
2161   }
2162   Values[OperandToUpdate] = ToC;
2163   
2164   Constant *Replacement = 0;
2165   if (isAllZeros) {
2166     Replacement = ConstantAggregateZero::get(getType());
2167   } else {
2168     // Check to see if we have this array type already.
2169     bool Exists;
2170     StructConstantsTy::MapTy::iterator I =
2171       StructConstants->InsertOrGetItem(Lookup, Exists);
2172     
2173     if (Exists) {
2174       Replacement = I->second;
2175     } else {
2176       // Okay, the new shape doesn't exist in the system yet.  Instead of
2177       // creating a new constant struct, inserting it, replaceallusesof'ing the
2178       // old with the new, then deleting the old... just update the current one
2179       // in place!
2180       StructConstants->MoveConstantToNewSlot(this, I);
2181       
2182       // Update to the new value.
2183       setOperand(OperandToUpdate, ToC);
2184       return;
2185     }
2186   }
2187   
2188   assert(Replacement != this && "I didn't contain From!");
2189   
2190   // Everyone using this now uses the replacement.
2191   uncheckedReplaceAllUsesWith(Replacement);
2192   
2193   // Delete the old constant!
2194   destroyConstant();
2195 }
2196
2197 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2198                                                  Use *U) {
2199   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2200   
2201   std::vector<Constant*> Values;
2202   Values.reserve(getNumOperands());  // Build replacement array...
2203   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2204     Constant *Val = getOperand(i);
2205     if (Val == From) Val = cast<Constant>(To);
2206     Values.push_back(Val);
2207   }
2208   
2209   Constant *Replacement = ConstantVector::get(getType(), Values);
2210   assert(Replacement != this && "I didn't contain From!");
2211   
2212   // Everyone using this now uses the replacement.
2213   uncheckedReplaceAllUsesWith(Replacement);
2214   
2215   // Delete the old constant!
2216   destroyConstant();
2217 }
2218
2219 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2220                                                Use *U) {
2221   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2222   Constant *To = cast<Constant>(ToV);
2223   
2224   Constant *Replacement = 0;
2225   if (getOpcode() == Instruction::GetElementPtr) {
2226     SmallVector<Constant*, 8> Indices;
2227     Constant *Pointer = getOperand(0);
2228     Indices.reserve(getNumOperands()-1);
2229     if (Pointer == From) Pointer = To;
2230     
2231     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2232       Constant *Val = getOperand(i);
2233       if (Val == From) Val = To;
2234       Indices.push_back(Val);
2235     }
2236     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2237                                                  &Indices[0], Indices.size());
2238   } else if (isCast()) {
2239     assert(getOperand(0) == From && "Cast only has one use!");
2240     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2241   } else if (getOpcode() == Instruction::Select) {
2242     Constant *C1 = getOperand(0);
2243     Constant *C2 = getOperand(1);
2244     Constant *C3 = getOperand(2);
2245     if (C1 == From) C1 = To;
2246     if (C2 == From) C2 = To;
2247     if (C3 == From) C3 = To;
2248     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2249   } else if (getOpcode() == Instruction::ExtractElement) {
2250     Constant *C1 = getOperand(0);
2251     Constant *C2 = getOperand(1);
2252     if (C1 == From) C1 = To;
2253     if (C2 == From) C2 = To;
2254     Replacement = ConstantExpr::getExtractElement(C1, C2);
2255   } else if (getOpcode() == Instruction::InsertElement) {
2256     Constant *C1 = getOperand(0);
2257     Constant *C2 = getOperand(1);
2258     Constant *C3 = getOperand(1);
2259     if (C1 == From) C1 = To;
2260     if (C2 == From) C2 = To;
2261     if (C3 == From) C3 = To;
2262     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2263   } else if (getOpcode() == Instruction::ShuffleVector) {
2264     Constant *C1 = getOperand(0);
2265     Constant *C2 = getOperand(1);
2266     Constant *C3 = getOperand(2);
2267     if (C1 == From) C1 = To;
2268     if (C2 == From) C2 = To;
2269     if (C3 == From) C3 = To;
2270     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2271   } else if (isCompare()) {
2272     Constant *C1 = getOperand(0);
2273     Constant *C2 = getOperand(1);
2274     if (C1 == From) C1 = To;
2275     if (C2 == From) C2 = To;
2276     if (getOpcode() == Instruction::ICmp)
2277       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2278     else
2279       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2280   } else if (getNumOperands() == 2) {
2281     Constant *C1 = getOperand(0);
2282     Constant *C2 = getOperand(1);
2283     if (C1 == From) C1 = To;
2284     if (C2 == From) C2 = To;
2285     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2286   } else {
2287     assert(0 && "Unknown ConstantExpr type!");
2288     return;
2289   }
2290   
2291   assert(Replacement != this && "I didn't contain From!");
2292   
2293   // Everyone using this now uses the replacement.
2294   uncheckedReplaceAllUsesWith(Replacement);
2295   
2296   // Delete the old constant!
2297   destroyConstant();
2298 }
2299
2300
2301 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2302 /// global into a string value.  Return an empty string if we can't do it.
2303 /// Parameter Chop determines if the result is chopped at the first null
2304 /// terminator.
2305 ///
2306 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2307   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2308     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2309       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2310       if (Init->isString()) {
2311         std::string Result = Init->getAsString();
2312         if (Offset < Result.size()) {
2313           // If we are pointing INTO The string, erase the beginning...
2314           Result.erase(Result.begin(), Result.begin()+Offset);
2315
2316           // Take off the null terminator, and any string fragments after it.
2317           if (Chop) {
2318             std::string::size_type NullPos = Result.find_first_of((char)0);
2319             if (NullPos != std::string::npos)
2320               Result.erase(Result.begin()+NullPos, Result.end());
2321           }
2322           return Result;
2323         }
2324       }
2325     }
2326   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2327     if (CE->getOpcode() == Instruction::GetElementPtr) {
2328       // Turn a gep into the specified offset.
2329       if (CE->getNumOperands() == 3 &&
2330           cast<Constant>(CE->getOperand(1))->isNullValue() &&
2331           isa<ConstantInt>(CE->getOperand(2))) {
2332         Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2333         return CE->getOperand(0)->getStringValue(Chop, Offset);
2334       }
2335     }
2336   }
2337   return "";
2338 }