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