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