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