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