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