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