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