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