]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/VMCore/Constants.cpp
Merge bmake-20130123
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 #include <cstdarg>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 //                              Constant Class
41 //===----------------------------------------------------------------------===//
42
43 void Constant::anchor() { }
44
45 bool Constant::isNegativeZeroValue() const {
46   // Floating point values have an explicit -0.0 value.
47   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48     return CFP->isZero() && CFP->isNegative();
49
50   // Otherwise, just use +0.0.
51   return isNullValue();
52 }
53
54 bool Constant::isNullValue() const {
55   // 0 is null.
56   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
57     return CI->isZero();
58
59   // +0.0 is null.
60   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
61     return CFP->isZero() && !CFP->isNegative();
62
63   // constant zero is zero for aggregates and cpnull is null for pointers.
64   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
65 }
66
67 bool Constant::isAllOnesValue() const {
68   // Check for -1 integers
69   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
70     return CI->isMinusOne();
71
72   // Check for FP which are bitcasted from -1 integers
73   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
74     return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
75
76   // Check for constant vectors which are splats of -1 values.
77   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
78     if (Constant *Splat = CV->getSplatValue())
79       return Splat->isAllOnesValue();
80
81   // Check for constant vectors which are splats of -1 values.
82   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
83     if (Constant *Splat = CV->getSplatValue())
84       return Splat->isAllOnesValue();
85
86   return false;
87 }
88
89 // Constructor to create a '0' constant of arbitrary type...
90 Constant *Constant::getNullValue(Type *Ty) {
91   switch (Ty->getTypeID()) {
92   case Type::IntegerTyID:
93     return ConstantInt::get(Ty, 0);
94   case Type::HalfTyID:
95     return ConstantFP::get(Ty->getContext(),
96                            APFloat::getZero(APFloat::IEEEhalf));
97   case Type::FloatTyID:
98     return ConstantFP::get(Ty->getContext(),
99                            APFloat::getZero(APFloat::IEEEsingle));
100   case Type::DoubleTyID:
101     return ConstantFP::get(Ty->getContext(),
102                            APFloat::getZero(APFloat::IEEEdouble));
103   case Type::X86_FP80TyID:
104     return ConstantFP::get(Ty->getContext(),
105                            APFloat::getZero(APFloat::x87DoubleExtended));
106   case Type::FP128TyID:
107     return ConstantFP::get(Ty->getContext(),
108                            APFloat::getZero(APFloat::IEEEquad));
109   case Type::PPC_FP128TyID:
110     return ConstantFP::get(Ty->getContext(),
111                            APFloat(APInt::getNullValue(128)));
112   case Type::PointerTyID:
113     return ConstantPointerNull::get(cast<PointerType>(Ty));
114   case Type::StructTyID:
115   case Type::ArrayTyID:
116   case Type::VectorTyID:
117     return ConstantAggregateZero::get(Ty);
118   default:
119     // Function, Label, or Opaque type?
120     llvm_unreachable("Cannot create a null constant of that type!");
121   }
122 }
123
124 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
125   Type *ScalarTy = Ty->getScalarType();
126
127   // Create the base integer constant.
128   Constant *C = ConstantInt::get(Ty->getContext(), V);
129
130   // Convert an integer to a pointer, if necessary.
131   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
132     C = ConstantExpr::getIntToPtr(C, PTy);
133
134   // Broadcast a scalar to a vector, if necessary.
135   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
136     C = ConstantVector::getSplat(VTy->getNumElements(), C);
137
138   return C;
139 }
140
141 Constant *Constant::getAllOnesValue(Type *Ty) {
142   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
143     return ConstantInt::get(Ty->getContext(),
144                             APInt::getAllOnesValue(ITy->getBitWidth()));
145
146   if (Ty->isFloatingPointTy()) {
147     APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
148                                           !Ty->isPPC_FP128Ty());
149     return ConstantFP::get(Ty->getContext(), FL);
150   }
151
152   VectorType *VTy = cast<VectorType>(Ty);
153   return ConstantVector::getSplat(VTy->getNumElements(),
154                                   getAllOnesValue(VTy->getElementType()));
155 }
156
157 /// getAggregateElement - For aggregates (struct/array/vector) return the
158 /// constant that corresponds to the specified element if possible, or null if
159 /// not.  This can return null if the element index is a ConstantExpr, or if
160 /// 'this' is a constant expr.
161 Constant *Constant::getAggregateElement(unsigned Elt) const {
162   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
163     return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
164
165   if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
166     return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
167
168   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
169     return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
170
171   if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
172     return CAZ->getElementValue(Elt);
173
174   if (const UndefValue *UV = dyn_cast<UndefValue>(this))
175     return UV->getElementValue(Elt);
176
177   if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
178     return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
179   return 0;
180 }
181
182 Constant *Constant::getAggregateElement(Constant *Elt) const {
183   assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
184   if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
185     return getAggregateElement(CI->getZExtValue());
186   return 0;
187 }
188
189
190 void Constant::destroyConstantImpl() {
191   // When a Constant is destroyed, there may be lingering
192   // references to the constant by other constants in the constant pool.  These
193   // constants are implicitly dependent on the module that is being deleted,
194   // but they don't know that.  Because we only find out when the CPV is
195   // deleted, we must now notify all of our users (that should only be
196   // Constants) that they are, in fact, invalid now and should be deleted.
197   //
198   while (!use_empty()) {
199     Value *V = use_back();
200 #ifndef NDEBUG      // Only in -g mode...
201     if (!isa<Constant>(V)) {
202       dbgs() << "While deleting: " << *this
203              << "\n\nUse still stuck around after Def is destroyed: "
204              << *V << "\n\n";
205     }
206 #endif
207     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
208     cast<Constant>(V)->destroyConstant();
209
210     // The constant should remove itself from our use list...
211     assert((use_empty() || use_back() != V) && "Constant not removed!");
212   }
213
214   // Value has no outstanding references it is safe to delete it now...
215   delete this;
216 }
217
218 /// canTrap - Return true if evaluation of this constant could trap.  This is
219 /// true for things like constant expressions that could divide by zero.
220 bool Constant::canTrap() const {
221   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
222   // The only thing that could possibly trap are constant exprs.
223   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
224   if (!CE) return false;
225
226   // ConstantExpr traps if any operands can trap.
227   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
228     if (CE->getOperand(i)->canTrap())
229       return true;
230
231   // Otherwise, only specific operations can trap.
232   switch (CE->getOpcode()) {
233   default:
234     return false;
235   case Instruction::UDiv:
236   case Instruction::SDiv:
237   case Instruction::FDiv:
238   case Instruction::URem:
239   case Instruction::SRem:
240   case Instruction::FRem:
241     // Div and rem can trap if the RHS is not known to be non-zero.
242     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
243       return true;
244     return false;
245   }
246 }
247
248 /// isThreadDependent - Return true if the value can vary between threads.
249 bool Constant::isThreadDependent() const {
250   SmallPtrSet<const Constant*, 64> Visited;
251   SmallVector<const Constant*, 64> WorkList;
252   WorkList.push_back(this);
253   Visited.insert(this);
254
255   while (!WorkList.empty()) {
256     const Constant *C = WorkList.pop_back_val();
257
258     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
259       if (GV->isThreadLocal())
260         return true;
261     }
262
263     for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
264       const Constant *D = dyn_cast<Constant>(C->getOperand(I));
265       if (!D)
266         continue;
267       if (Visited.insert(D))
268         WorkList.push_back(D);
269     }
270   }
271
272   return false;
273 }
274
275 /// isConstantUsed - Return true if the constant has users other than constant
276 /// exprs and other dangling things.
277 bool Constant::isConstantUsed() const {
278   for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
279     const Constant *UC = dyn_cast<Constant>(*UI);
280     if (UC == 0 || isa<GlobalValue>(UC))
281       return true;
282
283     if (UC->isConstantUsed())
284       return true;
285   }
286   return false;
287 }
288
289
290
291 /// getRelocationInfo - This method classifies the entry according to
292 /// whether or not it may generate a relocation entry.  This must be
293 /// conservative, so if it might codegen to a relocatable entry, it should say
294 /// so.  The return values are:
295 /// 
296 ///  NoRelocation: This constant pool entry is guaranteed to never have a
297 ///     relocation applied to it (because it holds a simple constant like
298 ///     '4').
299 ///  LocalRelocation: This entry has relocations, but the entries are
300 ///     guaranteed to be resolvable by the static linker, so the dynamic
301 ///     linker will never see them.
302 ///  GlobalRelocations: This entry may have arbitrary relocations.
303 ///
304 /// FIXME: This really should not be in VMCore.
305 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
306   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
307     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
308       return LocalRelocation;  // Local to this file/library.
309     return GlobalRelocations;    // Global reference.
310   }
311   
312   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
313     return BA->getFunction()->getRelocationInfo();
314   
315   // While raw uses of blockaddress need to be relocated, differences between
316   // two of them don't when they are for labels in the same function.  This is a
317   // common idiom when creating a table for the indirect goto extension, so we
318   // handle it efficiently here.
319   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
320     if (CE->getOpcode() == Instruction::Sub) {
321       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
322       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
323       if (LHS && RHS &&
324           LHS->getOpcode() == Instruction::PtrToInt &&
325           RHS->getOpcode() == Instruction::PtrToInt &&
326           isa<BlockAddress>(LHS->getOperand(0)) &&
327           isa<BlockAddress>(RHS->getOperand(0)) &&
328           cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
329             cast<BlockAddress>(RHS->getOperand(0))->getFunction())
330         return NoRelocation;
331     }
332
333   PossibleRelocationsTy Result = NoRelocation;
334   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
335     Result = std::max(Result,
336                       cast<Constant>(getOperand(i))->getRelocationInfo());
337
338   return Result;
339 }
340
341 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
342 /// it.  This involves recursively eliminating any dead users of the
343 /// constantexpr.
344 static bool removeDeadUsersOfConstant(const Constant *C) {
345   if (isa<GlobalValue>(C)) return false; // Cannot remove this
346
347   while (!C->use_empty()) {
348     const Constant *User = dyn_cast<Constant>(C->use_back());
349     if (!User) return false; // Non-constant usage;
350     if (!removeDeadUsersOfConstant(User))
351       return false; // Constant wasn't dead
352   }
353
354   const_cast<Constant*>(C)->destroyConstant();
355   return true;
356 }
357
358
359 /// removeDeadConstantUsers - If there are any dead constant users dangling
360 /// off of this constant, remove them.  This method is useful for clients
361 /// that want to check to see if a global is unused, but don't want to deal
362 /// with potentially dead constants hanging off of the globals.
363 void Constant::removeDeadConstantUsers() const {
364   Value::const_use_iterator I = use_begin(), E = use_end();
365   Value::const_use_iterator LastNonDeadUser = E;
366   while (I != E) {
367     const Constant *User = dyn_cast<Constant>(*I);
368     if (User == 0) {
369       LastNonDeadUser = I;
370       ++I;
371       continue;
372     }
373
374     if (!removeDeadUsersOfConstant(User)) {
375       // If the constant wasn't dead, remember that this was the last live use
376       // and move on to the next constant.
377       LastNonDeadUser = I;
378       ++I;
379       continue;
380     }
381
382     // If the constant was dead, then the iterator is invalidated.
383     if (LastNonDeadUser == E) {
384       I = use_begin();
385       if (I == E) break;
386     } else {
387       I = LastNonDeadUser;
388       ++I;
389     }
390   }
391 }
392
393
394
395 //===----------------------------------------------------------------------===//
396 //                                ConstantInt
397 //===----------------------------------------------------------------------===//
398
399 void ConstantInt::anchor() { }
400
401 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
402   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
403   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
404 }
405
406 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
407   LLVMContextImpl *pImpl = Context.pImpl;
408   if (!pImpl->TheTrueVal)
409     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
410   return pImpl->TheTrueVal;
411 }
412
413 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
414   LLVMContextImpl *pImpl = Context.pImpl;
415   if (!pImpl->TheFalseVal)
416     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
417   return pImpl->TheFalseVal;
418 }
419
420 Constant *ConstantInt::getTrue(Type *Ty) {
421   VectorType *VTy = dyn_cast<VectorType>(Ty);
422   if (!VTy) {
423     assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
424     return ConstantInt::getTrue(Ty->getContext());
425   }
426   assert(VTy->getElementType()->isIntegerTy(1) &&
427          "True must be vector of i1 or i1.");
428   return ConstantVector::getSplat(VTy->getNumElements(),
429                                   ConstantInt::getTrue(Ty->getContext()));
430 }
431
432 Constant *ConstantInt::getFalse(Type *Ty) {
433   VectorType *VTy = dyn_cast<VectorType>(Ty);
434   if (!VTy) {
435     assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
436     return ConstantInt::getFalse(Ty->getContext());
437   }
438   assert(VTy->getElementType()->isIntegerTy(1) &&
439          "False must be vector of i1 or i1.");
440   return ConstantVector::getSplat(VTy->getNumElements(),
441                                   ConstantInt::getFalse(Ty->getContext()));
442 }
443
444
445 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
446 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
447 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
448 // compare APInt's of different widths, which would violate an APInt class
449 // invariant which generates an assertion.
450 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
451   // Get the corresponding integer type for the bit width of the value.
452   IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
453   // get an existing value or the insertion position
454   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
455   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
456   if (!Slot) Slot = new ConstantInt(ITy, V);
457   return Slot;
458 }
459
460 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
461   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
462
463   // For vectors, broadcast the value.
464   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
465     return ConstantVector::getSplat(VTy->getNumElements(), C);
466
467   return C;
468 }
469
470 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, 
471                               bool isSigned) {
472   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
473 }
474
475 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
476   return get(Ty, V, true);
477 }
478
479 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
480   return get(Ty, V, true);
481 }
482
483 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
484   ConstantInt *C = get(Ty->getContext(), V);
485   assert(C->getType() == Ty->getScalarType() &&
486          "ConstantInt type doesn't match the type implied by its value!");
487
488   // For vectors, broadcast the value.
489   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
490     return ConstantVector::getSplat(VTy->getNumElements(), C);
491
492   return C;
493 }
494
495 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
496                               uint8_t radix) {
497   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
498 }
499
500 //===----------------------------------------------------------------------===//
501 //                                ConstantFP
502 //===----------------------------------------------------------------------===//
503
504 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
505   if (Ty->isHalfTy())
506     return &APFloat::IEEEhalf;
507   if (Ty->isFloatTy())
508     return &APFloat::IEEEsingle;
509   if (Ty->isDoubleTy())
510     return &APFloat::IEEEdouble;
511   if (Ty->isX86_FP80Ty())
512     return &APFloat::x87DoubleExtended;
513   else if (Ty->isFP128Ty())
514     return &APFloat::IEEEquad;
515
516   assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
517   return &APFloat::PPCDoubleDouble;
518 }
519
520 void ConstantFP::anchor() { }
521
522 /// get() - This returns a constant fp for the specified value in the
523 /// specified type.  This should only be used for simple constant values like
524 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
525 Constant *ConstantFP::get(Type *Ty, double V) {
526   LLVMContext &Context = Ty->getContext();
527
528   APFloat FV(V);
529   bool ignored;
530   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
531              APFloat::rmNearestTiesToEven, &ignored);
532   Constant *C = get(Context, FV);
533
534   // For vectors, broadcast the value.
535   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
536     return ConstantVector::getSplat(VTy->getNumElements(), C);
537
538   return C;
539 }
540
541
542 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
543   LLVMContext &Context = Ty->getContext();
544
545   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
546   Constant *C = get(Context, FV);
547
548   // For vectors, broadcast the value.
549   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
550     return ConstantVector::getSplat(VTy->getNumElements(), C);
551
552   return C; 
553 }
554
555
556 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
557   LLVMContext &Context = Ty->getContext();
558   APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
559   apf.changeSign();
560   return get(Context, apf);
561 }
562
563
564 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
565   Type *ScalarTy = Ty->getScalarType();
566   if (ScalarTy->isFloatingPointTy()) {
567     Constant *C = getNegativeZero(ScalarTy);
568     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
569       return ConstantVector::getSplat(VTy->getNumElements(), C);
570     return C;
571   }
572
573   return Constant::getNullValue(Ty);
574 }
575
576
577 // ConstantFP accessors.
578 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
579   DenseMapAPFloatKeyInfo::KeyTy Key(V);
580
581   LLVMContextImpl* pImpl = Context.pImpl;
582
583   ConstantFP *&Slot = pImpl->FPConstants[Key];
584
585   if (!Slot) {
586     Type *Ty;
587     if (&V.getSemantics() == &APFloat::IEEEhalf)
588       Ty = Type::getHalfTy(Context);
589     else if (&V.getSemantics() == &APFloat::IEEEsingle)
590       Ty = Type::getFloatTy(Context);
591     else if (&V.getSemantics() == &APFloat::IEEEdouble)
592       Ty = Type::getDoubleTy(Context);
593     else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
594       Ty = Type::getX86_FP80Ty(Context);
595     else if (&V.getSemantics() == &APFloat::IEEEquad)
596       Ty = Type::getFP128Ty(Context);
597     else {
598       assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
599              "Unknown FP format");
600       Ty = Type::getPPC_FP128Ty(Context);
601     }
602     Slot = new ConstantFP(Ty, V);
603   }
604
605   return Slot;
606 }
607
608 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
609   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
610   return ConstantFP::get(Ty->getContext(),
611                          APFloat::getInf(Semantics, Negative));
612 }
613
614 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
615   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
616   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
617          "FP type Mismatch");
618 }
619
620 bool ConstantFP::isExactlyValue(const APFloat &V) const {
621   return Val.bitwiseIsEqual(V);
622 }
623
624 //===----------------------------------------------------------------------===//
625 //                   ConstantAggregateZero Implementation
626 //===----------------------------------------------------------------------===//
627
628 /// getSequentialElement - If this CAZ has array or vector type, return a zero
629 /// with the right element type.
630 Constant *ConstantAggregateZero::getSequentialElement() const {
631   return Constant::getNullValue(getType()->getSequentialElementType());
632 }
633
634 /// getStructElement - If this CAZ has struct type, return a zero with the
635 /// right element type for the specified element.
636 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
637   return Constant::getNullValue(getType()->getStructElementType(Elt));
638 }
639
640 /// getElementValue - Return a zero of the right value for the specified GEP
641 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
642 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
643   if (isa<SequentialType>(getType()))
644     return getSequentialElement();
645   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
646 }
647
648 /// getElementValue - Return a zero of the right value for the specified GEP
649 /// index.
650 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
651   if (isa<SequentialType>(getType()))
652     return getSequentialElement();
653   return getStructElement(Idx);
654 }
655
656
657 //===----------------------------------------------------------------------===//
658 //                         UndefValue Implementation
659 //===----------------------------------------------------------------------===//
660
661 /// getSequentialElement - If this undef has array or vector type, return an
662 /// undef with the right element type.
663 UndefValue *UndefValue::getSequentialElement() const {
664   return UndefValue::get(getType()->getSequentialElementType());
665 }
666
667 /// getStructElement - If this undef has struct type, return a zero with the
668 /// right element type for the specified element.
669 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
670   return UndefValue::get(getType()->getStructElementType(Elt));
671 }
672
673 /// getElementValue - Return an undef of the right value for the specified GEP
674 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
675 UndefValue *UndefValue::getElementValue(Constant *C) const {
676   if (isa<SequentialType>(getType()))
677     return getSequentialElement();
678   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
679 }
680
681 /// getElementValue - Return an undef of the right value for the specified GEP
682 /// index.
683 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
684   if (isa<SequentialType>(getType()))
685     return getSequentialElement();
686   return getStructElement(Idx);
687 }
688
689
690
691 //===----------------------------------------------------------------------===//
692 //                            ConstantXXX Classes
693 //===----------------------------------------------------------------------===//
694
695 template <typename ItTy, typename EltTy>
696 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
697   for (; Start != End; ++Start)
698     if (*Start != Elt)
699       return false;
700   return true;
701 }
702
703 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
704   : Constant(T, ConstantArrayVal,
705              OperandTraits<ConstantArray>::op_end(this) - V.size(),
706              V.size()) {
707   assert(V.size() == T->getNumElements() &&
708          "Invalid initializer vector for constant array");
709   for (unsigned i = 0, e = V.size(); i != e; ++i)
710     assert(V[i]->getType() == T->getElementType() &&
711            "Initializer for array element doesn't match array element type!");
712   std::copy(V.begin(), V.end(), op_begin());
713 }
714
715 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
716   // Empty arrays are canonicalized to ConstantAggregateZero.
717   if (V.empty())
718     return ConstantAggregateZero::get(Ty);
719
720   for (unsigned i = 0, e = V.size(); i != e; ++i) {
721     assert(V[i]->getType() == Ty->getElementType() &&
722            "Wrong type in array element initializer");
723   }
724   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
725
726   // If this is an all-zero array, return a ConstantAggregateZero object.  If
727   // all undef, return an UndefValue, if "all simple", then return a
728   // ConstantDataArray.
729   Constant *C = V[0];
730   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
731     return UndefValue::get(Ty);
732
733   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
734     return ConstantAggregateZero::get(Ty);
735
736   // Check to see if all of the elements are ConstantFP or ConstantInt and if
737   // the element type is compatible with ConstantDataVector.  If so, use it.
738   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
739     // We speculatively build the elements here even if it turns out that there
740     // is a constantexpr or something else weird in the array, since it is so
741     // uncommon for that to happen.
742     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
743       if (CI->getType()->isIntegerTy(8)) {
744         SmallVector<uint8_t, 16> Elts;
745         for (unsigned i = 0, e = V.size(); i != e; ++i)
746           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
747             Elts.push_back(CI->getZExtValue());
748           else
749             break;
750         if (Elts.size() == V.size())
751           return ConstantDataArray::get(C->getContext(), Elts);
752       } else if (CI->getType()->isIntegerTy(16)) {
753         SmallVector<uint16_t, 16> Elts;
754         for (unsigned i = 0, e = V.size(); i != e; ++i)
755           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
756             Elts.push_back(CI->getZExtValue());
757           else
758             break;
759         if (Elts.size() == V.size())
760           return ConstantDataArray::get(C->getContext(), Elts);
761       } else if (CI->getType()->isIntegerTy(32)) {
762         SmallVector<uint32_t, 16> Elts;
763         for (unsigned i = 0, e = V.size(); i != e; ++i)
764           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
765             Elts.push_back(CI->getZExtValue());
766           else
767             break;
768         if (Elts.size() == V.size())
769           return ConstantDataArray::get(C->getContext(), Elts);
770       } else if (CI->getType()->isIntegerTy(64)) {
771         SmallVector<uint64_t, 16> Elts;
772         for (unsigned i = 0, e = V.size(); i != e; ++i)
773           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
774             Elts.push_back(CI->getZExtValue());
775           else
776             break;
777         if (Elts.size() == V.size())
778           return ConstantDataArray::get(C->getContext(), Elts);
779       }
780     }
781
782     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
783       if (CFP->getType()->isFloatTy()) {
784         SmallVector<float, 16> Elts;
785         for (unsigned i = 0, e = V.size(); i != e; ++i)
786           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
787             Elts.push_back(CFP->getValueAPF().convertToFloat());
788           else
789             break;
790         if (Elts.size() == V.size())
791           return ConstantDataArray::get(C->getContext(), Elts);
792       } else if (CFP->getType()->isDoubleTy()) {
793         SmallVector<double, 16> Elts;
794         for (unsigned i = 0, e = V.size(); i != e; ++i)
795           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
796             Elts.push_back(CFP->getValueAPF().convertToDouble());
797           else
798             break;
799         if (Elts.size() == V.size())
800           return ConstantDataArray::get(C->getContext(), Elts);
801       }
802     }
803   }
804
805   // Otherwise, we really do want to create a ConstantArray.
806   return pImpl->ArrayConstants.getOrCreate(Ty, V);
807 }
808
809 /// getTypeForElements - Return an anonymous struct type to use for a constant
810 /// with the specified set of elements.  The list must not be empty.
811 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
812                                                ArrayRef<Constant*> V,
813                                                bool Packed) {
814   unsigned VecSize = V.size();
815   SmallVector<Type*, 16> EltTypes(VecSize);
816   for (unsigned i = 0; i != VecSize; ++i)
817     EltTypes[i] = V[i]->getType();
818
819   return StructType::get(Context, EltTypes, Packed);
820 }
821
822
823 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
824                                                bool Packed) {
825   assert(!V.empty() &&
826          "ConstantStruct::getTypeForElements cannot be called on empty list");
827   return getTypeForElements(V[0]->getContext(), V, Packed);
828 }
829
830
831 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
832   : Constant(T, ConstantStructVal,
833              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
834              V.size()) {
835   assert(V.size() == T->getNumElements() &&
836          "Invalid initializer vector for constant structure");
837   for (unsigned i = 0, e = V.size(); i != e; ++i)
838     assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
839            "Initializer for struct element doesn't match struct element type!");
840   std::copy(V.begin(), V.end(), op_begin());
841 }
842
843 // ConstantStruct accessors.
844 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
845   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
846          "Incorrect # elements specified to ConstantStruct::get");
847
848   // Create a ConstantAggregateZero value if all elements are zeros.
849   bool isZero = true;
850   bool isUndef = false;
851   
852   if (!V.empty()) {
853     isUndef = isa<UndefValue>(V[0]);
854     isZero = V[0]->isNullValue();
855     if (isUndef || isZero) {
856       for (unsigned i = 0, e = V.size(); i != e; ++i) {
857         if (!V[i]->isNullValue())
858           isZero = false;
859         if (!isa<UndefValue>(V[i]))
860           isUndef = false;
861       }
862     }
863   }
864   if (isZero)
865     return ConstantAggregateZero::get(ST);
866   if (isUndef)
867     return UndefValue::get(ST);
868
869   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
870 }
871
872 Constant *ConstantStruct::get(StructType *T, ...) {
873   va_list ap;
874   SmallVector<Constant*, 8> Values;
875   va_start(ap, T);
876   while (Constant *Val = va_arg(ap, llvm::Constant*))
877     Values.push_back(Val);
878   va_end(ap);
879   return get(T, Values);
880 }
881
882 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
883   : Constant(T, ConstantVectorVal,
884              OperandTraits<ConstantVector>::op_end(this) - V.size(),
885              V.size()) {
886   for (size_t i = 0, e = V.size(); i != e; i++)
887     assert(V[i]->getType() == T->getElementType() &&
888            "Initializer for vector element doesn't match vector element type!");
889   std::copy(V.begin(), V.end(), op_begin());
890 }
891
892 // ConstantVector accessors.
893 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
894   assert(!V.empty() && "Vectors can't be empty");
895   VectorType *T = VectorType::get(V.front()->getType(), V.size());
896   LLVMContextImpl *pImpl = T->getContext().pImpl;
897
898   // If this is an all-undef or all-zero vector, return a
899   // ConstantAggregateZero or UndefValue.
900   Constant *C = V[0];
901   bool isZero = C->isNullValue();
902   bool isUndef = isa<UndefValue>(C);
903
904   if (isZero || isUndef) {
905     for (unsigned i = 1, e = V.size(); i != e; ++i)
906       if (V[i] != C) {
907         isZero = isUndef = false;
908         break;
909       }
910   }
911
912   if (isZero)
913     return ConstantAggregateZero::get(T);
914   if (isUndef)
915     return UndefValue::get(T);
916
917   // Check to see if all of the elements are ConstantFP or ConstantInt and if
918   // the element type is compatible with ConstantDataVector.  If so, use it.
919   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
920     // We speculatively build the elements here even if it turns out that there
921     // is a constantexpr or something else weird in the array, since it is so
922     // uncommon for that to happen.
923     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
924       if (CI->getType()->isIntegerTy(8)) {
925         SmallVector<uint8_t, 16> Elts;
926         for (unsigned i = 0, e = V.size(); i != e; ++i)
927           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
928             Elts.push_back(CI->getZExtValue());
929           else
930             break;
931         if (Elts.size() == V.size())
932           return ConstantDataVector::get(C->getContext(), Elts);
933       } else if (CI->getType()->isIntegerTy(16)) {
934         SmallVector<uint16_t, 16> Elts;
935         for (unsigned i = 0, e = V.size(); i != e; ++i)
936           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
937             Elts.push_back(CI->getZExtValue());
938           else
939             break;
940         if (Elts.size() == V.size())
941           return ConstantDataVector::get(C->getContext(), Elts);
942       } else if (CI->getType()->isIntegerTy(32)) {
943         SmallVector<uint32_t, 16> Elts;
944         for (unsigned i = 0, e = V.size(); i != e; ++i)
945           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
946             Elts.push_back(CI->getZExtValue());
947           else
948             break;
949         if (Elts.size() == V.size())
950           return ConstantDataVector::get(C->getContext(), Elts);
951       } else if (CI->getType()->isIntegerTy(64)) {
952         SmallVector<uint64_t, 16> Elts;
953         for (unsigned i = 0, e = V.size(); i != e; ++i)
954           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
955             Elts.push_back(CI->getZExtValue());
956           else
957             break;
958         if (Elts.size() == V.size())
959           return ConstantDataVector::get(C->getContext(), Elts);
960       }
961     }
962
963     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
964       if (CFP->getType()->isFloatTy()) {
965         SmallVector<float, 16> Elts;
966         for (unsigned i = 0, e = V.size(); i != e; ++i)
967           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
968             Elts.push_back(CFP->getValueAPF().convertToFloat());
969           else
970             break;
971         if (Elts.size() == V.size())
972           return ConstantDataVector::get(C->getContext(), Elts);
973       } else if (CFP->getType()->isDoubleTy()) {
974         SmallVector<double, 16> Elts;
975         for (unsigned i = 0, e = V.size(); i != e; ++i)
976           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
977             Elts.push_back(CFP->getValueAPF().convertToDouble());
978           else
979             break;
980         if (Elts.size() == V.size())
981           return ConstantDataVector::get(C->getContext(), Elts);
982       }
983     }
984   }
985
986   // Otherwise, the element type isn't compatible with ConstantDataVector, or
987   // the operand list constants a ConstantExpr or something else strange.
988   return pImpl->VectorConstants.getOrCreate(T, V);
989 }
990
991 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
992   // If this splat is compatible with ConstantDataVector, use it instead of
993   // ConstantVector.
994   if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
995       ConstantDataSequential::isElementTypeCompatible(V->getType()))
996     return ConstantDataVector::getSplat(NumElts, V);
997
998   SmallVector<Constant*, 32> Elts(NumElts, V);
999   return get(Elts);
1000 }
1001
1002
1003 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1004 // can't be inline because we don't want to #include Instruction.h into
1005 // Constant.h
1006 bool ConstantExpr::isCast() const {
1007   return Instruction::isCast(getOpcode());
1008 }
1009
1010 bool ConstantExpr::isCompare() const {
1011   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1012 }
1013
1014 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1015   if (getOpcode() != Instruction::GetElementPtr) return false;
1016
1017   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1018   User::const_op_iterator OI = llvm::next(this->op_begin());
1019
1020   // Skip the first index, as it has no static limit.
1021   ++GEPI;
1022   ++OI;
1023
1024   // The remaining indices must be compile-time known integers within the
1025   // bounds of the corresponding notional static array types.
1026   for (; GEPI != E; ++GEPI, ++OI) {
1027     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1028     if (!CI) return false;
1029     if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1030       if (CI->getValue().getActiveBits() > 64 ||
1031           CI->getZExtValue() >= ATy->getNumElements())
1032         return false;
1033   }
1034
1035   // All the indices checked out.
1036   return true;
1037 }
1038
1039 bool ConstantExpr::hasIndices() const {
1040   return getOpcode() == Instruction::ExtractValue ||
1041          getOpcode() == Instruction::InsertValue;
1042 }
1043
1044 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1045   if (const ExtractValueConstantExpr *EVCE =
1046         dyn_cast<ExtractValueConstantExpr>(this))
1047     return EVCE->Indices;
1048
1049   return cast<InsertValueConstantExpr>(this)->Indices;
1050 }
1051
1052 unsigned ConstantExpr::getPredicate() const {
1053   assert(isCompare());
1054   return ((const CompareConstantExpr*)this)->predicate;
1055 }
1056
1057 /// getWithOperandReplaced - Return a constant expression identical to this
1058 /// one, but with the specified operand set to the specified value.
1059 Constant *
1060 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1061   assert(Op->getType() == getOperand(OpNo)->getType() &&
1062          "Replacing operand with value of different type!");
1063   if (getOperand(OpNo) == Op)
1064     return const_cast<ConstantExpr*>(this);
1065
1066   SmallVector<Constant*, 8> NewOps;
1067   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1068     NewOps.push_back(i == OpNo ? Op : getOperand(i));
1069
1070   return getWithOperands(NewOps);
1071 }
1072
1073 /// getWithOperands - This returns the current constant expression with the
1074 /// operands replaced with the specified values.  The specified array must
1075 /// have the same number of operands as our current one.
1076 Constant *ConstantExpr::
1077 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
1078   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1079   bool AnyChange = Ty != getType();
1080   for (unsigned i = 0; i != Ops.size(); ++i)
1081     AnyChange |= Ops[i] != getOperand(i);
1082
1083   if (!AnyChange)  // No operands changed, return self.
1084     return const_cast<ConstantExpr*>(this);
1085
1086   switch (getOpcode()) {
1087   case Instruction::Trunc:
1088   case Instruction::ZExt:
1089   case Instruction::SExt:
1090   case Instruction::FPTrunc:
1091   case Instruction::FPExt:
1092   case Instruction::UIToFP:
1093   case Instruction::SIToFP:
1094   case Instruction::FPToUI:
1095   case Instruction::FPToSI:
1096   case Instruction::PtrToInt:
1097   case Instruction::IntToPtr:
1098   case Instruction::BitCast:
1099     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
1100   case Instruction::Select:
1101     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1102   case Instruction::InsertElement:
1103     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1104   case Instruction::ExtractElement:
1105     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1106   case Instruction::InsertValue:
1107     return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1108   case Instruction::ExtractValue:
1109     return ConstantExpr::getExtractValue(Ops[0], getIndices());
1110   case Instruction::ShuffleVector:
1111     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1112   case Instruction::GetElementPtr:
1113     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1114                                       cast<GEPOperator>(this)->isInBounds());
1115   case Instruction::ICmp:
1116   case Instruction::FCmp:
1117     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1118   default:
1119     assert(getNumOperands() == 2 && "Must be binary operator?");
1120     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1121   }
1122 }
1123
1124
1125 //===----------------------------------------------------------------------===//
1126 //                      isValueValidForType implementations
1127
1128 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1129   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1130   if (Ty->isIntegerTy(1))
1131     return Val == 0 || Val == 1;
1132   if (NumBits >= 64)
1133     return true; // always true, has to fit in largest type
1134   uint64_t Max = (1ll << NumBits) - 1;
1135   return Val <= Max;
1136 }
1137
1138 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1139   unsigned NumBits = Ty->getIntegerBitWidth();
1140   if (Ty->isIntegerTy(1))
1141     return Val == 0 || Val == 1 || Val == -1;
1142   if (NumBits >= 64)
1143     return true; // always true, has to fit in largest type
1144   int64_t Min = -(1ll << (NumBits-1));
1145   int64_t Max = (1ll << (NumBits-1)) - 1;
1146   return (Val >= Min && Val <= Max);
1147 }
1148
1149 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1150   // convert modifies in place, so make a copy.
1151   APFloat Val2 = APFloat(Val);
1152   bool losesInfo;
1153   switch (Ty->getTypeID()) {
1154   default:
1155     return false;         // These can't be represented as floating point!
1156
1157   // FIXME rounding mode needs to be more flexible
1158   case Type::HalfTyID: {
1159     if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1160       return true;
1161     Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1162     return !losesInfo;
1163   }
1164   case Type::FloatTyID: {
1165     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1166       return true;
1167     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1168     return !losesInfo;
1169   }
1170   case Type::DoubleTyID: {
1171     if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1172         &Val2.getSemantics() == &APFloat::IEEEsingle ||
1173         &Val2.getSemantics() == &APFloat::IEEEdouble)
1174       return true;
1175     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1176     return !losesInfo;
1177   }
1178   case Type::X86_FP80TyID:
1179     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1180            &Val2.getSemantics() == &APFloat::IEEEsingle || 
1181            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1182            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1183   case Type::FP128TyID:
1184     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1185            &Val2.getSemantics() == &APFloat::IEEEsingle || 
1186            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1187            &Val2.getSemantics() == &APFloat::IEEEquad;
1188   case Type::PPC_FP128TyID:
1189     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1190            &Val2.getSemantics() == &APFloat::IEEEsingle || 
1191            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1192            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1193   }
1194 }
1195
1196
1197 //===----------------------------------------------------------------------===//
1198 //                      Factory Function Implementation
1199
1200 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1201   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1202          "Cannot create an aggregate zero of non-aggregate type!");
1203   
1204   ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1205   if (Entry == 0)
1206     Entry = new ConstantAggregateZero(Ty);
1207
1208   return Entry;
1209 }
1210
1211 /// destroyConstant - Remove the constant from the constant table.
1212 ///
1213 void ConstantAggregateZero::destroyConstant() {
1214   getContext().pImpl->CAZConstants.erase(getType());
1215   destroyConstantImpl();
1216 }
1217
1218 /// destroyConstant - Remove the constant from the constant table...
1219 ///
1220 void ConstantArray::destroyConstant() {
1221   getType()->getContext().pImpl->ArrayConstants.remove(this);
1222   destroyConstantImpl();
1223 }
1224
1225
1226 //---- ConstantStruct::get() implementation...
1227 //
1228
1229 // destroyConstant - Remove the constant from the constant table...
1230 //
1231 void ConstantStruct::destroyConstant() {
1232   getType()->getContext().pImpl->StructConstants.remove(this);
1233   destroyConstantImpl();
1234 }
1235
1236 // destroyConstant - Remove the constant from the constant table...
1237 //
1238 void ConstantVector::destroyConstant() {
1239   getType()->getContext().pImpl->VectorConstants.remove(this);
1240   destroyConstantImpl();
1241 }
1242
1243 /// getSplatValue - If this is a splat constant, where all of the
1244 /// elements have the same value, return that value. Otherwise return null.
1245 Constant *ConstantVector::getSplatValue() const {
1246   // Check out first element.
1247   Constant *Elt = getOperand(0);
1248   // Then make sure all remaining elements point to the same value.
1249   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1250     if (getOperand(I) != Elt)
1251       return 0;
1252   return Elt;
1253 }
1254
1255 //---- ConstantPointerNull::get() implementation.
1256 //
1257
1258 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1259   ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1260   if (Entry == 0)
1261     Entry = new ConstantPointerNull(Ty);
1262
1263   return Entry;
1264 }
1265
1266 // destroyConstant - Remove the constant from the constant table...
1267 //
1268 void ConstantPointerNull::destroyConstant() {
1269   getContext().pImpl->CPNConstants.erase(getType());
1270   // Free the constant and any dangling references to it.
1271   destroyConstantImpl();
1272 }
1273
1274
1275 //---- UndefValue::get() implementation.
1276 //
1277
1278 UndefValue *UndefValue::get(Type *Ty) {
1279   UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1280   if (Entry == 0)
1281     Entry = new UndefValue(Ty);
1282
1283   return Entry;
1284 }
1285
1286 // destroyConstant - Remove the constant from the constant table.
1287 //
1288 void UndefValue::destroyConstant() {
1289   // Free the constant and any dangling references to it.
1290   getContext().pImpl->UVConstants.erase(getType());
1291   destroyConstantImpl();
1292 }
1293
1294 //---- BlockAddress::get() implementation.
1295 //
1296
1297 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1298   assert(BB->getParent() != 0 && "Block must have a parent");
1299   return get(BB->getParent(), BB);
1300 }
1301
1302 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1303   BlockAddress *&BA =
1304     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1305   if (BA == 0)
1306     BA = new BlockAddress(F, BB);
1307
1308   assert(BA->getFunction() == F && "Basic block moved between functions");
1309   return BA;
1310 }
1311
1312 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1313 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1314            &Op<0>(), 2) {
1315   setOperand(0, F);
1316   setOperand(1, BB);
1317   BB->AdjustBlockAddressRefCount(1);
1318 }
1319
1320
1321 // destroyConstant - Remove the constant from the constant table.
1322 //
1323 void BlockAddress::destroyConstant() {
1324   getFunction()->getType()->getContext().pImpl
1325     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1326   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1327   destroyConstantImpl();
1328 }
1329
1330 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1331   // This could be replacing either the Basic Block or the Function.  In either
1332   // case, we have to remove the map entry.
1333   Function *NewF = getFunction();
1334   BasicBlock *NewBB = getBasicBlock();
1335
1336   if (U == &Op<0>())
1337     NewF = cast<Function>(To);
1338   else
1339     NewBB = cast<BasicBlock>(To);
1340
1341   // See if the 'new' entry already exists, if not, just update this in place
1342   // and return early.
1343   BlockAddress *&NewBA =
1344     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1345   if (NewBA == 0) {
1346     getBasicBlock()->AdjustBlockAddressRefCount(-1);
1347
1348     // Remove the old entry, this can't cause the map to rehash (just a
1349     // tombstone will get added).
1350     getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1351                                                             getBasicBlock()));
1352     NewBA = this;
1353     setOperand(0, NewF);
1354     setOperand(1, NewBB);
1355     getBasicBlock()->AdjustBlockAddressRefCount(1);
1356     return;
1357   }
1358
1359   // Otherwise, I do need to replace this with an existing value.
1360   assert(NewBA != this && "I didn't contain From!");
1361
1362   // Everyone using this now uses the replacement.
1363   replaceAllUsesWith(NewBA);
1364
1365   destroyConstant();
1366 }
1367
1368 //---- ConstantExpr::get() implementations.
1369 //
1370
1371 /// This is a utility function to handle folding of casts and lookup of the
1372 /// cast in the ExprConstants map. It is used by the various get* methods below.
1373 static inline Constant *getFoldedCast(
1374   Instruction::CastOps opc, Constant *C, Type *Ty) {
1375   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1376   // Fold a few common cases
1377   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1378     return FC;
1379
1380   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1381
1382   // Look up the constant in the table first to ensure uniqueness
1383   std::vector<Constant*> argVec(1, C);
1384   ExprMapKeyType Key(opc, argVec);
1385
1386   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1387 }
1388
1389 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1390   Instruction::CastOps opc = Instruction::CastOps(oc);
1391   assert(Instruction::isCast(opc) && "opcode out of range");
1392   assert(C && Ty && "Null arguments to getCast");
1393   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1394
1395   switch (opc) {
1396   default:
1397     llvm_unreachable("Invalid cast opcode");
1398   case Instruction::Trunc:    return getTrunc(C, Ty);
1399   case Instruction::ZExt:     return getZExt(C, Ty);
1400   case Instruction::SExt:     return getSExt(C, Ty);
1401   case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1402   case Instruction::FPExt:    return getFPExtend(C, Ty);
1403   case Instruction::UIToFP:   return getUIToFP(C, Ty);
1404   case Instruction::SIToFP:   return getSIToFP(C, Ty);
1405   case Instruction::FPToUI:   return getFPToUI(C, Ty);
1406   case Instruction::FPToSI:   return getFPToSI(C, Ty);
1407   case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1408   case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1409   case Instruction::BitCast:  return getBitCast(C, Ty);
1410   }
1411 }
1412
1413 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1414   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1415     return getBitCast(C, Ty);
1416   return getZExt(C, Ty);
1417 }
1418
1419 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1420   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1421     return getBitCast(C, Ty);
1422   return getSExt(C, Ty);
1423 }
1424
1425 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1426   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1427     return getBitCast(C, Ty);
1428   return getTrunc(C, Ty);
1429 }
1430
1431 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1432   assert(S->getType()->isPointerTy() && "Invalid cast");
1433   assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1434
1435   if (Ty->isIntegerTy())
1436     return getPtrToInt(S, Ty);
1437   return getBitCast(S, Ty);
1438 }
1439
1440 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, 
1441                                        bool isSigned) {
1442   assert(C->getType()->isIntOrIntVectorTy() &&
1443          Ty->isIntOrIntVectorTy() && "Invalid cast");
1444   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1445   unsigned DstBits = Ty->getScalarSizeInBits();
1446   Instruction::CastOps opcode =
1447     (SrcBits == DstBits ? Instruction::BitCast :
1448      (SrcBits > DstBits ? Instruction::Trunc :
1449       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1450   return getCast(opcode, C, Ty);
1451 }
1452
1453 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1454   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1455          "Invalid cast");
1456   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1457   unsigned DstBits = Ty->getScalarSizeInBits();
1458   if (SrcBits == DstBits)
1459     return C; // Avoid a useless cast
1460   Instruction::CastOps opcode =
1461     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1462   return getCast(opcode, C, Ty);
1463 }
1464
1465 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1466 #ifndef NDEBUG
1467   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1468   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1469 #endif
1470   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1471   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1472   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1473   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1474          "SrcTy must be larger than DestTy for Trunc!");
1475
1476   return getFoldedCast(Instruction::Trunc, C, Ty);
1477 }
1478
1479 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1480 #ifndef NDEBUG
1481   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1482   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1483 #endif
1484   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1485   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1486   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1487   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1488          "SrcTy must be smaller than DestTy for SExt!");
1489
1490   return getFoldedCast(Instruction::SExt, C, Ty);
1491 }
1492
1493 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1494 #ifndef NDEBUG
1495   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1496   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1497 #endif
1498   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1499   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1500   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1501   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1502          "SrcTy must be smaller than DestTy for ZExt!");
1503
1504   return getFoldedCast(Instruction::ZExt, C, Ty);
1505 }
1506
1507 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1508 #ifndef NDEBUG
1509   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1510   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1511 #endif
1512   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1513   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1514          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1515          "This is an illegal floating point truncation!");
1516   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1517 }
1518
1519 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1520 #ifndef NDEBUG
1521   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1522   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1523 #endif
1524   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1525   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1526          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1527          "This is an illegal floating point extension!");
1528   return getFoldedCast(Instruction::FPExt, C, Ty);
1529 }
1530
1531 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1532 #ifndef NDEBUG
1533   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1534   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1535 #endif
1536   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1537   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1538          "This is an illegal uint to floating point cast!");
1539   return getFoldedCast(Instruction::UIToFP, C, Ty);
1540 }
1541
1542 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1543 #ifndef NDEBUG
1544   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1545   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1546 #endif
1547   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1548   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1549          "This is an illegal sint to floating point cast!");
1550   return getFoldedCast(Instruction::SIToFP, C, Ty);
1551 }
1552
1553 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1554 #ifndef NDEBUG
1555   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1556   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1557 #endif
1558   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1559   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1560          "This is an illegal floating point to uint cast!");
1561   return getFoldedCast(Instruction::FPToUI, C, Ty);
1562 }
1563
1564 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1565 #ifndef NDEBUG
1566   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1567   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1568 #endif
1569   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1570   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1571          "This is an illegal floating point to sint cast!");
1572   return getFoldedCast(Instruction::FPToSI, C, Ty);
1573 }
1574
1575 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1576   assert(C->getType()->getScalarType()->isPointerTy() &&
1577          "PtrToInt source must be pointer or pointer vector");
1578   assert(DstTy->getScalarType()->isIntegerTy() && 
1579          "PtrToInt destination must be integer or integer vector");
1580   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1581   if (isa<VectorType>(C->getType()))
1582     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1583            "Invalid cast between a different number of vector elements");
1584   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1585 }
1586
1587 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1588   assert(C->getType()->getScalarType()->isIntegerTy() &&
1589          "IntToPtr source must be integer or integer vector");
1590   assert(DstTy->getScalarType()->isPointerTy() &&
1591          "IntToPtr destination must be a pointer or pointer vector");
1592   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1593   if (isa<VectorType>(C->getType()))
1594     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1595            "Invalid cast between a different number of vector elements");
1596   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1597 }
1598
1599 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1600   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1601          "Invalid constantexpr bitcast!");
1602
1603   // It is common to ask for a bitcast of a value to its own type, handle this
1604   // speedily.
1605   if (C->getType() == DstTy) return C;
1606
1607   return getFoldedCast(Instruction::BitCast, C, DstTy);
1608 }
1609
1610 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1611                             unsigned Flags) {
1612   // Check the operands for consistency first.
1613   assert(Opcode >= Instruction::BinaryOpsBegin &&
1614          Opcode <  Instruction::BinaryOpsEnd   &&
1615          "Invalid opcode in binary constant expression");
1616   assert(C1->getType() == C2->getType() &&
1617          "Operand types in binary constant expression should match");
1618
1619 #ifndef NDEBUG
1620   switch (Opcode) {
1621   case Instruction::Add:
1622   case Instruction::Sub:
1623   case Instruction::Mul:
1624     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1625     assert(C1->getType()->isIntOrIntVectorTy() &&
1626            "Tried to create an integer operation on a non-integer type!");
1627     break;
1628   case Instruction::FAdd:
1629   case Instruction::FSub:
1630   case Instruction::FMul:
1631     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1632     assert(C1->getType()->isFPOrFPVectorTy() &&
1633            "Tried to create a floating-point operation on a "
1634            "non-floating-point type!");
1635     break;
1636   case Instruction::UDiv: 
1637   case Instruction::SDiv: 
1638     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1639     assert(C1->getType()->isIntOrIntVectorTy() &&
1640            "Tried to create an arithmetic operation on a non-arithmetic type!");
1641     break;
1642   case Instruction::FDiv:
1643     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1644     assert(C1->getType()->isFPOrFPVectorTy() &&
1645            "Tried to create an arithmetic operation on a non-arithmetic type!");
1646     break;
1647   case Instruction::URem: 
1648   case Instruction::SRem: 
1649     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1650     assert(C1->getType()->isIntOrIntVectorTy() &&
1651            "Tried to create an arithmetic operation on a non-arithmetic type!");
1652     break;
1653   case Instruction::FRem:
1654     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1655     assert(C1->getType()->isFPOrFPVectorTy() &&
1656            "Tried to create an arithmetic operation on a non-arithmetic type!");
1657     break;
1658   case Instruction::And:
1659   case Instruction::Or:
1660   case Instruction::Xor:
1661     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1662     assert(C1->getType()->isIntOrIntVectorTy() &&
1663            "Tried to create a logical operation on a non-integral type!");
1664     break;
1665   case Instruction::Shl:
1666   case Instruction::LShr:
1667   case Instruction::AShr:
1668     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1669     assert(C1->getType()->isIntOrIntVectorTy() &&
1670            "Tried to create a shift operation on a non-integer type!");
1671     break;
1672   default:
1673     break;
1674   }
1675 #endif
1676
1677   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1678     return FC;          // Fold a few common cases.
1679
1680   std::vector<Constant*> argVec(1, C1);
1681   argVec.push_back(C2);
1682   ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1683
1684   LLVMContextImpl *pImpl = C1->getContext().pImpl;
1685   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1686 }
1687
1688 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1689   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1690   // Note that a non-inbounds gep is used, as null isn't within any object.
1691   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1692   Constant *GEP = getGetElementPtr(
1693                  Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1694   return getPtrToInt(GEP, 
1695                      Type::getInt64Ty(Ty->getContext()));
1696 }
1697
1698 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1699   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1700   // Note that a non-inbounds gep is used, as null isn't within any object.
1701   Type *AligningTy = 
1702     StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1703   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1704   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1705   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1706   Constant *Indices[2] = { Zero, One };
1707   Constant *GEP = getGetElementPtr(NullPtr, Indices);
1708   return getPtrToInt(GEP,
1709                      Type::getInt64Ty(Ty->getContext()));
1710 }
1711
1712 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1713   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1714                                            FieldNo));
1715 }
1716
1717 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1718   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1719   // Note that a non-inbounds gep is used, as null isn't within any object.
1720   Constant *GEPIdx[] = {
1721     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1722     FieldNo
1723   };
1724   Constant *GEP = getGetElementPtr(
1725                 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1726   return getPtrToInt(GEP,
1727                      Type::getInt64Ty(Ty->getContext()));
1728 }
1729
1730 Constant *ConstantExpr::getCompare(unsigned short Predicate, 
1731                                    Constant *C1, Constant *C2) {
1732   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1733
1734   switch (Predicate) {
1735   default: llvm_unreachable("Invalid CmpInst predicate");
1736   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1737   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1738   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1739   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1740   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1741   case CmpInst::FCMP_TRUE:
1742     return getFCmp(Predicate, C1, C2);
1743
1744   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1745   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1746   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1747   case CmpInst::ICMP_SLE:
1748     return getICmp(Predicate, C1, C2);
1749   }
1750 }
1751
1752 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1753   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1754
1755   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1756     return SC;        // Fold common cases
1757
1758   std::vector<Constant*> argVec(3, C);
1759   argVec[1] = V1;
1760   argVec[2] = V2;
1761   ExprMapKeyType Key(Instruction::Select, argVec);
1762
1763   LLVMContextImpl *pImpl = C->getContext().pImpl;
1764   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1765 }
1766
1767 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1768                                          bool InBounds) {
1769   if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1770     return FC;          // Fold a few common cases.
1771
1772   // Get the result type of the getelementptr!
1773   Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1774   assert(Ty && "GEP indices invalid!");
1775   unsigned AS = C->getType()->getPointerAddressSpace();
1776   Type *ReqTy = Ty->getPointerTo(AS);
1777
1778   assert(C->getType()->isPointerTy() &&
1779          "Non-pointer type for constant GetElementPtr expression");
1780   // Look up the constant in the table first to ensure uniqueness
1781   std::vector<Constant*> ArgVec;
1782   ArgVec.reserve(1 + Idxs.size());
1783   ArgVec.push_back(C);
1784   for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1785     ArgVec.push_back(cast<Constant>(Idxs[i]));
1786   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1787                            InBounds ? GEPOperator::IsInBounds : 0);
1788
1789   LLVMContextImpl *pImpl = C->getContext().pImpl;
1790   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1791 }
1792
1793 Constant *
1794 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1795   assert(LHS->getType() == RHS->getType());
1796   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1797          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1798
1799   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1800     return FC;          // Fold a few common cases...
1801
1802   // Look up the constant in the table first to ensure uniqueness
1803   std::vector<Constant*> ArgVec;
1804   ArgVec.push_back(LHS);
1805   ArgVec.push_back(RHS);
1806   // Get the key type with both the opcode and predicate
1807   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1808
1809   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1810   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1811     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1812
1813   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1814   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1815 }
1816
1817 Constant *
1818 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1819   assert(LHS->getType() == RHS->getType());
1820   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1821
1822   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1823     return FC;          // Fold a few common cases...
1824
1825   // Look up the constant in the table first to ensure uniqueness
1826   std::vector<Constant*> ArgVec;
1827   ArgVec.push_back(LHS);
1828   ArgVec.push_back(RHS);
1829   // Get the key type with both the opcode and predicate
1830   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1831
1832   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1833   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1834     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1835
1836   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1837   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1838 }
1839
1840 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1841   assert(Val->getType()->isVectorTy() &&
1842          "Tried to create extractelement operation on non-vector type!");
1843   assert(Idx->getType()->isIntegerTy(32) &&
1844          "Extractelement index must be i32 type!");
1845
1846   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1847     return FC;          // Fold a few common cases.
1848
1849   // Look up the constant in the table first to ensure uniqueness
1850   std::vector<Constant*> ArgVec(1, Val);
1851   ArgVec.push_back(Idx);
1852   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1853
1854   LLVMContextImpl *pImpl = Val->getContext().pImpl;
1855   Type *ReqTy = Val->getType()->getVectorElementType();
1856   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1857 }
1858
1859 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1860                                          Constant *Idx) {
1861   assert(Val->getType()->isVectorTy() &&
1862          "Tried to create insertelement operation on non-vector type!");
1863   assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1864          "Insertelement types must match!");
1865   assert(Idx->getType()->isIntegerTy(32) &&
1866          "Insertelement index must be i32 type!");
1867
1868   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1869     return FC;          // Fold a few common cases.
1870   // Look up the constant in the table first to ensure uniqueness
1871   std::vector<Constant*> ArgVec(1, Val);
1872   ArgVec.push_back(Elt);
1873   ArgVec.push_back(Idx);
1874   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1875
1876   LLVMContextImpl *pImpl = Val->getContext().pImpl;
1877   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1878 }
1879
1880 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1881                                          Constant *Mask) {
1882   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1883          "Invalid shuffle vector constant expr operands!");
1884
1885   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1886     return FC;          // Fold a few common cases.
1887
1888   unsigned NElts = Mask->getType()->getVectorNumElements();
1889   Type *EltTy = V1->getType()->getVectorElementType();
1890   Type *ShufTy = VectorType::get(EltTy, NElts);
1891
1892   // Look up the constant in the table first to ensure uniqueness
1893   std::vector<Constant*> ArgVec(1, V1);
1894   ArgVec.push_back(V2);
1895   ArgVec.push_back(Mask);
1896   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1897
1898   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1899   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1900 }
1901
1902 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1903                                        ArrayRef<unsigned> Idxs) {
1904   assert(ExtractValueInst::getIndexedType(Agg->getType(),
1905                                           Idxs) == Val->getType() &&
1906          "insertvalue indices invalid!");
1907   assert(Agg->getType()->isFirstClassType() &&
1908          "Non-first-class type for constant insertvalue expression");
1909   Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1910   assert(FC && "insertvalue constant expr couldn't be folded!");
1911   return FC;
1912 }
1913
1914 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1915                                         ArrayRef<unsigned> Idxs) {
1916   assert(Agg->getType()->isFirstClassType() &&
1917          "Tried to create extractelement operation on non-first-class type!");
1918
1919   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1920   (void)ReqTy;
1921   assert(ReqTy && "extractvalue indices invalid!");
1922
1923   assert(Agg->getType()->isFirstClassType() &&
1924          "Non-first-class type for constant extractvalue expression");
1925   Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1926   assert(FC && "ExtractValue constant expr couldn't be folded!");
1927   return FC;
1928 }
1929
1930 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1931   assert(C->getType()->isIntOrIntVectorTy() &&
1932          "Cannot NEG a nonintegral value!");
1933   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1934                 C, HasNUW, HasNSW);
1935 }
1936
1937 Constant *ConstantExpr::getFNeg(Constant *C) {
1938   assert(C->getType()->isFPOrFPVectorTy() &&
1939          "Cannot FNEG a non-floating-point value!");
1940   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1941 }
1942
1943 Constant *ConstantExpr::getNot(Constant *C) {
1944   assert(C->getType()->isIntOrIntVectorTy() &&
1945          "Cannot NOT a nonintegral value!");
1946   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1947 }
1948
1949 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1950                                bool HasNUW, bool HasNSW) {
1951   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1952                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1953   return get(Instruction::Add, C1, C2, Flags);
1954 }
1955
1956 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1957   return get(Instruction::FAdd, C1, C2);
1958 }
1959
1960 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1961                                bool HasNUW, bool HasNSW) {
1962   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1963                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1964   return get(Instruction::Sub, C1, C2, Flags);
1965 }
1966
1967 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1968   return get(Instruction::FSub, C1, C2);
1969 }
1970
1971 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1972                                bool HasNUW, bool HasNSW) {
1973   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1974                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1975   return get(Instruction::Mul, C1, C2, Flags);
1976 }
1977
1978 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1979   return get(Instruction::FMul, C1, C2);
1980 }
1981
1982 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1983   return get(Instruction::UDiv, C1, C2,
1984              isExact ? PossiblyExactOperator::IsExact : 0);
1985 }
1986
1987 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1988   return get(Instruction::SDiv, C1, C2,
1989              isExact ? PossiblyExactOperator::IsExact : 0);
1990 }
1991
1992 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1993   return get(Instruction::FDiv, C1, C2);
1994 }
1995
1996 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1997   return get(Instruction::URem, C1, C2);
1998 }
1999
2000 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2001   return get(Instruction::SRem, C1, C2);
2002 }
2003
2004 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2005   return get(Instruction::FRem, C1, C2);
2006 }
2007
2008 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2009   return get(Instruction::And, C1, C2);
2010 }
2011
2012 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2013   return get(Instruction::Or, C1, C2);
2014 }
2015
2016 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2017   return get(Instruction::Xor, C1, C2);
2018 }
2019
2020 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2021                                bool HasNUW, bool HasNSW) {
2022   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2023                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2024   return get(Instruction::Shl, C1, C2, Flags);
2025 }
2026
2027 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2028   return get(Instruction::LShr, C1, C2,
2029              isExact ? PossiblyExactOperator::IsExact : 0);
2030 }
2031
2032 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2033   return get(Instruction::AShr, C1, C2,
2034              isExact ? PossiblyExactOperator::IsExact : 0);
2035 }
2036
2037 /// getBinOpIdentity - Return the identity for the given binary operation,
2038 /// i.e. a constant C such that X op C = X and C op X = X for every X.  It
2039 /// returns null if the operator doesn't have an identity.
2040 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2041   switch (Opcode) {
2042   default:
2043     // Doesn't have an identity.
2044     return 0;
2045
2046   case Instruction::Add:
2047   case Instruction::Or:
2048   case Instruction::Xor:
2049     return Constant::getNullValue(Ty);
2050
2051   case Instruction::Mul:
2052     return ConstantInt::get(Ty, 1);
2053
2054   case Instruction::And:
2055     return Constant::getAllOnesValue(Ty);
2056   }
2057 }
2058
2059 /// getBinOpAbsorber - Return the absorbing element for the given binary
2060 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2061 /// every X.  For example, this returns zero for integer multiplication.
2062 /// It returns null if the operator doesn't have an absorbing element.
2063 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2064   switch (Opcode) {
2065   default:
2066     // Doesn't have an absorber.
2067     return 0;
2068
2069   case Instruction::Or:
2070     return Constant::getAllOnesValue(Ty);
2071
2072   case Instruction::And:
2073   case Instruction::Mul:
2074     return Constant::getNullValue(Ty);
2075   }
2076 }
2077
2078 // destroyConstant - Remove the constant from the constant table...
2079 //
2080 void ConstantExpr::destroyConstant() {
2081   getType()->getContext().pImpl->ExprConstants.remove(this);
2082   destroyConstantImpl();
2083 }
2084
2085 const char *ConstantExpr::getOpcodeName() const {
2086   return Instruction::getOpcodeName(getOpcode());
2087 }
2088
2089
2090
2091 GetElementPtrConstantExpr::
2092 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2093                           Type *DestTy)
2094   : ConstantExpr(DestTy, Instruction::GetElementPtr,
2095                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2096                  - (IdxList.size()+1), IdxList.size()+1) {
2097   OperandList[0] = C;
2098   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2099     OperandList[i+1] = IdxList[i];
2100 }
2101
2102 //===----------------------------------------------------------------------===//
2103 //                       ConstantData* implementations
2104
2105 void ConstantDataArray::anchor() {}
2106 void ConstantDataVector::anchor() {}
2107
2108 /// getElementType - Return the element type of the array/vector.
2109 Type *ConstantDataSequential::getElementType() const {
2110   return getType()->getElementType();
2111 }
2112
2113 StringRef ConstantDataSequential::getRawDataValues() const {
2114   return StringRef(DataElements, getNumElements()*getElementByteSize());
2115 }
2116
2117 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2118 /// formed with a vector or array of the specified element type.
2119 /// ConstantDataArray only works with normal float and int types that are
2120 /// stored densely in memory, not with things like i42 or x86_f80.
2121 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2122   if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2123   if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2124     switch (IT->getBitWidth()) {
2125     case 8:
2126     case 16:
2127     case 32:
2128     case 64:
2129       return true;
2130     default: break;
2131     }
2132   }
2133   return false;
2134 }
2135
2136 /// getNumElements - Return the number of elements in the array or vector.
2137 unsigned ConstantDataSequential::getNumElements() const {
2138   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2139     return AT->getNumElements();
2140   return getType()->getVectorNumElements();
2141 }
2142
2143
2144 /// getElementByteSize - Return the size in bytes of the elements in the data.
2145 uint64_t ConstantDataSequential::getElementByteSize() const {
2146   return getElementType()->getPrimitiveSizeInBits()/8;
2147 }
2148
2149 /// getElementPointer - Return the start of the specified element.
2150 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2151   assert(Elt < getNumElements() && "Invalid Elt");
2152   return DataElements+Elt*getElementByteSize();
2153 }
2154
2155
2156 /// isAllZeros - return true if the array is empty or all zeros.
2157 static bool isAllZeros(StringRef Arr) {
2158   for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2159     if (*I != 0)
2160       return false;
2161   return true;
2162 }
2163
2164 /// getImpl - This is the underlying implementation of all of the
2165 /// ConstantDataSequential::get methods.  They all thunk down to here, providing
2166 /// the correct element type.  We take the bytes in as a StringRef because
2167 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2168 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2169   assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2170   // If the elements are all zero or there are no elements, return a CAZ, which
2171   // is more dense and canonical.
2172   if (isAllZeros(Elements))
2173     return ConstantAggregateZero::get(Ty);
2174
2175   // Do a lookup to see if we have already formed one of these.
2176   StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2177     Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2178
2179   // The bucket can point to a linked list of different CDS's that have the same
2180   // body but different types.  For example, 0,0,0,1 could be a 4 element array
2181   // of i8, or a 1-element array of i32.  They'll both end up in the same
2182   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
2183   ConstantDataSequential **Entry = &Slot.getValue();
2184   for (ConstantDataSequential *Node = *Entry; Node != 0;
2185        Entry = &Node->Next, Node = *Entry)
2186     if (Node->getType() == Ty)
2187       return Node;
2188
2189   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
2190   // and return it.
2191   if (isa<ArrayType>(Ty))
2192     return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2193
2194   assert(isa<VectorType>(Ty));
2195   return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2196 }
2197
2198 void ConstantDataSequential::destroyConstant() {
2199   // Remove the constant from the StringMap.
2200   StringMap<ConstantDataSequential*> &CDSConstants = 
2201     getType()->getContext().pImpl->CDSConstants;
2202
2203   StringMap<ConstantDataSequential*>::iterator Slot =
2204     CDSConstants.find(getRawDataValues());
2205
2206   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2207
2208   ConstantDataSequential **Entry = &Slot->getValue();
2209
2210   // Remove the entry from the hash table.
2211   if ((*Entry)->Next == 0) {
2212     // If there is only one value in the bucket (common case) it must be this
2213     // entry, and removing the entry should remove the bucket completely.
2214     assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2215     getContext().pImpl->CDSConstants.erase(Slot);
2216   } else {
2217     // Otherwise, there are multiple entries linked off the bucket, unlink the 
2218     // node we care about but keep the bucket around.
2219     for (ConstantDataSequential *Node = *Entry; ;
2220          Entry = &Node->Next, Node = *Entry) {
2221       assert(Node && "Didn't find entry in its uniquing hash table!");
2222       // If we found our entry, unlink it from the list and we're done.
2223       if (Node == this) {
2224         *Entry = Node->Next;
2225         break;
2226       }
2227     }
2228   }
2229
2230   // If we were part of a list, make sure that we don't delete the list that is
2231   // still owned by the uniquing map.
2232   Next = 0;
2233
2234   // Finally, actually delete it.
2235   destroyConstantImpl();
2236 }
2237
2238 /// get() constructors - Return a constant with array type with an element
2239 /// count and element type matching the ArrayRef passed in.  Note that this
2240 /// can return a ConstantAggregateZero object.
2241 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2242   Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2243   const char *Data = reinterpret_cast<const char *>(Elts.data());
2244   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2245 }
2246 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2247   Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2248   const char *Data = reinterpret_cast<const char *>(Elts.data());
2249   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2250 }
2251 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2252   Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2253   const char *Data = reinterpret_cast<const char *>(Elts.data());
2254   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2255 }
2256 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2257   Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2258   const char *Data = reinterpret_cast<const char *>(Elts.data());
2259   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2260 }
2261 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2262   Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2263   const char *Data = reinterpret_cast<const char *>(Elts.data());
2264   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2265 }
2266 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2267   Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2268   const char *Data = reinterpret_cast<const char *>(Elts.data());
2269   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2270 }
2271
2272 /// getString - This method constructs a CDS and initializes it with a text
2273 /// string. The default behavior (AddNull==true) causes a null terminator to
2274 /// be placed at the end of the array (increasing the length of the string by
2275 /// one more than the StringRef would normally indicate.  Pass AddNull=false
2276 /// to disable this behavior.
2277 Constant *ConstantDataArray::getString(LLVMContext &Context,
2278                                        StringRef Str, bool AddNull) {
2279   if (!AddNull) {
2280     const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2281     return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2282                Str.size()));
2283   }
2284
2285   SmallVector<uint8_t, 64> ElementVals;
2286   ElementVals.append(Str.begin(), Str.end());
2287   ElementVals.push_back(0);
2288   return get(Context, ElementVals);
2289 }
2290
2291 /// get() constructors - Return a constant with vector type with an element
2292 /// count and element type matching the ArrayRef passed in.  Note that this
2293 /// can return a ConstantAggregateZero object.
2294 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2295   Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2296   const char *Data = reinterpret_cast<const char *>(Elts.data());
2297   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2298 }
2299 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2300   Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2301   const char *Data = reinterpret_cast<const char *>(Elts.data());
2302   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2303 }
2304 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2305   Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2306   const char *Data = reinterpret_cast<const char *>(Elts.data());
2307   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2308 }
2309 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2310   Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2311   const char *Data = reinterpret_cast<const char *>(Elts.data());
2312   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2313 }
2314 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2315   Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2316   const char *Data = reinterpret_cast<const char *>(Elts.data());
2317   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2318 }
2319 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2320   Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2321   const char *Data = reinterpret_cast<const char *>(Elts.data());
2322   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2323 }
2324
2325 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2326   assert(isElementTypeCompatible(V->getType()) &&
2327          "Element type not compatible with ConstantData");
2328   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2329     if (CI->getType()->isIntegerTy(8)) {
2330       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2331       return get(V->getContext(), Elts);
2332     }
2333     if (CI->getType()->isIntegerTy(16)) {
2334       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2335       return get(V->getContext(), Elts);
2336     }
2337     if (CI->getType()->isIntegerTy(32)) {
2338       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2339       return get(V->getContext(), Elts);
2340     }
2341     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2342     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2343     return get(V->getContext(), Elts);
2344   }
2345
2346   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2347     if (CFP->getType()->isFloatTy()) {
2348       SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2349       return get(V->getContext(), Elts);
2350     }
2351     if (CFP->getType()->isDoubleTy()) {
2352       SmallVector<double, 16> Elts(NumElts,
2353                                    CFP->getValueAPF().convertToDouble());
2354       return get(V->getContext(), Elts);
2355     }
2356   }
2357   return ConstantVector::getSplat(NumElts, V);
2358 }
2359
2360
2361 /// getElementAsInteger - If this is a sequential container of integers (of
2362 /// any size), return the specified element in the low bits of a uint64_t.
2363 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2364   assert(isa<IntegerType>(getElementType()) &&
2365          "Accessor can only be used when element is an integer");
2366   const char *EltPtr = getElementPointer(Elt);
2367
2368   // The data is stored in host byte order, make sure to cast back to the right
2369   // type to load with the right endianness.
2370   switch (getElementType()->getIntegerBitWidth()) {
2371   default: llvm_unreachable("Invalid bitwidth for CDS");
2372   case 8:
2373     return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2374   case 16:
2375     return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2376   case 32:
2377     return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2378   case 64:
2379     return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2380   }
2381 }
2382
2383 /// getElementAsAPFloat - If this is a sequential container of floating point
2384 /// type, return the specified element as an APFloat.
2385 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2386   const char *EltPtr = getElementPointer(Elt);
2387
2388   switch (getElementType()->getTypeID()) {
2389   default:
2390     llvm_unreachable("Accessor can only be used when element is float/double!");
2391   case Type::FloatTyID: {
2392       const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2393       return APFloat(*const_cast<float *>(FloatPrt));
2394     }
2395   case Type::DoubleTyID: {
2396       const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2397       return APFloat(*const_cast<double *>(DoublePtr));
2398     }
2399   }
2400 }
2401
2402 /// getElementAsFloat - If this is an sequential container of floats, return
2403 /// the specified element as a float.
2404 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2405   assert(getElementType()->isFloatTy() &&
2406          "Accessor can only be used when element is a 'float'");
2407   const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2408   return *const_cast<float *>(EltPtr);
2409 }
2410
2411 /// getElementAsDouble - If this is an sequential container of doubles, return
2412 /// the specified element as a float.
2413 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2414   assert(getElementType()->isDoubleTy() &&
2415          "Accessor can only be used when element is a 'float'");
2416   const double *EltPtr =
2417       reinterpret_cast<const double *>(getElementPointer(Elt));
2418   return *const_cast<double *>(EltPtr);
2419 }
2420
2421 /// getElementAsConstant - Return a Constant for a specified index's element.
2422 /// Note that this has to compute a new constant to return, so it isn't as
2423 /// efficient as getElementAsInteger/Float/Double.
2424 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2425   if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2426     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2427
2428   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2429 }
2430
2431 /// isString - This method returns true if this is an array of i8.
2432 bool ConstantDataSequential::isString() const {
2433   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2434 }
2435
2436 /// isCString - This method returns true if the array "isString", ends with a
2437 /// nul byte, and does not contains any other nul bytes.
2438 bool ConstantDataSequential::isCString() const {
2439   if (!isString())
2440     return false;
2441
2442   StringRef Str = getAsString();
2443
2444   // The last value must be nul.
2445   if (Str.back() != 0) return false;
2446
2447   // Other elements must be non-nul.
2448   return Str.drop_back().find(0) == StringRef::npos;
2449 }
2450
2451 /// getSplatValue - If this is a splat constant, meaning that all of the
2452 /// elements have the same value, return that value. Otherwise return NULL.
2453 Constant *ConstantDataVector::getSplatValue() const {
2454   const char *Base = getRawDataValues().data();
2455
2456   // Compare elements 1+ to the 0'th element.
2457   unsigned EltSize = getElementByteSize();
2458   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2459     if (memcmp(Base, Base+i*EltSize, EltSize))
2460       return 0;
2461
2462   // If they're all the same, return the 0th one as a representative.
2463   return getElementAsConstant(0);
2464 }
2465
2466 //===----------------------------------------------------------------------===//
2467 //                replaceUsesOfWithOnConstant implementations
2468
2469 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2470 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2471 /// etc.
2472 ///
2473 /// Note that we intentionally replace all uses of From with To here.  Consider
2474 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2475 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2476 /// single invocation handles all 1000 uses.  Handling them one at a time would
2477 /// work, but would be really slow because it would have to unique each updated
2478 /// array instance.
2479 ///
2480 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2481                                                 Use *U) {
2482   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2483   Constant *ToC = cast<Constant>(To);
2484
2485   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2486
2487   SmallVector<Constant*, 8> Values;
2488   LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2489   Lookup.first = cast<ArrayType>(getType());
2490   Values.reserve(getNumOperands());  // Build replacement array.
2491
2492   // Fill values with the modified operands of the constant array.  Also,
2493   // compute whether this turns into an all-zeros array.
2494   unsigned NumUpdated = 0;
2495
2496   // Keep track of whether all the values in the array are "ToC".
2497   bool AllSame = true;
2498   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2499     Constant *Val = cast<Constant>(O->get());
2500     if (Val == From) {
2501       Val = ToC;
2502       ++NumUpdated;
2503     }
2504     Values.push_back(Val);
2505     AllSame &= Val == ToC;
2506   }
2507
2508   Constant *Replacement = 0;
2509   if (AllSame && ToC->isNullValue()) {
2510     Replacement = ConstantAggregateZero::get(getType());
2511   } else if (AllSame && isa<UndefValue>(ToC)) {
2512     Replacement = UndefValue::get(getType());
2513   } else {
2514     // Check to see if we have this array type already.
2515     Lookup.second = makeArrayRef(Values);
2516     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2517       pImpl->ArrayConstants.find(Lookup);
2518
2519     if (I != pImpl->ArrayConstants.map_end()) {
2520       Replacement = I->first;
2521     } else {
2522       // Okay, the new shape doesn't exist in the system yet.  Instead of
2523       // creating a new constant array, inserting it, replaceallusesof'ing the
2524       // old with the new, then deleting the old... just update the current one
2525       // in place!
2526       pImpl->ArrayConstants.remove(this);
2527
2528       // Update to the new value.  Optimize for the case when we have a single
2529       // operand that we're changing, but handle bulk updates efficiently.
2530       if (NumUpdated == 1) {
2531         unsigned OperandToUpdate = U - OperandList;
2532         assert(getOperand(OperandToUpdate) == From &&
2533                "ReplaceAllUsesWith broken!");
2534         setOperand(OperandToUpdate, ToC);
2535       } else {
2536         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2537           if (getOperand(i) == From)
2538             setOperand(i, ToC);
2539       }
2540       pImpl->ArrayConstants.insert(this);
2541       return;
2542     }
2543   }
2544
2545   // Otherwise, I do need to replace this with an existing value.
2546   assert(Replacement != this && "I didn't contain From!");
2547
2548   // Everyone using this now uses the replacement.
2549   replaceAllUsesWith(Replacement);
2550
2551   // Delete the old constant!
2552   destroyConstant();
2553 }
2554
2555 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2556                                                  Use *U) {
2557   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2558   Constant *ToC = cast<Constant>(To);
2559
2560   unsigned OperandToUpdate = U-OperandList;
2561   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2562
2563   SmallVector<Constant*, 8> Values;
2564   LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2565   Lookup.first = cast<StructType>(getType());
2566   Values.reserve(getNumOperands());  // Build replacement struct.
2567
2568   // Fill values with the modified operands of the constant struct.  Also,
2569   // compute whether this turns into an all-zeros struct.
2570   bool isAllZeros = false;
2571   bool isAllUndef = false;
2572   if (ToC->isNullValue()) {
2573     isAllZeros = true;
2574     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2575       Constant *Val = cast<Constant>(O->get());
2576       Values.push_back(Val);
2577       if (isAllZeros) isAllZeros = Val->isNullValue();
2578     }
2579   } else if (isa<UndefValue>(ToC)) {
2580     isAllUndef = true;
2581     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2582       Constant *Val = cast<Constant>(O->get());
2583       Values.push_back(Val);
2584       if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2585     }
2586   } else {
2587     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2588       Values.push_back(cast<Constant>(O->get()));
2589   }
2590   Values[OperandToUpdate] = ToC;
2591
2592   LLVMContextImpl *pImpl = getContext().pImpl;
2593
2594   Constant *Replacement = 0;
2595   if (isAllZeros) {
2596     Replacement = ConstantAggregateZero::get(getType());
2597   } else if (isAllUndef) {
2598     Replacement = UndefValue::get(getType());
2599   } else {
2600     // Check to see if we have this struct type already.
2601     Lookup.second = makeArrayRef(Values);
2602     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2603       pImpl->StructConstants.find(Lookup);
2604
2605     if (I != pImpl->StructConstants.map_end()) {
2606       Replacement = I->first;
2607     } else {
2608       // Okay, the new shape doesn't exist in the system yet.  Instead of
2609       // creating a new constant struct, inserting it, replaceallusesof'ing the
2610       // old with the new, then deleting the old... just update the current one
2611       // in place!
2612       pImpl->StructConstants.remove(this);
2613
2614       // Update to the new value.
2615       setOperand(OperandToUpdate, ToC);
2616       pImpl->StructConstants.insert(this);
2617       return;
2618     }
2619   }
2620
2621   assert(Replacement != this && "I didn't contain From!");
2622
2623   // Everyone using this now uses the replacement.
2624   replaceAllUsesWith(Replacement);
2625
2626   // Delete the old constant!
2627   destroyConstant();
2628 }
2629
2630 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2631                                                  Use *U) {
2632   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2633
2634   SmallVector<Constant*, 8> Values;
2635   Values.reserve(getNumOperands());  // Build replacement array...
2636   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2637     Constant *Val = getOperand(i);
2638     if (Val == From) Val = cast<Constant>(To);
2639     Values.push_back(Val);
2640   }
2641
2642   Constant *Replacement = get(Values);
2643   assert(Replacement != this && "I didn't contain From!");
2644
2645   // Everyone using this now uses the replacement.
2646   replaceAllUsesWith(Replacement);
2647
2648   // Delete the old constant!
2649   destroyConstant();
2650 }
2651
2652 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2653                                                Use *U) {
2654   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2655   Constant *To = cast<Constant>(ToV);
2656
2657   SmallVector<Constant*, 8> NewOps;
2658   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2659     Constant *Op = getOperand(i);
2660     NewOps.push_back(Op == From ? To : Op);
2661   }
2662
2663   Constant *Replacement = getWithOperands(NewOps);
2664   assert(Replacement != this && "I didn't contain From!");
2665
2666   // Everyone using this now uses the replacement.
2667   replaceAllUsesWith(Replacement);
2668
2669   // Delete the old constant!
2670   destroyConstant();
2671 }