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