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     } else if (CE->getOpcode() == Instruction::InsertElement) {
857       if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
858         if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
859                                 APSInt(CIdx->getValue()))) {
860           return CE->getOperand(1);
861         } else {
862           return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
863         }
864       }
865     }
866   }
867 
868   // CAZ of type ScalableVectorType and n < CAZ->getMinNumElements() =>
869   //   extractelt CAZ, n -> 0
870   if (auto *ValSVTy = dyn_cast<ScalableVectorType>(Val->getType())) {
871     if (!CIdx->uge(ValSVTy->getMinNumElements())) {
872       if (auto *CAZ = dyn_cast<ConstantAggregateZero>(Val))
873         return CAZ->getElementValue(CIdx->getZExtValue());
874     }
875     return nullptr;
876   }
877 
878   return Val->getAggregateElement(CIdx);
879 }
880 
881 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
882                                                      Constant *Elt,
883                                                      Constant *Idx) {
884   if (isa<UndefValue>(Idx))
885     return UndefValue::get(Val->getType());
886 
887   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
888   if (!CIdx) return nullptr;
889 
890   // Do not iterate on scalable vector. The num of elements is unknown at
891   // compile-time.
892   if (isa<ScalableVectorType>(Val->getType()))
893     return nullptr;
894 
895   auto *ValTy = cast<FixedVectorType>(Val->getType());
896 
897   unsigned NumElts = ValTy->getNumElements();
898   if (CIdx->uge(NumElts))
899     return UndefValue::get(Val->getType());
900 
901   SmallVector<Constant*, 16> Result;
902   Result.reserve(NumElts);
903   auto *Ty = Type::getInt32Ty(Val->getContext());
904   uint64_t IdxVal = CIdx->getZExtValue();
905   for (unsigned i = 0; i != NumElts; ++i) {
906     if (i == IdxVal) {
907       Result.push_back(Elt);
908       continue;
909     }
910 
911     Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
912     Result.push_back(C);
913   }
914 
915   return ConstantVector::get(Result);
916 }
917 
918 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,
919                                                      ArrayRef<int> Mask) {
920   auto *V1VTy = cast<VectorType>(V1->getType());
921   unsigned MaskNumElts = Mask.size();
922   auto MaskEltCount =
923       ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
924   Type *EltTy = V1VTy->getElementType();
925 
926   // Undefined shuffle mask -> undefined value.
927   if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
928     return UndefValue::get(FixedVectorType::get(EltTy, MaskNumElts));
929   }
930 
931   // If the mask is all zeros this is a splat, no need to go through all
932   // elements.
933   if (all_of(Mask, [](int Elt) { return Elt == 0; }) &&
934       !MaskEltCount.isScalable()) {
935     Type *Ty = IntegerType::get(V1->getContext(), 32);
936     Constant *Elt =
937         ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));
938     return ConstantVector::getSplat(MaskEltCount, Elt);
939   }
940   // Do not iterate on scalable vector. The num of elements is unknown at
941   // compile-time.
942   if (isa<ScalableVectorType>(V1VTy))
943     return nullptr;
944 
945   unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
946 
947   // Loop over the shuffle mask, evaluating each element.
948   SmallVector<Constant*, 32> Result;
949   for (unsigned i = 0; i != MaskNumElts; ++i) {
950     int Elt = Mask[i];
951     if (Elt == -1) {
952       Result.push_back(UndefValue::get(EltTy));
953       continue;
954     }
955     Constant *InElt;
956     if (unsigned(Elt) >= SrcNumElts*2)
957       InElt = UndefValue::get(EltTy);
958     else if (unsigned(Elt) >= SrcNumElts) {
959       Type *Ty = IntegerType::get(V2->getContext(), 32);
960       InElt =
961         ConstantExpr::getExtractElement(V2,
962                                         ConstantInt::get(Ty, Elt - SrcNumElts));
963     } else {
964       Type *Ty = IntegerType::get(V1->getContext(), 32);
965       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
966     }
967     Result.push_back(InElt);
968   }
969 
970   return ConstantVector::get(Result);
971 }
972 
973 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
974                                                     ArrayRef<unsigned> Idxs) {
975   // Base case: no indices, so return the entire value.
976   if (Idxs.empty())
977     return Agg;
978 
979   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
980     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
981 
982   return nullptr;
983 }
984 
985 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
986                                                    Constant *Val,
987                                                    ArrayRef<unsigned> Idxs) {
988   // Base case: no indices, so replace the entire value.
989   if (Idxs.empty())
990     return Val;
991 
992   unsigned NumElts;
993   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
994     NumElts = ST->getNumElements();
995   else
996     NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
997 
998   SmallVector<Constant*, 32> Result;
999   for (unsigned i = 0; i != NumElts; ++i) {
1000     Constant *C = Agg->getAggregateElement(i);
1001     if (!C) return nullptr;
1002 
1003     if (Idxs[0] == i)
1004       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
1005 
1006     Result.push_back(C);
1007   }
1008 
1009   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
1010     return ConstantStruct::get(ST, Result);
1011   return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
1012 }
1013 
1014 Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
1015   assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
1016 
1017   // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
1018   // vectors are always evaluated per element.
1019   bool IsScalableVector = isa<ScalableVectorType>(C->getType());
1020   bool HasScalarUndefOrScalableVectorUndef =
1021       (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
1022 
1023   if (HasScalarUndefOrScalableVectorUndef) {
1024     switch (static_cast<Instruction::UnaryOps>(Opcode)) {
1025     case Instruction::FNeg:
1026       return C; // -undef -> undef
1027     case Instruction::UnaryOpsEnd:
1028       llvm_unreachable("Invalid UnaryOp");
1029     }
1030   }
1031 
1032   // Constant should not be UndefValue, unless these are vector constants.
1033   assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
1034   // We only have FP UnaryOps right now.
1035   assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
1036 
1037   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1038     const APFloat &CV = CFP->getValueAPF();
1039     switch (Opcode) {
1040     default:
1041       break;
1042     case Instruction::FNeg:
1043       return ConstantFP::get(C->getContext(), neg(CV));
1044     }
1045   } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
1046 
1047     Type *Ty = IntegerType::get(VTy->getContext(), 32);
1048     // Fast path for splatted constants.
1049     if (Constant *Splat = C->getSplatValue()) {
1050       Constant *Elt = ConstantExpr::get(Opcode, Splat);
1051       return ConstantVector::getSplat(VTy->getElementCount(), Elt);
1052     }
1053 
1054     // Fold each element and create a vector constant from those constants.
1055     SmallVector<Constant *, 16> Result;
1056     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1057       Constant *ExtractIdx = ConstantInt::get(Ty, i);
1058       Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
1059 
1060       Result.push_back(ConstantExpr::get(Opcode, Elt));
1061     }
1062 
1063     return ConstantVector::get(Result);
1064   }
1065 
1066   // We don't know how to fold this.
1067   return nullptr;
1068 }
1069 
1070 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
1071                                               Constant *C2) {
1072   assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
1073 
1074   // Simplify BinOps with their identity values first. They are no-ops and we
1075   // can always return the other value, including undef or poison values.
1076   // FIXME: remove unnecessary duplicated identity patterns below.
1077   // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops,
1078   //        like X << 0 = X.
1079   Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, C1->getType());
1080   if (Identity) {
1081     if (C1 == Identity)
1082       return C2;
1083     if (C2 == Identity)
1084       return C1;
1085   }
1086 
1087   // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
1088   // vectors are always evaluated per element.
1089   bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
1090   bool HasScalarUndefOrScalableVectorUndef =
1091       (!C1->getType()->isVectorTy() || IsScalableVector) &&
1092       (isa<UndefValue>(C1) || isa<UndefValue>(C2));
1093   if (HasScalarUndefOrScalableVectorUndef) {
1094     switch (static_cast<Instruction::BinaryOps>(Opcode)) {
1095     case Instruction::Xor:
1096       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1097         // Handle undef ^ undef -> 0 special case. This is a common
1098         // idiom (misuse).
1099         return Constant::getNullValue(C1->getType());
1100       LLVM_FALLTHROUGH;
1101     case Instruction::Add:
1102     case Instruction::Sub:
1103       return UndefValue::get(C1->getType());
1104     case Instruction::And:
1105       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
1106         return C1;
1107       return Constant::getNullValue(C1->getType());   // undef & X -> 0
1108     case Instruction::Mul: {
1109       // undef * undef -> undef
1110       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1111         return C1;
1112       const APInt *CV;
1113       // X * undef -> undef   if X is odd
1114       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
1115         if ((*CV)[0])
1116           return UndefValue::get(C1->getType());
1117 
1118       // X * undef -> 0       otherwise
1119       return Constant::getNullValue(C1->getType());
1120     }
1121     case Instruction::SDiv:
1122     case Instruction::UDiv:
1123       // X / undef -> undef
1124       if (isa<UndefValue>(C2))
1125         return C2;
1126       // undef / 0 -> undef
1127       // undef / 1 -> undef
1128       if (match(C2, m_Zero()) || match(C2, m_One()))
1129         return C1;
1130       // undef / X -> 0       otherwise
1131       return Constant::getNullValue(C1->getType());
1132     case Instruction::URem:
1133     case Instruction::SRem:
1134       // X % undef -> undef
1135       if (match(C2, m_Undef()))
1136         return C2;
1137       // undef % 0 -> undef
1138       if (match(C2, m_Zero()))
1139         return C1;
1140       // undef % X -> 0       otherwise
1141       return Constant::getNullValue(C1->getType());
1142     case Instruction::Or:                          // X | undef -> -1
1143       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
1144         return C1;
1145       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
1146     case Instruction::LShr:
1147       // X >>l undef -> undef
1148       if (isa<UndefValue>(C2))
1149         return C2;
1150       // undef >>l 0 -> undef
1151       if (match(C2, m_Zero()))
1152         return C1;
1153       // undef >>l X -> 0
1154       return Constant::getNullValue(C1->getType());
1155     case Instruction::AShr:
1156       // X >>a undef -> undef
1157       if (isa<UndefValue>(C2))
1158         return C2;
1159       // undef >>a 0 -> undef
1160       if (match(C2, m_Zero()))
1161         return C1;
1162       // TODO: undef >>a X -> undef if the shift is exact
1163       // undef >>a X -> 0
1164       return Constant::getNullValue(C1->getType());
1165     case Instruction::Shl:
1166       // X << undef -> undef
1167       if (isa<UndefValue>(C2))
1168         return C2;
1169       // undef << 0 -> undef
1170       if (match(C2, m_Zero()))
1171         return C1;
1172       // undef << X -> 0
1173       return Constant::getNullValue(C1->getType());
1174     case Instruction::FSub:
1175       // -0.0 - undef --> undef (consistent with "fneg undef")
1176       if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
1177         return C2;
1178       LLVM_FALLTHROUGH;
1179     case Instruction::FAdd:
1180     case Instruction::FMul:
1181     case Instruction::FDiv:
1182     case Instruction::FRem:
1183       // [any flop] undef, undef -> undef
1184       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1185         return C1;
1186       // [any flop] C, undef -> NaN
1187       // [any flop] undef, C -> NaN
1188       // We could potentially specialize NaN/Inf constants vs. 'normal'
1189       // constants (possibly differently depending on opcode and operand). This
1190       // would allow returning undef sometimes. But it is always safe to fold to
1191       // NaN because we can choose the undef operand as NaN, and any FP opcode
1192       // with a NaN operand will propagate NaN.
1193       return ConstantFP::getNaN(C1->getType());
1194     case Instruction::BinaryOpsEnd:
1195       llvm_unreachable("Invalid BinaryOp");
1196     }
1197   }
1198 
1199   // Neither constant should be UndefValue, unless these are vector constants.
1200   assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
1201 
1202   // Handle simplifications when the RHS is a constant int.
1203   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1204     switch (Opcode) {
1205     case Instruction::Add:
1206       if (CI2->isZero()) return C1;                             // X + 0 == X
1207       break;
1208     case Instruction::Sub:
1209       if (CI2->isZero()) return C1;                             // X - 0 == X
1210       break;
1211     case Instruction::Mul:
1212       if (CI2->isZero()) return C2;                             // X * 0 == 0
1213       if (CI2->isOne())
1214         return C1;                                              // X * 1 == X
1215       break;
1216     case Instruction::UDiv:
1217     case Instruction::SDiv:
1218       if (CI2->isOne())
1219         return C1;                                            // X / 1 == X
1220       if (CI2->isZero())
1221         return UndefValue::get(CI2->getType());               // X / 0 == undef
1222       break;
1223     case Instruction::URem:
1224     case Instruction::SRem:
1225       if (CI2->isOne())
1226         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
1227       if (CI2->isZero())
1228         return UndefValue::get(CI2->getType());               // X % 0 == undef
1229       break;
1230     case Instruction::And:
1231       if (CI2->isZero()) return C2;                           // X & 0 == 0
1232       if (CI2->isMinusOne())
1233         return C1;                                            // X & -1 == X
1234 
1235       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1236         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1237         if (CE1->getOpcode() == Instruction::ZExt) {
1238           unsigned DstWidth = CI2->getType()->getBitWidth();
1239           unsigned SrcWidth =
1240             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1241           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1242           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1243             return C1;
1244         }
1245 
1246         // If and'ing the address of a global with a constant, fold it.
1247         if (CE1->getOpcode() == Instruction::PtrToInt &&
1248             isa<GlobalValue>(CE1->getOperand(0))) {
1249           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1250 
1251           MaybeAlign GVAlign;
1252 
1253           if (Module *TheModule = GV->getParent()) {
1254             const DataLayout &DL = TheModule->getDataLayout();
1255             GVAlign = GV->getPointerAlignment(DL);
1256 
1257             // If the function alignment is not specified then assume that it
1258             // is 4.
1259             // This is dangerous; on x86, the alignment of the pointer
1260             // corresponds to the alignment of the function, but might be less
1261             // than 4 if it isn't explicitly specified.
1262             // However, a fix for this behaviour was reverted because it
1263             // increased code size (see https://reviews.llvm.org/D55115)
1264             // FIXME: This code should be deleted once existing targets have
1265             // appropriate defaults
1266             if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
1267               GVAlign = Align(4);
1268           } else if (isa<Function>(GV)) {
1269             // Without a datalayout we have to assume the worst case: that the
1270             // function pointer isn't aligned at all.
1271             GVAlign = llvm::None;
1272           } else if (isa<GlobalVariable>(GV)) {
1273             GVAlign = cast<GlobalVariable>(GV)->getAlign();
1274           }
1275 
1276           if (GVAlign && *GVAlign > 1) {
1277             unsigned DstWidth = CI2->getType()->getBitWidth();
1278             unsigned SrcWidth = std::min(DstWidth, Log2(*GVAlign));
1279             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1280 
1281             // If checking bits we know are clear, return zero.
1282             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1283               return Constant::getNullValue(CI2->getType());
1284           }
1285         }
1286       }
1287       break;
1288     case Instruction::Or:
1289       if (CI2->isZero()) return C1;        // X | 0 == X
1290       if (CI2->isMinusOne())
1291         return C2;                         // X | -1 == -1
1292       break;
1293     case Instruction::Xor:
1294       if (CI2->isZero()) return C1;        // X ^ 0 == X
1295 
1296       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1297         switch (CE1->getOpcode()) {
1298         default: break;
1299         case Instruction::ICmp:
1300         case Instruction::FCmp:
1301           // cmp pred ^ true -> cmp !pred
1302           assert(CI2->isOne());
1303           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1304           pred = CmpInst::getInversePredicate(pred);
1305           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1306                                           CE1->getOperand(1));
1307         }
1308       }
1309       break;
1310     case Instruction::AShr:
1311       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1312       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1313         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1314           return ConstantExpr::getLShr(C1, C2);
1315       break;
1316     }
1317   } else if (isa<ConstantInt>(C1)) {
1318     // If C1 is a ConstantInt and C2 is not, swap the operands.
1319     if (Instruction::isCommutative(Opcode))
1320       return ConstantExpr::get(Opcode, C2, C1);
1321   }
1322 
1323   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1324     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1325       const APInt &C1V = CI1->getValue();
1326       const APInt &C2V = CI2->getValue();
1327       switch (Opcode) {
1328       default:
1329         break;
1330       case Instruction::Add:
1331         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1332       case Instruction::Sub:
1333         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1334       case Instruction::Mul:
1335         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1336       case Instruction::UDiv:
1337         assert(!CI2->isZero() && "Div by zero handled above");
1338         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1339       case Instruction::SDiv:
1340         assert(!CI2->isZero() && "Div by zero handled above");
1341         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1342           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1343         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1344       case Instruction::URem:
1345         assert(!CI2->isZero() && "Div by zero handled above");
1346         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1347       case Instruction::SRem:
1348         assert(!CI2->isZero() && "Div by zero handled above");
1349         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1350           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1351         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1352       case Instruction::And:
1353         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1354       case Instruction::Or:
1355         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1356       case Instruction::Xor:
1357         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1358       case Instruction::Shl:
1359         if (C2V.ult(C1V.getBitWidth()))
1360           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
1361         return UndefValue::get(C1->getType()); // too big shift is undef
1362       case Instruction::LShr:
1363         if (C2V.ult(C1V.getBitWidth()))
1364           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
1365         return UndefValue::get(C1->getType()); // too big shift is undef
1366       case Instruction::AShr:
1367         if (C2V.ult(C1V.getBitWidth()))
1368           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
1369         return UndefValue::get(C1->getType()); // too big shift is undef
1370       }
1371     }
1372 
1373     switch (Opcode) {
1374     case Instruction::SDiv:
1375     case Instruction::UDiv:
1376     case Instruction::URem:
1377     case Instruction::SRem:
1378     case Instruction::LShr:
1379     case Instruction::AShr:
1380     case Instruction::Shl:
1381       if (CI1->isZero()) return C1;
1382       break;
1383     default:
1384       break;
1385     }
1386   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1387     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1388       const APFloat &C1V = CFP1->getValueAPF();
1389       const APFloat &C2V = CFP2->getValueAPF();
1390       APFloat C3V = C1V;  // copy for modification
1391       switch (Opcode) {
1392       default:
1393         break;
1394       case Instruction::FAdd:
1395         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1396         return ConstantFP::get(C1->getContext(), C3V);
1397       case Instruction::FSub:
1398         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1399         return ConstantFP::get(C1->getContext(), C3V);
1400       case Instruction::FMul:
1401         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1402         return ConstantFP::get(C1->getContext(), C3V);
1403       case Instruction::FDiv:
1404         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1405         return ConstantFP::get(C1->getContext(), C3V);
1406       case Instruction::FRem:
1407         (void)C3V.mod(C2V);
1408         return ConstantFP::get(C1->getContext(), C3V);
1409       }
1410     }
1411   } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
1412     // Fast path for splatted constants.
1413     if (Constant *C2Splat = C2->getSplatValue()) {
1414       if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
1415         return UndefValue::get(VTy);
1416       if (Constant *C1Splat = C1->getSplatValue()) {
1417         return ConstantVector::getSplat(
1418             VTy->getElementCount(),
1419             ConstantExpr::get(Opcode, C1Splat, C2Splat));
1420       }
1421     }
1422 
1423     if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
1424       // Fold each element and create a vector constant from those constants.
1425       SmallVector<Constant*, 16> Result;
1426       Type *Ty = IntegerType::get(FVTy->getContext(), 32);
1427       for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
1428         Constant *ExtractIdx = ConstantInt::get(Ty, i);
1429         Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
1430         Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
1431 
1432         // If any element of a divisor vector is zero, the whole op is undef.
1433         if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
1434           return UndefValue::get(VTy);
1435 
1436         Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1437       }
1438 
1439       return ConstantVector::get(Result);
1440     }
1441   }
1442 
1443   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1444     // There are many possible foldings we could do here.  We should probably
1445     // at least fold add of a pointer with an integer into the appropriate
1446     // getelementptr.  This will improve alias analysis a bit.
1447 
1448     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1449     // (a + (b + c)).
1450     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1451       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1452       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1453         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1454     }
1455   } else if (isa<ConstantExpr>(C2)) {
1456     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1457     // other way if possible.
1458     if (Instruction::isCommutative(Opcode))
1459       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1460   }
1461 
1462   // i1 can be simplified in many cases.
1463   if (C1->getType()->isIntegerTy(1)) {
1464     switch (Opcode) {
1465     case Instruction::Add:
1466     case Instruction::Sub:
1467       return ConstantExpr::getXor(C1, C2);
1468     case Instruction::Mul:
1469       return ConstantExpr::getAnd(C1, C2);
1470     case Instruction::Shl:
1471     case Instruction::LShr:
1472     case Instruction::AShr:
1473       // We can assume that C2 == 0.  If it were one the result would be
1474       // undefined because the shift value is as large as the bitwidth.
1475       return C1;
1476     case Instruction::SDiv:
1477     case Instruction::UDiv:
1478       // We can assume that C2 == 1.  If it were zero the result would be
1479       // undefined through division by zero.
1480       return C1;
1481     case Instruction::URem:
1482     case Instruction::SRem:
1483       // We can assume that C2 == 1.  If it were zero the result would be
1484       // undefined through division by zero.
1485       return ConstantInt::getFalse(C1->getContext());
1486     default:
1487       break;
1488     }
1489   }
1490 
1491   // We don't know how to fold this.
1492   return nullptr;
1493 }
1494 
1495 /// This type is zero-sized if it's an array or structure of zero-sized types.
1496 /// The only leaf zero-sized type is an empty structure.
1497 static bool isMaybeZeroSizedType(Type *Ty) {
1498   if (StructType *STy = dyn_cast<StructType>(Ty)) {
1499     if (STy->isOpaque()) return true;  // Can't say.
1500 
1501     // If all of elements have zero size, this does too.
1502     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1503       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1504     return true;
1505 
1506   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1507     return isMaybeZeroSizedType(ATy->getElementType());
1508   }
1509   return false;
1510 }
1511 
1512 /// Compare the two constants as though they were getelementptr indices.
1513 /// This allows coercion of the types to be the same thing.
1514 ///
1515 /// If the two constants are the "same" (after coercion), return 0.  If the
1516 /// first is less than the second, return -1, if the second is less than the
1517 /// first, return 1.  If the constants are not integral, return -2.
1518 ///
1519 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1520   if (C1 == C2) return 0;
1521 
1522   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1523   // anything with them.
1524   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1525     return -2; // don't know!
1526 
1527   // We cannot compare the indices if they don't fit in an int64_t.
1528   if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
1529       cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
1530     return -2; // don't know!
1531 
1532   // Ok, we have two differing integer indices.  Sign extend them to be the same
1533   // type.
1534   int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
1535   int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
1536 
1537   if (C1Val == C2Val) return 0;  // They are equal
1538 
1539   // If the type being indexed over is really just a zero sized type, there is
1540   // no pointer difference being made here.
1541   if (isMaybeZeroSizedType(ElTy))
1542     return -2; // dunno.
1543 
1544   // If they are really different, now that they are the same type, then we
1545   // found a difference!
1546   if (C1Val < C2Val)
1547     return -1;
1548   else
1549     return 1;
1550 }
1551 
1552 /// This function determines if there is anything we can decide about the two
1553 /// constants provided. This doesn't need to handle simple things like
1554 /// ConstantFP comparisons, but should instead handle ConstantExprs.
1555 /// If we can determine that the two constants have a particular relation to
1556 /// each other, we should return the corresponding FCmpInst predicate,
1557 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1558 /// ConstantFoldCompareInstruction.
1559 ///
1560 /// To simplify this code we canonicalize the relation so that the first
1561 /// operand is always the most "complex" of the two.  We consider ConstantFP
1562 /// to be the simplest, and ConstantExprs to be the most complex.
1563 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1564   assert(V1->getType() == V2->getType() &&
1565          "Cannot compare values of different types!");
1566 
1567   // We do not know if a constant expression will evaluate to a number or NaN.
1568   // Therefore, we can only say that the relation is unordered or equal.
1569   if (V1 == V2) return FCmpInst::FCMP_UEQ;
1570 
1571   if (!isa<ConstantExpr>(V1)) {
1572     if (!isa<ConstantExpr>(V2)) {
1573       // Simple case, use the standard constant folder.
1574       ConstantInt *R = nullptr;
1575       R = dyn_cast<ConstantInt>(
1576                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1577       if (R && !R->isZero())
1578         return FCmpInst::FCMP_OEQ;
1579       R = dyn_cast<ConstantInt>(
1580                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1581       if (R && !R->isZero())
1582         return FCmpInst::FCMP_OLT;
1583       R = dyn_cast<ConstantInt>(
1584                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1585       if (R && !R->isZero())
1586         return FCmpInst::FCMP_OGT;
1587 
1588       // Nothing more we can do
1589       return FCmpInst::BAD_FCMP_PREDICATE;
1590     }
1591 
1592     // If the first operand is simple and second is ConstantExpr, swap operands.
1593     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1594     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1595       return FCmpInst::getSwappedPredicate(SwappedRelation);
1596   } else {
1597     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1598     // constantexpr or a simple constant.
1599     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1600     switch (CE1->getOpcode()) {
1601     case Instruction::FPTrunc:
1602     case Instruction::FPExt:
1603     case Instruction::UIToFP:
1604     case Instruction::SIToFP:
1605       // We might be able to do something with these but we don't right now.
1606       break;
1607     default:
1608       break;
1609     }
1610   }
1611   // There are MANY other foldings that we could perform here.  They will
1612   // probably be added on demand, as they seem needed.
1613   return FCmpInst::BAD_FCMP_PREDICATE;
1614 }
1615 
1616 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1617                                                       const GlobalValue *GV2) {
1618   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1619     if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
1620       return true;
1621     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1622       Type *Ty = GVar->getValueType();
1623       // A global with opaque type might end up being zero sized.
1624       if (!Ty->isSized())
1625         return true;
1626       // A global with an empty type might lie at the address of any other
1627       // global.
1628       if (Ty->isEmptyTy())
1629         return true;
1630     }
1631     return false;
1632   };
1633   // Don't try to decide equality of aliases.
1634   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1635     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1636       return ICmpInst::ICMP_NE;
1637   return ICmpInst::BAD_ICMP_PREDICATE;
1638 }
1639 
1640 /// This function determines if there is anything we can decide about the two
1641 /// constants provided. This doesn't need to handle simple things like integer
1642 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
1643 /// If we can determine that the two constants have a particular relation to
1644 /// each other, we should return the corresponding ICmp predicate, otherwise
1645 /// return ICmpInst::BAD_ICMP_PREDICATE.
1646 ///
1647 /// To simplify this code we canonicalize the relation so that the first
1648 /// operand is always the most "complex" of the two.  We consider simple
1649 /// constants (like ConstantInt) to be the simplest, followed by
1650 /// GlobalValues, followed by ConstantExpr's (the most complex).
1651 ///
1652 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1653                                                 bool isSigned) {
1654   assert(V1->getType() == V2->getType() &&
1655          "Cannot compare different types of values!");
1656   if (V1 == V2) return ICmpInst::ICMP_EQ;
1657 
1658   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1659       !isa<BlockAddress>(V1)) {
1660     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1661         !isa<BlockAddress>(V2)) {
1662       // We distilled this down to a simple case, use the standard constant
1663       // folder.
1664       ConstantInt *R = nullptr;
1665       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1666       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1667       if (R && !R->isZero())
1668         return pred;
1669       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1670       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1671       if (R && !R->isZero())
1672         return pred;
1673       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1674       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1675       if (R && !R->isZero())
1676         return pred;
1677 
1678       // If we couldn't figure it out, bail.
1679       return ICmpInst::BAD_ICMP_PREDICATE;
1680     }
1681 
1682     // If the first operand is simple, swap operands.
1683     ICmpInst::Predicate SwappedRelation =
1684       evaluateICmpRelation(V2, V1, isSigned);
1685     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1686       return ICmpInst::getSwappedPredicate(SwappedRelation);
1687 
1688   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1689     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1690       ICmpInst::Predicate SwappedRelation =
1691         evaluateICmpRelation(V2, V1, isSigned);
1692       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1693         return ICmpInst::getSwappedPredicate(SwappedRelation);
1694       return ICmpInst::BAD_ICMP_PREDICATE;
1695     }
1696 
1697     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1698     // constant (which, since the types must match, means that it's a
1699     // ConstantPointerNull).
1700     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1701       return areGlobalsPotentiallyEqual(GV, GV2);
1702     } else if (isa<BlockAddress>(V2)) {
1703       return ICmpInst::ICMP_NE; // Globals never equal labels.
1704     } else {
1705       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1706       // GlobalVals can never be null unless they have external weak linkage.
1707       // We don't try to evaluate aliases here.
1708       // NOTE: We should not be doing this constant folding if null pointer
1709       // is considered valid for the function. But currently there is no way to
1710       // query it from the Constant type.
1711       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
1712           !NullPointerIsDefined(nullptr /* F */,
1713                                 GV->getType()->getAddressSpace()))
1714         return ICmpInst::ICMP_NE;
1715     }
1716   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1717     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1718       ICmpInst::Predicate SwappedRelation =
1719         evaluateICmpRelation(V2, V1, isSigned);
1720       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1721         return ICmpInst::getSwappedPredicate(SwappedRelation);
1722       return ICmpInst::BAD_ICMP_PREDICATE;
1723     }
1724 
1725     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1726     // constant (which, since the types must match, means that it is a
1727     // ConstantPointerNull).
1728     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1729       // Block address in another function can't equal this one, but block
1730       // addresses in the current function might be the same if blocks are
1731       // empty.
1732       if (BA2->getFunction() != BA->getFunction())
1733         return ICmpInst::ICMP_NE;
1734     } else {
1735       // Block addresses aren't null, don't equal the address of globals.
1736       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1737              "Canonicalization guarantee!");
1738       return ICmpInst::ICMP_NE;
1739     }
1740   } else {
1741     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1742     // constantexpr, a global, block address, or a simple constant.
1743     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1744     Constant *CE1Op0 = CE1->getOperand(0);
1745 
1746     switch (CE1->getOpcode()) {
1747     case Instruction::Trunc:
1748     case Instruction::FPTrunc:
1749     case Instruction::FPExt:
1750     case Instruction::FPToUI:
1751     case Instruction::FPToSI:
1752       break; // We can't evaluate floating point casts or truncations.
1753 
1754     case Instruction::BitCast:
1755       // If this is a global value cast, check to see if the RHS is also a
1756       // GlobalValue.
1757       if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0))
1758         if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2))
1759           return areGlobalsPotentiallyEqual(GV, GV2);
1760       LLVM_FALLTHROUGH;
1761     case Instruction::UIToFP:
1762     case Instruction::SIToFP:
1763     case Instruction::ZExt:
1764     case Instruction::SExt:
1765       // We can't evaluate floating point casts or truncations.
1766       if (CE1Op0->getType()->isFPOrFPVectorTy())
1767         break;
1768 
1769       // If the cast is not actually changing bits, and the second operand is a
1770       // null pointer, do the comparison with the pre-casted value.
1771       if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
1772         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1773         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1774         return evaluateICmpRelation(CE1Op0,
1775                                     Constant::getNullValue(CE1Op0->getType()),
1776                                     isSigned);
1777       }
1778       break;
1779 
1780     case Instruction::GetElementPtr: {
1781       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1782       // Ok, since this is a getelementptr, we know that the constant has a
1783       // pointer type.  Check the various cases.
1784       if (isa<ConstantPointerNull>(V2)) {
1785         // If we are comparing a GEP to a null pointer, check to see if the base
1786         // of the GEP equals the null pointer.
1787         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1788           if (GV->hasExternalWeakLinkage())
1789             // Weak linkage GVals could be zero or not. We're comparing that
1790             // to null pointer so its greater-or-equal
1791             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1792           else
1793             // If its not weak linkage, the GVal must have a non-zero address
1794             // so the result is greater-than
1795             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1796         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1797           // If we are indexing from a null pointer, check to see if we have any
1798           // non-zero indices.
1799           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1800             if (!CE1->getOperand(i)->isNullValue())
1801               // Offsetting from null, must not be equal.
1802               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1803           // Only zero indexes from null, must still be zero.
1804           return ICmpInst::ICMP_EQ;
1805         }
1806         // Otherwise, we can't really say if the first operand is null or not.
1807       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1808         if (isa<ConstantPointerNull>(CE1Op0)) {
1809           if (GV2->hasExternalWeakLinkage())
1810             // Weak linkage GVals could be zero or not. We're comparing it to
1811             // a null pointer, so its less-or-equal
1812             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1813           else
1814             // If its not weak linkage, the GVal must have a non-zero address
1815             // so the result is less-than
1816             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1817         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1818           if (GV == GV2) {
1819             // If this is a getelementptr of the same global, then it must be
1820             // different.  Because the types must match, the getelementptr could
1821             // only have at most one index, and because we fold getelementptr's
1822             // with a single zero index, it must be nonzero.
1823             assert(CE1->getNumOperands() == 2 &&
1824                    !CE1->getOperand(1)->isNullValue() &&
1825                    "Surprising getelementptr!");
1826             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1827           } else {
1828             if (CE1GEP->hasAllZeroIndices())
1829               return areGlobalsPotentiallyEqual(GV, GV2);
1830             return ICmpInst::BAD_ICMP_PREDICATE;
1831           }
1832         }
1833       } else {
1834         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1835         Constant *CE2Op0 = CE2->getOperand(0);
1836 
1837         // There are MANY other foldings that we could perform here.  They will
1838         // probably be added on demand, as they seem needed.
1839         switch (CE2->getOpcode()) {
1840         default: break;
1841         case Instruction::GetElementPtr:
1842           // By far the most common case to handle is when the base pointers are
1843           // obviously to the same global.
1844           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1845             // Don't know relative ordering, but check for inequality.
1846             if (CE1Op0 != CE2Op0) {
1847               GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1848               if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1849                 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1850                                                   cast<GlobalValue>(CE2Op0));
1851               return ICmpInst::BAD_ICMP_PREDICATE;
1852             }
1853             // Ok, we know that both getelementptr instructions are based on the
1854             // same global.  From this, we can precisely determine the relative
1855             // ordering of the resultant pointers.
1856             unsigned i = 1;
1857 
1858             // The logic below assumes that the result of the comparison
1859             // can be determined by finding the first index that differs.
1860             // This doesn't work if there is over-indexing in any
1861             // subsequent indices, so check for that case first.
1862             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1863                 !CE2->isGEPWithNoNotionalOverIndexing())
1864                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1865 
1866             // Compare all of the operands the GEP's have in common.
1867             gep_type_iterator GTI = gep_type_begin(CE1);
1868             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1869                  ++i, ++GTI)
1870               switch (IdxCompare(CE1->getOperand(i),
1871                                  CE2->getOperand(i), GTI.getIndexedType())) {
1872               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1873               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1874               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1875               }
1876 
1877             // Ok, we ran out of things they have in common.  If any leftovers
1878             // are non-zero then we have a difference, otherwise we are equal.
1879             for (; i < CE1->getNumOperands(); ++i)
1880               if (!CE1->getOperand(i)->isNullValue()) {
1881                 if (isa<ConstantInt>(CE1->getOperand(i)))
1882                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1883                 else
1884                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1885               }
1886 
1887             for (; i < CE2->getNumOperands(); ++i)
1888               if (!CE2->getOperand(i)->isNullValue()) {
1889                 if (isa<ConstantInt>(CE2->getOperand(i)))
1890                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1891                 else
1892                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1893               }
1894             return ICmpInst::ICMP_EQ;
1895           }
1896         }
1897       }
1898       break;
1899     }
1900     default:
1901       break;
1902     }
1903   }
1904 
1905   return ICmpInst::BAD_ICMP_PREDICATE;
1906 }
1907 
1908 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1909                                                Constant *C1, Constant *C2) {
1910   Type *ResultTy;
1911   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1912     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1913                                VT->getElementCount());
1914   else
1915     ResultTy = Type::getInt1Ty(C1->getContext());
1916 
1917   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1918   if (pred == FCmpInst::FCMP_FALSE)
1919     return Constant::getNullValue(ResultTy);
1920 
1921   if (pred == FCmpInst::FCMP_TRUE)
1922     return Constant::getAllOnesValue(ResultTy);
1923 
1924   // Handle some degenerate cases first
1925   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1926     CmpInst::Predicate Predicate = CmpInst::Predicate(pred);
1927     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
1928     // For EQ and NE, we can always pick a value for the undef to make the
1929     // predicate pass or fail, so we can return undef.
1930     // Also, if both operands are undef, we can return undef for int comparison.
1931     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
1932       return UndefValue::get(ResultTy);
1933 
1934     // Otherwise, for integer compare, pick the same value as the non-undef
1935     // operand, and fold it to true or false.
1936     if (isIntegerPredicate)
1937       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
1938 
1939     // Choosing NaN for the undef will always make unordered comparison succeed
1940     // and ordered comparison fails.
1941     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
1942   }
1943 
1944   // icmp eq/ne(null,GV) -> false/true
1945   if (C1->isNullValue()) {
1946     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1947       // Don't try to evaluate aliases.  External weak GV can be null.
1948       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
1949           !NullPointerIsDefined(nullptr /* F */,
1950                                 GV->getType()->getAddressSpace())) {
1951         if (pred == ICmpInst::ICMP_EQ)
1952           return ConstantInt::getFalse(C1->getContext());
1953         else if (pred == ICmpInst::ICMP_NE)
1954           return ConstantInt::getTrue(C1->getContext());
1955       }
1956   // icmp eq/ne(GV,null) -> false/true
1957   } else if (C2->isNullValue()) {
1958     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1959       // Don't try to evaluate aliases.  External weak GV can be null.
1960       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
1961           !NullPointerIsDefined(nullptr /* F */,
1962                                 GV->getType()->getAddressSpace())) {
1963         if (pred == ICmpInst::ICMP_EQ)
1964           return ConstantInt::getFalse(C1->getContext());
1965         else if (pred == ICmpInst::ICMP_NE)
1966           return ConstantInt::getTrue(C1->getContext());
1967       }
1968   }
1969 
1970   // If the comparison is a comparison between two i1's, simplify it.
1971   if (C1->getType()->isIntegerTy(1)) {
1972     switch(pred) {
1973     case ICmpInst::ICMP_EQ:
1974       if (isa<ConstantInt>(C2))
1975         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1976       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1977     case ICmpInst::ICMP_NE:
1978       return ConstantExpr::getXor(C1, C2);
1979     default:
1980       break;
1981     }
1982   }
1983 
1984   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1985     const APInt &V1 = cast<ConstantInt>(C1)->getValue();
1986     const APInt &V2 = cast<ConstantInt>(C2)->getValue();
1987     switch (pred) {
1988     default: llvm_unreachable("Invalid ICmp Predicate");
1989     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1990     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1991     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1992     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1993     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1994     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1995     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1996     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1997     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1998     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1999     }
2000   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
2001     const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
2002     const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
2003     APFloat::cmpResult R = C1V.compare(C2V);
2004     switch (pred) {
2005     default: llvm_unreachable("Invalid FCmp Predicate");
2006     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
2007     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
2008     case FCmpInst::FCMP_UNO:
2009       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
2010     case FCmpInst::FCMP_ORD:
2011       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
2012     case FCmpInst::FCMP_UEQ:
2013       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
2014                                         R==APFloat::cmpEqual);
2015     case FCmpInst::FCMP_OEQ:
2016       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
2017     case FCmpInst::FCMP_UNE:
2018       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
2019     case FCmpInst::FCMP_ONE:
2020       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
2021                                         R==APFloat::cmpGreaterThan);
2022     case FCmpInst::FCMP_ULT:
2023       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
2024                                         R==APFloat::cmpLessThan);
2025     case FCmpInst::FCMP_OLT:
2026       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
2027     case FCmpInst::FCMP_UGT:
2028       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
2029                                         R==APFloat::cmpGreaterThan);
2030     case FCmpInst::FCMP_OGT:
2031       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
2032     case FCmpInst::FCMP_ULE:
2033       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
2034     case FCmpInst::FCMP_OLE:
2035       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
2036                                         R==APFloat::cmpEqual);
2037     case FCmpInst::FCMP_UGE:
2038       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
2039     case FCmpInst::FCMP_OGE:
2040       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
2041                                         R==APFloat::cmpEqual);
2042     }
2043   } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
2044 
2045     // Do not iterate on scalable vector. The number of elements is unknown at
2046     // compile-time.
2047     if (isa<ScalableVectorType>(C1VTy))
2048       return nullptr;
2049 
2050     // Fast path for splatted constants.
2051     if (Constant *C1Splat = C1->getSplatValue())
2052       if (Constant *C2Splat = C2->getSplatValue())
2053         return ConstantVector::getSplat(
2054             C1VTy->getElementCount(),
2055             ConstantExpr::getCompare(pred, C1Splat, C2Splat));
2056 
2057     // If we can constant fold the comparison of each element, constant fold
2058     // the whole vector comparison.
2059     SmallVector<Constant*, 4> ResElts;
2060     Type *Ty = IntegerType::get(C1->getContext(), 32);
2061     // Compare the elements, producing an i1 result or constant expr.
2062     for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
2063          I != E; ++I) {
2064       Constant *C1E =
2065           ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));
2066       Constant *C2E =
2067           ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));
2068 
2069       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
2070     }
2071 
2072     return ConstantVector::get(ResElts);
2073   }
2074 
2075   if (C1->getType()->isFloatingPointTy() &&
2076       // Only call evaluateFCmpRelation if we have a constant expr to avoid
2077       // infinite recursive loop
2078       (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
2079     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
2080     switch (evaluateFCmpRelation(C1, C2)) {
2081     default: llvm_unreachable("Unknown relation!");
2082     case FCmpInst::FCMP_UNO:
2083     case FCmpInst::FCMP_ORD:
2084     case FCmpInst::FCMP_UNE:
2085     case FCmpInst::FCMP_ULT:
2086     case FCmpInst::FCMP_UGT:
2087     case FCmpInst::FCMP_ULE:
2088     case FCmpInst::FCMP_UGE:
2089     case FCmpInst::FCMP_TRUE:
2090     case FCmpInst::FCMP_FALSE:
2091     case FCmpInst::BAD_FCMP_PREDICATE:
2092       break; // Couldn't determine anything about these constants.
2093     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
2094       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
2095                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
2096                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
2097       break;
2098     case FCmpInst::FCMP_OLT: // We know that C1 < C2
2099       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
2100                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
2101                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
2102       break;
2103     case FCmpInst::FCMP_OGT: // We know that C1 > C2
2104       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
2105                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
2106                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
2107       break;
2108     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
2109       // We can only partially decide this relation.
2110       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
2111         Result = 0;
2112       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
2113         Result = 1;
2114       break;
2115     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
2116       // We can only partially decide this relation.
2117       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
2118         Result = 0;
2119       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
2120         Result = 1;
2121       break;
2122     case FCmpInst::FCMP_ONE: // We know that C1 != C2
2123       // We can only partially decide this relation.
2124       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
2125         Result = 0;
2126       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
2127         Result = 1;
2128       break;
2129     case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2).
2130       // We can only partially decide this relation.
2131       if (pred == FCmpInst::FCMP_ONE)
2132         Result = 0;
2133       else if (pred == FCmpInst::FCMP_UEQ)
2134         Result = 1;
2135       break;
2136     }
2137 
2138     // If we evaluated the result, return it now.
2139     if (Result != -1)
2140       return ConstantInt::get(ResultTy, Result);
2141 
2142   } else {
2143     // Evaluate the relation between the two constants, per the predicate.
2144     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
2145     switch (evaluateICmpRelation(C1, C2,
2146                                  CmpInst::isSigned((CmpInst::Predicate)pred))) {
2147     default: llvm_unreachable("Unknown relational!");
2148     case ICmpInst::BAD_ICMP_PREDICATE:
2149       break;  // Couldn't determine anything about these constants.
2150     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
2151       // If we know the constants are equal, we can decide the result of this
2152       // computation precisely.
2153       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
2154       break;
2155     case ICmpInst::ICMP_ULT:
2156       switch (pred) {
2157       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
2158         Result = 1; break;
2159       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
2160         Result = 0; break;
2161       }
2162       break;
2163     case ICmpInst::ICMP_SLT:
2164       switch (pred) {
2165       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
2166         Result = 1; break;
2167       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
2168         Result = 0; break;
2169       }
2170       break;
2171     case ICmpInst::ICMP_UGT:
2172       switch (pred) {
2173       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
2174         Result = 1; break;
2175       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
2176         Result = 0; break;
2177       }
2178       break;
2179     case ICmpInst::ICMP_SGT:
2180       switch (pred) {
2181       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
2182         Result = 1; break;
2183       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
2184         Result = 0; break;
2185       }
2186       break;
2187     case ICmpInst::ICMP_ULE:
2188       if (pred == ICmpInst::ICMP_UGT) Result = 0;
2189       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
2190       break;
2191     case ICmpInst::ICMP_SLE:
2192       if (pred == ICmpInst::ICMP_SGT) Result = 0;
2193       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2194       break;
2195     case ICmpInst::ICMP_UGE:
2196       if (pred == ICmpInst::ICMP_ULT) Result = 0;
2197       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2198       break;
2199     case ICmpInst::ICMP_SGE:
2200       if (pred == ICmpInst::ICMP_SLT) Result = 0;
2201       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2202       break;
2203     case ICmpInst::ICMP_NE:
2204       if (pred == ICmpInst::ICMP_EQ) Result = 0;
2205       if (pred == ICmpInst::ICMP_NE) Result = 1;
2206       break;
2207     }
2208 
2209     // If we evaluated the result, return it now.
2210     if (Result != -1)
2211       return ConstantInt::get(ResultTy, Result);
2212 
2213     // If the right hand side is a bitcast, try using its inverse to simplify
2214     // it by moving it to the left hand side.  We can't do this if it would turn
2215     // a vector compare into a scalar compare or visa versa, or if it would turn
2216     // the operands into FP values.
2217     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2218       Constant *CE2Op0 = CE2->getOperand(0);
2219       if (CE2->getOpcode() == Instruction::BitCast &&
2220           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() &&
2221           !CE2Op0->getType()->isFPOrFPVectorTy()) {
2222         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2223         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2224       }
2225     }
2226 
2227     // If the left hand side is an extension, try eliminating it.
2228     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2229       if ((CE1->getOpcode() == Instruction::SExt &&
2230            ICmpInst::isSigned((ICmpInst::Predicate)pred)) ||
2231           (CE1->getOpcode() == Instruction::ZExt &&
2232            !ICmpInst::isSigned((ICmpInst::Predicate)pred))){
2233         Constant *CE1Op0 = CE1->getOperand(0);
2234         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2235         if (CE1Inverse == CE1Op0) {
2236           // Check whether we can safely truncate the right hand side.
2237           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2238           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
2239                                     C2->getType()) == C2)
2240             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2241         }
2242       }
2243     }
2244 
2245     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2246         (C1->isNullValue() && !C2->isNullValue())) {
2247       // If C2 is a constant expr and C1 isn't, flip them around and fold the
2248       // other way if possible.
2249       // Also, if C1 is null and C2 isn't, flip them around.
2250       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2251       return ConstantExpr::getICmp(pred, C2, C1);
2252     }
2253   }
2254   return nullptr;
2255 }
2256 
2257 /// Test whether the given sequence of *normalized* indices is "inbounds".
2258 template<typename IndexTy>
2259 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
2260   // No indices means nothing that could be out of bounds.
2261   if (Idxs.empty()) return true;
2262 
2263   // If the first index is zero, it's in bounds.
2264   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
2265 
2266   // If the first index is one and all the rest are zero, it's in bounds,
2267   // by the one-past-the-end rule.
2268   if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
2269     if (!CI->isOne())
2270       return false;
2271   } else {
2272     auto *CV = cast<ConstantDataVector>(Idxs[0]);
2273     CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
2274     if (!CI || !CI->isOne())
2275       return false;
2276   }
2277 
2278   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
2279     if (!cast<Constant>(Idxs[i])->isNullValue())
2280       return false;
2281   return true;
2282 }
2283 
2284 /// Test whether a given ConstantInt is in-range for a SequentialType.
2285 static bool isIndexInRangeOfArrayType(uint64_t NumElements,
2286                                       const ConstantInt *CI) {
2287   // We cannot bounds check the index if it doesn't fit in an int64_t.
2288   if (CI->getValue().getMinSignedBits() > 64)
2289     return false;
2290 
2291   // A negative index or an index past the end of our sequential type is
2292   // considered out-of-range.
2293   int64_t IndexVal = CI->getSExtValue();
2294   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
2295     return false;
2296 
2297   // Otherwise, it is in-range.
2298   return true;
2299 }
2300 
2301 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
2302                                           bool InBounds,
2303                                           Optional<unsigned> InRangeIndex,
2304                                           ArrayRef<Value *> Idxs) {
2305   if (Idxs.empty()) return C;
2306 
2307   Type *GEPTy = GetElementPtrInst::getGEPReturnType(
2308       PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size()));
2309 
2310   if (isa<UndefValue>(C))
2311     return UndefValue::get(GEPTy);
2312 
2313   Constant *Idx0 = cast<Constant>(Idxs[0]);
2314   if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0)))
2315     return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
2316                ? ConstantVector::getSplat(
2317                      cast<VectorType>(GEPTy)->getElementCount(), C)
2318                : C;
2319 
2320   if (C->isNullValue()) {
2321     bool isNull = true;
2322     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2323       if (!isa<UndefValue>(Idxs[i]) &&
2324           !cast<Constant>(Idxs[i])->isNullValue()) {
2325         isNull = false;
2326         break;
2327       }
2328     if (isNull) {
2329       PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
2330       Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
2331 
2332       assert(Ty && "Invalid indices for GEP!");
2333       Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2334       Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2335       if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
2336         GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
2337 
2338       // The GEP returns a vector of pointers when one of more of
2339       // its arguments is a vector.
2340       for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2341         if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) {
2342           assert((!isa<VectorType>(GEPTy) || isa<ScalableVectorType>(GEPTy) ==
2343                                                  isa<ScalableVectorType>(VT)) &&
2344                  "Mismatched GEPTy vector types");
2345           GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
2346           break;
2347         }
2348       }
2349 
2350       return Constant::getNullValue(GEPTy);
2351     }
2352   }
2353 
2354   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2355     // Combine Indices - If the source pointer to this getelementptr instruction
2356     // is a getelementptr instruction, combine the indices of the two
2357     // getelementptr instructions into a single instruction.
2358     //
2359     if (CE->getOpcode() == Instruction::GetElementPtr) {
2360       gep_type_iterator LastI = gep_type_end(CE);
2361       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2362            I != E; ++I)
2363         LastI = I;
2364 
2365       // We cannot combine indices if doing so would take us outside of an
2366       // array or vector.  Doing otherwise could trick us if we evaluated such a
2367       // GEP as part of a load.
2368       //
2369       // e.g. Consider if the original GEP was:
2370       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2371       //                    i32 0, i32 0, i64 0)
2372       //
2373       // If we then tried to offset it by '8' to get to the third element,
2374       // an i8, we should *not* get:
2375       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2376       //                    i32 0, i32 0, i64 8)
2377       //
2378       // This GEP tries to index array element '8  which runs out-of-bounds.
2379       // Subsequent evaluation would get confused and produce erroneous results.
2380       //
2381       // The following prohibits such a GEP from being formed by checking to see
2382       // if the index is in-range with respect to an array.
2383       // TODO: This code may be extended to handle vectors as well.
2384       bool PerformFold = false;
2385       if (Idx0->isNullValue())
2386         PerformFold = true;
2387       else if (LastI.isSequential())
2388         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2389           PerformFold = (!LastI.isBoundedSequential() ||
2390                          isIndexInRangeOfArrayType(
2391                              LastI.getSequentialNumElements(), CI)) &&
2392                         !CE->getOperand(CE->getNumOperands() - 1)
2393                              ->getType()
2394                              ->isVectorTy();
2395 
2396       if (PerformFold) {
2397         SmallVector<Value*, 16> NewIndices;
2398         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2399         NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
2400 
2401         // Add the last index of the source with the first index of the new GEP.
2402         // Make sure to handle the case when they are actually different types.
2403         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2404         // Otherwise it must be an array.
2405         if (!Idx0->isNullValue()) {
2406           Type *IdxTy = Combined->getType();
2407           if (IdxTy != Idx0->getType()) {
2408             unsigned CommonExtendedWidth =
2409                 std::max(IdxTy->getIntegerBitWidth(),
2410                          Idx0->getType()->getIntegerBitWidth());
2411             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2412 
2413             Type *CommonTy =
2414                 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
2415             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
2416             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
2417             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2418           } else {
2419             Combined =
2420               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2421           }
2422         }
2423 
2424         NewIndices.push_back(Combined);
2425         NewIndices.append(Idxs.begin() + 1, Idxs.end());
2426 
2427         // The combined GEP normally inherits its index inrange attribute from
2428         // the inner GEP, but if the inner GEP's last index was adjusted by the
2429         // outer GEP, any inbounds attribute on that index is invalidated.
2430         Optional<unsigned> IRIndex = cast<GEPOperator>(CE)->getInRangeIndex();
2431         if (IRIndex && *IRIndex == CE->getNumOperands() - 2 && !Idx0->isNullValue())
2432           IRIndex = None;
2433 
2434         return ConstantExpr::getGetElementPtr(
2435             cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0),
2436             NewIndices, InBounds && cast<GEPOperator>(CE)->isInBounds(),
2437             IRIndex);
2438       }
2439     }
2440 
2441     // Attempt to fold casts to the same type away.  For example, folding:
2442     //
2443     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2444     //                       i64 0, i64 0)
2445     // into:
2446     //
2447     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2448     //
2449     // Don't fold if the cast is changing address spaces.
2450     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2451       PointerType *SrcPtrTy =
2452         dyn_cast<PointerType>(CE->getOperand(0)->getType());
2453       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2454       if (SrcPtrTy && DstPtrTy) {
2455         ArrayType *SrcArrayTy =
2456           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2457         ArrayType *DstArrayTy =
2458           dyn_cast<ArrayType>(DstPtrTy->getElementType());
2459         if (SrcArrayTy && DstArrayTy
2460             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2461             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2462           return ConstantExpr::getGetElementPtr(SrcArrayTy,
2463                                                 (Constant *)CE->getOperand(0),
2464                                                 Idxs, InBounds, InRangeIndex);
2465       }
2466     }
2467   }
2468 
2469   // Check to see if any array indices are not within the corresponding
2470   // notional array or vector bounds. If so, try to determine if they can be
2471   // factored out into preceding dimensions.
2472   SmallVector<Constant *, 8> NewIdxs;
2473   Type *Ty = PointeeTy;
2474   Type *Prev = C->getType();
2475   auto GEPIter = gep_type_begin(PointeeTy, Idxs);
2476   bool Unknown =
2477       !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
2478   for (unsigned i = 1, e = Idxs.size(); i != e;
2479        Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) {
2480     if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
2481       // We don't know if it's in range or not.
2482       Unknown = true;
2483       continue;
2484     }
2485     if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
2486       // Skip if the type of the previous index is not supported.
2487       continue;
2488     if (InRangeIndex && i == *InRangeIndex + 1) {
2489       // If an index is marked inrange, we cannot apply this canonicalization to
2490       // the following index, as that will cause the inrange index to point to
2491       // the wrong element.
2492       continue;
2493     }
2494     if (isa<StructType>(Ty)) {
2495       // The verify makes sure that GEPs into a struct are in range.
2496       continue;
2497     }
2498     if (isa<VectorType>(Ty)) {
2499       // There can be awkward padding in after a non-power of two vector.
2500       Unknown = true;
2501       continue;
2502     }
2503     auto *STy = cast<ArrayType>(Ty);
2504     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2505       if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
2506         // It's in range, skip to the next index.
2507         continue;
2508       if (CI->getSExtValue() < 0) {
2509         // It's out of range and negative, don't try to factor it.
2510         Unknown = true;
2511         continue;
2512       }
2513     } else {
2514       auto *CV = cast<ConstantDataVector>(Idxs[i]);
2515       bool InRange = true;
2516       for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
2517         auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
2518         InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
2519         if (CI->getSExtValue() < 0) {
2520           Unknown = true;
2521           break;
2522         }
2523       }
2524       if (InRange || Unknown)
2525         // It's in range, skip to the next index.
2526         // It's out of range and negative, don't try to factor it.
2527         continue;
2528     }
2529     if (isa<StructType>(Prev)) {
2530       // It's out of range, but the prior dimension is a struct
2531       // so we can't do anything about it.
2532       Unknown = true;
2533       continue;
2534     }
2535     // It's out of range, but we can factor it into the prior
2536     // dimension.
2537     NewIdxs.resize(Idxs.size());
2538     // Determine the number of elements in our sequential type.
2539     uint64_t NumElements = STy->getArrayNumElements();
2540 
2541     // Expand the current index or the previous index to a vector from a scalar
2542     // if necessary.
2543     Constant *CurrIdx = cast<Constant>(Idxs[i]);
2544     auto *PrevIdx =
2545         NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
2546     bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
2547     bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
2548     bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
2549 
2550     if (!IsCurrIdxVector && IsPrevIdxVector)
2551       CurrIdx = ConstantDataVector::getSplat(
2552           cast<FixedVectorType>(PrevIdx->getType())->getNumElements(), CurrIdx);
2553 
2554     if (!IsPrevIdxVector && IsCurrIdxVector)
2555       PrevIdx = ConstantDataVector::getSplat(
2556           cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), PrevIdx);
2557 
2558     Constant *Factor =
2559         ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
2560     if (UseVector)
2561       Factor = ConstantDataVector::getSplat(
2562           IsPrevIdxVector
2563               ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
2564               : cast<FixedVectorType>(CurrIdx->getType())->getNumElements(),
2565           Factor);
2566 
2567     NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor);
2568 
2569     Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor);
2570 
2571     unsigned CommonExtendedWidth =
2572         std::max(PrevIdx->getType()->getScalarSizeInBits(),
2573                  Div->getType()->getScalarSizeInBits());
2574     CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2575 
2576     // Before adding, extend both operands to i64 to avoid
2577     // overflow trouble.
2578     Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
2579     if (UseVector)
2580       ExtendedTy = FixedVectorType::get(
2581           ExtendedTy,
2582           IsPrevIdxVector
2583               ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
2584               : cast<FixedVectorType>(CurrIdx->getType())->getNumElements());
2585 
2586     if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2587       PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
2588 
2589     if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2590       Div = ConstantExpr::getSExt(Div, ExtendedTy);
2591 
2592     NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
2593   }
2594 
2595   // If we did any factoring, start over with the adjusted indices.
2596   if (!NewIdxs.empty()) {
2597     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2598       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2599     return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
2600                                           InRangeIndex);
2601   }
2602 
2603   // If all indices are known integers and normalized, we can do a simple
2604   // check for the "inbounds" property.
2605   if (!Unknown && !InBounds)
2606     if (auto *GV = dyn_cast<GlobalVariable>(C))
2607       if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2608         return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
2609                                               /*InBounds=*/true, InRangeIndex);
2610 
2611   return nullptr;
2612 }
2613