make the constantexpr interfaces for inbounds GEPs follow the same style
[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 // Utility function for determining if a ConstantExpr is a CastOp or not. This
643 // can't be inline because we don't want to #include Instruction.h into
644 // Constant.h
645 bool ConstantExpr::isCast() const {
646   return Instruction::isCast(getOpcode());
647 }
648
649 bool ConstantExpr::isCompare() const {
650   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
651 }
652
653 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
654   if (getOpcode() != Instruction::GetElementPtr) return false;
655
656   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
657   User::const_op_iterator OI = llvm::next(this->op_begin());
658
659   // Skip the first index, as it has no static limit.
660   ++GEPI;
661   ++OI;
662
663   // The remaining indices must be compile-time known integers within the
664   // bounds of the corresponding notional static array types.
665   for (; GEPI != E; ++GEPI, ++OI) {
666     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
667     if (!CI) return false;
668     if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
669       if (CI->getValue().getActiveBits() > 64 ||
670           CI->getZExtValue() >= ATy->getNumElements())
671         return false;
672   }
673
674   // All the indices checked out.
675   return true;
676 }
677
678 bool ConstantExpr::hasIndices() const {
679   return getOpcode() == Instruction::ExtractValue ||
680          getOpcode() == Instruction::InsertValue;
681 }
682
683 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
684   if (const ExtractValueConstantExpr *EVCE =
685         dyn_cast<ExtractValueConstantExpr>(this))
686     return EVCE->Indices;
687
688   return cast<InsertValueConstantExpr>(this)->Indices;
689 }
690
691 unsigned ConstantExpr::getPredicate() const {
692   assert(getOpcode() == Instruction::FCmp || 
693          getOpcode() == Instruction::ICmp);
694   return ((const CompareConstantExpr*)this)->predicate;
695 }
696
697 /// getWithOperandReplaced - Return a constant expression identical to this
698 /// one, but with the specified operand set to the specified value.
699 Constant *
700 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
701   assert(OpNo < getNumOperands() && "Operand num is out of range!");
702   assert(Op->getType() == getOperand(OpNo)->getType() &&
703          "Replacing operand with value of different type!");
704   if (getOperand(OpNo) == Op)
705     return const_cast<ConstantExpr*>(this);
706   
707   Constant *Op0, *Op1, *Op2;
708   switch (getOpcode()) {
709   case Instruction::Trunc:
710   case Instruction::ZExt:
711   case Instruction::SExt:
712   case Instruction::FPTrunc:
713   case Instruction::FPExt:
714   case Instruction::UIToFP:
715   case Instruction::SIToFP:
716   case Instruction::FPToUI:
717   case Instruction::FPToSI:
718   case Instruction::PtrToInt:
719   case Instruction::IntToPtr:
720   case Instruction::BitCast:
721     return ConstantExpr::getCast(getOpcode(), Op, getType());
722   case Instruction::Select:
723     Op0 = (OpNo == 0) ? Op : getOperand(0);
724     Op1 = (OpNo == 1) ? Op : getOperand(1);
725     Op2 = (OpNo == 2) ? Op : getOperand(2);
726     return ConstantExpr::getSelect(Op0, Op1, Op2);
727   case Instruction::InsertElement:
728     Op0 = (OpNo == 0) ? Op : getOperand(0);
729     Op1 = (OpNo == 1) ? Op : getOperand(1);
730     Op2 = (OpNo == 2) ? Op : getOperand(2);
731     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
732   case Instruction::ExtractElement:
733     Op0 = (OpNo == 0) ? Op : getOperand(0);
734     Op1 = (OpNo == 1) ? Op : getOperand(1);
735     return ConstantExpr::getExtractElement(Op0, Op1);
736   case Instruction::ShuffleVector:
737     Op0 = (OpNo == 0) ? Op : getOperand(0);
738     Op1 = (OpNo == 1) ? Op : getOperand(1);
739     Op2 = (OpNo == 2) ? Op : getOperand(2);
740     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
741   case Instruction::GetElementPtr: {
742     SmallVector<Constant*, 8> Ops;
743     Ops.resize(getNumOperands()-1);
744     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
745       Ops[i-1] = getOperand(i);
746     if (OpNo == 0)
747       return cast<GEPOperator>(this)->isInBounds() ?
748         ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
749         ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
750     Ops[OpNo-1] = Op;
751     return cast<GEPOperator>(this)->isInBounds() ?
752       ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
753       ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
754   }
755   default:
756     assert(getNumOperands() == 2 && "Must be binary operator?");
757     Op0 = (OpNo == 0) ? Op : getOperand(0);
758     Op1 = (OpNo == 1) ? Op : getOperand(1);
759     return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
760   }
761 }
762
763 /// getWithOperands - This returns the current constant expression with the
764 /// operands replaced with the specified values.  The specified operands must
765 /// match count and type with the existing ones.
766 Constant *ConstantExpr::
767 getWithOperands(Constant *const *Ops, unsigned NumOps) const {
768   assert(NumOps == getNumOperands() && "Operand count mismatch!");
769   bool AnyChange = false;
770   for (unsigned i = 0; i != NumOps; ++i) {
771     assert(Ops[i]->getType() == getOperand(i)->getType() &&
772            "Operand type mismatch!");
773     AnyChange |= Ops[i] != getOperand(i);
774   }
775   if (!AnyChange)  // No operands changed, return self.
776     return const_cast<ConstantExpr*>(this);
777
778   switch (getOpcode()) {
779   case Instruction::Trunc:
780   case Instruction::ZExt:
781   case Instruction::SExt:
782   case Instruction::FPTrunc:
783   case Instruction::FPExt:
784   case Instruction::UIToFP:
785   case Instruction::SIToFP:
786   case Instruction::FPToUI:
787   case Instruction::FPToSI:
788   case Instruction::PtrToInt:
789   case Instruction::IntToPtr:
790   case Instruction::BitCast:
791     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
792   case Instruction::Select:
793     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
794   case Instruction::InsertElement:
795     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
796   case Instruction::ExtractElement:
797     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
798   case Instruction::ShuffleVector:
799     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
800   case Instruction::GetElementPtr:
801     return cast<GEPOperator>(this)->isInBounds() ?
802       ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
803       ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
804   case Instruction::ICmp:
805   case Instruction::FCmp:
806     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
807   default:
808     assert(getNumOperands() == 2 && "Must be binary operator?");
809     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
810   }
811 }
812
813
814 //===----------------------------------------------------------------------===//
815 //                      isValueValidForType implementations
816
817 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
818   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
819   if (Ty == Type::getInt1Ty(Ty->getContext()))
820     return Val == 0 || Val == 1;
821   if (NumBits >= 64)
822     return true; // always true, has to fit in largest type
823   uint64_t Max = (1ll << NumBits) - 1;
824   return Val <= Max;
825 }
826
827 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
828   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
829   if (Ty == Type::getInt1Ty(Ty->getContext()))
830     return Val == 0 || Val == 1 || Val == -1;
831   if (NumBits >= 64)
832     return true; // always true, has to fit in largest type
833   int64_t Min = -(1ll << (NumBits-1));
834   int64_t Max = (1ll << (NumBits-1)) - 1;
835   return (Val >= Min && Val <= Max);
836 }
837
838 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
839   // convert modifies in place, so make a copy.
840   APFloat Val2 = APFloat(Val);
841   bool losesInfo;
842   switch (Ty->getTypeID()) {
843   default:
844     return false;         // These can't be represented as floating point!
845
846   // FIXME rounding mode needs to be more flexible
847   case Type::FloatTyID: {
848     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
849       return true;
850     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
851     return !losesInfo;
852   }
853   case Type::DoubleTyID: {
854     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
855         &Val2.getSemantics() == &APFloat::IEEEdouble)
856       return true;
857     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
858     return !losesInfo;
859   }
860   case Type::X86_FP80TyID:
861     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
862            &Val2.getSemantics() == &APFloat::IEEEdouble ||
863            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
864   case Type::FP128TyID:
865     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
866            &Val2.getSemantics() == &APFloat::IEEEdouble ||
867            &Val2.getSemantics() == &APFloat::IEEEquad;
868   case Type::PPC_FP128TyID:
869     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
870            &Val2.getSemantics() == &APFloat::IEEEdouble ||
871            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
872   }
873 }
874
875 //===----------------------------------------------------------------------===//
876 //                      Factory Function Implementation
877
878 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
879   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
880          "Cannot create an aggregate zero of non-aggregate type!");
881   
882   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
883   return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
884 }
885
886 /// destroyConstant - Remove the constant from the constant table...
887 ///
888 void ConstantAggregateZero::destroyConstant() {
889   getRawType()->getContext().pImpl->AggZeroConstants.remove(this);
890   destroyConstantImpl();
891 }
892
893 /// destroyConstant - Remove the constant from the constant table...
894 ///
895 void ConstantArray::destroyConstant() {
896   getRawType()->getContext().pImpl->ArrayConstants.remove(this);
897   destroyConstantImpl();
898 }
899
900 /// isString - This method returns true if the array is an array of i8, and 
901 /// if the elements of the array are all ConstantInt's.
902 bool ConstantArray::isString() const {
903   // Check the element type for i8...
904   if (!getType()->getElementType()->isIntegerTy(8))
905     return false;
906   // Check the elements to make sure they are all integers, not constant
907   // expressions.
908   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
909     if (!isa<ConstantInt>(getOperand(i)))
910       return false;
911   return true;
912 }
913
914 /// isCString - This method returns true if the array is a string (see
915 /// isString) and it ends in a null byte \\0 and does not contains any other
916 /// null bytes except its terminator.
917 bool ConstantArray::isCString() const {
918   // Check the element type for i8...
919   if (!getType()->getElementType()->isIntegerTy(8))
920     return false;
921
922   // Last element must be a null.
923   if (!getOperand(getNumOperands()-1)->isNullValue())
924     return false;
925   // Other elements must be non-null integers.
926   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
927     if (!isa<ConstantInt>(getOperand(i)))
928       return false;
929     if (getOperand(i)->isNullValue())
930       return false;
931   }
932   return true;
933 }
934
935
936 /// getAsString - If the sub-element type of this array is i8
937 /// then this method converts the array to an std::string and returns it.
938 /// Otherwise, it asserts out.
939 ///
940 std::string ConstantArray::getAsString() const {
941   assert(isString() && "Not a string!");
942   std::string Result;
943   Result.reserve(getNumOperands());
944   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
945     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
946   return Result;
947 }
948
949
950 //---- ConstantStruct::get() implementation...
951 //
952
953 namespace llvm {
954
955 }
956
957 // destroyConstant - Remove the constant from the constant table...
958 //
959 void ConstantStruct::destroyConstant() {
960   getRawType()->getContext().pImpl->StructConstants.remove(this);
961   destroyConstantImpl();
962 }
963
964 // destroyConstant - Remove the constant from the constant table...
965 //
966 void ConstantVector::destroyConstant() {
967   getRawType()->getContext().pImpl->VectorConstants.remove(this);
968   destroyConstantImpl();
969 }
970
971 /// This function will return true iff every element in this vector constant
972 /// is set to all ones.
973 /// @returns true iff this constant's emements are all set to all ones.
974 /// @brief Determine if the value is all ones.
975 bool ConstantVector::isAllOnesValue() const {
976   // Check out first element.
977   const Constant *Elt = getOperand(0);
978   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
979   if (!CI || !CI->isAllOnesValue()) return false;
980   // Then make sure all remaining elements point to the same value.
981   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
982     if (getOperand(I) != Elt) return false;
983   }
984   return true;
985 }
986
987 /// getSplatValue - If this is a splat constant, where all of the
988 /// elements have the same value, return that value. Otherwise return null.
989 Constant *ConstantVector::getSplatValue() const {
990   // Check out first element.
991   Constant *Elt = getOperand(0);
992   // Then make sure all remaining elements point to the same value.
993   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
994     if (getOperand(I) != Elt) return 0;
995   return Elt;
996 }
997
998 //---- ConstantPointerNull::get() implementation.
999 //
1000
1001 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1002   return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1003 }
1004
1005 // destroyConstant - Remove the constant from the constant table...
1006 //
1007 void ConstantPointerNull::destroyConstant() {
1008   getRawType()->getContext().pImpl->NullPtrConstants.remove(this);
1009   destroyConstantImpl();
1010 }
1011
1012
1013 //---- UndefValue::get() implementation.
1014 //
1015
1016 UndefValue *UndefValue::get(const Type *Ty) {
1017   return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1018 }
1019
1020 // destroyConstant - Remove the constant from the constant table.
1021 //
1022 void UndefValue::destroyConstant() {
1023   getRawType()->getContext().pImpl->UndefValueConstants.remove(this);
1024   destroyConstantImpl();
1025 }
1026
1027 //---- BlockAddress::get() implementation.
1028 //
1029
1030 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1031   assert(BB->getParent() != 0 && "Block must have a parent");
1032   return get(BB->getParent(), BB);
1033 }
1034
1035 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1036   BlockAddress *&BA =
1037     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1038   if (BA == 0)
1039     BA = new BlockAddress(F, BB);
1040   
1041   assert(BA->getFunction() == F && "Basic block moved between functions");
1042   return BA;
1043 }
1044
1045 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1046 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1047            &Op<0>(), 2) {
1048   setOperand(0, F);
1049   setOperand(1, BB);
1050   BB->AdjustBlockAddressRefCount(1);
1051 }
1052
1053
1054 // destroyConstant - Remove the constant from the constant table.
1055 //
1056 void BlockAddress::destroyConstant() {
1057   getFunction()->getRawType()->getContext().pImpl
1058     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1059   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1060   destroyConstantImpl();
1061 }
1062
1063 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1064   // This could be replacing either the Basic Block or the Function.  In either
1065   // case, we have to remove the map entry.
1066   Function *NewF = getFunction();
1067   BasicBlock *NewBB = getBasicBlock();
1068   
1069   if (U == &Op<0>())
1070     NewF = cast<Function>(To);
1071   else
1072     NewBB = cast<BasicBlock>(To);
1073   
1074   // See if the 'new' entry already exists, if not, just update this in place
1075   // and return early.
1076   BlockAddress *&NewBA =
1077     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1078   if (NewBA == 0) {
1079     getBasicBlock()->AdjustBlockAddressRefCount(-1);
1080     
1081     // Remove the old entry, this can't cause the map to rehash (just a
1082     // tombstone will get added).
1083     getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1084                                                             getBasicBlock()));
1085     NewBA = this;
1086     setOperand(0, NewF);
1087     setOperand(1, NewBB);
1088     getBasicBlock()->AdjustBlockAddressRefCount(1);
1089     return;
1090   }
1091
1092   // Otherwise, I do need to replace this with an existing value.
1093   assert(NewBA != this && "I didn't contain From!");
1094   
1095   // Everyone using this now uses the replacement.
1096   uncheckedReplaceAllUsesWith(NewBA);
1097   
1098   destroyConstant();
1099 }
1100
1101 //---- ConstantExpr::get() implementations.
1102 //
1103
1104 /// This is a utility function to handle folding of casts and lookup of the
1105 /// cast in the ExprConstants map. It is used by the various get* methods below.
1106 static inline Constant *getFoldedCast(
1107   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1108   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1109   // Fold a few common cases
1110   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1111     return FC;
1112
1113   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1114
1115   // Look up the constant in the table first to ensure uniqueness
1116   std::vector<Constant*> argVec(1, C);
1117   ExprMapKeyType Key(opc, argVec);
1118   
1119   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1120 }
1121  
1122 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1123   Instruction::CastOps opc = Instruction::CastOps(oc);
1124   assert(Instruction::isCast(opc) && "opcode out of range");
1125   assert(C && Ty && "Null arguments to getCast");
1126   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1127
1128   switch (opc) {
1129   default:
1130     llvm_unreachable("Invalid cast opcode");
1131     break;
1132   case Instruction::Trunc:    return getTrunc(C, Ty);
1133   case Instruction::ZExt:     return getZExt(C, Ty);
1134   case Instruction::SExt:     return getSExt(C, Ty);
1135   case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1136   case Instruction::FPExt:    return getFPExtend(C, Ty);
1137   case Instruction::UIToFP:   return getUIToFP(C, Ty);
1138   case Instruction::SIToFP:   return getSIToFP(C, Ty);
1139   case Instruction::FPToUI:   return getFPToUI(C, Ty);
1140   case Instruction::FPToSI:   return getFPToSI(C, Ty);
1141   case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1142   case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1143   case Instruction::BitCast:  return getBitCast(C, Ty);
1144   }
1145   return 0;
1146
1147
1148 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1149   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1150     return getBitCast(C, Ty);
1151   return getZExt(C, Ty);
1152 }
1153
1154 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1155   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1156     return getBitCast(C, Ty);
1157   return getSExt(C, Ty);
1158 }
1159
1160 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1161   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1162     return getBitCast(C, Ty);
1163   return getTrunc(C, Ty);
1164 }
1165
1166 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1167   assert(S->getType()->isPointerTy() && "Invalid cast");
1168   assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1169
1170   if (Ty->isIntegerTy())
1171     return getPtrToInt(S, Ty);
1172   return getBitCast(S, Ty);
1173 }
1174
1175 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1176                                        bool isSigned) {
1177   assert(C->getType()->isIntOrIntVectorTy() &&
1178          Ty->isIntOrIntVectorTy() && "Invalid cast");
1179   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1180   unsigned DstBits = Ty->getScalarSizeInBits();
1181   Instruction::CastOps opcode =
1182     (SrcBits == DstBits ? Instruction::BitCast :
1183      (SrcBits > DstBits ? Instruction::Trunc :
1184       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1185   return getCast(opcode, C, Ty);
1186 }
1187
1188 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1189   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1190          "Invalid cast");
1191   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1192   unsigned DstBits = Ty->getScalarSizeInBits();
1193   if (SrcBits == DstBits)
1194     return C; // Avoid a useless cast
1195   Instruction::CastOps opcode =
1196     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1197   return getCast(opcode, C, Ty);
1198 }
1199
1200 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1201 #ifndef NDEBUG
1202   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1203   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1204 #endif
1205   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1206   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1207   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1208   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1209          "SrcTy must be larger than DestTy for Trunc!");
1210
1211   return getFoldedCast(Instruction::Trunc, C, Ty);
1212 }
1213
1214 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1215 #ifndef NDEBUG
1216   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1217   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1218 #endif
1219   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1220   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1221   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1222   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1223          "SrcTy must be smaller than DestTy for SExt!");
1224
1225   return getFoldedCast(Instruction::SExt, C, Ty);
1226 }
1227
1228 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1229 #ifndef NDEBUG
1230   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1231   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1232 #endif
1233   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1234   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1235   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1236   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1237          "SrcTy must be smaller than DestTy for ZExt!");
1238
1239   return getFoldedCast(Instruction::ZExt, C, Ty);
1240 }
1241
1242 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1243 #ifndef NDEBUG
1244   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1245   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1246 #endif
1247   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1248   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1249          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1250          "This is an illegal floating point truncation!");
1251   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1252 }
1253
1254 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1255 #ifndef NDEBUG
1256   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1257   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1258 #endif
1259   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1260   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1261          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1262          "This is an illegal floating point extension!");
1263   return getFoldedCast(Instruction::FPExt, C, Ty);
1264 }
1265
1266 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1267 #ifndef NDEBUG
1268   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1269   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1270 #endif
1271   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1272   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1273          "This is an illegal uint to floating point cast!");
1274   return getFoldedCast(Instruction::UIToFP, C, Ty);
1275 }
1276
1277 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1278 #ifndef NDEBUG
1279   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1280   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1281 #endif
1282   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1283   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1284          "This is an illegal sint to floating point cast!");
1285   return getFoldedCast(Instruction::SIToFP, C, Ty);
1286 }
1287
1288 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1289 #ifndef NDEBUG
1290   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1291   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1292 #endif
1293   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1294   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1295          "This is an illegal floating point to uint cast!");
1296   return getFoldedCast(Instruction::FPToUI, C, Ty);
1297 }
1298
1299 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1300 #ifndef NDEBUG
1301   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1302   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1303 #endif
1304   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1305   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1306          "This is an illegal floating point to sint cast!");
1307   return getFoldedCast(Instruction::FPToSI, C, Ty);
1308 }
1309
1310 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1311   assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1312   assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1313   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1314 }
1315
1316 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1317   assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1318   assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1319   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1320 }
1321
1322 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1323   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1324          "Invalid constantexpr bitcast!");
1325   
1326   // It is common to ask for a bitcast of a value to its own type, handle this
1327   // speedily.
1328   if (C->getType() == DstTy) return C;
1329   
1330   return getFoldedCast(Instruction::BitCast, C, DstTy);
1331 }
1332
1333 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1334                               Constant *C1, Constant *C2,
1335                               unsigned Flags) {
1336   // Check the operands for consistency first
1337   assert(Opcode >= Instruction::BinaryOpsBegin &&
1338          Opcode <  Instruction::BinaryOpsEnd   &&
1339          "Invalid opcode in binary constant expression");
1340   assert(C1->getType() == C2->getType() &&
1341          "Operand types in binary constant expression should match");
1342
1343   if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1344     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1345       return FC;          // Fold a few common cases...
1346
1347   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1348   ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1349   
1350   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1351   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1352 }
1353
1354 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1355                                      Constant *C1, Constant *C2) {
1356   switch (predicate) {
1357     default: llvm_unreachable("Invalid CmpInst predicate");
1358     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1359     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1360     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1361     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1362     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1363     case CmpInst::FCMP_TRUE:
1364       return getFCmp(predicate, C1, C2);
1365
1366     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1367     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1368     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1369     case CmpInst::ICMP_SLE:
1370       return getICmp(predicate, C1, C2);
1371   }
1372 }
1373
1374 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1375                             unsigned Flags) {
1376 #ifndef NDEBUG
1377   switch (Opcode) {
1378   case Instruction::Add:
1379   case Instruction::Sub:
1380   case Instruction::Mul:
1381     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1382     assert(C1->getType()->isIntOrIntVectorTy() &&
1383            "Tried to create an integer operation on a non-integer type!");
1384     break;
1385   case Instruction::FAdd:
1386   case Instruction::FSub:
1387   case Instruction::FMul:
1388     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1389     assert(C1->getType()->isFPOrFPVectorTy() &&
1390            "Tried to create a floating-point operation on a "
1391            "non-floating-point type!");
1392     break;
1393   case Instruction::UDiv: 
1394   case Instruction::SDiv: 
1395     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1396     assert(C1->getType()->isIntOrIntVectorTy() &&
1397            "Tried to create an arithmetic operation on a non-arithmetic type!");
1398     break;
1399   case Instruction::FDiv:
1400     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1401     assert(C1->getType()->isFPOrFPVectorTy() &&
1402            "Tried to create an arithmetic operation on a non-arithmetic type!");
1403     break;
1404   case Instruction::URem: 
1405   case Instruction::SRem: 
1406     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1407     assert(C1->getType()->isIntOrIntVectorTy() &&
1408            "Tried to create an arithmetic operation on a non-arithmetic type!");
1409     break;
1410   case Instruction::FRem:
1411     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1412     assert(C1->getType()->isFPOrFPVectorTy() &&
1413            "Tried to create an arithmetic operation on a non-arithmetic type!");
1414     break;
1415   case Instruction::And:
1416   case Instruction::Or:
1417   case Instruction::Xor:
1418     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1419     assert(C1->getType()->isIntOrIntVectorTy() &&
1420            "Tried to create a logical operation on a non-integral type!");
1421     break;
1422   case Instruction::Shl:
1423   case Instruction::LShr:
1424   case Instruction::AShr:
1425     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1426     assert(C1->getType()->isIntOrIntVectorTy() &&
1427            "Tried to create a shift operation on a non-integer type!");
1428     break;
1429   default:
1430     break;
1431   }
1432 #endif
1433
1434   return getTy(C1->getType(), Opcode, C1, C2, Flags);
1435 }
1436
1437 Constant *ConstantExpr::getSizeOf(const Type* Ty) {
1438   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1439   // Note that a non-inbounds gep is used, as null isn't within any object.
1440   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1441   Constant *GEP = getGetElementPtr(
1442                  Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1443   return getPtrToInt(GEP, 
1444                      Type::getInt64Ty(Ty->getContext()));
1445 }
1446
1447 Constant *ConstantExpr::getAlignOf(const Type* Ty) {
1448   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1449   // Note that a non-inbounds gep is used, as null isn't within any object.
1450   const Type *AligningTy = StructType::get(Ty->getContext(),
1451                                    Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1452   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1453   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1454   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1455   Constant *Indices[2] = { Zero, One };
1456   Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1457   return getPtrToInt(GEP,
1458                      Type::getInt64Ty(Ty->getContext()));
1459 }
1460
1461 Constant *ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1462   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1463                                            FieldNo));
1464 }
1465
1466 Constant *ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1467   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1468   // Note that a non-inbounds gep is used, as null isn't within any object.
1469   Constant *GEPIdx[] = {
1470     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1471     FieldNo
1472   };
1473   Constant *GEP = getGetElementPtr(
1474                 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1475   return getPtrToInt(GEP,
1476                      Type::getInt64Ty(Ty->getContext()));
1477 }
1478
1479 Constant *ConstantExpr::getCompare(unsigned short pred, 
1480                             Constant *C1, Constant *C2) {
1481   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482   return getCompareTy(pred, C1, C2);
1483 }
1484
1485 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1486                                     Constant *V1, Constant *V2) {
1487   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1488
1489   if (ReqTy == V1->getType())
1490     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1491       return SC;        // Fold common cases
1492
1493   std::vector<Constant*> argVec(3, C);
1494   argVec[1] = V1;
1495   argVec[2] = V2;
1496   ExprMapKeyType Key(Instruction::Select, argVec);
1497   
1498   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1499   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1500 }
1501
1502 template<typename IndexTy>
1503 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1504                                            IndexTy const *Idxs,
1505                                            unsigned NumIdx, bool InBounds) {
1506   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1507                                            Idxs+NumIdx) ==
1508          cast<PointerType>(ReqTy)->getElementType() &&
1509          "GEP indices invalid!");
1510
1511   if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1512     return FC;          // Fold a few common cases.
1513
1514   assert(C->getType()->isPointerTy() &&
1515          "Non-pointer type for constant GetElementPtr expression");
1516   // Look up the constant in the table first to ensure uniqueness
1517   std::vector<Constant*> ArgVec;
1518   ArgVec.reserve(NumIdx+1);
1519   ArgVec.push_back(C);
1520   for (unsigned i = 0; i != NumIdx; ++i)
1521     ArgVec.push_back(cast<Constant>(Idxs[i]));
1522   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1523                            InBounds ? GEPOperator::IsInBounds : 0);
1524
1525   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1526   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1527 }
1528
1529 template<typename IndexTy>
1530 Constant *ConstantExpr::getGetElementPtrImpl(Constant *C, IndexTy const *Idxs,
1531                                              unsigned NumIdx, bool InBounds) {
1532   // Get the result type of the getelementptr!
1533   const Type *Ty = 
1534     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1535   assert(Ty && "GEP indices invalid!");
1536   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1537   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx,InBounds);
1538 }
1539
1540 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1541                                          unsigned NumIdx, bool InBounds) {
1542   return getGetElementPtrImpl(C, Idxs, NumIdx, InBounds);
1543 }
1544
1545 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant *const *Idxs,
1546                                          unsigned NumIdx, bool InBounds) {
1547   return getGetElementPtrImpl(C, Idxs, NumIdx, InBounds);
1548 }
1549
1550 Constant *
1551 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1552   assert(LHS->getType() == RHS->getType());
1553   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1554          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1555
1556   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1557     return FC;          // Fold a few common cases...
1558
1559   // Look up the constant in the table first to ensure uniqueness
1560   std::vector<Constant*> ArgVec;
1561   ArgVec.push_back(LHS);
1562   ArgVec.push_back(RHS);
1563   // Get the key type with both the opcode and predicate
1564   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1565
1566   const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1567   if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1568     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1569
1570   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1571   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1572 }
1573
1574 Constant *
1575 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1576   assert(LHS->getType() == RHS->getType());
1577   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1578
1579   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1580     return FC;          // Fold a few common cases...
1581
1582   // Look up the constant in the table first to ensure uniqueness
1583   std::vector<Constant*> ArgVec;
1584   ArgVec.push_back(LHS);
1585   ArgVec.push_back(RHS);
1586   // Get the key type with both the opcode and predicate
1587   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1588
1589   const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1590   if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1591     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1592
1593   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1594   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1595 }
1596
1597 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1598                                             Constant *Idx) {
1599   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1600     return FC;          // Fold a few common cases.
1601   // Look up the constant in the table first to ensure uniqueness
1602   std::vector<Constant*> ArgVec(1, Val);
1603   ArgVec.push_back(Idx);
1604   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1605   
1606   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1607   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1608 }
1609
1610 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1611   assert(Val->getType()->isVectorTy() &&
1612          "Tried to create extractelement operation on non-vector type!");
1613   assert(Idx->getType()->isIntegerTy(32) &&
1614          "Extractelement index must be i32 type!");
1615   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1616                              Val, Idx);
1617 }
1618
1619 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1620                                            Constant *Elt, Constant *Idx) {
1621   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1622     return FC;          // Fold a few common cases.
1623   // Look up the constant in the table first to ensure uniqueness
1624   std::vector<Constant*> ArgVec(1, Val);
1625   ArgVec.push_back(Elt);
1626   ArgVec.push_back(Idx);
1627   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1628   
1629   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1630   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1631 }
1632
1633 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1634                                          Constant *Idx) {
1635   assert(Val->getType()->isVectorTy() &&
1636          "Tried to create insertelement operation on non-vector type!");
1637   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1638          && "Insertelement types must match!");
1639   assert(Idx->getType()->isIntegerTy(32) &&
1640          "Insertelement index must be i32 type!");
1641   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1642 }
1643
1644 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1645                                            Constant *V2, Constant *Mask) {
1646   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1647     return FC;          // Fold a few common cases...
1648   // Look up the constant in the table first to ensure uniqueness
1649   std::vector<Constant*> ArgVec(1, V1);
1650   ArgVec.push_back(V2);
1651   ArgVec.push_back(Mask);
1652   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1653   
1654   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1655   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1656 }
1657
1658 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1659                                          Constant *Mask) {
1660   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1661          "Invalid shuffle vector constant expr operands!");
1662
1663   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1664   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1665   const Type *ShufTy = VectorType::get(EltTy, NElts);
1666   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1667 }
1668
1669 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1670                                          Constant *Val,
1671                                         const unsigned *Idxs, unsigned NumIdx) {
1672   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1673                                           Idxs+NumIdx) == Val->getType() &&
1674          "insertvalue indices invalid!");
1675   assert(Agg->getType() == ReqTy &&
1676          "insertvalue type invalid!");
1677   assert(Agg->getType()->isFirstClassType() &&
1678          "Non-first-class type for constant InsertValue expression");
1679   Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
1680   assert(FC && "InsertValue constant expr couldn't be folded!");
1681   return FC;
1682 }
1683
1684 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1685                                      const unsigned *IdxList, unsigned NumIdx) {
1686   assert(Agg->getType()->isFirstClassType() &&
1687          "Tried to create insertelement operation on non-first-class type!");
1688
1689   const Type *ReqTy = Agg->getType();
1690 #ifndef NDEBUG
1691   const Type *ValTy =
1692     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1693 #endif
1694   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1695   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1696 }
1697
1698 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1699                                         const unsigned *Idxs, unsigned NumIdx) {
1700   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1701                                           Idxs+NumIdx) == ReqTy &&
1702          "extractvalue indices invalid!");
1703   assert(Agg->getType()->isFirstClassType() &&
1704          "Non-first-class type for constant extractvalue expression");
1705   Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
1706   assert(FC && "ExtractValue constant expr couldn't be folded!");
1707   return FC;
1708 }
1709
1710 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1711                                      const unsigned *IdxList, unsigned NumIdx) {
1712   assert(Agg->getType()->isFirstClassType() &&
1713          "Tried to create extractelement operation on non-first-class type!");
1714
1715   const Type *ReqTy =
1716     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1717   assert(ReqTy && "extractvalue indices invalid!");
1718   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1719 }
1720
1721 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1722   assert(C->getType()->isIntOrIntVectorTy() &&
1723          "Cannot NEG a nonintegral value!");
1724   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1725                 C, HasNUW, HasNSW);
1726 }
1727
1728 Constant *ConstantExpr::getFNeg(Constant *C) {
1729   assert(C->getType()->isFPOrFPVectorTy() &&
1730          "Cannot FNEG a non-floating-point value!");
1731   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1732 }
1733
1734 Constant *ConstantExpr::getNot(Constant *C) {
1735   assert(C->getType()->isIntOrIntVectorTy() &&
1736          "Cannot NOT a nonintegral value!");
1737   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1738 }
1739
1740 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1741                                bool HasNUW, bool HasNSW) {
1742   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1743                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1744   return get(Instruction::Add, C1, C2, Flags);
1745 }
1746
1747 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1748   return get(Instruction::FAdd, C1, C2);
1749 }
1750
1751 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1752                                bool HasNUW, bool HasNSW) {
1753   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1754                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1755   return get(Instruction::Sub, C1, C2, Flags);
1756 }
1757
1758 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1759   return get(Instruction::FSub, C1, C2);
1760 }
1761
1762 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1763                                bool HasNUW, bool HasNSW) {
1764   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1765                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1766   return get(Instruction::Mul, C1, C2, Flags);
1767 }
1768
1769 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1770   return get(Instruction::FMul, C1, C2);
1771 }
1772
1773 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1774   return get(Instruction::UDiv, C1, C2,
1775              isExact ? PossiblyExactOperator::IsExact : 0);
1776 }
1777
1778 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1779   return get(Instruction::SDiv, C1, C2,
1780              isExact ? PossiblyExactOperator::IsExact : 0);
1781 }
1782
1783 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1784   return get(Instruction::FDiv, C1, C2);
1785 }
1786
1787 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1788   return get(Instruction::URem, C1, C2);
1789 }
1790
1791 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1792   return get(Instruction::SRem, C1, C2);
1793 }
1794
1795 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1796   return get(Instruction::FRem, C1, C2);
1797 }
1798
1799 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1800   return get(Instruction::And, C1, C2);
1801 }
1802
1803 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1804   return get(Instruction::Or, C1, C2);
1805 }
1806
1807 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1808   return get(Instruction::Xor, C1, C2);
1809 }
1810
1811 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1812                                bool HasNUW, bool HasNSW) {
1813   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1814                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1815   return get(Instruction::Shl, C1, C2, Flags);
1816 }
1817
1818 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1819   return get(Instruction::LShr, C1, C2,
1820              isExact ? PossiblyExactOperator::IsExact : 0);
1821 }
1822
1823 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1824   return get(Instruction::AShr, C1, C2,
1825              isExact ? PossiblyExactOperator::IsExact : 0);
1826 }
1827
1828 // destroyConstant - Remove the constant from the constant table...
1829 //
1830 void ConstantExpr::destroyConstant() {
1831   getRawType()->getContext().pImpl->ExprConstants.remove(this);
1832   destroyConstantImpl();
1833 }
1834
1835 const char *ConstantExpr::getOpcodeName() const {
1836   return Instruction::getOpcodeName(getOpcode());
1837 }
1838
1839
1840
1841 GetElementPtrConstantExpr::
1842 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1843                           const Type *DestTy)
1844   : ConstantExpr(DestTy, Instruction::GetElementPtr,
1845                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1846                  - (IdxList.size()+1), IdxList.size()+1) {
1847   OperandList[0] = C;
1848   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1849     OperandList[i+1] = IdxList[i];
1850 }
1851
1852
1853 //===----------------------------------------------------------------------===//
1854 //                replaceUsesOfWithOnConstant implementations
1855
1856 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1857 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1858 /// etc.
1859 ///
1860 /// Note that we intentionally replace all uses of From with To here.  Consider
1861 /// a large array that uses 'From' 1000 times.  By handling this case all here,
1862 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1863 /// single invocation handles all 1000 uses.  Handling them one at a time would
1864 /// work, but would be really slow because it would have to unique each updated
1865 /// array instance.
1866 ///
1867 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1868                                                 Use *U) {
1869   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1870   Constant *ToC = cast<Constant>(To);
1871
1872   LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
1873
1874   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1875   Lookup.first.first = cast<ArrayType>(getRawType());
1876   Lookup.second = this;
1877
1878   std::vector<Constant*> &Values = Lookup.first.second;
1879   Values.reserve(getNumOperands());  // Build replacement array.
1880
1881   // Fill values with the modified operands of the constant array.  Also, 
1882   // compute whether this turns into an all-zeros array.
1883   bool isAllZeros = false;
1884   unsigned NumUpdated = 0;
1885   if (!ToC->isNullValue()) {
1886     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1887       Constant *Val = cast<Constant>(O->get());
1888       if (Val == From) {
1889         Val = ToC;
1890         ++NumUpdated;
1891       }
1892       Values.push_back(Val);
1893     }
1894   } else {
1895     isAllZeros = true;
1896     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1897       Constant *Val = cast<Constant>(O->get());
1898       if (Val == From) {
1899         Val = ToC;
1900         ++NumUpdated;
1901       }
1902       Values.push_back(Val);
1903       if (isAllZeros) isAllZeros = Val->isNullValue();
1904     }
1905   }
1906   
1907   Constant *Replacement = 0;
1908   if (isAllZeros) {
1909     Replacement = ConstantAggregateZero::get(getRawType());
1910   } else {
1911     // Check to see if we have this array type already.
1912     bool Exists;
1913     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1914       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1915     
1916     if (Exists) {
1917       Replacement = I->second;
1918     } else {
1919       // Okay, the new shape doesn't exist in the system yet.  Instead of
1920       // creating a new constant array, inserting it, replaceallusesof'ing the
1921       // old with the new, then deleting the old... just update the current one
1922       // in place!
1923       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1924       
1925       // Update to the new value.  Optimize for the case when we have a single
1926       // operand that we're changing, but handle bulk updates efficiently.
1927       if (NumUpdated == 1) {
1928         unsigned OperandToUpdate = U - OperandList;
1929         assert(getOperand(OperandToUpdate) == From &&
1930                "ReplaceAllUsesWith broken!");
1931         setOperand(OperandToUpdate, ToC);
1932       } else {
1933         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1934           if (getOperand(i) == From)
1935             setOperand(i, ToC);
1936       }
1937       return;
1938     }
1939   }
1940  
1941   // Otherwise, I do need to replace this with an existing value.
1942   assert(Replacement != this && "I didn't contain From!");
1943   
1944   // Everyone using this now uses the replacement.
1945   uncheckedReplaceAllUsesWith(Replacement);
1946   
1947   // Delete the old constant!
1948   destroyConstant();
1949 }
1950
1951 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1952                                                  Use *U) {
1953   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1954   Constant *ToC = cast<Constant>(To);
1955
1956   unsigned OperandToUpdate = U-OperandList;
1957   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1958
1959   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1960   Lookup.first.first = cast<StructType>(getRawType());
1961   Lookup.second = this;
1962   std::vector<Constant*> &Values = Lookup.first.second;
1963   Values.reserve(getNumOperands());  // Build replacement struct.
1964   
1965   
1966   // Fill values with the modified operands of the constant struct.  Also, 
1967   // compute whether this turns into an all-zeros struct.
1968   bool isAllZeros = false;
1969   if (!ToC->isNullValue()) {
1970     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1971       Values.push_back(cast<Constant>(O->get()));
1972   } else {
1973     isAllZeros = true;
1974     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1975       Constant *Val = cast<Constant>(O->get());
1976       Values.push_back(Val);
1977       if (isAllZeros) isAllZeros = Val->isNullValue();
1978     }
1979   }
1980   Values[OperandToUpdate] = ToC;
1981   
1982   LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
1983   
1984   Constant *Replacement = 0;
1985   if (isAllZeros) {
1986     Replacement = ConstantAggregateZero::get(getRawType());
1987   } else {
1988     // Check to see if we have this struct type already.
1989     bool Exists;
1990     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1991       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1992     
1993     if (Exists) {
1994       Replacement = I->second;
1995     } else {
1996       // Okay, the new shape doesn't exist in the system yet.  Instead of
1997       // creating a new constant struct, inserting it, replaceallusesof'ing the
1998       // old with the new, then deleting the old... just update the current one
1999       // in place!
2000       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2001       
2002       // Update to the new value.
2003       setOperand(OperandToUpdate, ToC);
2004       return;
2005     }
2006   }
2007   
2008   assert(Replacement != this && "I didn't contain From!");
2009   
2010   // Everyone using this now uses the replacement.
2011   uncheckedReplaceAllUsesWith(Replacement);
2012   
2013   // Delete the old constant!
2014   destroyConstant();
2015 }
2016
2017 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2018                                                  Use *U) {
2019   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2020   
2021   std::vector<Constant*> Values;
2022   Values.reserve(getNumOperands());  // Build replacement array...
2023   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2024     Constant *Val = getOperand(i);
2025     if (Val == From) Val = cast<Constant>(To);
2026     Values.push_back(Val);
2027   }
2028   
2029   Constant *Replacement = get(cast<VectorType>(getRawType()), Values);
2030   assert(Replacement != this && "I didn't contain From!");
2031   
2032   // Everyone using this now uses the replacement.
2033   uncheckedReplaceAllUsesWith(Replacement);
2034   
2035   // Delete the old constant!
2036   destroyConstant();
2037 }
2038
2039 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2040                                                Use *U) {
2041   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2042   Constant *To = cast<Constant>(ToV);
2043   
2044   Constant *Replacement = 0;
2045   if (getOpcode() == Instruction::GetElementPtr) {
2046     SmallVector<Constant*, 8> Indices;
2047     Constant *Pointer = getOperand(0);
2048     Indices.reserve(getNumOperands()-1);
2049     if (Pointer == From) Pointer = To;
2050     
2051     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2052       Constant *Val = getOperand(i);
2053       if (Val == From) Val = To;
2054       Indices.push_back(Val);
2055     }
2056     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2057                                                  &Indices[0], Indices.size());
2058   } else if (getOpcode() == Instruction::ExtractValue) {
2059     Constant *Agg = getOperand(0);
2060     if (Agg == From) Agg = To;
2061     
2062     const SmallVector<unsigned, 4> &Indices = getIndices();
2063     Replacement = ConstantExpr::getExtractValue(Agg,
2064                                                 &Indices[0], Indices.size());
2065   } else if (getOpcode() == Instruction::InsertValue) {
2066     Constant *Agg = getOperand(0);
2067     Constant *Val = getOperand(1);
2068     if (Agg == From) Agg = To;
2069     if (Val == From) Val = To;
2070     
2071     const SmallVector<unsigned, 4> &Indices = getIndices();
2072     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2073                                                &Indices[0], Indices.size());
2074   } else if (isCast()) {
2075     assert(getOperand(0) == From && "Cast only has one use!");
2076     Replacement = ConstantExpr::getCast(getOpcode(), To, getRawType());
2077   } else if (getOpcode() == Instruction::Select) {
2078     Constant *C1 = getOperand(0);
2079     Constant *C2 = getOperand(1);
2080     Constant *C3 = getOperand(2);
2081     if (C1 == From) C1 = To;
2082     if (C2 == From) C2 = To;
2083     if (C3 == From) C3 = To;
2084     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2085   } else if (getOpcode() == Instruction::ExtractElement) {
2086     Constant *C1 = getOperand(0);
2087     Constant *C2 = getOperand(1);
2088     if (C1 == From) C1 = To;
2089     if (C2 == From) C2 = To;
2090     Replacement = ConstantExpr::getExtractElement(C1, C2);
2091   } else if (getOpcode() == Instruction::InsertElement) {
2092     Constant *C1 = getOperand(0);
2093     Constant *C2 = getOperand(1);
2094     Constant *C3 = getOperand(1);
2095     if (C1 == From) C1 = To;
2096     if (C2 == From) C2 = To;
2097     if (C3 == From) C3 = To;
2098     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2099   } else if (getOpcode() == Instruction::ShuffleVector) {
2100     Constant *C1 = getOperand(0);
2101     Constant *C2 = getOperand(1);
2102     Constant *C3 = getOperand(2);
2103     if (C1 == From) C1 = To;
2104     if (C2 == From) C2 = To;
2105     if (C3 == From) C3 = To;
2106     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2107   } else if (isCompare()) {
2108     Constant *C1 = getOperand(0);
2109     Constant *C2 = getOperand(1);
2110     if (C1 == From) C1 = To;
2111     if (C2 == From) C2 = To;
2112     if (getOpcode() == Instruction::ICmp)
2113       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2114     else {
2115       assert(getOpcode() == Instruction::FCmp);
2116       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2117     }
2118   } else if (getNumOperands() == 2) {
2119     Constant *C1 = getOperand(0);
2120     Constant *C2 = getOperand(1);
2121     if (C1 == From) C1 = To;
2122     if (C2 == From) C2 = To;
2123     Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2124   } else {
2125     llvm_unreachable("Unknown ConstantExpr type!");
2126     return;
2127   }
2128   
2129   assert(Replacement != this && "I didn't contain From!");
2130   
2131   // Everyone using this now uses the replacement.
2132   uncheckedReplaceAllUsesWith(Replacement);
2133   
2134   // Delete the old constant!
2135   destroyConstant();
2136 }