1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
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 folding of constants for LLVM.  This implements the
11 // (internal) ConstantFold.h interface, which is used by the
12 // ConstantExpr::get* methods to automatically fold constants when possible.
13 //
14 // The current constant folding implementation is implemented in two pieces: the
15 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
16 // a dependence in IR on Target.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "ConstantFold.h"
21 #include "llvm/ADT/APSInt.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GetElementPtrTypeIterator.h"
27 #include "llvm/IR/GlobalAlias.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MathExtras.h"
36 using namespace llvm;
37 using namespace llvm::PatternMatch;
38 
39 //===----------------------------------------------------------------------===//
40 //                ConstantFold*Instruction Implementations
41 //===----------------------------------------------------------------------===//
42 
43 /// Convert the specified vector Constant node to the specified vector type.
44 /// At this point, we know that the elements of the input vector constant are
45 /// all simple integer or FP values.
46 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
47 
48   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
49   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
50 
51   // If this cast changes element count then we can't handle it here:
52   // doing so requires endianness information.  This should be handled by
53   // Analysis/ConstantFolding.cpp
54   unsigned NumElts = DstTy->getNumElements();
55   if (NumElts != CV->getType()->getVectorNumElements())
56     return nullptr;
57 
58   Type *DstEltTy = DstTy->getElementType();
59 
60   SmallVector<Constant*, 16> Result;
61   Type *Ty = IntegerType::get(CV->getContext(), 32);
62   for (unsigned i = 0; i != NumElts; ++i) {
63     Constant *C =
64       ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
65     C = ConstantExpr::getBitCast(C, DstEltTy);
66     Result.push_back(C);
67   }
68 
69   return ConstantVector::get(Result);
70 }
71 
72 /// This function determines which opcode to use to fold two constant cast
73 /// expressions together. It uses CastInst::isEliminableCastPair to determine
74 /// the opcode. Consequently its just a wrapper around that function.
75 /// Determine if it is valid to fold a cast of a cast
76 static unsigned
77 foldConstantCastPair(
78   unsigned opc,          ///< opcode of the second cast constant expression
79   ConstantExpr *Op,      ///< the first cast constant expression
80   Type *DstTy            ///< destination type of the first cast
81 ) {
82   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
83   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
84   assert(CastInst::isCast(opc) && "Invalid cast opcode");
85 
86   // The types and opcodes for the two Cast constant expressions
87   Type *SrcTy = Op->getOperand(0)->getType();
88   Type *MidTy = Op->getType();
89   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
90   Instruction::CastOps secondOp = Instruction::CastOps(opc);
91 
92   // Assume that pointers are never more than 64 bits wide, and only use this
93   // for the middle type. Otherwise we could end up folding away illegal
94   // bitcasts between address spaces with different sizes.
95   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
96 
97   // Let CastInst::isEliminableCastPair do the heavy lifting.
98   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
99                                         nullptr, FakeIntPtrTy, nullptr);
100 }
101 
102 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
103   Type *SrcTy = V->getType();
104   if (SrcTy == DestTy)
105     return V; // no-op cast
106 
107   // Check to see if we are casting a pointer to an aggregate to a pointer to
108   // the first element.  If so, return the appropriate GEP instruction.
109   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
110     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
111       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
112           && PTy->getElementType()->isSized()) {
113         SmallVector<Value*, 8> IdxList;
114         Value *Zero =
115           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
116         IdxList.push_back(Zero);
117         Type *ElTy = PTy->getElementType();
118         while (ElTy != DPTy->getElementType()) {
119           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
120             if (STy->getNumElements() == 0) break;
121             ElTy = STy->getElementType(0);
122             IdxList.push_back(Zero);
123           } else if (SequentialType *STy =
124                      dyn_cast<SequentialType>(ElTy)) {
125             ElTy = STy->getElementType();
126             IdxList.push_back(Zero);
127           } else {
128             break;
129           }
130         }
131 
132         if (ElTy == DPTy->getElementType())
133           // This GEP is inbounds because all indices are zero.
134           return ConstantExpr::getInBoundsGetElementPtr(PTy->getElementType(),
135                                                         V, IdxList);
136       }
137 
138   // Handle casts from one vector constant to another.  We know that the src
139   // and dest type have the same size (otherwise its an illegal cast).
140   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
141     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
142       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
143              "Not cast between same sized vectors!");
144       SrcTy = nullptr;
145       // First, check for null.  Undef is already handled.
146       if (isa<ConstantAggregateZero>(V))
147         return Constant::getNullValue(DestTy);
148 
149       // Handle ConstantVector and ConstantAggregateVector.
150       return BitCastConstantVector(V, DestPTy);
151     }
152 
153     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
154     // This allows for other simplifications (although some of them
155     // can only be handled by Analysis/ConstantFolding.cpp).
156     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
157       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
158   }
159 
160   // Finally, implement bitcast folding now.   The code below doesn't handle
161   // bitcast right.
162   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
163     return ConstantPointerNull::get(cast<PointerType>(DestTy));
164 
165   // Handle integral constant input.
166   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
167     if (DestTy->isIntegerTy())
168       // Integral -> Integral. This is a no-op because the bit widths must
169       // be the same. Consequently, we just fold to V.
170       return V;
171 
172     // See note below regarding the PPC_FP128 restriction.
173     if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
174       return ConstantFP::get(DestTy->getContext(),
175                              APFloat(DestTy->getFltSemantics(),
176                                      CI->getValue()));
177 
178     // Otherwise, can't fold this (vector?)
179     return nullptr;
180   }
181 
182   // Handle ConstantFP input: FP -> Integral.
183   if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
184     // PPC_FP128 is really the sum of two consecutive doubles, where the first
185     // double is always stored first in memory, regardless of the target
186     // endianness. The memory layout of i128, however, depends on the target
187     // endianness, and so we can't fold this without target endianness
188     // information. This should instead be handled by
189     // Analysis/ConstantFolding.cpp
190     if (FP->getType()->isPPC_FP128Ty())
191       return nullptr;
192 
193     // Make sure dest type is compatible with the folded integer constant.
194     if (!DestTy->isIntegerTy())
195       return nullptr;
196 
197     return ConstantInt::get(FP->getContext(),
198                             FP->getValueAPF().bitcastToAPInt());
199   }
200 
201   return nullptr;
202 }
203 
204 
205 /// V is an integer constant which only has a subset of its bytes used.
206 /// The bytes used are indicated by ByteStart (which is the first byte used,
207 /// counting from the least significant byte) and ByteSize, which is the number
208 /// of bytes used.
209 ///
210 /// This function analyzes the specified constant to see if the specified byte
211 /// range can be returned as a simplified constant.  If so, the constant is
212 /// returned, otherwise null is returned.
213 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
214                                       unsigned ByteSize) {
215   assert(C->getType()->isIntegerTy() &&
216          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
217          "Non-byte sized integer input");
218   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
219   assert(ByteSize && "Must be accessing some piece");
220   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
221   assert(ByteSize != CSize && "Should not extract everything");
222 
223   // Constant Integers are simple.
224   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
225     APInt V = CI->getValue();
226     if (ByteStart)
227       V.lshrInPlace(ByteStart*8);
228     V = V.trunc(ByteSize*8);
229     return ConstantInt::get(CI->getContext(), V);
230   }
231 
232   // In the input is a constant expr, we might be able to recursively simplify.
233   // If not, we definitely can't do anything.
234   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
235   if (!CE) return nullptr;
236 
237   switch (CE->getOpcode()) {
238   default: return nullptr;
239   case Instruction::Or: {
240     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
241     if (!RHS)
242       return nullptr;
243 
244     // X | -1 -> -1.
245     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
246       if (RHSC->isMinusOne())
247         return RHSC;
248 
249     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
250     if (!LHS)
251       return nullptr;
252     return ConstantExpr::getOr(LHS, RHS);
253   }
254   case Instruction::And: {
255     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
256     if (!RHS)
257       return nullptr;
258 
259     // X & 0 -> 0.
260     if (RHS->isNullValue())
261       return RHS;
262 
263     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
264     if (!LHS)
265       return nullptr;
266     return ConstantExpr::getAnd(LHS, RHS);
267   }
268   case Instruction::LShr: {
269     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
270     if (!Amt)
271       return nullptr;
272     unsigned ShAmt = Amt->getZExtValue();
273     // Cannot analyze non-byte shifts.
274     if ((ShAmt & 7) != 0)
275       return nullptr;
276     ShAmt >>= 3;
277 
278     // If the extract is known to be all zeros, return zero.
279     if (ByteStart >= CSize-ShAmt)
280       return Constant::getNullValue(IntegerType::get(CE->getContext(),
281                                                      ByteSize*8));
282     // If the extract is known to be fully in the input, extract it.
283     if (ByteStart+ByteSize+ShAmt <= CSize)
284       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
285 
286     // TODO: Handle the 'partially zero' case.
287     return nullptr;
288   }
289 
290   case Instruction::Shl: {
291     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
292     if (!Amt)
293       return nullptr;
294     unsigned ShAmt = Amt->getZExtValue();
295     // Cannot analyze non-byte shifts.
296     if ((ShAmt & 7) != 0)
297       return nullptr;
298     ShAmt >>= 3;
299 
300     // If the extract is known to be all zeros, return zero.
301     if (ByteStart+ByteSize <= ShAmt)
302       return Constant::getNullValue(IntegerType::get(CE->getContext(),
303                                                      ByteSize*8));
304     // If the extract is known to be fully in the input, extract it.
305     if (ByteStart >= ShAmt)
306       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
307 
308     // TODO: Handle the 'partially zero' case.
309     return nullptr;
310   }
311 
312   case Instruction::ZExt: {
313     unsigned SrcBitSize =
314       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
315 
316     // If extracting something that is completely zero, return 0.
317     if (ByteStart*8 >= SrcBitSize)
318       return Constant::getNullValue(IntegerType::get(CE->getContext(),
319                                                      ByteSize*8));
320 
321     // If exactly extracting the input, return it.
322     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
323       return CE->getOperand(0);
324 
325     // If extracting something completely in the input, if the input is a
326     // multiple of 8 bits, recurse.
327     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
328       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
329 
330     // Otherwise, if extracting a subset of the input, which is not multiple of
331     // 8 bits, do a shift and trunc to get the bits.
332     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
333       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
334       Constant *Res = CE->getOperand(0);
335       if (ByteStart)
336         Res = ConstantExpr::getLShr(Res,
337                                  ConstantInt::get(Res->getType(), ByteStart*8));
338       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
339                                                           ByteSize*8));
340     }
341 
342     // TODO: Handle the 'partially zero' case.
343     return nullptr;
344   }
345   }
346 }
347 
348 /// Return a ConstantExpr with type DestTy for sizeof on Ty, with any known
349 /// factors factored out. If Folded is false, return null if no factoring was
350 /// possible, to avoid endlessly bouncing an unfoldable expression back into the
351 /// top-level folder.
352 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded) {
353   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
354     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
355     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
356     return ConstantExpr::getNUWMul(E, N);
357   }
358 
359   if (StructType *STy = dyn_cast<StructType>(Ty))
360     if (!STy->isPacked()) {
361       unsigned NumElems = STy->getNumElements();
362       // An empty struct has size zero.
363       if (NumElems == 0)
364         return ConstantExpr::getNullValue(DestTy);
365       // Check for a struct with all members having the same size.
366       Constant *MemberSize =
367         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
368       bool AllSame = true;
369       for (unsigned i = 1; i != NumElems; ++i)
370         if (MemberSize !=
371             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
372           AllSame = false;
373           break;
374         }
375       if (AllSame) {
376         Constant *N = ConstantInt::get(DestTy, NumElems);
377         return ConstantExpr::getNUWMul(MemberSize, N);
378       }
379     }
380 
381   // Pointer size doesn't depend on the pointee type, so canonicalize them
382   // to an arbitrary pointee.
383   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
384     if (!PTy->getElementType()->isIntegerTy(1))
385       return
386         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
387                                          PTy->getAddressSpace()),
388                         DestTy, true);
389 
390   // If there's no interesting folding happening, bail so that we don't create
391   // a constant that looks like it needs folding but really doesn't.
392   if (!Folded)
393     return nullptr;
394 
395   // Base case: Get a regular sizeof expression.
396   Constant *C = ConstantExpr::getSizeOf(Ty);
397   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
398                                                     DestTy, false),
399                             C, DestTy);
400   return C;
401 }
402 
403 /// Return a ConstantExpr with type DestTy for alignof on Ty, with any known
404 /// factors factored out. If Folded is false, return null if no factoring was
405 /// possible, to avoid endlessly bouncing an unfoldable expression back into the
406 /// top-level folder.
407 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy, bool Folded) {
408   // The alignment of an array is equal to the alignment of the
409   // array element. Note that this is not always true for vectors.
410   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
411     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
412     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
413                                                       DestTy,
414                                                       false),
415                               C, DestTy);
416     return C;
417   }
418 
419   if (StructType *STy = dyn_cast<StructType>(Ty)) {
420     // Packed structs always have an alignment of 1.
421     if (STy->isPacked())
422       return ConstantInt::get(DestTy, 1);
423 
424     // Otherwise, struct alignment is the maximum alignment of any member.
425     // Without target data, we can't compare much, but we can check to see
426     // if all the members have the same alignment.
427     unsigned NumElems = STy->getNumElements();
428     // An empty struct has minimal alignment.
429     if (NumElems == 0)
430       return ConstantInt::get(DestTy, 1);
431     // Check for a struct with all members having the same alignment.
432     Constant *MemberAlign =
433       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
434     bool AllSame = true;
435     for (unsigned i = 1; i != NumElems; ++i)
436       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
437         AllSame = false;
438         break;
439       }
440     if (AllSame)
441       return MemberAlign;
442   }
443 
444   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
445   // to an arbitrary pointee.
446   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
447     if (!PTy->getElementType()->isIntegerTy(1))
448       return
449         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
450                                                            1),
451                                           PTy->getAddressSpace()),
452                          DestTy, true);
453 
454   // If there's no interesting folding happening, bail so that we don't create
455   // a constant that looks like it needs folding but really doesn't.
456   if (!Folded)
457     return nullptr;
458 
459   // Base case: Get a regular alignof expression.
460   Constant *C = ConstantExpr::getAlignOf(Ty);
461   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
462                                                     DestTy, false),
463                             C, DestTy);
464   return C;
465 }
466 
467 /// Return a ConstantExpr with type DestTy for offsetof on Ty and FieldNo, with
468 /// any known factors factored out. If Folded is false, return null if no
469 /// factoring was possible, to avoid endlessly bouncing an unfoldable expression
470 /// back into the top-level folder.
471 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo, Type *DestTy,
472                                    bool Folded) {
473   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
474     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
475                                                                 DestTy, false),
476                                         FieldNo, DestTy);
477     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
478     return ConstantExpr::getNUWMul(E, N);
479   }
480 
481   if (StructType *STy = dyn_cast<StructType>(Ty))
482     if (!STy->isPacked()) {
483       unsigned NumElems = STy->getNumElements();
484       // An empty struct has no members.
485       if (NumElems == 0)
486         return nullptr;
487       // Check for a struct with all members having the same size.
488       Constant *MemberSize =
489         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
490       bool AllSame = true;
491       for (unsigned i = 1; i != NumElems; ++i)
492         if (MemberSize !=
493             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
494           AllSame = false;
495           break;
496         }
497       if (AllSame) {
498         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
499                                                                     false,
500                                                                     DestTy,
501                                                                     false),
502                                             FieldNo, DestTy);
503         return ConstantExpr::getNUWMul(MemberSize, N);
504       }
505     }
506 
507   // If there's no interesting folding happening, bail so that we don't create
508   // a constant that looks like it needs folding but really doesn't.
509   if (!Folded)
510     return nullptr;
511 
512   // Base case: Get a regular offsetof expression.
513   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
514   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
515                                                     DestTy, false),
516                             C, DestTy);
517   return C;
518 }
519 
520 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
521                                             Type *DestTy) {
522   if (isa<UndefValue>(V)) {
523     // zext(undef) = 0, because the top bits will be zero.
524     // sext(undef) = 0, because the top bits will all be the same.
525     // [us]itofp(undef) = 0, because the result value is bounded.
526     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
527         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
528       return Constant::getNullValue(DestTy);
529     return UndefValue::get(DestTy);
530   }
531 
532   if (V->isNullValue() && !DestTy->isX86_MMXTy() &&
533       opc != Instruction::AddrSpaceCast)
534     return Constant::getNullValue(DestTy);
535 
536   // If the cast operand is a constant expression, there's a few things we can
537   // do to try to simplify it.
538   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
539     if (CE->isCast()) {
540       // Try hard to fold cast of cast because they are often eliminable.
541       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
542         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
543     } else if (CE->getOpcode() == Instruction::GetElementPtr &&
544                // Do not fold addrspacecast (gep 0, .., 0). It might make the
545                // addrspacecast uncanonicalized.
546                opc != Instruction::AddrSpaceCast &&
547                // Do not fold bitcast (gep) with inrange index, as this loses
548                // information.
549                !cast<GEPOperator>(CE)->getInRangeIndex().hasValue() &&
550                // Do not fold if the gep type is a vector, as bitcasting
551                // operand 0 of a vector gep will result in a bitcast between
552                // different sizes.
553                !CE->getType()->isVectorTy()) {
554       // If all of the indexes in the GEP are null values, there is no pointer
555       // adjustment going on.  We might as well cast the source pointer.
556       bool isAllNull = true;
557       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
558         if (!CE->getOperand(i)->isNullValue()) {
559           isAllNull = false;
560           break;
561         }
562       if (isAllNull)
563         // This is casting one pointer type to another, always BitCast
564         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
565     }
566   }
567 
568   // If the cast operand is a constant vector, perform the cast by
569   // operating on each element. In the cast of bitcasts, the element
570   // count may be mismatched; don't attempt to handle that here.
571   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
572       DestTy->isVectorTy() &&
573       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
574     SmallVector<Constant*, 16> res;
575     VectorType *DestVecTy = cast<VectorType>(DestTy);
576     Type *DstEltTy = DestVecTy->getElementType();
577     Type *Ty = IntegerType::get(V->getContext(), 32);
578     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
579       Constant *C =
580         ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
581       res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
582     }
583     return ConstantVector::get(res);
584   }
585 
586   // We actually have to do a cast now. Perform the cast according to the
587   // opcode specified.
588   switch (opc) {
589   default:
590     llvm_unreachable("Failed to cast constant expression");
591   case Instruction::FPTrunc:
592   case Instruction::FPExt:
593     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
594       bool ignored;
595       APFloat Val = FPC->getValueAPF();
596       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf() :
597                   DestTy->isFloatTy() ? APFloat::IEEEsingle() :
598                   DestTy->isDoubleTy() ? APFloat::IEEEdouble() :
599                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended() :
600                   DestTy->isFP128Ty() ? APFloat::IEEEquad() :
601                   DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble() :
602                   APFloat::Bogus(),
603                   APFloat::rmNearestTiesToEven, &ignored);
604       return ConstantFP::get(V->getContext(), Val);
605     }
606     return nullptr; // Can't fold.
607   case Instruction::FPToUI:
608   case Instruction::FPToSI:
609     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
610       const APFloat &V = FPC->getValueAPF();
611       bool ignored;
612       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
613       APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
614       if (APFloat::opInvalidOp ==
615           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
616         // Undefined behavior invoked - the destination type can't represent
617         // the input constant.
618         return UndefValue::get(DestTy);
619       }
620       return ConstantInt::get(FPC->getContext(), IntVal);
621     }
622     return nullptr; // Can't fold.
623   case Instruction::IntToPtr:   //always treated as unsigned
624     if (V->isNullValue())       // Is it an integral null value?
625       return ConstantPointerNull::get(cast<PointerType>(DestTy));
626     return nullptr;                   // Other pointer types cannot be casted
627   case Instruction::PtrToInt:   // always treated as unsigned
628     // Is it a null pointer value?
629     if (V->isNullValue())
630       return ConstantInt::get(DestTy, 0);
631     // If this is a sizeof-like expression, pull out multiplications by
632     // known factors to expose them to subsequent folding. If it's an
633     // alignof-like expression, factor out known factors.
634     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
635       if (CE->getOpcode() == Instruction::GetElementPtr &&
636           CE->getOperand(0)->isNullValue()) {
637         // FIXME: Looks like getFoldedSizeOf(), getFoldedOffsetOf() and
638         // getFoldedAlignOf() don't handle the case when DestTy is a vector of
639         // pointers yet. We end up in asserts in CastInst::getCastOpcode (see
640         // test/Analysis/ConstantFolding/cast-vector.ll). I've only seen this
641         // happen in one "real" C-code test case, so it does not seem to be an
642         // important optimization to handle vectors here. For now, simply bail
643         // out.
644         if (DestTy->isVectorTy())
645           return nullptr;
646         GEPOperator *GEPO = cast<GEPOperator>(CE);
647         Type *Ty = GEPO->getSourceElementType();
648         if (CE->getNumOperands() == 2) {
649           // Handle a sizeof-like expression.
650           Constant *Idx = CE->getOperand(1);
651           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
652           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
653             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
654                                                                 DestTy, false),
655                                         Idx, DestTy);
656             return ConstantExpr::getMul(C, Idx);
657           }
658         } else if (CE->getNumOperands() == 3 &&
659                    CE->getOperand(1)->isNullValue()) {
660           // Handle an alignof-like expression.
661           if (StructType *STy = dyn_cast<StructType>(Ty))
662             if (!STy->isPacked()) {
663               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
664               if (CI->isOne() &&
665                   STy->getNumElements() == 2 &&
666                   STy->getElementType(0)->isIntegerTy(1)) {
667                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
668               }
669             }
670           // Handle an offsetof-like expression.
671           if (Ty->isStructTy() || Ty->isArrayTy()) {
672             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
673                                                 DestTy, false))
674               return C;
675           }
676         }
677       }
678     // Other pointer types cannot be casted
679     return nullptr;
680   case Instruction::UIToFP:
681   case Instruction::SIToFP:
682     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
683       const APInt &api = CI->getValue();
684       APFloat apf(DestTy->getFltSemantics(),
685                   APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
686       apf.convertFromAPInt(api, opc==Instruction::SIToFP,
687                            APFloat::rmNearestTiesToEven);
688       return ConstantFP::get(V->getContext(), apf);
689     }
690     return nullptr;
691   case Instruction::ZExt:
692     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
693       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
694       return ConstantInt::get(V->getContext(),
695                               CI->getValue().zext(BitWidth));
696     }
697     return nullptr;
698   case Instruction::SExt:
699     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
700       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
701       return ConstantInt::get(V->getContext(),
702                               CI->getValue().sext(BitWidth));
703     }
704     return nullptr;
705   case Instruction::Trunc: {
706     if (V->getType()->isVectorTy())
707       return nullptr;
708 
709     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
710     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
711       return ConstantInt::get(V->getContext(),
712                               CI->getValue().trunc(DestBitWidth));
713     }
714 
715     // The input must be a constantexpr.  See if we can simplify this based on
716     // the bytes we are demanding.  Only do this if the source and dest are an
717     // even multiple of a byte.
718     if ((DestBitWidth & 7) == 0 &&
719         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
720       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
721         return Res;
722 
723     return nullptr;
724   }
725   case Instruction::BitCast:
726     return FoldBitCast(V, DestTy);
727   case Instruction::AddrSpaceCast:
728     return nullptr;
729   }
730 }
731 
732 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
733                                               Constant *V1, Constant *V2) {
734   // Check for i1 and vector true/false conditions.
735   if (Cond->isNullValue()) return V2;
736   if (Cond->isAllOnesValue()) return V1;
737 
738   // If the condition is a vector constant, fold the result elementwise.
739   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
740     SmallVector<Constant*, 16> Result;
741     Type *Ty = IntegerType::get(CondV->getContext(), 32);
742     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
743       Constant *V;
744       Constant *V1Element = ConstantExpr::getExtractElement(V1,
745                                                     ConstantInt::get(Ty, i));
746       Constant *V2Element = ConstantExpr::getExtractElement(V2,
747                                                     ConstantInt::get(Ty, i));
748       Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
749       if (V1Element == V2Element) {
750         V = V1Element;
751       } else if (isa<UndefValue>(Cond)) {
752         V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
753       } else {
754         if (!isa<ConstantInt>(Cond)) break;
755         V = Cond->isNullValue() ? V2Element : V1Element;
756       }
757       Result.push_back(V);
758     }
759 
760     // If we were able to build the vector, return it.
761     if (Result.size() == V1->getType()->getVectorNumElements())
762       return ConstantVector::get(Result);
763   }
764 
765   if (isa<UndefValue>(Cond)) {
766     if (isa<UndefValue>(V1)) return V1;
767     return V2;
768   }
769   if (isa<UndefValue>(V1)) return V2;
770   if (isa<UndefValue>(V2)) return V1;
771   if (V1 == V2) return V1;
772 
773   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
774     if (TrueVal->getOpcode() == Instruction::Select)
775       if (TrueVal->getOperand(0) == Cond)
776         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
777   }
778   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
779     if (FalseVal->getOpcode() == Instruction::Select)
780       if (FalseVal->getOperand(0) == Cond)
781         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
782   }
783 
784   return nullptr;
785 }
786 
787 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
788                                                       Constant *Idx) {
789   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
790     return UndefValue::get(Val->getType()->getVectorElementType());
791   if (Val->isNullValue())  // ee(zero, x) -> zero
792     return Constant::getNullValue(Val->getType()->getVectorElementType());
793   // ee({w,x,y,z}, undef) -> undef
794   if (isa<UndefValue>(Idx))
795     return UndefValue::get(Val->getType()->getVectorElementType());
796 
797   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
798     // ee({w,x,y,z}, wrong_value) -> undef
799     if (CIdx->uge(Val->getType()->getVectorNumElements()))
800       return UndefValue::get(Val->getType()->getVectorElementType());
801     return Val->getAggregateElement(CIdx->getZExtValue());
802   }
803   return nullptr;
804 }
805 
806 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
807                                                      Constant *Elt,
808                                                      Constant *Idx) {
809   if (isa<UndefValue>(Idx))
810     return UndefValue::get(Val->getType());
811 
812   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
813   if (!CIdx) return nullptr;
814 
815   unsigned NumElts = Val->getType()->getVectorNumElements();
816   if (CIdx->uge(NumElts))
817     return UndefValue::get(Val->getType());
818 
819   SmallVector<Constant*, 16> Result;
820   Result.reserve(NumElts);
821   auto *Ty = Type::getInt32Ty(Val->getContext());
822   uint64_t IdxVal = CIdx->getZExtValue();
823   for (unsigned i = 0; i != NumElts; ++i) {
824     if (i == IdxVal) {
825       Result.push_back(Elt);
826       continue;
827     }
828 
829     Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
830     Result.push_back(C);
831   }
832 
833   return ConstantVector::get(Result);
834 }
835 
836 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
837                                                      Constant *V2,
838                                                      Constant *Mask) {
839   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
840   Type *EltTy = V1->getType()->getVectorElementType();
841 
842   // Undefined shuffle mask -> undefined value.
843   if (isa<UndefValue>(Mask))
844     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
845 
846   // Don't break the bitcode reader hack.
847   if (isa<ConstantExpr>(Mask)) return nullptr;
848 
849   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
850 
851   // Loop over the shuffle mask, evaluating each element.
852   SmallVector<Constant*, 32> Result;
853   for (unsigned i = 0; i != MaskNumElts; ++i) {
854     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
855     if (Elt == -1) {
856       Result.push_back(UndefValue::get(EltTy));
857       continue;
858     }
859     Constant *InElt;
860     if (unsigned(Elt) >= SrcNumElts*2)
861       InElt = UndefValue::get(EltTy);
862     else if (unsigned(Elt) >= SrcNumElts) {
863       Type *Ty = IntegerType::get(V2->getContext(), 32);
864       InElt =
865         ConstantExpr::getExtractElement(V2,
866                                         ConstantInt::get(Ty, Elt - SrcNumElts));
867     } else {
868       Type *Ty = IntegerType::get(V1->getContext(), 32);
869       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
870     }
871     Result.push_back(InElt);
872   }
873 
874   return ConstantVector::get(Result);
875 }
876 
877 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
878                                                     ArrayRef<unsigned> Idxs) {
879   // Base case: no indices, so return the entire value.
880   if (Idxs.empty())
881     return Agg;
882 
883   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
884     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
885 
886   return nullptr;
887 }
888 
889 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
890                                                    Constant *Val,
891                                                    ArrayRef<unsigned> Idxs) {
892   // Base case: no indices, so replace the entire value.
893   if (Idxs.empty())
894     return Val;
895 
896   unsigned NumElts;
897   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
898     NumElts = ST->getNumElements();
899   else
900     NumElts = cast<SequentialType>(Agg->getType())->getNumElements();
901 
902   SmallVector<Constant*, 32> Result;
903   for (unsigned i = 0; i != NumElts; ++i) {
904     Constant *C = Agg->getAggregateElement(i);
905     if (!C) return nullptr;
906 
907     if (Idxs[0] == i)
908       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
909 
910     Result.push_back(C);
911   }
912 
913   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
914     return ConstantStruct::get(ST, Result);
915   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
916     return ConstantArray::get(AT, Result);
917   return ConstantVector::get(Result);
918 }
919 
920 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
921                                               Constant *C2) {
922   assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
923 
924   // Handle scalar UndefValue. Vectors are always evaluated per element.
925   bool HasScalarUndef = !C1->getType()->isVectorTy() &&
926                         (isa<UndefValue>(C1) || isa<UndefValue>(C2));
927   if (HasScalarUndef) {
928     switch (static_cast<Instruction::BinaryOps>(Opcode)) {
929     case Instruction::Xor:
930       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
931         // Handle undef ^ undef -> 0 special case. This is a common
932         // idiom (misuse).
933         return Constant::getNullValue(C1->getType());
934       LLVM_FALLTHROUGH;
935     case Instruction::Add:
936     case Instruction::Sub:
937       return UndefValue::get(C1->getType());
938     case Instruction::And:
939       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
940         return C1;
941       return Constant::getNullValue(C1->getType());   // undef & X -> 0
942     case Instruction::Mul: {
943       // undef * undef -> undef
944       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
945         return C1;
946       const APInt *CV;
947       // X * undef -> undef   if X is odd
948       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
949         if ((*CV)[0])
950           return UndefValue::get(C1->getType());
951 
952       // X * undef -> 0       otherwise
953       return Constant::getNullValue(C1->getType());
954     }
955     case Instruction::SDiv:
956     case Instruction::UDiv:
957       // X / undef -> undef
958       if (isa<UndefValue>(C2))
959         return C2;
960       // undef / 0 -> undef
961       // undef / 1 -> undef
962       if (match(C2, m_Zero()) || match(C2, m_One()))
963         return C1;
964       // undef / X -> 0       otherwise
965       return Constant::getNullValue(C1->getType());
966     case Instruction::URem:
967     case Instruction::SRem:
968       // X % undef -> undef
969       if (match(C2, m_Undef()))
970         return C2;
971       // undef % 0 -> undef
972       if (match(C2, m_Zero()))
973         return C1;
974       // undef % X -> 0       otherwise
975       return Constant::getNullValue(C1->getType());
976     case Instruction::Or:                          // X | undef -> -1
977       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
978         return C1;
979       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
980     case Instruction::LShr:
981       // X >>l undef -> undef
982       if (isa<UndefValue>(C2))
983         return C2;
984       // undef >>l 0 -> undef
985       if (match(C2, m_Zero()))
986         return C1;
987       // undef >>l X -> 0
988       return Constant::getNullValue(C1->getType());
989     case Instruction::AShr:
990       // X >>a undef -> undef
991       if (isa<UndefValue>(C2))
992         return C2;
993       // undef >>a 0 -> undef
994       if (match(C2, m_Zero()))
995         return C1;
996       // TODO: undef >>a X -> undef if the shift is exact
997       // undef >>a X -> 0
998       return Constant::getNullValue(C1->getType());
999     case Instruction::Shl:
1000       // X << undef -> undef
1001       if (isa<UndefValue>(C2))
1002         return C2;
1003       // undef << 0 -> undef
1004       if (match(C2, m_Zero()))
1005         return C1;
1006       // undef << X -> 0
1007       return Constant::getNullValue(C1->getType());
1008     case Instruction::FAdd:
1009     case Instruction::FSub:
1010     case Instruction::FMul:
1011     case Instruction::FDiv:
1012     case Instruction::FRem:
1013       // [any flop] undef, undef -> undef
1014       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1015         return C1;
1016       // [any flop] C, undef -> NaN
1017       // [any flop] undef, C -> NaN
1018       // We could potentially specialize NaN/Inf constants vs. 'normal'
1019       // constants (possibly differently depending on opcode and operand). This
1020       // would allow returning undef sometimes. But it is always safe to fold to
1021       // NaN because we can choose the undef operand as NaN, and any FP opcode
1022       // with a NaN operand will propagate NaN.
1023       return ConstantFP::getNaN(C1->getType());
1024     case Instruction::BinaryOpsEnd:
1025       llvm_unreachable("Invalid BinaryOp");
1026     }
1027   }
1028 
1029   // Neither constant should be UndefValue, unless these are vector constants.
1030   assert(!HasScalarUndef && "Unexpected UndefValue");
1031 
1032   // Handle simplifications when the RHS is a constant int.
1033   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1034     switch (Opcode) {
1035     case Instruction::Add:
1036       if (CI2->isZero()) return C1;                             // X + 0 == X
1037       break;
1038     case Instruction::Sub:
1039       if (CI2->isZero()) return C1;                             // X - 0 == X
1040       break;
1041     case Instruction::Mul:
1042       if (CI2->isZero()) return C2;                             // X * 0 == 0
1043       if (CI2->isOne())
1044         return C1;                                              // X * 1 == X
1045       break;
1046     case Instruction::UDiv:
1047     case Instruction::SDiv:
1048       if (CI2->isOne())
1049         return C1;                                            // X / 1 == X
1050       if (CI2->isZero())
1051         return UndefValue::get(CI2->getType());               // X / 0 == undef
1052       break;
1053     case Instruction::URem:
1054     case Instruction::SRem:
1055       if (CI2->isOne())
1056         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
1057       if (CI2->isZero())
1058         return UndefValue::get(CI2->getType());               // X % 0 == undef
1059       break;
1060     case Instruction::And:
1061       if (CI2->isZero()) return C2;                           // X & 0 == 0
1062       if (CI2->isMinusOne())
1063         return C1;                                            // X & -1 == X
1064 
1065       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1066         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1067         if (CE1->getOpcode() == Instruction::ZExt) {
1068           unsigned DstWidth = CI2->getType()->getBitWidth();
1069           unsigned SrcWidth =
1070             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1071           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1072           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1073             return C1;
1074         }
1075 
1076         // If and'ing the address of a global with a constant, fold it.
1077         if (CE1->getOpcode() == Instruction::PtrToInt &&
1078             isa<GlobalValue>(CE1->getOperand(0))) {
1079           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1080 
1081           unsigned GVAlign =
1082               GV->getParent()
1083                   ? GV->getPointerAlignment(GV->getParent()->getDataLayout())
1084                   : 0;
1085 
1086           if (GVAlign > 1) {
1087             unsigned DstWidth = CI2->getType()->getBitWidth();
1088             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1089             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1090 
1091             // If checking bits we know are clear, return zero.
1092             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1093               return Constant::getNullValue(CI2->getType());
1094           }
1095         }
1096       }
1097       break;
1098     case Instruction::Or:
1099       if (CI2->isZero()) return C1;        // X | 0 == X
1100       if (CI2->isMinusOne())
1101         return C2;                         // X | -1 == -1
1102       break;
1103     case Instruction::Xor:
1104       if (CI2->isZero()) return C1;        // X ^ 0 == X
1105 
1106       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1107         switch (CE1->getOpcode()) {
1108         default: break;
1109         case Instruction::ICmp:
1110         case Instruction::FCmp:
1111           // cmp pred ^ true -> cmp !pred
1112           assert(CI2->isOne());
1113           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1114           pred = CmpInst::getInversePredicate(pred);
1115           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1116                                           CE1->getOperand(1));
1117         }
1118       }
1119       break;
1120     case Instruction::AShr:
1121       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1122       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1123         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1124           return ConstantExpr::getLShr(C1, C2);
1125       break;
1126     }
1127   } else if (isa<ConstantInt>(C1)) {
1128     // If C1 is a ConstantInt and C2 is not, swap the operands.
1129     if (Instruction::isCommutative(Opcode))
1130       return ConstantExpr::get(Opcode, C2, C1);
1131   }
1132 
1133   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1134     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1135       const APInt &C1V = CI1->getValue();
1136       const APInt &C2V = CI2->getValue();
1137       switch (Opcode) {
1138       default:
1139         break;
1140       case Instruction::Add:
1141         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1142       case Instruction::Sub:
1143         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1144       case Instruction::Mul:
1145         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1146       case Instruction::UDiv:
1147         assert(!CI2->isZero() && "Div by zero handled above");
1148         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1149       case Instruction::SDiv:
1150         assert(!CI2->isZero() && "Div by zero handled above");
1151         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1152           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1153         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1154       case Instruction::URem:
1155         assert(!CI2->isZero() && "Div by zero handled above");
1156         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1157       case Instruction::SRem:
1158         assert(!CI2->isZero() && "Div by zero handled above");
1159         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1160           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1161         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1162       case Instruction::And:
1163         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1164       case Instruction::Or:
1165         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1166       case Instruction::Xor:
1167         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1168       case Instruction::Shl:
1169         if (C2V.ult(C1V.getBitWidth()))
1170           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
1171         return UndefValue::get(C1->getType()); // too big shift is undef
1172       case Instruction::LShr:
1173         if (C2V.ult(C1V.getBitWidth()))
1174           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
1175         return UndefValue::get(C1->getType()); // too big shift is undef
1176       case Instruction::AShr:
1177         if (C2V.ult(C1V.getBitWidth()))
1178           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
1179         return UndefValue::get(C1->getType()); // too big shift is undef
1180       }
1181     }
1182 
1183     switch (Opcode) {
1184     case Instruction::SDiv:
1185     case Instruction::UDiv:
1186     case Instruction::URem:
1187     case Instruction::SRem:
1188     case Instruction::LShr:
1189     case Instruction::AShr:
1190     case Instruction::Shl:
1191       if (CI1->isZero()) return C1;
1192       break;
1193     default:
1194       break;
1195     }
1196   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1197     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1198       const APFloat &C1V = CFP1->getValueAPF();
1199       const APFloat &C2V = CFP2->getValueAPF();
1200       APFloat C3V = C1V;  // copy for modification
1201       switch (Opcode) {
1202       default:
1203         break;
1204       case Instruction::FAdd:
1205         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1206         return ConstantFP::get(C1->getContext(), C3V);
1207       case Instruction::FSub:
1208         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1209         return ConstantFP::get(C1->getContext(), C3V);
1210       case Instruction::FMul:
1211         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1212         return ConstantFP::get(C1->getContext(), C3V);
1213       case Instruction::FDiv:
1214         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1215         return ConstantFP::get(C1->getContext(), C3V);
1216       case Instruction::FRem:
1217         (void)C3V.mod(C2V);
1218         return ConstantFP::get(C1->getContext(), C3V);
1219       }
1220     }
1221   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1222     // Fold each element and create a vector constant from those constants.
1223     SmallVector<Constant*, 16> Result;
1224     Type *Ty = IntegerType::get(VTy->getContext(), 32);
1225     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1226       Constant *ExtractIdx = ConstantInt::get(Ty, i);
1227       Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
1228       Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
1229 
1230       // If any element of a divisor vector is zero, the whole op is undef.
1231       if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
1232         return UndefValue::get(VTy);
1233 
1234       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1235     }
1236 
1237     return ConstantVector::get(Result);
1238   }
1239 
1240   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1241     // There are many possible foldings we could do here.  We should probably
1242     // at least fold add of a pointer with an integer into the appropriate
1243     // getelementptr.  This will improve alias analysis a bit.
1244 
1245     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1246     // (a + (b + c)).
1247     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1248       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1249       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1250         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1251     }
1252   } else if (isa<ConstantExpr>(C2)) {
1253     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1254     // other way if possible.
1255     if (Instruction::isCommutative(Opcode))
1256       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1257   }
1258 
1259   // i1 can be simplified in many cases.
1260   if (C1->getType()->isIntegerTy(1)) {
1261     switch (Opcode) {
1262     case Instruction::Add:
1263     case Instruction::Sub:
1264       return ConstantExpr::getXor(C1, C2);
1265     case Instruction::Mul:
1266       return ConstantExpr::getAnd(C1, C2);
1267     case Instruction::Shl:
1268     case Instruction::LShr:
1269     case Instruction::AShr:
1270       // We can assume that C2 == 0.  If it were one the result would be
1271       // undefined because the shift value is as large as the bitwidth.
1272       return C1;
1273     case Instruction::SDiv:
1274     case Instruction::UDiv:
1275       // We can assume that C2 == 1.  If it were zero the result would be
1276       // undefined through division by zero.
1277       return C1;
1278     case Instruction::URem:
1279     case Instruction::SRem:
1280       // We can assume that C2 == 1.  If it were zero the result would be
1281       // undefined through division by zero.
1282       return ConstantInt::getFalse(C1->getContext());
1283     default:
1284       break;
1285     }
1286   }
1287 
1288   // We don't know how to fold this.
1289   return nullptr;
1290 }
1291 
1292 /// This type is zero-sized if it's an array or structure of zero-sized types.
1293 /// The only leaf zero-sized type is an empty structure.
1294 static bool isMaybeZeroSizedType(Type *Ty) {
1295   if (StructType *STy = dyn_cast<StructType>(Ty)) {
1296     if (STy->isOpaque()) return true;  // Can't say.
1297 
1298     // If all of elements have zero size, this does too.
1299     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1300       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1301     return true;
1302 
1303   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1304     return isMaybeZeroSizedType(ATy->getElementType());
1305   }
1306   return false;
1307 }
1308 
1309 /// Compare the two constants as though they were getelementptr indices.
1310 /// This allows coercion of the types to be the same thing.
1311 ///
1312 /// If the two constants are the "same" (after coercion), return 0.  If the
1313 /// first is less than the second, return -1, if the second is less than the
1314 /// first, return 1.  If the constants are not integral, return -2.
1315 ///
1316 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1317   if (C1 == C2) return 0;
1318 
1319   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1320   // anything with them.
1321   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1322     return -2; // don't know!
1323 
1324   // We cannot compare the indices if they don't fit in an int64_t.
1325   if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
1326       cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
1327     return -2; // don't know!
1328 
1329   // Ok, we have two differing integer indices.  Sign extend them to be the same
1330   // type.
1331   int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
1332   int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
1333 
1334   if (C1Val == C2Val) return 0;  // They are equal
1335 
1336   // If the type being indexed over is really just a zero sized type, there is
1337   // no pointer difference being made here.
1338   if (isMaybeZeroSizedType(ElTy))
1339     return -2; // dunno.
1340 
1341   // If they are really different, now that they are the same type, then we
1342   // found a difference!
1343   if (C1Val < C2Val)
1344     return -1;
1345   else
1346     return 1;
1347 }
1348 
1349 /// This function determines if there is anything we can decide about the two
1350 /// constants provided. This doesn't need to handle simple things like
1351 /// ConstantFP comparisons, but should instead handle ConstantExprs.
1352 /// If we can determine that the two constants have a particular relation to
1353 /// each other, we should return the corresponding FCmpInst predicate,
1354 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1355 /// ConstantFoldCompareInstruction.
1356 ///
1357 /// To simplify this code we canonicalize the relation so that the first
1358 /// operand is always the most "complex" of the two.  We consider ConstantFP
1359 /// to be the simplest, and ConstantExprs to be the most complex.
1360 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1361   assert(V1->getType() == V2->getType() &&
1362          "Cannot compare values of different types!");
1363 
1364   // Handle degenerate case quickly
1365   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1366 
1367   if (!isa<ConstantExpr>(V1)) {
1368     if (!isa<ConstantExpr>(V2)) {
1369       // Simple case, use the standard constant folder.
1370       ConstantInt *R = nullptr;
1371       R = dyn_cast<ConstantInt>(
1372                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1373       if (R && !R->isZero())
1374         return FCmpInst::FCMP_OEQ;
1375       R = dyn_cast<ConstantInt>(
1376                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1377       if (R && !R->isZero())
1378         return FCmpInst::FCMP_OLT;
1379       R = dyn_cast<ConstantInt>(
1380                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1381       if (R && !R->isZero())
1382         return FCmpInst::FCMP_OGT;
1383 
1384       // Nothing more we can do
1385       return FCmpInst::BAD_FCMP_PREDICATE;
1386     }
1387 
1388     // If the first operand is simple and second is ConstantExpr, swap operands.
1389     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1390     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1391       return FCmpInst::getSwappedPredicate(SwappedRelation);
1392   } else {
1393     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1394     // constantexpr or a simple constant.
1395     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1396     switch (CE1->getOpcode()) {
1397     case Instruction::FPTrunc:
1398     case Instruction::FPExt:
1399     case Instruction::UIToFP:
1400     case Instruction::SIToFP:
1401       // We might be able to do something with these but we don't right now.
1402       break;
1403     default:
1404       break;
1405     }
1406   }
1407   // There are MANY other foldings that we could perform here.  They will
1408   // probably be added on demand, as they seem needed.
1409   return FCmpInst::BAD_FCMP_PREDICATE;
1410 }
1411 
1412 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1413                                                       const GlobalValue *GV2) {
1414   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1415     if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
1416       return true;
1417     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1418       Type *Ty = GVar->getValueType();
1419       // A global with opaque type might end up being zero sized.
1420       if (!Ty->isSized())
1421         return true;
1422       // A global with an empty type might lie at the address of any other
1423       // global.
1424       if (Ty->isEmptyTy())
1425         return true;
1426     }
1427     return false;
1428   };
1429   // Don't try to decide equality of aliases.
1430   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1431     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1432       return ICmpInst::ICMP_NE;
1433   return ICmpInst::BAD_ICMP_PREDICATE;
1434 }
1435 
1436 /// This function determines if there is anything we can decide about the two
1437 /// constants provided. This doesn't need to handle simple things like integer
1438 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
1439 /// If we can determine that the two constants have a particular relation to
1440 /// each other, we should return the corresponding ICmp predicate, otherwise
1441 /// return ICmpInst::BAD_ICMP_PREDICATE.
1442 ///
1443 /// To simplify this code we canonicalize the relation so that the first
1444 /// operand is always the most "complex" of the two.  We consider simple
1445 /// constants (like ConstantInt) to be the simplest, followed by
1446 /// GlobalValues, followed by ConstantExpr's (the most complex).
1447 ///
1448 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1449                                                 bool isSigned) {
1450   assert(V1->getType() == V2->getType() &&
1451          "Cannot compare different types of values!");
1452   if (V1 == V2) return ICmpInst::ICMP_EQ;
1453 
1454   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1455       !isa<BlockAddress>(V1)) {
1456     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1457         !isa<BlockAddress>(V2)) {
1458       // We distilled this down to a simple case, use the standard constant
1459       // folder.
1460       ConstantInt *R = nullptr;
1461       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1462       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1463       if (R && !R->isZero())
1464         return pred;
1465       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1466       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1467       if (R && !R->isZero())
1468         return pred;
1469       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1470       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1471       if (R && !R->isZero())
1472         return pred;
1473 
1474       // If we couldn't figure it out, bail.
1475       return ICmpInst::BAD_ICMP_PREDICATE;
1476     }
1477 
1478     // If the first operand is simple, swap operands.
1479     ICmpInst::Predicate SwappedRelation =
1480       evaluateICmpRelation(V2, V1, isSigned);
1481     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1482       return ICmpInst::getSwappedPredicate(SwappedRelation);
1483 
1484   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1485     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1486       ICmpInst::Predicate SwappedRelation =
1487         evaluateICmpRelation(V2, V1, isSigned);
1488       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1489         return ICmpInst::getSwappedPredicate(SwappedRelation);
1490       return ICmpInst::BAD_ICMP_PREDICATE;
1491     }
1492 
1493     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1494     // constant (which, since the types must match, means that it's a
1495     // ConstantPointerNull).
1496     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1497       return areGlobalsPotentiallyEqual(GV, GV2);
1498     } else if (isa<BlockAddress>(V2)) {
1499       return ICmpInst::ICMP_NE; // Globals never equal labels.
1500     } else {
1501       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1502       // GlobalVals can never be null unless they have external weak linkage.
1503       // We don't try to evaluate aliases here.
1504       // NOTE: We should not be doing this constant folding if null pointer
1505       // is considered valid for the function. But currently there is no way to
1506       // query it from the Constant type.
1507       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
1508           !NullPointerIsDefined(nullptr /* F */,
1509                                 GV->getType()->getAddressSpace()))
1510         return ICmpInst::ICMP_NE;
1511     }
1512   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1513     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1514       ICmpInst::Predicate SwappedRelation =
1515         evaluateICmpRelation(V2, V1, isSigned);
1516       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1517         return ICmpInst::getSwappedPredicate(SwappedRelation);
1518       return ICmpInst::BAD_ICMP_PREDICATE;
1519     }
1520 
1521     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1522     // constant (which, since the types must match, means that it is a
1523     // ConstantPointerNull).
1524     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1525       // Block address in another function can't equal this one, but block
1526       // addresses in the current function might be the same if blocks are
1527       // empty.
1528       if (BA2->getFunction() != BA->getFunction())
1529         return ICmpInst::ICMP_NE;
1530     } else {
1531       // Block addresses aren't null, don't equal the address of globals.
1532       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1533              "Canonicalization guarantee!");
1534       return ICmpInst::ICMP_NE;
1535     }
1536   } else {
1537     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1538     // constantexpr, a global, block address, or a simple constant.
1539     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1540     Constant *CE1Op0 = CE1->getOperand(0);
1541 
1542     switch (CE1->getOpcode()) {
1543     case Instruction::Trunc:
1544     case Instruction::FPTrunc:
1545     case Instruction::FPExt:
1546     case Instruction::FPToUI:
1547     case Instruction::FPToSI:
1548       break; // We can't evaluate floating point casts or truncations.
1549 
1550     case Instruction::UIToFP:
1551     case Instruction::SIToFP:
1552     case Instruction::BitCast:
1553     case Instruction::ZExt:
1554     case Instruction::SExt:
1555       // We can't evaluate floating point casts or truncations.
1556       if (CE1Op0->getType()->isFloatingPointTy())
1557         break;
1558 
1559       // If the cast is not actually changing bits, and the second operand is a
1560       // null pointer, do the comparison with the pre-casted value.
1561       if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
1562         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1563         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1564         return evaluateICmpRelation(CE1Op0,
1565                                     Constant::getNullValue(CE1Op0->getType()),
1566                                     isSigned);
1567       }
1568       break;
1569 
1570     case Instruction::GetElementPtr: {
1571       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1572       // Ok, since this is a getelementptr, we know that the constant has a
1573       // pointer type.  Check the various cases.
1574       if (isa<ConstantPointerNull>(V2)) {
1575         // If we are comparing a GEP to a null pointer, check to see if the base
1576         // of the GEP equals the null pointer.
1577         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1578           if (GV->hasExternalWeakLinkage())
1579             // Weak linkage GVals could be zero or not. We're comparing that
1580             // to null pointer so its greater-or-equal
1581             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1582           else
1583             // If its not weak linkage, the GVal must have a non-zero address
1584             // so the result is greater-than
1585             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1586         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1587           // If we are indexing from a null pointer, check to see if we have any
1588           // non-zero indices.
1589           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1590             if (!CE1->getOperand(i)->isNullValue())
1591               // Offsetting from null, must not be equal.
1592               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1593           // Only zero indexes from null, must still be zero.
1594           return ICmpInst::ICMP_EQ;
1595         }
1596         // Otherwise, we can't really say if the first operand is null or not.
1597       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1598         if (isa<ConstantPointerNull>(CE1Op0)) {
1599           if (GV2->hasExternalWeakLinkage())
1600             // Weak linkage GVals could be zero or not. We're comparing it to
1601             // a null pointer, so its less-or-equal
1602             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1603           else
1604             // If its not weak linkage, the GVal must have a non-zero address
1605             // so the result is less-than
1606             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1607         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1608           if (GV == GV2) {
1609             // If this is a getelementptr of the same global, then it must be
1610             // different.  Because the types must match, the getelementptr could
1611             // only have at most one index, and because we fold getelementptr's
1612             // with a single zero index, it must be nonzero.
1613             assert(CE1->getNumOperands() == 2 &&
1614                    !CE1->getOperand(1)->isNullValue() &&
1615                    "Surprising getelementptr!");
1616             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1617           } else {
1618             if (CE1GEP->hasAllZeroIndices())
1619               return areGlobalsPotentiallyEqual(GV, GV2);
1620             return ICmpInst::BAD_ICMP_PREDICATE;
1621           }
1622         }
1623       } else {
1624         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1625         Constant *CE2Op0 = CE2->getOperand(0);
1626 
1627         // There are MANY other foldings that we could perform here.  They will
1628         // probably be added on demand, as they seem needed.
1629         switch (CE2->getOpcode()) {
1630         default: break;
1631         case Instruction::GetElementPtr:
1632           // By far the most common case to handle is when the base pointers are
1633           // obviously to the same global.
1634           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1635             // Don't know relative ordering, but check for inequality.
1636             if (CE1Op0 != CE2Op0) {
1637               GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1638               if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1639                 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1640                                                   cast<GlobalValue>(CE2Op0));
1641               return ICmpInst::BAD_ICMP_PREDICATE;
1642             }
1643             // Ok, we know that both getelementptr instructions are based on the
1644             // same global.  From this, we can precisely determine the relative
1645             // ordering of the resultant pointers.
1646             unsigned i = 1;
1647 
1648             // The logic below assumes that the result of the comparison
1649             // can be determined by finding the first index that differs.
1650             // This doesn't work if there is over-indexing in any
1651             // subsequent indices, so check for that case first.
1652             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1653                 !CE2->isGEPWithNoNotionalOverIndexing())
1654                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1655 
1656             // Compare all of the operands the GEP's have in common.
1657             gep_type_iterator GTI = gep_type_begin(CE1);
1658             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1659                  ++i, ++GTI)
1660               switch (IdxCompare(CE1->getOperand(i),
1661                                  CE2->getOperand(i), GTI.getIndexedType())) {
1662               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1663               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1664               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1665               }
1666 
1667             // Ok, we ran out of things they have in common.  If any leftovers
1668             // are non-zero then we have a difference, otherwise we are equal.
1669             for (; i < CE1->getNumOperands(); ++i)
1670               if (!CE1->getOperand(i)->isNullValue()) {
1671                 if (isa<ConstantInt>(CE1->getOperand(i)))
1672                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1673                 else
1674                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1675               }
1676 
1677             for (; i < CE2->getNumOperands(); ++i)
1678               if (!CE2->getOperand(i)->isNullValue()) {
1679                 if (isa<ConstantInt>(CE2->getOperand(i)))
1680                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1681                 else
1682                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1683               }
1684             return ICmpInst::ICMP_EQ;
1685           }
1686         }
1687       }
1688       break;
1689     }
1690     default:
1691       break;
1692     }
1693   }
1694 
1695   return ICmpInst::BAD_ICMP_PREDICATE;
1696 }
1697 
1698 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1699                                                Constant *C1, Constant *C2) {
1700   Type *ResultTy;
1701   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1702     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1703                                VT->getNumElements());
1704   else
1705     ResultTy = Type::getInt1Ty(C1->getContext());
1706 
1707   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1708   if (pred == FCmpInst::FCMP_FALSE)
1709     return Constant::getNullValue(ResultTy);
1710 
1711   if (pred == FCmpInst::FCMP_TRUE)
1712     return Constant::getAllOnesValue(ResultTy);
1713 
1714   // Handle some degenerate cases first
1715   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1716     CmpInst::Predicate Predicate = CmpInst::Predicate(pred);
1717     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
1718     // For EQ and NE, we can always pick a value for the undef to make the
1719     // predicate pass or fail, so we can return undef.
1720     // Also, if both operands are undef, we can return undef for int comparison.
1721     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
1722       return UndefValue::get(ResultTy);
1723 
1724     // Otherwise, for integer compare, pick the same value as the non-undef
1725     // operand, and fold it to true or false.
1726     if (isIntegerPredicate)
1727       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
1728 
1729     // Choosing NaN for the undef will always make unordered comparison succeed
1730     // and ordered comparison fails.
1731     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
1732   }
1733 
1734   // icmp eq/ne(null,GV) -> false/true
1735   if (C1->isNullValue()) {
1736     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1737       // Don't try to evaluate aliases.  External weak GV can be null.
1738       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
1739           !NullPointerIsDefined(nullptr /* F */,
1740                                 GV->getType()->getAddressSpace())) {
1741         if (pred == ICmpInst::ICMP_EQ)
1742           return ConstantInt::getFalse(C1->getContext());
1743         else if (pred == ICmpInst::ICMP_NE)
1744           return ConstantInt::getTrue(C1->getContext());
1745       }
1746   // icmp eq/ne(GV,null) -> false/true
1747   } else if (C2->isNullValue()) {
1748     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1749       // Don't try to evaluate aliases.  External weak GV can be null.
1750       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
1751           !NullPointerIsDefined(nullptr /* F */,
1752                                 GV->getType()->getAddressSpace())) {
1753         if (pred == ICmpInst::ICMP_EQ)
1754           return ConstantInt::getFalse(C1->getContext());
1755         else if (pred == ICmpInst::ICMP_NE)
1756           return ConstantInt::getTrue(C1->getContext());
1757       }
1758   }
1759 
1760   // If the comparison is a comparison between two i1's, simplify it.
1761   if (C1->getType()->isIntegerTy(1)) {
1762     switch(pred) {
1763     case ICmpInst::ICMP_EQ:
1764       if (isa<ConstantInt>(C2))
1765         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1766       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1767     case ICmpInst::ICMP_NE:
1768       return ConstantExpr::getXor(C1, C2);
1769     default:
1770       break;
1771     }
1772   }
1773 
1774   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1775     const APInt &V1 = cast<ConstantInt>(C1)->getValue();
1776     const APInt &V2 = cast<ConstantInt>(C2)->getValue();
1777     switch (pred) {
1778     default: llvm_unreachable("Invalid ICmp Predicate");
1779     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1780     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1781     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1782     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1783     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1784     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1785     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1786     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1787     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1788     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1789     }
1790   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1791     const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
1792     const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
1793     APFloat::cmpResult R = C1V.compare(C2V);
1794     switch (pred) {
1795     default: llvm_unreachable("Invalid FCmp Predicate");
1796     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1797     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1798     case FCmpInst::FCMP_UNO:
1799       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1800     case FCmpInst::FCMP_ORD:
1801       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1802     case FCmpInst::FCMP_UEQ:
1803       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1804                                         R==APFloat::cmpEqual);
1805     case FCmpInst::FCMP_OEQ:
1806       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1807     case FCmpInst::FCMP_UNE:
1808       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1809     case FCmpInst::FCMP_ONE:
1810       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1811                                         R==APFloat::cmpGreaterThan);
1812     case FCmpInst::FCMP_ULT:
1813       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1814                                         R==APFloat::cmpLessThan);
1815     case FCmpInst::FCMP_OLT:
1816       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1817     case FCmpInst::FCMP_UGT:
1818       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1819                                         R==APFloat::cmpGreaterThan);
1820     case FCmpInst::FCMP_OGT:
1821       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1822     case FCmpInst::FCMP_ULE:
1823       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1824     case FCmpInst::FCMP_OLE:
1825       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1826                                         R==APFloat::cmpEqual);
1827     case FCmpInst::FCMP_UGE:
1828       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1829     case FCmpInst::FCMP_OGE:
1830       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1831                                         R==APFloat::cmpEqual);
1832     }
1833   } else if (C1->getType()->isVectorTy()) {
1834     // If we can constant fold the comparison of each element, constant fold
1835     // the whole vector comparison.
1836     SmallVector<Constant*, 4> ResElts;
1837     Type *Ty = IntegerType::get(C1->getContext(), 32);
1838     // Compare the elements, producing an i1 result or constant expr.
1839     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1840       Constant *C1E =
1841         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1842       Constant *C2E =
1843         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1844 
1845       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1846     }
1847 
1848     return ConstantVector::get(ResElts);
1849   }
1850 
1851   if (C1->getType()->isFloatingPointTy() &&
1852       // Only call evaluateFCmpRelation if we have a constant expr to avoid
1853       // infinite recursive loop
1854       (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
1855     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1856     switch (evaluateFCmpRelation(C1, C2)) {
1857     default: llvm_unreachable("Unknown relation!");
1858     case FCmpInst::FCMP_UNO:
1859     case FCmpInst::FCMP_ORD:
1860     case FCmpInst::FCMP_UEQ:
1861     case FCmpInst::FCMP_UNE:
1862     case FCmpInst::FCMP_ULT:
1863     case FCmpInst::FCMP_UGT:
1864     case FCmpInst::FCMP_ULE:
1865     case FCmpInst::FCMP_UGE:
1866     case FCmpInst::FCMP_TRUE:
1867     case FCmpInst::FCMP_FALSE:
1868     case FCmpInst::BAD_FCMP_PREDICATE:
1869       break; // Couldn't determine anything about these constants.
1870     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1871       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1872                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1873                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1874       break;
1875     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1876       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1877                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1878                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1879       break;
1880     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1881       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1882                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1883                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1884       break;
1885     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1886       // We can only partially decide this relation.
1887       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1888         Result = 0;
1889       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1890         Result = 1;
1891       break;
1892     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1893       // We can only partially decide this relation.
1894       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1895         Result = 0;
1896       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1897         Result = 1;
1898       break;
1899     case FCmpInst::FCMP_ONE: // We know that C1 != C2
1900       // We can only partially decide this relation.
1901       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1902         Result = 0;
1903       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1904         Result = 1;
1905       break;
1906     }
1907 
1908     // If we evaluated the result, return it now.
1909     if (Result != -1)
1910       return ConstantInt::get(ResultTy, Result);
1911 
1912   } else {
1913     // Evaluate the relation between the two constants, per the predicate.
1914     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1915     switch (evaluateICmpRelation(C1, C2,
1916                                  CmpInst::isSigned((CmpInst::Predicate)pred))) {
1917     default: llvm_unreachable("Unknown relational!");
1918     case ICmpInst::BAD_ICMP_PREDICATE:
1919       break;  // Couldn't determine anything about these constants.
1920     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1921       // If we know the constants are equal, we can decide the result of this
1922       // computation precisely.
1923       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1924       break;
1925     case ICmpInst::ICMP_ULT:
1926       switch (pred) {
1927       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1928         Result = 1; break;
1929       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1930         Result = 0; break;
1931       }
1932       break;
1933     case ICmpInst::ICMP_SLT:
1934       switch (pred) {
1935       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1936         Result = 1; break;
1937       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1938         Result = 0; break;
1939       }
1940       break;
1941     case ICmpInst::ICMP_UGT:
1942       switch (pred) {
1943       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1944         Result = 1; break;
1945       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1946         Result = 0; break;
1947       }
1948       break;
1949     case ICmpInst::ICMP_SGT:
1950       switch (pred) {
1951       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1952         Result = 1; break;
1953       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1954         Result = 0; break;
1955       }
1956       break;
1957     case ICmpInst::ICMP_ULE:
1958       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1959       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1960       break;
1961     case ICmpInst::ICMP_SLE:
1962       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1963       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1964       break;
1965     case ICmpInst::ICMP_UGE:
1966       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1967       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1968       break;
1969     case ICmpInst::ICMP_SGE:
1970       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1971       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1972       break;
1973     case ICmpInst::ICMP_NE:
1974       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1975       if (pred == ICmpInst::ICMP_NE) Result = 1;
1976       break;
1977     }
1978 
1979     // If we evaluated the result, return it now.
1980     if (Result != -1)
1981       return ConstantInt::get(ResultTy, Result);
1982 
1983     // If the right hand side is a bitcast, try using its inverse to simplify
1984     // it by moving it to the left hand side.  We can't do this if it would turn
1985     // a vector compare into a scalar compare or visa versa.
1986     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1987       Constant *CE2Op0 = CE2->getOperand(0);
1988       if (CE2->getOpcode() == Instruction::BitCast &&
1989           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1990         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1991         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1992       }
1993     }
1994 
1995     // If the left hand side is an extension, try eliminating it.
1996     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1997       if ((CE1->getOpcode() == Instruction::SExt &&
1998            ICmpInst::isSigned((ICmpInst::Predicate)pred)) ||
1999           (CE1->getOpcode() == Instruction::ZExt &&
2000            !ICmpInst::isSigned((ICmpInst::Predicate)pred))){
2001         Constant *CE1Op0 = CE1->getOperand(0);
2002         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2003         if (CE1Inverse == CE1Op0) {
2004           // Check whether we can safely truncate the right hand side.
2005           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2006           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
2007                                     C2->getType()) == C2)
2008             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2009         }
2010       }
2011     }
2012 
2013     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2014         (C1->isNullValue() && !C2->isNullValue())) {
2015       // If C2 is a constant expr and C1 isn't, flip them around and fold the
2016       // other way if possible.
2017       // Also, if C1 is null and C2 isn't, flip them around.
2018       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2019       return ConstantExpr::getICmp(pred, C2, C1);
2020     }
2021   }
2022   return nullptr;
2023 }
2024 
2025 /// Test whether the given sequence of *normalized* indices is "inbounds".
2026 template<typename IndexTy>
2027 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
2028   // No indices means nothing that could be out of bounds.
2029   if (Idxs.empty()) return true;
2030 
2031   // If the first index is zero, it's in bounds.
2032   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
2033 
2034   // If the first index is one and all the rest are zero, it's in bounds,
2035   // by the one-past-the-end rule.
2036   if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
2037     if (!CI->isOne())
2038       return false;
2039   } else {
2040     auto *CV = cast<ConstantDataVector>(Idxs[0]);
2041     CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
2042     if (!CI || !CI->isOne())
2043       return false;
2044   }
2045 
2046   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
2047     if (!cast<Constant>(Idxs[i])->isNullValue())
2048       return false;
2049   return true;
2050 }
2051 
2052 /// Test whether a given ConstantInt is in-range for a SequentialType.
2053 static bool isIndexInRangeOfArrayType(uint64_t NumElements,
2054                                       const ConstantInt *CI) {
2055   // We cannot bounds check the index if it doesn't fit in an int64_t.
2056   if (CI->getValue().getMinSignedBits() > 64)
2057     return false;
2058 
2059   // A negative index or an index past the end of our sequential type is
2060   // considered out-of-range.
2061   int64_t IndexVal = CI->getSExtValue();
2062   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
2063     return false;
2064 
2065   // Otherwise, it is in-range.
2066   return true;
2067 }
2068 
2069 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
2070                                           bool InBounds,
2071                                           Optional<unsigned> InRangeIndex,
2072                                           ArrayRef<Value *> Idxs) {
2073   if (Idxs.empty()) return C;
2074 
2075   Type *GEPTy = GetElementPtrInst::getGEPReturnType(
2076       C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size()));
2077 
2078   if (isa<UndefValue>(C))
2079     return UndefValue::get(GEPTy);
2080 
2081   Constant *Idx0 = cast<Constant>(Idxs[0]);
2082   if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0)))
2083     return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
2084                ? ConstantVector::getSplat(
2085                      cast<VectorType>(GEPTy)->getNumElements(), C)
2086                : C;
2087 
2088   if (C->isNullValue()) {
2089     bool isNull = true;
2090     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2091       if (!isa<UndefValue>(Idxs[i]) &&
2092           !cast<Constant>(Idxs[i])->isNullValue()) {
2093         isNull = false;
2094         break;
2095       }
2096     if (isNull) {
2097       PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
2098       Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
2099 
2100       assert(Ty && "Invalid indices for GEP!");
2101       Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2102       Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2103       if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
2104         GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements());
2105 
2106       // The GEP returns a vector of pointers when one of more of
2107       // its arguments is a vector.
2108       for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2109         if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) {
2110           GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements());
2111           break;
2112         }
2113       }
2114 
2115       return Constant::getNullValue(GEPTy);
2116     }
2117   }
2118 
2119   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2120     // Combine Indices - If the source pointer to this getelementptr instruction
2121     // is a getelementptr instruction, combine the indices of the two
2122     // getelementptr instructions into a single instruction.
2123     //
2124     if (CE->getOpcode() == Instruction::GetElementPtr) {
2125       gep_type_iterator LastI = gep_type_end(CE);
2126       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2127            I != E; ++I)
2128         LastI = I;
2129 
2130       // We cannot combine indices if doing so would take us outside of an
2131       // array or vector.  Doing otherwise could trick us if we evaluated such a
2132       // GEP as part of a load.
2133       //
2134       // e.g. Consider if the original GEP was:
2135       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2136       //                    i32 0, i32 0, i64 0)
2137       //
2138       // If we then tried to offset it by '8' to get to the third element,
2139       // an i8, we should *not* get:
2140       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2141       //                    i32 0, i32 0, i64 8)
2142       //
2143       // This GEP tries to index array element '8  which runs out-of-bounds.
2144       // Subsequent evaluation would get confused and produce erroneous results.
2145       //
2146       // The following prohibits such a GEP from being formed by checking to see
2147       // if the index is in-range with respect to an array.
2148       // TODO: This code may be extended to handle vectors as well.
2149       bool PerformFold = false;
2150       if (Idx0->isNullValue())
2151         PerformFold = true;
2152       else if (LastI.isSequential())
2153         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2154           PerformFold = (!LastI.isBoundedSequential() ||
2155                          isIndexInRangeOfArrayType(
2156                              LastI.getSequentialNumElements(), CI)) &&
2157                         !CE->getOperand(CE->getNumOperands() - 1)
2158                              ->getType()
2159                              ->isVectorTy();
2160 
2161       if (PerformFold) {
2162         SmallVector<Value*, 16> NewIndices;
2163         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2164         NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
2165 
2166         // Add the last index of the source with the first index of the new GEP.
2167         // Make sure to handle the case when they are actually different types.
2168         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2169         // Otherwise it must be an array.
2170         if (!Idx0->isNullValue()) {
2171           Type *IdxTy = Combined->getType();
2172           if (IdxTy != Idx0->getType()) {
2173             unsigned CommonExtendedWidth =
2174                 std::max(IdxTy->getIntegerBitWidth(),
2175                          Idx0->getType()->getIntegerBitWidth());
2176             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2177 
2178             Type *CommonTy =
2179                 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
2180             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
2181             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
2182             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2183           } else {
2184             Combined =
2185               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2186           }
2187         }
2188 
2189         NewIndices.push_back(Combined);
2190         NewIndices.append(Idxs.begin() + 1, Idxs.end());
2191 
2192         // The combined GEP normally inherits its index inrange attribute from
2193         // the inner GEP, but if the inner GEP's last index was adjusted by the
2194         // outer GEP, any inbounds attribute on that index is invalidated.
2195         Optional<unsigned> IRIndex = cast<GEPOperator>(CE)->getInRangeIndex();
2196         if (IRIndex && *IRIndex == CE->getNumOperands() - 2 && !Idx0->isNullValue())
2197           IRIndex = None;
2198 
2199         return ConstantExpr::getGetElementPtr(
2200             cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0),
2201             NewIndices, InBounds && cast<GEPOperator>(CE)->isInBounds(),
2202             IRIndex);
2203       }
2204     }
2205 
2206     // Attempt to fold casts to the same type away.  For example, folding:
2207     //
2208     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2209     //                       i64 0, i64 0)
2210     // into:
2211     //
2212     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2213     //
2214     // Don't fold if the cast is changing address spaces.
2215     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2216       PointerType *SrcPtrTy =
2217         dyn_cast<PointerType>(CE->getOperand(0)->getType());
2218       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2219       if (SrcPtrTy && DstPtrTy) {
2220         ArrayType *SrcArrayTy =
2221           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2222         ArrayType *DstArrayTy =
2223           dyn_cast<ArrayType>(DstPtrTy->getElementType());
2224         if (SrcArrayTy && DstArrayTy
2225             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2226             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2227           return ConstantExpr::getGetElementPtr(SrcArrayTy,
2228                                                 (Constant *)CE->getOperand(0),
2229                                                 Idxs, InBounds, InRangeIndex);
2230       }
2231     }
2232   }
2233 
2234   // Check to see if any array indices are not within the corresponding
2235   // notional array or vector bounds. If so, try to determine if they can be
2236   // factored out into preceding dimensions.
2237   SmallVector<Constant *, 8> NewIdxs;
2238   Type *Ty = PointeeTy;
2239   Type *Prev = C->getType();
2240   bool Unknown =
2241       !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
2242   for (unsigned i = 1, e = Idxs.size(); i != e;
2243        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2244     if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
2245       // We don't know if it's in range or not.
2246       Unknown = true;
2247       continue;
2248     }
2249     if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
2250       // Skip if the type of the previous index is not supported.
2251       continue;
2252     if (InRangeIndex && i == *InRangeIndex + 1) {
2253       // If an index is marked inrange, we cannot apply this canonicalization to
2254       // the following index, as that will cause the inrange index to point to
2255       // the wrong element.
2256       continue;
2257     }
2258     if (isa<StructType>(Ty)) {
2259       // The verify makes sure that GEPs into a struct are in range.
2260       continue;
2261     }
2262     auto *STy = cast<SequentialType>(Ty);
2263     if (isa<VectorType>(STy)) {
2264       // There can be awkward padding in after a non-power of two vector.
2265       Unknown = true;
2266       continue;
2267     }
2268     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2269       if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
2270         // It's in range, skip to the next index.
2271         continue;
2272       if (CI->getSExtValue() < 0) {
2273         // It's out of range and negative, don't try to factor it.
2274         Unknown = true;
2275         continue;
2276       }
2277     } else {
2278       auto *CV = cast<ConstantDataVector>(Idxs[i]);
2279       bool InRange = true;
2280       for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
2281         auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
2282         InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
2283         if (CI->getSExtValue() < 0) {
2284           Unknown = true;
2285           break;
2286         }
2287       }
2288       if (InRange || Unknown)
2289         // It's in range, skip to the next index.
2290         // It's out of range and negative, don't try to factor it.
2291         continue;
2292     }
2293     if (isa<StructType>(Prev)) {
2294       // It's out of range, but the prior dimension is a struct
2295       // so we can't do anything about it.
2296       Unknown = true;
2297       continue;
2298     }
2299     // It's out of range, but we can factor it into the prior
2300     // dimension.
2301     NewIdxs.resize(Idxs.size());
2302     // Determine the number of elements in our sequential type.
2303     uint64_t NumElements = STy->getArrayNumElements();
2304 
2305     // Expand the current index or the previous index to a vector from a scalar
2306     // if necessary.
2307     Constant *CurrIdx = cast<Constant>(Idxs[i]);
2308     auto *PrevIdx =
2309         NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
2310     bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
2311     bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
2312     bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
2313 
2314     if (!IsCurrIdxVector && IsPrevIdxVector)
2315       CurrIdx = ConstantDataVector::getSplat(
2316           PrevIdx->getType()->getVectorNumElements(), CurrIdx);
2317 
2318     if (!IsPrevIdxVector && IsCurrIdxVector)
2319       PrevIdx = ConstantDataVector::getSplat(
2320           CurrIdx->getType()->getVectorNumElements(), PrevIdx);
2321 
2322     Constant *Factor =
2323         ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
2324     if (UseVector)
2325       Factor = ConstantDataVector::getSplat(
2326           IsPrevIdxVector ? PrevIdx->getType()->getVectorNumElements()
2327                           : CurrIdx->getType()->getVectorNumElements(),
2328           Factor);
2329 
2330     NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor);
2331 
2332     Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor);
2333 
2334     unsigned CommonExtendedWidth =
2335         std::max(PrevIdx->getType()->getScalarSizeInBits(),
2336                  Div->getType()->getScalarSizeInBits());
2337     CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2338 
2339     // Before adding, extend both operands to i64 to avoid
2340     // overflow trouble.
2341     Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
2342     if (UseVector)
2343       ExtendedTy = VectorType::get(
2344           ExtendedTy, IsPrevIdxVector
2345                           ? PrevIdx->getType()->getVectorNumElements()
2346                           : CurrIdx->getType()->getVectorNumElements());
2347 
2348     if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2349       PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
2350 
2351     if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2352       Div = ConstantExpr::getSExt(Div, ExtendedTy);
2353 
2354     NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
2355   }
2356 
2357   // If we did any factoring, start over with the adjusted indices.
2358   if (!NewIdxs.empty()) {
2359     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2360       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2361     return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
2362                                           InRangeIndex);
2363   }
2364 
2365   // If all indices are known integers and normalized, we can do a simple
2366   // check for the "inbounds" property.
2367   if (!Unknown && !InBounds)
2368     if (auto *GV = dyn_cast<GlobalVariable>(C))
2369       if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2370         return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
2371                                               /*InBounds=*/true, InRangeIndex);
2372 
2373   return nullptr;
2374 }
2375