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