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