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