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