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