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