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