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