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