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