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