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