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