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