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