xref: /llvm-project/llvm/lib/IR/ConstantFold.cpp (revision deab451e7a7f2dff42097049274637052c87eabd)
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 "llvm/IR/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 /// This function determines which opcode to use to fold two constant cast
41 /// expressions together. It uses CastInst::isEliminableCastPair to determine
42 /// the opcode. Consequently its just a wrapper around that function.
43 /// Determine if it is valid to fold a cast of a cast
44 static unsigned
45 foldConstantCastPair(
46   unsigned opc,          ///< opcode of the second cast constant expression
47   ConstantExpr *Op,      ///< the first cast constant expression
48   Type *DstTy            ///< destination type of the first cast
49 ) {
50   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
51   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
52   assert(CastInst::isCast(opc) && "Invalid cast opcode");
53 
54   // The types and opcodes for the two Cast constant expressions
55   Type *SrcTy = Op->getOperand(0)->getType();
56   Type *MidTy = Op->getType();
57   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
58   Instruction::CastOps secondOp = Instruction::CastOps(opc);
59 
60   // Assume that pointers are never more than 64 bits wide, and only use this
61   // for the middle type. Otherwise we could end up folding away illegal
62   // bitcasts between address spaces with different sizes.
63   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
64 
65   // Let CastInst::isEliminableCastPair do the heavy lifting.
66   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
67                                         nullptr, FakeIntPtrTy, nullptr);
68 }
69 
70 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
71   Type *SrcTy = V->getType();
72   if (SrcTy == DestTy)
73     return V; // no-op cast
74 
75   // Handle casts from one vector constant to another.  We know that the src
76   // and dest type have the same size (otherwise its an illegal cast).
77   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
78     if (V->isAllOnesValue())
79       return Constant::getAllOnesValue(DestTy);
80 
81     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
82     // This allows for other simplifications (although some of them
83     // can only be handled by Analysis/ConstantFolding.cpp).
84     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
85       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
86     return nullptr;
87   }
88 
89   // Handle integral constant input.
90   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
91     // See note below regarding the PPC_FP128 restriction.
92     if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
93       return ConstantFP::get(DestTy->getContext(),
94                              APFloat(DestTy->getFltSemantics(),
95                                      CI->getValue()));
96 
97     // Otherwise, can't fold this (vector?)
98     return nullptr;
99   }
100 
101   // Handle ConstantFP input: FP -> Integral.
102   if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
103     // PPC_FP128 is really the sum of two consecutive doubles, where the first
104     // double is always stored first in memory, regardless of the target
105     // endianness. The memory layout of i128, however, depends on the target
106     // endianness, and so we can't fold this without target endianness
107     // information. This should instead be handled by
108     // Analysis/ConstantFolding.cpp
109     if (FP->getType()->isPPC_FP128Ty())
110       return nullptr;
111 
112     // Make sure dest type is compatible with the folded integer constant.
113     if (!DestTy->isIntegerTy())
114       return nullptr;
115 
116     return ConstantInt::get(FP->getContext(),
117                             FP->getValueAPF().bitcastToAPInt());
118   }
119 
120   return nullptr;
121 }
122 
123 
124 /// V is an integer constant which only has a subset of its bytes used.
125 /// The bytes used are indicated by ByteStart (which is the first byte used,
126 /// counting from the least significant byte) and ByteSize, which is the number
127 /// of bytes used.
128 ///
129 /// This function analyzes the specified constant to see if the specified byte
130 /// range can be returned as a simplified constant.  If so, the constant is
131 /// returned, otherwise null is returned.
132 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
133                                       unsigned ByteSize) {
134   assert(C->getType()->isIntegerTy() &&
135          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
136          "Non-byte sized integer input");
137   [[maybe_unused]] unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
138   assert(ByteSize && "Must be accessing some piece");
139   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
140   assert(ByteSize != CSize && "Should not extract everything");
141 
142   // Constant Integers are simple.
143   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
144     APInt V = CI->getValue();
145     if (ByteStart)
146       V.lshrInPlace(ByteStart*8);
147     V = V.trunc(ByteSize*8);
148     return ConstantInt::get(CI->getContext(), V);
149   }
150 
151   // In the input is a constant expr, we might be able to recursively simplify.
152   // If not, we definitely can't do anything.
153   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
154   if (!CE) return nullptr;
155 
156   switch (CE->getOpcode()) {
157   default: return nullptr;
158   case Instruction::Shl: {
159     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
160     if (!Amt)
161       return nullptr;
162     APInt ShAmt = Amt->getValue();
163     // Cannot analyze non-byte shifts.
164     if ((ShAmt & 7) != 0)
165       return nullptr;
166     ShAmt.lshrInPlace(3);
167 
168     // If the extract is known to be all zeros, return zero.
169     if (ShAmt.uge(ByteStart + ByteSize))
170       return Constant::getNullValue(
171           IntegerType::get(CE->getContext(), ByteSize * 8));
172     // If the extract is known to be fully in the input, extract it.
173     if (ShAmt.ule(ByteStart))
174       return ExtractConstantBytes(CE->getOperand(0),
175                                   ByteStart - ShAmt.getZExtValue(), ByteSize);
176 
177     // TODO: Handle the 'partially zero' case.
178     return nullptr;
179   }
180   }
181 }
182 
183 static Constant *foldMaybeUndesirableCast(unsigned opc, Constant *V,
184                                           Type *DestTy) {
185   return ConstantExpr::isDesirableCastOp(opc)
186              ? ConstantExpr::getCast(opc, V, DestTy)
187              : ConstantFoldCastInstruction(opc, V, DestTy);
188 }
189 
190 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
191                                             Type *DestTy) {
192   if (isa<PoisonValue>(V))
193     return PoisonValue::get(DestTy);
194 
195   if (isa<UndefValue>(V)) {
196     // zext(undef) = 0, because the top bits will be zero.
197     // sext(undef) = 0, because the top bits will all be the same.
198     // [us]itofp(undef) = 0, because the result value is bounded.
199     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
200         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
201       return Constant::getNullValue(DestTy);
202     return UndefValue::get(DestTy);
203   }
204 
205   if (V->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&
206       opc != Instruction::AddrSpaceCast)
207     return Constant::getNullValue(DestTy);
208 
209   // If the cast operand is a constant expression, there's a few things we can
210   // do to try to simplify it.
211   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
212     if (CE->isCast()) {
213       // Try hard to fold cast of cast because they are often eliminable.
214       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
215         return foldMaybeUndesirableCast(newOpc, CE->getOperand(0), DestTy);
216     }
217   }
218 
219   // If the cast operand is a constant vector, perform the cast by
220   // operating on each element. In the cast of bitcasts, the element
221   // count may be mismatched; don't attempt to handle that here.
222   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
223       DestTy->isVectorTy() &&
224       cast<FixedVectorType>(DestTy)->getNumElements() ==
225           cast<FixedVectorType>(V->getType())->getNumElements()) {
226     VectorType *DestVecTy = cast<VectorType>(DestTy);
227     Type *DstEltTy = DestVecTy->getElementType();
228     // Fast path for splatted constants.
229     if (Constant *Splat = V->getSplatValue()) {
230       Constant *Res = foldMaybeUndesirableCast(opc, Splat, DstEltTy);
231       if (!Res)
232         return nullptr;
233       return ConstantVector::getSplat(
234           cast<VectorType>(DestTy)->getElementCount(), Res);
235     }
236     SmallVector<Constant *, 16> res;
237     Type *Ty = IntegerType::get(V->getContext(), 32);
238     for (unsigned i = 0,
239                   e = cast<FixedVectorType>(V->getType())->getNumElements();
240          i != e; ++i) {
241       Constant *C = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
242       Constant *Casted = foldMaybeUndesirableCast(opc, C, DstEltTy);
243       if (!Casted)
244         return nullptr;
245       res.push_back(Casted);
246     }
247     return ConstantVector::get(res);
248   }
249 
250   // We actually have to do a cast now. Perform the cast according to the
251   // opcode specified.
252   switch (opc) {
253   default:
254     llvm_unreachable("Failed to cast constant expression");
255   case Instruction::FPTrunc:
256   case Instruction::FPExt:
257     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
258       bool ignored;
259       APFloat Val = FPC->getValueAPF();
260       Val.convert(DestTy->getFltSemantics(), APFloat::rmNearestTiesToEven,
261                   &ignored);
262       return ConstantFP::get(V->getContext(), Val);
263     }
264     return nullptr; // Can't fold.
265   case Instruction::FPToUI:
266   case Instruction::FPToSI:
267     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
268       const APFloat &V = FPC->getValueAPF();
269       bool ignored;
270       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
271       APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
272       if (APFloat::opInvalidOp ==
273           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
274         // Undefined behavior invoked - the destination type can't represent
275         // the input constant.
276         return PoisonValue::get(DestTy);
277       }
278       return ConstantInt::get(FPC->getContext(), IntVal);
279     }
280     return nullptr; // Can't fold.
281   case Instruction::UIToFP:
282   case Instruction::SIToFP:
283     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
284       const APInt &api = CI->getValue();
285       APFloat apf(DestTy->getFltSemantics(),
286                   APInt::getZero(DestTy->getPrimitiveSizeInBits()));
287       apf.convertFromAPInt(api, opc==Instruction::SIToFP,
288                            APFloat::rmNearestTiesToEven);
289       return ConstantFP::get(V->getContext(), apf);
290     }
291     return nullptr;
292   case Instruction::ZExt:
293     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
294       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
295       return ConstantInt::get(V->getContext(),
296                               CI->getValue().zext(BitWidth));
297     }
298     return nullptr;
299   case Instruction::SExt:
300     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
301       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
302       return ConstantInt::get(V->getContext(),
303                               CI->getValue().sext(BitWidth));
304     }
305     return nullptr;
306   case Instruction::Trunc: {
307     if (V->getType()->isVectorTy())
308       return nullptr;
309 
310     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
311     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
312       return ConstantInt::get(V->getContext(),
313                               CI->getValue().trunc(DestBitWidth));
314     }
315 
316     // The input must be a constantexpr.  See if we can simplify this based on
317     // the bytes we are demanding.  Only do this if the source and dest are an
318     // even multiple of a byte.
319     if ((DestBitWidth & 7) == 0 &&
320         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
321       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
322         return Res;
323 
324     return nullptr;
325   }
326   case Instruction::BitCast:
327     return FoldBitCast(V, DestTy);
328   case Instruction::AddrSpaceCast:
329   case Instruction::IntToPtr:
330   case Instruction::PtrToInt:
331     return nullptr;
332   }
333 }
334 
335 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
336                                               Constant *V1, Constant *V2) {
337   // Check for i1 and vector true/false conditions.
338   if (Cond->isNullValue()) return V2;
339   if (Cond->isAllOnesValue()) return V1;
340 
341   // If the condition is a vector constant, fold the result elementwise.
342   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
343     auto *V1VTy = CondV->getType();
344     SmallVector<Constant*, 16> Result;
345     Type *Ty = IntegerType::get(CondV->getContext(), 32);
346     for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
347       Constant *V;
348       Constant *V1Element = ConstantExpr::getExtractElement(V1,
349                                                     ConstantInt::get(Ty, i));
350       Constant *V2Element = ConstantExpr::getExtractElement(V2,
351                                                     ConstantInt::get(Ty, i));
352       auto *Cond = cast<Constant>(CondV->getOperand(i));
353       if (isa<PoisonValue>(Cond)) {
354         V = PoisonValue::get(V1Element->getType());
355       } else if (V1Element == V2Element) {
356         V = V1Element;
357       } else if (isa<UndefValue>(Cond)) {
358         V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
359       } else {
360         if (!isa<ConstantInt>(Cond)) break;
361         V = Cond->isNullValue() ? V2Element : V1Element;
362       }
363       Result.push_back(V);
364     }
365 
366     // If we were able to build the vector, return it.
367     if (Result.size() == V1VTy->getNumElements())
368       return ConstantVector::get(Result);
369   }
370 
371   if (isa<PoisonValue>(Cond))
372     return PoisonValue::get(V1->getType());
373 
374   if (isa<UndefValue>(Cond)) {
375     if (isa<UndefValue>(V1)) return V1;
376     return V2;
377   }
378 
379   if (V1 == V2) return V1;
380 
381   if (isa<PoisonValue>(V1))
382     return V2;
383   if (isa<PoisonValue>(V2))
384     return V1;
385 
386   // If the true or false value is undef, we can fold to the other value as
387   // long as the other value isn't poison.
388   auto NotPoison = [](Constant *C) {
389     if (isa<PoisonValue>(C))
390       return false;
391 
392     // TODO: We can analyze ConstExpr by opcode to determine if there is any
393     //       possibility of poison.
394     if (isa<ConstantExpr>(C))
395       return false;
396 
397     if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||
398         isa<ConstantPointerNull>(C) || isa<Function>(C))
399       return true;
400 
401     if (C->getType()->isVectorTy())
402       return !C->containsPoisonElement() && !C->containsConstantExpression();
403 
404     // TODO: Recursively analyze aggregates or other constants.
405     return false;
406   };
407   if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;
408   if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;
409 
410   return nullptr;
411 }
412 
413 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
414                                                       Constant *Idx) {
415   auto *ValVTy = cast<VectorType>(Val->getType());
416 
417   // extractelt poison, C -> poison
418   // extractelt C, undef -> poison
419   if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
420     return PoisonValue::get(ValVTy->getElementType());
421 
422   // extractelt undef, C -> undef
423   if (isa<UndefValue>(Val))
424     return UndefValue::get(ValVTy->getElementType());
425 
426   auto *CIdx = dyn_cast<ConstantInt>(Idx);
427   if (!CIdx)
428     return nullptr;
429 
430   if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
431     // ee({w,x,y,z}, wrong_value) -> poison
432     if (CIdx->uge(ValFVTy->getNumElements()))
433       return PoisonValue::get(ValFVTy->getElementType());
434   }
435 
436   // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
437   if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
438     if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
439       SmallVector<Constant *, 8> Ops;
440       Ops.reserve(CE->getNumOperands());
441       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
442         Constant *Op = CE->getOperand(i);
443         if (Op->getType()->isVectorTy()) {
444           Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);
445           if (!ScalarOp)
446             return nullptr;
447           Ops.push_back(ScalarOp);
448         } else
449           Ops.push_back(Op);
450       }
451       return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
452                                  GEP->getSourceElementType());
453     } else if (CE->getOpcode() == Instruction::InsertElement) {
454       if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
455         if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
456                                 APSInt(CIdx->getValue()))) {
457           return CE->getOperand(1);
458         } else {
459           return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
460         }
461       }
462     }
463   }
464 
465   if (Constant *C = Val->getAggregateElement(CIdx))
466     return C;
467 
468   // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
469   if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
470     if (Constant *SplatVal = Val->getSplatValue())
471       return SplatVal;
472   }
473 
474   return nullptr;
475 }
476 
477 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
478                                                      Constant *Elt,
479                                                      Constant *Idx) {
480   if (isa<UndefValue>(Idx))
481     return PoisonValue::get(Val->getType());
482 
483   // Inserting null into all zeros is still all zeros.
484   // TODO: This is true for undef and poison splats too.
485   if (isa<ConstantAggregateZero>(Val) && Elt->isNullValue())
486     return Val;
487 
488   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
489   if (!CIdx) return nullptr;
490 
491   // Do not iterate on scalable vector. The num of elements is unknown at
492   // compile-time.
493   if (isa<ScalableVectorType>(Val->getType()))
494     return nullptr;
495 
496   auto *ValTy = cast<FixedVectorType>(Val->getType());
497 
498   unsigned NumElts = ValTy->getNumElements();
499   if (CIdx->uge(NumElts))
500     return PoisonValue::get(Val->getType());
501 
502   SmallVector<Constant*, 16> Result;
503   Result.reserve(NumElts);
504   auto *Ty = Type::getInt32Ty(Val->getContext());
505   uint64_t IdxVal = CIdx->getZExtValue();
506   for (unsigned i = 0; i != NumElts; ++i) {
507     if (i == IdxVal) {
508       Result.push_back(Elt);
509       continue;
510     }
511 
512     Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
513     Result.push_back(C);
514   }
515 
516   return ConstantVector::get(Result);
517 }
518 
519 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,
520                                                      ArrayRef<int> Mask) {
521   auto *V1VTy = cast<VectorType>(V1->getType());
522   unsigned MaskNumElts = Mask.size();
523   auto MaskEltCount =
524       ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
525   Type *EltTy = V1VTy->getElementType();
526 
527   // Poison shuffle mask -> poison value.
528   if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
529     return PoisonValue::get(VectorType::get(EltTy, MaskEltCount));
530   }
531 
532   // If the mask is all zeros this is a splat, no need to go through all
533   // elements.
534   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
535     Type *Ty = IntegerType::get(V1->getContext(), 32);
536     Constant *Elt =
537         ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));
538 
539     if (Elt->isNullValue()) {
540       auto *VTy = VectorType::get(EltTy, MaskEltCount);
541       return ConstantAggregateZero::get(VTy);
542     } else if (!MaskEltCount.isScalable())
543       return ConstantVector::getSplat(MaskEltCount, Elt);
544   }
545 
546   // Do not iterate on scalable vector. The num of elements is unknown at
547   // compile-time.
548   if (isa<ScalableVectorType>(V1VTy))
549     return nullptr;
550 
551   unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
552 
553   // Loop over the shuffle mask, evaluating each element.
554   SmallVector<Constant*, 32> Result;
555   for (unsigned i = 0; i != MaskNumElts; ++i) {
556     int Elt = Mask[i];
557     if (Elt == -1) {
558       Result.push_back(UndefValue::get(EltTy));
559       continue;
560     }
561     Constant *InElt;
562     if (unsigned(Elt) >= SrcNumElts*2)
563       InElt = UndefValue::get(EltTy);
564     else if (unsigned(Elt) >= SrcNumElts) {
565       Type *Ty = IntegerType::get(V2->getContext(), 32);
566       InElt =
567         ConstantExpr::getExtractElement(V2,
568                                         ConstantInt::get(Ty, Elt - SrcNumElts));
569     } else {
570       Type *Ty = IntegerType::get(V1->getContext(), 32);
571       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
572     }
573     Result.push_back(InElt);
574   }
575 
576   return ConstantVector::get(Result);
577 }
578 
579 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
580                                                     ArrayRef<unsigned> Idxs) {
581   // Base case: no indices, so return the entire value.
582   if (Idxs.empty())
583     return Agg;
584 
585   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
586     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
587 
588   return nullptr;
589 }
590 
591 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
592                                                    Constant *Val,
593                                                    ArrayRef<unsigned> Idxs) {
594   // Base case: no indices, so replace the entire value.
595   if (Idxs.empty())
596     return Val;
597 
598   unsigned NumElts;
599   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
600     NumElts = ST->getNumElements();
601   else
602     NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
603 
604   SmallVector<Constant*, 32> Result;
605   for (unsigned i = 0; i != NumElts; ++i) {
606     Constant *C = Agg->getAggregateElement(i);
607     if (!C) return nullptr;
608 
609     if (Idxs[0] == i)
610       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
611 
612     Result.push_back(C);
613   }
614 
615   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
616     return ConstantStruct::get(ST, Result);
617   return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
618 }
619 
620 Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
621   assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
622 
623   // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
624   // vectors are always evaluated per element.
625   bool IsScalableVector = isa<ScalableVectorType>(C->getType());
626   bool HasScalarUndefOrScalableVectorUndef =
627       (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
628 
629   if (HasScalarUndefOrScalableVectorUndef) {
630     switch (static_cast<Instruction::UnaryOps>(Opcode)) {
631     case Instruction::FNeg:
632       return C; // -undef -> undef
633     case Instruction::UnaryOpsEnd:
634       llvm_unreachable("Invalid UnaryOp");
635     }
636   }
637 
638   // Constant should not be UndefValue, unless these are vector constants.
639   assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
640   // We only have FP UnaryOps right now.
641   assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
642 
643   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
644     const APFloat &CV = CFP->getValueAPF();
645     switch (Opcode) {
646     default:
647       break;
648     case Instruction::FNeg:
649       return ConstantFP::get(C->getContext(), neg(CV));
650     }
651   } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
652 
653     Type *Ty = IntegerType::get(VTy->getContext(), 32);
654     // Fast path for splatted constants.
655     if (Constant *Splat = C->getSplatValue())
656       if (Constant *Elt = ConstantFoldUnaryInstruction(Opcode, Splat))
657         return ConstantVector::getSplat(VTy->getElementCount(), Elt);
658 
659     // Fold each element and create a vector constant from those constants.
660     SmallVector<Constant *, 16> Result;
661     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
662       Constant *ExtractIdx = ConstantInt::get(Ty, i);
663       Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
664       Constant *Res = ConstantFoldUnaryInstruction(Opcode, Elt);
665       if (!Res)
666         return nullptr;
667       Result.push_back(Res);
668     }
669 
670     return ConstantVector::get(Result);
671   }
672 
673   // We don't know how to fold this.
674   return nullptr;
675 }
676 
677 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
678                                               Constant *C2) {
679   assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
680 
681   // Simplify BinOps with their identity values first. They are no-ops and we
682   // can always return the other value, including undef or poison values.
683   if (Constant *Identity = ConstantExpr::getBinOpIdentity(
684           Opcode, C1->getType(), /*AllowRHSIdentity*/ false)) {
685     if (C1 == Identity)
686       return C2;
687     if (C2 == Identity)
688       return C1;
689   } else if (Constant *Identity = ConstantExpr::getBinOpIdentity(
690                  Opcode, C1->getType(), /*AllowRHSIdentity*/ true)) {
691     if (C2 == Identity)
692       return C1;
693   }
694 
695   // Binary operations propagate poison.
696   if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
697     return PoisonValue::get(C1->getType());
698 
699   // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
700   // vectors are always evaluated per element.
701   bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
702   bool HasScalarUndefOrScalableVectorUndef =
703       (!C1->getType()->isVectorTy() || IsScalableVector) &&
704       (isa<UndefValue>(C1) || isa<UndefValue>(C2));
705   if (HasScalarUndefOrScalableVectorUndef) {
706     switch (static_cast<Instruction::BinaryOps>(Opcode)) {
707     case Instruction::Xor:
708       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
709         // Handle undef ^ undef -> 0 special case. This is a common
710         // idiom (misuse).
711         return Constant::getNullValue(C1->getType());
712       [[fallthrough]];
713     case Instruction::Add:
714     case Instruction::Sub:
715       return UndefValue::get(C1->getType());
716     case Instruction::And:
717       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
718         return C1;
719       return Constant::getNullValue(C1->getType());   // undef & X -> 0
720     case Instruction::Mul: {
721       // undef * undef -> undef
722       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
723         return C1;
724       const APInt *CV;
725       // X * undef -> undef   if X is odd
726       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
727         if ((*CV)[0])
728           return UndefValue::get(C1->getType());
729 
730       // X * undef -> 0       otherwise
731       return Constant::getNullValue(C1->getType());
732     }
733     case Instruction::SDiv:
734     case Instruction::UDiv:
735       // X / undef -> poison
736       // X / 0 -> poison
737       if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
738         return PoisonValue::get(C2->getType());
739       // undef / X -> 0       otherwise
740       return Constant::getNullValue(C1->getType());
741     case Instruction::URem:
742     case Instruction::SRem:
743       // X % undef -> poison
744       // X % 0 -> poison
745       if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
746         return PoisonValue::get(C2->getType());
747       // undef % X -> 0       otherwise
748       return Constant::getNullValue(C1->getType());
749     case Instruction::Or:                          // X | undef -> -1
750       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
751         return C1;
752       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
753     case Instruction::LShr:
754       // X >>l undef -> poison
755       if (isa<UndefValue>(C2))
756         return PoisonValue::get(C2->getType());
757       // undef >>l X -> 0
758       return Constant::getNullValue(C1->getType());
759     case Instruction::AShr:
760       // X >>a undef -> poison
761       if (isa<UndefValue>(C2))
762         return PoisonValue::get(C2->getType());
763       // TODO: undef >>a X -> poison if the shift is exact
764       // undef >>a X -> 0
765       return Constant::getNullValue(C1->getType());
766     case Instruction::Shl:
767       // X << undef -> undef
768       if (isa<UndefValue>(C2))
769         return PoisonValue::get(C2->getType());
770       // undef << X -> 0
771       return Constant::getNullValue(C1->getType());
772     case Instruction::FSub:
773       // -0.0 - undef --> undef (consistent with "fneg undef")
774       if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
775         return C2;
776       [[fallthrough]];
777     case Instruction::FAdd:
778     case Instruction::FMul:
779     case Instruction::FDiv:
780     case Instruction::FRem:
781       // [any flop] undef, undef -> undef
782       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
783         return C1;
784       // [any flop] C, undef -> NaN
785       // [any flop] undef, C -> NaN
786       // We could potentially specialize NaN/Inf constants vs. 'normal'
787       // constants (possibly differently depending on opcode and operand). This
788       // would allow returning undef sometimes. But it is always safe to fold to
789       // NaN because we can choose the undef operand as NaN, and any FP opcode
790       // with a NaN operand will propagate NaN.
791       return ConstantFP::getNaN(C1->getType());
792     case Instruction::BinaryOpsEnd:
793       llvm_unreachable("Invalid BinaryOp");
794     }
795   }
796 
797   // Neither constant should be UndefValue, unless these are vector constants.
798   assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
799 
800   // Handle simplifications when the RHS is a constant int.
801   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
802     switch (Opcode) {
803     case Instruction::Mul:
804       if (CI2->isZero())
805         return C2; // X * 0 == 0
806       break;
807     case Instruction::UDiv:
808     case Instruction::SDiv:
809       if (CI2->isZero())
810         return PoisonValue::get(CI2->getType());              // X / 0 == poison
811       break;
812     case Instruction::URem:
813     case Instruction::SRem:
814       if (CI2->isOne())
815         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
816       if (CI2->isZero())
817         return PoisonValue::get(CI2->getType());              // X % 0 == poison
818       break;
819     case Instruction::And:
820       if (CI2->isZero())
821         return C2; // X & 0 == 0
822 
823       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
824         // If and'ing the address of a global with a constant, fold it.
825         if (CE1->getOpcode() == Instruction::PtrToInt &&
826             isa<GlobalValue>(CE1->getOperand(0))) {
827           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
828 
829           Align GVAlign; // defaults to 1
830 
831           if (Module *TheModule = GV->getParent()) {
832             const DataLayout &DL = TheModule->getDataLayout();
833             GVAlign = GV->getPointerAlignment(DL);
834 
835             // If the function alignment is not specified then assume that it
836             // is 4.
837             // This is dangerous; on x86, the alignment of the pointer
838             // corresponds to the alignment of the function, but might be less
839             // than 4 if it isn't explicitly specified.
840             // However, a fix for this behaviour was reverted because it
841             // increased code size (see https://reviews.llvm.org/D55115)
842             // FIXME: This code should be deleted once existing targets have
843             // appropriate defaults
844             if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
845               GVAlign = Align(4);
846           } else if (isa<GlobalVariable>(GV)) {
847             GVAlign = cast<GlobalVariable>(GV)->getAlign().valueOrOne();
848           }
849 
850           if (GVAlign > 1) {
851             unsigned DstWidth = CI2->getBitWidth();
852             unsigned SrcWidth = std::min(DstWidth, Log2(GVAlign));
853             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
854 
855             // If checking bits we know are clear, return zero.
856             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
857               return Constant::getNullValue(CI2->getType());
858           }
859         }
860       }
861       break;
862     case Instruction::Or:
863       if (CI2->isMinusOne())
864         return C2; // X | -1 == -1
865       break;
866     }
867   } else if (isa<ConstantInt>(C1)) {
868     // If C1 is a ConstantInt and C2 is not, swap the operands.
869     if (Instruction::isCommutative(Opcode))
870       return ConstantExpr::isDesirableBinOp(Opcode)
871                  ? ConstantExpr::get(Opcode, C2, C1)
872                  : ConstantFoldBinaryInstruction(Opcode, C2, C1);
873   }
874 
875   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
876     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
877       const APInt &C1V = CI1->getValue();
878       const APInt &C2V = CI2->getValue();
879       switch (Opcode) {
880       default:
881         break;
882       case Instruction::Add:
883         return ConstantInt::get(CI1->getContext(), C1V + C2V);
884       case Instruction::Sub:
885         return ConstantInt::get(CI1->getContext(), C1V - C2V);
886       case Instruction::Mul:
887         return ConstantInt::get(CI1->getContext(), C1V * C2V);
888       case Instruction::UDiv:
889         assert(!CI2->isZero() && "Div by zero handled above");
890         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
891       case Instruction::SDiv:
892         assert(!CI2->isZero() && "Div by zero handled above");
893         if (C2V.isAllOnes() && C1V.isMinSignedValue())
894           return PoisonValue::get(CI1->getType());   // MIN_INT / -1 -> poison
895         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
896       case Instruction::URem:
897         assert(!CI2->isZero() && "Div by zero handled above");
898         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
899       case Instruction::SRem:
900         assert(!CI2->isZero() && "Div by zero handled above");
901         if (C2V.isAllOnes() && C1V.isMinSignedValue())
902           return PoisonValue::get(CI1->getType());   // MIN_INT % -1 -> poison
903         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
904       case Instruction::And:
905         return ConstantInt::get(CI1->getContext(), C1V & C2V);
906       case Instruction::Or:
907         return ConstantInt::get(CI1->getContext(), C1V | C2V);
908       case Instruction::Xor:
909         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
910       case Instruction::Shl:
911         if (C2V.ult(C1V.getBitWidth()))
912           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
913         return PoisonValue::get(C1->getType()); // too big shift is poison
914       case Instruction::LShr:
915         if (C2V.ult(C1V.getBitWidth()))
916           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
917         return PoisonValue::get(C1->getType()); // too big shift is poison
918       case Instruction::AShr:
919         if (C2V.ult(C1V.getBitWidth()))
920           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
921         return PoisonValue::get(C1->getType()); // too big shift is poison
922       }
923     }
924 
925     switch (Opcode) {
926     case Instruction::SDiv:
927     case Instruction::UDiv:
928     case Instruction::URem:
929     case Instruction::SRem:
930     case Instruction::LShr:
931     case Instruction::AShr:
932     case Instruction::Shl:
933       if (CI1->isZero()) return C1;
934       break;
935     default:
936       break;
937     }
938   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
939     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
940       const APFloat &C1V = CFP1->getValueAPF();
941       const APFloat &C2V = CFP2->getValueAPF();
942       APFloat C3V = C1V;  // copy for modification
943       switch (Opcode) {
944       default:
945         break;
946       case Instruction::FAdd:
947         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
948         return ConstantFP::get(C1->getContext(), C3V);
949       case Instruction::FSub:
950         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
951         return ConstantFP::get(C1->getContext(), C3V);
952       case Instruction::FMul:
953         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
954         return ConstantFP::get(C1->getContext(), C3V);
955       case Instruction::FDiv:
956         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
957         return ConstantFP::get(C1->getContext(), C3V);
958       case Instruction::FRem:
959         (void)C3V.mod(C2V);
960         return ConstantFP::get(C1->getContext(), C3V);
961       }
962     }
963   } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
964     // Fast path for splatted constants.
965     if (Constant *C2Splat = C2->getSplatValue()) {
966       if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
967         return PoisonValue::get(VTy);
968       if (Constant *C1Splat = C1->getSplatValue()) {
969         Constant *Res =
970             ConstantExpr::isDesirableBinOp(Opcode)
971                 ? ConstantExpr::get(Opcode, C1Splat, C2Splat)
972                 : ConstantFoldBinaryInstruction(Opcode, C1Splat, C2Splat);
973         if (!Res)
974           return nullptr;
975         return ConstantVector::getSplat(VTy->getElementCount(), Res);
976       }
977     }
978 
979     if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
980       // Fold each element and create a vector constant from those constants.
981       SmallVector<Constant*, 16> Result;
982       Type *Ty = IntegerType::get(FVTy->getContext(), 32);
983       for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
984         Constant *ExtractIdx = ConstantInt::get(Ty, i);
985         Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
986         Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
987 
988         // If any element of a divisor vector is zero, the whole op is poison.
989         if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
990           return PoisonValue::get(VTy);
991 
992         Constant *Res = ConstantExpr::isDesirableBinOp(Opcode)
993                             ? ConstantExpr::get(Opcode, LHS, RHS)
994                             : ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
995         if (!Res)
996           return nullptr;
997         Result.push_back(Res);
998       }
999 
1000       return ConstantVector::get(Result);
1001     }
1002   }
1003 
1004   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1005     // There are many possible foldings we could do here.  We should probably
1006     // at least fold add of a pointer with an integer into the appropriate
1007     // getelementptr.  This will improve alias analysis a bit.
1008 
1009     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1010     // (a + (b + c)).
1011     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1012       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1013       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1014         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1015     }
1016   } else if (isa<ConstantExpr>(C2)) {
1017     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1018     // other way if possible.
1019     if (Instruction::isCommutative(Opcode))
1020       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1021   }
1022 
1023   // i1 can be simplified in many cases.
1024   if (C1->getType()->isIntegerTy(1)) {
1025     switch (Opcode) {
1026     case Instruction::Add:
1027     case Instruction::Sub:
1028       return ConstantExpr::getXor(C1, C2);
1029     case Instruction::Shl:
1030     case Instruction::LShr:
1031     case Instruction::AShr:
1032       // We can assume that C2 == 0.  If it were one the result would be
1033       // undefined because the shift value is as large as the bitwidth.
1034       return C1;
1035     case Instruction::SDiv:
1036     case Instruction::UDiv:
1037       // We can assume that C2 == 1.  If it were zero the result would be
1038       // undefined through division by zero.
1039       return C1;
1040     case Instruction::URem:
1041     case Instruction::SRem:
1042       // We can assume that C2 == 1.  If it were zero the result would be
1043       // undefined through division by zero.
1044       return ConstantInt::getFalse(C1->getContext());
1045     default:
1046       break;
1047     }
1048   }
1049 
1050   // We don't know how to fold this.
1051   return nullptr;
1052 }
1053 
1054 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1055                                                       const GlobalValue *GV2) {
1056   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1057     if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
1058       return true;
1059     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1060       Type *Ty = GVar->getValueType();
1061       // A global with opaque type might end up being zero sized.
1062       if (!Ty->isSized())
1063         return true;
1064       // A global with an empty type might lie at the address of any other
1065       // global.
1066       if (Ty->isEmptyTy())
1067         return true;
1068     }
1069     return false;
1070   };
1071   // Don't try to decide equality of aliases.
1072   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1073     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1074       return ICmpInst::ICMP_NE;
1075   return ICmpInst::BAD_ICMP_PREDICATE;
1076 }
1077 
1078 /// This function determines if there is anything we can decide about the two
1079 /// constants provided. This doesn't need to handle simple things like integer
1080 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
1081 /// If we can determine that the two constants have a particular relation to
1082 /// each other, we should return the corresponding ICmp predicate, otherwise
1083 /// return ICmpInst::BAD_ICMP_PREDICATE.
1084 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2) {
1085   assert(V1->getType() == V2->getType() &&
1086          "Cannot compare different types of values!");
1087   if (V1 == V2) return ICmpInst::ICMP_EQ;
1088 
1089   // The following folds only apply to pointers.
1090   if (!V1->getType()->isPointerTy())
1091     return ICmpInst::BAD_ICMP_PREDICATE;
1092 
1093   // To simplify this code we canonicalize the relation so that the first
1094   // operand is always the most "complex" of the two.  We consider simple
1095   // constants (like ConstantPointerNull) to be the simplest, followed by
1096   // BlockAddress, GlobalValues, and ConstantExpr's (the most complex).
1097   auto GetComplexity = [](Constant *V) {
1098     if (isa<ConstantExpr>(V))
1099       return 3;
1100     if (isa<GlobalValue>(V))
1101       return 2;
1102     if (isa<BlockAddress>(V))
1103       return 1;
1104     return 0;
1105   };
1106   if (GetComplexity(V1) < GetComplexity(V2)) {
1107     ICmpInst::Predicate SwappedRelation = evaluateICmpRelation(V2, V1);
1108     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1109       return ICmpInst::getSwappedPredicate(SwappedRelation);
1110     return ICmpInst::BAD_ICMP_PREDICATE;
1111   }
1112 
1113   if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1114     // Now we know that the RHS is a BlockAddress or simple constant.
1115     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1116       // Block address in another function can't equal this one, but block
1117       // addresses in the current function might be the same if blocks are
1118       // empty.
1119       if (BA2->getFunction() != BA->getFunction())
1120         return ICmpInst::ICMP_NE;
1121     } else if (isa<ConstantPointerNull>(V2)) {
1122       return ICmpInst::ICMP_NE;
1123     }
1124   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1125     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1126     // constant.
1127     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1128       return areGlobalsPotentiallyEqual(GV, GV2);
1129     } else if (isa<BlockAddress>(V2)) {
1130       return ICmpInst::ICMP_NE; // Globals never equal labels.
1131     } else if (isa<ConstantPointerNull>(V2)) {
1132       // GlobalVals can never be null unless they have external weak linkage.
1133       // We don't try to evaluate aliases here.
1134       // NOTE: We should not be doing this constant folding if null pointer
1135       // is considered valid for the function. But currently there is no way to
1136       // query it from the Constant type.
1137       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
1138           !NullPointerIsDefined(nullptr /* F */,
1139                                 GV->getType()->getAddressSpace()))
1140         return ICmpInst::ICMP_UGT;
1141     }
1142   } else if (auto *CE1 = dyn_cast<ConstantExpr>(V1)) {
1143     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1144     // constantexpr, a global, block address, or a simple constant.
1145     Constant *CE1Op0 = CE1->getOperand(0);
1146 
1147     switch (CE1->getOpcode()) {
1148     case Instruction::GetElementPtr: {
1149       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1150       // Ok, since this is a getelementptr, we know that the constant has a
1151       // pointer type.  Check the various cases.
1152       if (isa<ConstantPointerNull>(V2)) {
1153         // If we are comparing a GEP to a null pointer, check to see if the base
1154         // of the GEP equals the null pointer.
1155         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1156           // If its not weak linkage, the GVal must have a non-zero address
1157           // so the result is greater-than
1158           if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())
1159             return ICmpInst::ICMP_UGT;
1160         }
1161       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1162         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1163           if (GV != GV2) {
1164             if (CE1GEP->hasAllZeroIndices())
1165               return areGlobalsPotentiallyEqual(GV, GV2);
1166             return ICmpInst::BAD_ICMP_PREDICATE;
1167           }
1168         }
1169       } else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {
1170         // By far the most common case to handle is when the base pointers are
1171         // obviously to the same global.
1172         const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());
1173         if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1174           // Don't know relative ordering, but check for inequality.
1175           if (CE1Op0 != CE2Op0) {
1176             if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1177               return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1178                                                 cast<GlobalValue>(CE2Op0));
1179             return ICmpInst::BAD_ICMP_PREDICATE;
1180           }
1181         }
1182       }
1183       break;
1184     }
1185     default:
1186       break;
1187     }
1188   }
1189 
1190   return ICmpInst::BAD_ICMP_PREDICATE;
1191 }
1192 
1193 Constant *llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,
1194                                                Constant *C1, Constant *C2) {
1195   Type *ResultTy;
1196   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1197     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1198                                VT->getElementCount());
1199   else
1200     ResultTy = Type::getInt1Ty(C1->getContext());
1201 
1202   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1203   if (Predicate == FCmpInst::FCMP_FALSE)
1204     return Constant::getNullValue(ResultTy);
1205 
1206   if (Predicate == FCmpInst::FCMP_TRUE)
1207     return Constant::getAllOnesValue(ResultTy);
1208 
1209   // Handle some degenerate cases first
1210   if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
1211     return PoisonValue::get(ResultTy);
1212 
1213   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1214     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
1215     // For EQ and NE, we can always pick a value for the undef to make the
1216     // predicate pass or fail, so we can return undef.
1217     // Also, if both operands are undef, we can return undef for int comparison.
1218     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
1219       return UndefValue::get(ResultTy);
1220 
1221     // Otherwise, for integer compare, pick the same value as the non-undef
1222     // operand, and fold it to true or false.
1223     if (isIntegerPredicate)
1224       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
1225 
1226     // Choosing NaN for the undef will always make unordered comparison succeed
1227     // and ordered comparison fails.
1228     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
1229   }
1230 
1231   if (C2->isNullValue()) {
1232     // The caller is expected to commute the operands if the constant expression
1233     // is C2.
1234     // C1 >= 0 --> true
1235     if (Predicate == ICmpInst::ICMP_UGE)
1236       return Constant::getAllOnesValue(ResultTy);
1237     // C1 < 0 --> false
1238     if (Predicate == ICmpInst::ICMP_ULT)
1239       return Constant::getNullValue(ResultTy);
1240   }
1241 
1242   // If the comparison is a comparison between two i1's, simplify it.
1243   if (C1->getType()->isIntegerTy(1)) {
1244     switch (Predicate) {
1245     case ICmpInst::ICMP_EQ:
1246       if (isa<ConstantInt>(C2))
1247         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1248       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1249     case ICmpInst::ICMP_NE:
1250       return ConstantExpr::getXor(C1, C2);
1251     default:
1252       break;
1253     }
1254   }
1255 
1256   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1257     const APInt &V1 = cast<ConstantInt>(C1)->getValue();
1258     const APInt &V2 = cast<ConstantInt>(C2)->getValue();
1259     return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));
1260   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1261     const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
1262     const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
1263     return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));
1264   } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
1265 
1266     // Fast path for splatted constants.
1267     if (Constant *C1Splat = C1->getSplatValue())
1268       if (Constant *C2Splat = C2->getSplatValue())
1269         if (Constant *Elt =
1270                 ConstantFoldCompareInstruction(Predicate, C1Splat, C2Splat))
1271           return ConstantVector::getSplat(C1VTy->getElementCount(), Elt);
1272 
1273     // Do not iterate on scalable vector. The number of elements is unknown at
1274     // compile-time.
1275     if (isa<ScalableVectorType>(C1VTy))
1276       return nullptr;
1277 
1278     // If we can constant fold the comparison of each element, constant fold
1279     // the whole vector comparison.
1280     SmallVector<Constant*, 4> ResElts;
1281     Type *Ty = IntegerType::get(C1->getContext(), 32);
1282     // Compare the elements, producing an i1 result or constant expr.
1283     for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
1284          I != E; ++I) {
1285       Constant *C1E =
1286           ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));
1287       Constant *C2E =
1288           ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));
1289       Constant *Elt = ConstantFoldCompareInstruction(Predicate, C1E, C2E);
1290       if (!Elt)
1291         return nullptr;
1292 
1293       ResElts.push_back(Elt);
1294     }
1295 
1296     return ConstantVector::get(ResElts);
1297   }
1298 
1299   if (C1->getType()->isFPOrFPVectorTy()) {
1300     if (C1 == C2) {
1301       // We know that C1 == C2 || isUnordered(C1, C2).
1302       if (Predicate == FCmpInst::FCMP_ONE)
1303         return ConstantInt::getFalse(ResultTy);
1304       else if (Predicate == FCmpInst::FCMP_UEQ)
1305         return ConstantInt::getTrue(ResultTy);
1306     }
1307   } else {
1308     // Evaluate the relation between the two constants, per the predicate.
1309     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1310     switch (evaluateICmpRelation(C1, C2)) {
1311     default: llvm_unreachable("Unknown relational!");
1312     case ICmpInst::BAD_ICMP_PREDICATE:
1313       break;  // Couldn't determine anything about these constants.
1314     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1315       // If we know the constants are equal, we can decide the result of this
1316       // computation precisely.
1317       Result = ICmpInst::isTrueWhenEqual(Predicate);
1318       break;
1319     case ICmpInst::ICMP_ULT:
1320       switch (Predicate) {
1321       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1322         Result = 1; break;
1323       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1324         Result = 0; break;
1325       default:
1326         break;
1327       }
1328       break;
1329     case ICmpInst::ICMP_SLT:
1330       switch (Predicate) {
1331       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1332         Result = 1; break;
1333       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1334         Result = 0; break;
1335       default:
1336         break;
1337       }
1338       break;
1339     case ICmpInst::ICMP_UGT:
1340       switch (Predicate) {
1341       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1342         Result = 1; break;
1343       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1344         Result = 0; break;
1345       default:
1346         break;
1347       }
1348       break;
1349     case ICmpInst::ICMP_SGT:
1350       switch (Predicate) {
1351       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1352         Result = 1; break;
1353       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1354         Result = 0; break;
1355       default:
1356         break;
1357       }
1358       break;
1359     case ICmpInst::ICMP_ULE:
1360       if (Predicate == ICmpInst::ICMP_UGT)
1361         Result = 0;
1362       if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)
1363         Result = 1;
1364       break;
1365     case ICmpInst::ICMP_SLE:
1366       if (Predicate == ICmpInst::ICMP_SGT)
1367         Result = 0;
1368       if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)
1369         Result = 1;
1370       break;
1371     case ICmpInst::ICMP_UGE:
1372       if (Predicate == ICmpInst::ICMP_ULT)
1373         Result = 0;
1374       if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)
1375         Result = 1;
1376       break;
1377     case ICmpInst::ICMP_SGE:
1378       if (Predicate == ICmpInst::ICMP_SLT)
1379         Result = 0;
1380       if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)
1381         Result = 1;
1382       break;
1383     case ICmpInst::ICMP_NE:
1384       if (Predicate == ICmpInst::ICMP_EQ)
1385         Result = 0;
1386       if (Predicate == ICmpInst::ICMP_NE)
1387         Result = 1;
1388       break;
1389     }
1390 
1391     // If we evaluated the result, return it now.
1392     if (Result != -1)
1393       return ConstantInt::get(ResultTy, Result);
1394 
1395     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1396         (C1->isNullValue() && !C2->isNullValue())) {
1397       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1398       // other way if possible.
1399       // Also, if C1 is null and C2 isn't, flip them around.
1400       Predicate = ICmpInst::getSwappedPredicate(Predicate);
1401       return ConstantFoldCompareInstruction(Predicate, C2, C1);
1402     }
1403   }
1404   return nullptr;
1405 }
1406 
1407 // Combine Indices - If the source pointer to this getelementptr instruction
1408 // is a getelementptr instruction, combine the indices of the two
1409 // getelementptr instructions into a single instruction.
1410 static Constant *foldGEPOfGEP(GEPOperator *GEP, Type *PointeeTy, bool InBounds,
1411                               ArrayRef<Value *> Idxs) {
1412   if (PointeeTy != GEP->getResultElementType())
1413     return nullptr;
1414 
1415   // Leave inrange handling to DL-aware constant folding.
1416   if (GEP->getInRange())
1417     return nullptr;
1418 
1419   Constant *Idx0 = cast<Constant>(Idxs[0]);
1420   if (Idx0->isNullValue()) {
1421     // Handle the simple case of a zero index.
1422     SmallVector<Value*, 16> NewIndices;
1423     NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
1424     NewIndices.append(GEP->idx_begin(), GEP->idx_end());
1425     NewIndices.append(Idxs.begin() + 1, Idxs.end());
1426     return ConstantExpr::getGetElementPtr(
1427         GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
1428         NewIndices, InBounds && GEP->isInBounds());
1429   }
1430 
1431   gep_type_iterator LastI = gep_type_end(GEP);
1432   for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
1433        I != E; ++I)
1434     LastI = I;
1435 
1436   // We can't combine GEPs if the last index is a struct type.
1437   if (!LastI.isSequential())
1438     return nullptr;
1439   // We could perform the transform with non-constant index, but prefer leaving
1440   // it as GEP of GEP rather than GEP of add for now.
1441   ConstantInt *CI = dyn_cast<ConstantInt>(Idx0);
1442   if (!CI)
1443     return nullptr;
1444 
1445   // TODO: This code may be extended to handle vectors as well.
1446   auto *LastIdx = cast<Constant>(GEP->getOperand(GEP->getNumOperands()-1));
1447   Type *LastIdxTy = LastIdx->getType();
1448   if (LastIdxTy->isVectorTy())
1449     return nullptr;
1450 
1451   SmallVector<Value*, 16> NewIndices;
1452   NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
1453   NewIndices.append(GEP->idx_begin(), GEP->idx_end() - 1);
1454 
1455   // Add the last index of the source with the first index of the new GEP.
1456   // Make sure to handle the case when they are actually different types.
1457   if (LastIdxTy != Idx0->getType()) {
1458     unsigned CommonExtendedWidth =
1459         std::max(LastIdxTy->getIntegerBitWidth(),
1460                  Idx0->getType()->getIntegerBitWidth());
1461     CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
1462 
1463     Type *CommonTy =
1464         Type::getIntNTy(LastIdxTy->getContext(), CommonExtendedWidth);
1465     if (Idx0->getType() != CommonTy)
1466       Idx0 = ConstantFoldCastInstruction(Instruction::SExt, Idx0, CommonTy);
1467     if (LastIdx->getType() != CommonTy)
1468       LastIdx =
1469           ConstantFoldCastInstruction(Instruction::SExt, LastIdx, CommonTy);
1470     if (!Idx0 || !LastIdx)
1471       return nullptr;
1472   }
1473 
1474   NewIndices.push_back(ConstantExpr::get(Instruction::Add, Idx0, LastIdx));
1475   NewIndices.append(Idxs.begin() + 1, Idxs.end());
1476 
1477   return ConstantExpr::getGetElementPtr(
1478       GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
1479       NewIndices, InBounds && GEP->isInBounds());
1480 }
1481 
1482 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
1483                                           bool InBounds,
1484                                           std::optional<ConstantRange> InRange,
1485                                           ArrayRef<Value *> Idxs) {
1486   if (Idxs.empty()) return C;
1487 
1488   Type *GEPTy = GetElementPtrInst::getGEPReturnType(
1489       C, ArrayRef((Value *const *)Idxs.data(), Idxs.size()));
1490 
1491   if (isa<PoisonValue>(C))
1492     return PoisonValue::get(GEPTy);
1493 
1494   if (isa<UndefValue>(C))
1495     return UndefValue::get(GEPTy);
1496 
1497   auto IsNoOp = [&]() {
1498     // Avoid losing inrange information.
1499     if (InRange)
1500       return false;
1501 
1502     return all_of(Idxs, [](Value *Idx) {
1503       Constant *IdxC = cast<Constant>(Idx);
1504       return IdxC->isNullValue() || isa<UndefValue>(IdxC);
1505     });
1506   };
1507   if (IsNoOp())
1508     return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
1509                ? ConstantVector::getSplat(
1510                      cast<VectorType>(GEPTy)->getElementCount(), C)
1511                : C;
1512 
1513   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1514     if (auto *GEP = dyn_cast<GEPOperator>(CE))
1515       if (Constant *C = foldGEPOfGEP(GEP, PointeeTy, InBounds, Idxs))
1516         return C;
1517 
1518   return nullptr;
1519 }
1520