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