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