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