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