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