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