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