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