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