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