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