10b57cec5SDimitry Andric //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements folding of constants for LLVM. This implements the
100b57cec5SDimitry Andric // (internal) ConstantFold.h interface, which is used by the
110b57cec5SDimitry Andric // ConstantExpr::get* methods to automatically fold constants when possible.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // The current constant folding implementation is implemented in two pieces: the
140b57cec5SDimitry Andric // pieces that don't need DataLayout, and the pieces that do. This is to avoid
150b57cec5SDimitry Andric // a dependence in IR on Target.
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
180b57cec5SDimitry Andric
1981ad6265SDimitry Andric #include "llvm/IR/ConstantFold.h"
200b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
230b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
240b57cec5SDimitry Andric #include "llvm/IR/Function.h"
250b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
260b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
270b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
280b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
290b57cec5SDimitry Andric #include "llvm/IR/Module.h"
300b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
310b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
320b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
330b57cec5SDimitry Andric using namespace llvm;
340b57cec5SDimitry Andric using namespace llvm::PatternMatch;
350b57cec5SDimitry Andric
360b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
370b57cec5SDimitry Andric // ConstantFold*Instruction Implementations
380b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
390b57cec5SDimitry Andric
400b57cec5SDimitry Andric /// This function determines which opcode to use to fold two constant cast
410b57cec5SDimitry Andric /// expressions together. It uses CastInst::isEliminableCastPair to determine
420b57cec5SDimitry Andric /// the opcode. Consequently its just a wrapper around that function.
430b57cec5SDimitry Andric /// Determine if it is valid to fold a cast of a cast
440b57cec5SDimitry Andric static unsigned
foldConstantCastPair(unsigned opc,ConstantExpr * Op,Type * DstTy)450b57cec5SDimitry Andric foldConstantCastPair(
460b57cec5SDimitry Andric unsigned opc, ///< opcode of the second cast constant expression
470b57cec5SDimitry Andric ConstantExpr *Op, ///< the first cast constant expression
480b57cec5SDimitry Andric Type *DstTy ///< destination type of the first cast
490b57cec5SDimitry Andric ) {
500b57cec5SDimitry Andric assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
510b57cec5SDimitry Andric assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
520b57cec5SDimitry Andric assert(CastInst::isCast(opc) && "Invalid cast opcode");
530b57cec5SDimitry Andric
540b57cec5SDimitry Andric // The types and opcodes for the two Cast constant expressions
550b57cec5SDimitry Andric Type *SrcTy = Op->getOperand(0)->getType();
560b57cec5SDimitry Andric Type *MidTy = Op->getType();
570b57cec5SDimitry Andric Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
580b57cec5SDimitry Andric Instruction::CastOps secondOp = Instruction::CastOps(opc);
590b57cec5SDimitry Andric
600b57cec5SDimitry Andric // Assume that pointers are never more than 64 bits wide, and only use this
610b57cec5SDimitry Andric // for the middle type. Otherwise we could end up folding away illegal
620b57cec5SDimitry Andric // bitcasts between address spaces with different sizes.
630b57cec5SDimitry Andric IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
640b57cec5SDimitry Andric
650b57cec5SDimitry Andric // Let CastInst::isEliminableCastPair do the heavy lifting.
660b57cec5SDimitry Andric return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
670b57cec5SDimitry Andric nullptr, FakeIntPtrTy, nullptr);
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric
FoldBitCast(Constant * V,Type * DestTy)700b57cec5SDimitry Andric static Constant *FoldBitCast(Constant *V, Type *DestTy) {
710b57cec5SDimitry Andric Type *SrcTy = V->getType();
720b57cec5SDimitry Andric if (SrcTy == DestTy)
730b57cec5SDimitry Andric return V; // no-op cast
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric // Handle casts from one vector constant to another. We know that the src
760b57cec5SDimitry Andric // and dest type have the same size (otherwise its an illegal cast).
770b57cec5SDimitry Andric if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
785f757f3fSDimitry Andric if (V->isAllOnesValue())
795f757f3fSDimitry Andric return Constant::getAllOnesValue(DestTy);
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
820b57cec5SDimitry Andric // This allows for other simplifications (although some of them
830b57cec5SDimitry Andric // can only be handled by Analysis/ConstantFolding.cpp).
840b57cec5SDimitry Andric if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
850b57cec5SDimitry Andric return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
865f757f3fSDimitry Andric return nullptr;
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric
890b57cec5SDimitry Andric // Handle integral constant input.
900b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
910b57cec5SDimitry Andric // See note below regarding the PPC_FP128 restriction.
920b57cec5SDimitry Andric if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
930b57cec5SDimitry Andric return ConstantFP::get(DestTy->getContext(),
940b57cec5SDimitry Andric APFloat(DestTy->getFltSemantics(),
950b57cec5SDimitry Andric CI->getValue()));
960b57cec5SDimitry Andric
970b57cec5SDimitry Andric // Otherwise, can't fold this (vector?)
980b57cec5SDimitry Andric return nullptr;
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric
1010b57cec5SDimitry Andric // Handle ConstantFP input: FP -> Integral.
1020b57cec5SDimitry Andric if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
1030b57cec5SDimitry Andric // PPC_FP128 is really the sum of two consecutive doubles, where the first
1040b57cec5SDimitry Andric // double is always stored first in memory, regardless of the target
1050b57cec5SDimitry Andric // endianness. The memory layout of i128, however, depends on the target
1060b57cec5SDimitry Andric // endianness, and so we can't fold this without target endianness
1070b57cec5SDimitry Andric // information. This should instead be handled by
1080b57cec5SDimitry Andric // Analysis/ConstantFolding.cpp
1090b57cec5SDimitry Andric if (FP->getType()->isPPC_FP128Ty())
1100b57cec5SDimitry Andric return nullptr;
1110b57cec5SDimitry Andric
1120b57cec5SDimitry Andric // Make sure dest type is compatible with the folded integer constant.
1130b57cec5SDimitry Andric if (!DestTy->isIntegerTy())
1140b57cec5SDimitry Andric return nullptr;
1150b57cec5SDimitry Andric
1160b57cec5SDimitry Andric return ConstantInt::get(FP->getContext(),
1170b57cec5SDimitry Andric FP->getValueAPF().bitcastToAPInt());
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric
1200b57cec5SDimitry Andric return nullptr;
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric
foldMaybeUndesirableCast(unsigned opc,Constant * V,Type * DestTy)1235f757f3fSDimitry Andric static Constant *foldMaybeUndesirableCast(unsigned opc, Constant *V,
1245f757f3fSDimitry Andric Type *DestTy) {
1255f757f3fSDimitry Andric return ConstantExpr::isDesirableCastOp(opc)
1265f757f3fSDimitry Andric ? ConstantExpr::getCast(opc, V, DestTy)
1275f757f3fSDimitry Andric : ConstantFoldCastInstruction(opc, V, DestTy);
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric
ConstantFoldCastInstruction(unsigned opc,Constant * V,Type * DestTy)1300b57cec5SDimitry Andric Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
1310b57cec5SDimitry Andric Type *DestTy) {
132e8d8bef9SDimitry Andric if (isa<PoisonValue>(V))
133e8d8bef9SDimitry Andric return PoisonValue::get(DestTy);
134e8d8bef9SDimitry Andric
1350b57cec5SDimitry Andric if (isa<UndefValue>(V)) {
1360b57cec5SDimitry Andric // zext(undef) = 0, because the top bits will be zero.
1370b57cec5SDimitry Andric // sext(undef) = 0, because the top bits will all be the same.
1380b57cec5SDimitry Andric // [us]itofp(undef) = 0, because the result value is bounded.
1390b57cec5SDimitry Andric if (opc == Instruction::ZExt || opc == Instruction::SExt ||
1400b57cec5SDimitry Andric opc == Instruction::UIToFP || opc == Instruction::SIToFP)
1410b57cec5SDimitry Andric return Constant::getNullValue(DestTy);
1420b57cec5SDimitry Andric return UndefValue::get(DestTy);
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric
145e8d8bef9SDimitry Andric if (V->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&
1460b57cec5SDimitry Andric opc != Instruction::AddrSpaceCast)
1470b57cec5SDimitry Andric return Constant::getNullValue(DestTy);
1480b57cec5SDimitry Andric
1490b57cec5SDimitry Andric // If the cast operand is a constant expression, there's a few things we can
1500b57cec5SDimitry Andric // do to try to simplify it.
1510b57cec5SDimitry Andric if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1520b57cec5SDimitry Andric if (CE->isCast()) {
1530b57cec5SDimitry Andric // Try hard to fold cast of cast because they are often eliminable.
1540b57cec5SDimitry Andric if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
1555f757f3fSDimitry Andric return foldMaybeUndesirableCast(newOpc, CE->getOperand(0), DestTy);
1560b57cec5SDimitry Andric }
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric
1590b57cec5SDimitry Andric // If the cast operand is a constant vector, perform the cast by
1600b57cec5SDimitry Andric // operating on each element. In the cast of bitcasts, the element
1610b57cec5SDimitry Andric // count may be mismatched; don't attempt to handle that here.
1620b57cec5SDimitry Andric if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
1630b57cec5SDimitry Andric DestTy->isVectorTy() &&
1645ffd83dbSDimitry Andric cast<FixedVectorType>(DestTy)->getNumElements() ==
1655ffd83dbSDimitry Andric cast<FixedVectorType>(V->getType())->getNumElements()) {
1660b57cec5SDimitry Andric VectorType *DestVecTy = cast<VectorType>(DestTy);
1670b57cec5SDimitry Andric Type *DstEltTy = DestVecTy->getElementType();
1685ffd83dbSDimitry Andric // Fast path for splatted constants.
1695ffd83dbSDimitry Andric if (Constant *Splat = V->getSplatValue()) {
1705f757f3fSDimitry Andric Constant *Res = foldMaybeUndesirableCast(opc, Splat, DstEltTy);
1715f757f3fSDimitry Andric if (!Res)
1725f757f3fSDimitry Andric return nullptr;
1735ffd83dbSDimitry Andric return ConstantVector::getSplat(
1745f757f3fSDimitry Andric cast<VectorType>(DestTy)->getElementCount(), Res);
1755ffd83dbSDimitry Andric }
1765ffd83dbSDimitry Andric SmallVector<Constant *, 16> res;
1770b57cec5SDimitry Andric Type *Ty = IntegerType::get(V->getContext(), 32);
1785ffd83dbSDimitry Andric for (unsigned i = 0,
1795ffd83dbSDimitry Andric e = cast<FixedVectorType>(V->getType())->getNumElements();
1805ffd83dbSDimitry Andric i != e; ++i) {
1815f757f3fSDimitry Andric Constant *C = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
1825f757f3fSDimitry Andric Constant *Casted = foldMaybeUndesirableCast(opc, C, DstEltTy);
1835f757f3fSDimitry Andric if (!Casted)
1845f757f3fSDimitry Andric return nullptr;
1855f757f3fSDimitry Andric res.push_back(Casted);
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric return ConstantVector::get(res);
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric // We actually have to do a cast now. Perform the cast according to the
1910b57cec5SDimitry Andric // opcode specified.
1920b57cec5SDimitry Andric switch (opc) {
1930b57cec5SDimitry Andric default:
1940b57cec5SDimitry Andric llvm_unreachable("Failed to cast constant expression");
1950b57cec5SDimitry Andric case Instruction::FPTrunc:
1960b57cec5SDimitry Andric case Instruction::FPExt:
1970b57cec5SDimitry Andric if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
1980b57cec5SDimitry Andric bool ignored;
1990b57cec5SDimitry Andric APFloat Val = FPC->getValueAPF();
20081ad6265SDimitry Andric Val.convert(DestTy->getFltSemantics(), APFloat::rmNearestTiesToEven,
20181ad6265SDimitry Andric &ignored);
2020b57cec5SDimitry Andric return ConstantFP::get(V->getContext(), Val);
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric return nullptr; // Can't fold.
2050b57cec5SDimitry Andric case Instruction::FPToUI:
2060b57cec5SDimitry Andric case Instruction::FPToSI:
2070b57cec5SDimitry Andric if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
2080b57cec5SDimitry Andric const APFloat &V = FPC->getValueAPF();
2090b57cec5SDimitry Andric bool ignored;
2100b57cec5SDimitry Andric uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
2110b57cec5SDimitry Andric APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
2120b57cec5SDimitry Andric if (APFloat::opInvalidOp ==
2130b57cec5SDimitry Andric V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
2140b57cec5SDimitry Andric // Undefined behavior invoked - the destination type can't represent
2150b57cec5SDimitry Andric // the input constant.
21628a41182SDimitry Andric return PoisonValue::get(DestTy);
2170b57cec5SDimitry Andric }
2180b57cec5SDimitry Andric return ConstantInt::get(FPC->getContext(), IntVal);
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric return nullptr; // Can't fold.
2210b57cec5SDimitry Andric case Instruction::UIToFP:
2220b57cec5SDimitry Andric case Instruction::SIToFP:
2230b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2240b57cec5SDimitry Andric const APInt &api = CI->getValue();
2250b57cec5SDimitry Andric APFloat apf(DestTy->getFltSemantics(),
226349cc55cSDimitry Andric APInt::getZero(DestTy->getPrimitiveSizeInBits()));
2270b57cec5SDimitry Andric apf.convertFromAPInt(api, opc==Instruction::SIToFP,
2280b57cec5SDimitry Andric APFloat::rmNearestTiesToEven);
2290b57cec5SDimitry Andric return ConstantFP::get(V->getContext(), apf);
2300b57cec5SDimitry Andric }
2310b57cec5SDimitry Andric return nullptr;
2320b57cec5SDimitry Andric case Instruction::ZExt:
2330b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2340b57cec5SDimitry Andric uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
2350b57cec5SDimitry Andric return ConstantInt::get(V->getContext(),
2360b57cec5SDimitry Andric CI->getValue().zext(BitWidth));
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric return nullptr;
2390b57cec5SDimitry Andric case Instruction::SExt:
2400b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2410b57cec5SDimitry Andric uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
2420b57cec5SDimitry Andric return ConstantInt::get(V->getContext(),
2430b57cec5SDimitry Andric CI->getValue().sext(BitWidth));
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric return nullptr;
2460b57cec5SDimitry Andric case Instruction::Trunc: {
2470b57cec5SDimitry Andric if (V->getType()->isVectorTy())
2480b57cec5SDimitry Andric return nullptr;
2490b57cec5SDimitry Andric
2500b57cec5SDimitry Andric uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
2510b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2520b57cec5SDimitry Andric return ConstantInt::get(V->getContext(),
2530b57cec5SDimitry Andric CI->getValue().trunc(DestBitWidth));
2540b57cec5SDimitry Andric }
2550b57cec5SDimitry Andric
2560b57cec5SDimitry Andric return nullptr;
2570b57cec5SDimitry Andric }
2580b57cec5SDimitry Andric case Instruction::BitCast:
2590b57cec5SDimitry Andric return FoldBitCast(V, DestTy);
2600b57cec5SDimitry Andric case Instruction::AddrSpaceCast:
2615f757f3fSDimitry Andric case Instruction::IntToPtr:
2625f757f3fSDimitry Andric case Instruction::PtrToInt:
2630b57cec5SDimitry Andric return nullptr;
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric
ConstantFoldSelectInstruction(Constant * Cond,Constant * V1,Constant * V2)2670b57cec5SDimitry Andric Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
2680b57cec5SDimitry Andric Constant *V1, Constant *V2) {
2690b57cec5SDimitry Andric // Check for i1 and vector true/false conditions.
2700b57cec5SDimitry Andric if (Cond->isNullValue()) return V2;
2710b57cec5SDimitry Andric if (Cond->isAllOnesValue()) return V1;
2720b57cec5SDimitry Andric
2730b57cec5SDimitry Andric // If the condition is a vector constant, fold the result elementwise.
2740b57cec5SDimitry Andric if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
2755ffd83dbSDimitry Andric auto *V1VTy = CondV->getType();
2760b57cec5SDimitry Andric SmallVector<Constant*, 16> Result;
2770b57cec5SDimitry Andric Type *Ty = IntegerType::get(CondV->getContext(), 32);
2785ffd83dbSDimitry Andric for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
2790b57cec5SDimitry Andric Constant *V;
2800b57cec5SDimitry Andric Constant *V1Element = ConstantExpr::getExtractElement(V1,
2810b57cec5SDimitry Andric ConstantInt::get(Ty, i));
2820b57cec5SDimitry Andric Constant *V2Element = ConstantExpr::getExtractElement(V2,
2830b57cec5SDimitry Andric ConstantInt::get(Ty, i));
2848bcb0991SDimitry Andric auto *Cond = cast<Constant>(CondV->getOperand(i));
285e8d8bef9SDimitry Andric if (isa<PoisonValue>(Cond)) {
286e8d8bef9SDimitry Andric V = PoisonValue::get(V1Element->getType());
287e8d8bef9SDimitry Andric } else if (V1Element == V2Element) {
2880b57cec5SDimitry Andric V = V1Element;
2890b57cec5SDimitry Andric } else if (isa<UndefValue>(Cond)) {
2900b57cec5SDimitry Andric V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
2910b57cec5SDimitry Andric } else {
2920b57cec5SDimitry Andric if (!isa<ConstantInt>(Cond)) break;
2930b57cec5SDimitry Andric V = Cond->isNullValue() ? V2Element : V1Element;
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric Result.push_back(V);
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric
2980b57cec5SDimitry Andric // If we were able to build the vector, return it.
2995ffd83dbSDimitry Andric if (Result.size() == V1VTy->getNumElements())
3000b57cec5SDimitry Andric return ConstantVector::get(Result);
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric
303e8d8bef9SDimitry Andric if (isa<PoisonValue>(Cond))
304e8d8bef9SDimitry Andric return PoisonValue::get(V1->getType());
305e8d8bef9SDimitry Andric
3060b57cec5SDimitry Andric if (isa<UndefValue>(Cond)) {
3070b57cec5SDimitry Andric if (isa<UndefValue>(V1)) return V1;
3080b57cec5SDimitry Andric return V2;
3090b57cec5SDimitry Andric }
310e8d8bef9SDimitry Andric
3110b57cec5SDimitry Andric if (V1 == V2) return V1;
3120b57cec5SDimitry Andric
313e8d8bef9SDimitry Andric if (isa<PoisonValue>(V1))
314e8d8bef9SDimitry Andric return V2;
315e8d8bef9SDimitry Andric if (isa<PoisonValue>(V2))
316e8d8bef9SDimitry Andric return V1;
317e8d8bef9SDimitry Andric
318e8d8bef9SDimitry Andric // If the true or false value is undef, we can fold to the other value as
319e8d8bef9SDimitry Andric // long as the other value isn't poison.
320e8d8bef9SDimitry Andric auto NotPoison = [](Constant *C) {
321e8d8bef9SDimitry Andric if (isa<PoisonValue>(C))
322e8d8bef9SDimitry Andric return false;
323e8d8bef9SDimitry Andric
324e8d8bef9SDimitry Andric // TODO: We can analyze ConstExpr by opcode to determine if there is any
325e8d8bef9SDimitry Andric // possibility of poison.
326e8d8bef9SDimitry Andric if (isa<ConstantExpr>(C))
327e8d8bef9SDimitry Andric return false;
328e8d8bef9SDimitry Andric
329e8d8bef9SDimitry Andric if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||
330e8d8bef9SDimitry Andric isa<ConstantPointerNull>(C) || isa<Function>(C))
331e8d8bef9SDimitry Andric return true;
332e8d8bef9SDimitry Andric
333e8d8bef9SDimitry Andric if (C->getType()->isVectorTy())
334e8d8bef9SDimitry Andric return !C->containsPoisonElement() && !C->containsConstantExpression();
335e8d8bef9SDimitry Andric
336e8d8bef9SDimitry Andric // TODO: Recursively analyze aggregates or other constants.
337e8d8bef9SDimitry Andric return false;
338e8d8bef9SDimitry Andric };
339e8d8bef9SDimitry Andric if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;
340e8d8bef9SDimitry Andric if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;
341e8d8bef9SDimitry Andric
3420b57cec5SDimitry Andric return nullptr;
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric
ConstantFoldExtractElementInstruction(Constant * Val,Constant * Idx)3450b57cec5SDimitry Andric Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
3460b57cec5SDimitry Andric Constant *Idx) {
3475ffd83dbSDimitry Andric auto *ValVTy = cast<VectorType>(Val->getType());
3485ffd83dbSDimitry Andric
349e8d8bef9SDimitry Andric // extractelt poison, C -> poison
350e8d8bef9SDimitry Andric // extractelt C, undef -> poison
351e8d8bef9SDimitry Andric if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
352e8d8bef9SDimitry Andric return PoisonValue::get(ValVTy->getElementType());
353e8d8bef9SDimitry Andric
3548bcb0991SDimitry Andric // extractelt undef, C -> undef
355e8d8bef9SDimitry Andric if (isa<UndefValue>(Val))
3565ffd83dbSDimitry Andric return UndefValue::get(ValVTy->getElementType());
3570b57cec5SDimitry Andric
358480093f4SDimitry Andric auto *CIdx = dyn_cast<ConstantInt>(Idx);
359480093f4SDimitry Andric if (!CIdx)
360480093f4SDimitry Andric return nullptr;
361480093f4SDimitry Andric
3625ffd83dbSDimitry Andric if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
363e8d8bef9SDimitry Andric // ee({w,x,y,z}, wrong_value) -> poison
3645ffd83dbSDimitry Andric if (CIdx->uge(ValFVTy->getNumElements()))
365e8d8bef9SDimitry Andric return PoisonValue::get(ValFVTy->getElementType());
3665ffd83dbSDimitry Andric }
367480093f4SDimitry Andric
368480093f4SDimitry Andric // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
369480093f4SDimitry Andric if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
370fe6060f1SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
371480093f4SDimitry Andric SmallVector<Constant *, 8> Ops;
372480093f4SDimitry Andric Ops.reserve(CE->getNumOperands());
373480093f4SDimitry Andric for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
374480093f4SDimitry Andric Constant *Op = CE->getOperand(i);
375480093f4SDimitry Andric if (Op->getType()->isVectorTy()) {
376480093f4SDimitry Andric Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);
377480093f4SDimitry Andric if (!ScalarOp)
3780b57cec5SDimitry Andric return nullptr;
379480093f4SDimitry Andric Ops.push_back(ScalarOp);
380480093f4SDimitry Andric } else
381480093f4SDimitry Andric Ops.push_back(Op);
382480093f4SDimitry Andric }
3835ffd83dbSDimitry Andric return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
384fe6060f1SDimitry Andric GEP->getSourceElementType());
385e8d8bef9SDimitry Andric } else if (CE->getOpcode() == Instruction::InsertElement) {
386e8d8bef9SDimitry Andric if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
387e8d8bef9SDimitry Andric if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
388e8d8bef9SDimitry Andric APSInt(CIdx->getValue()))) {
389e8d8bef9SDimitry Andric return CE->getOperand(1);
390e8d8bef9SDimitry Andric } else {
391e8d8bef9SDimitry Andric return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
392e8d8bef9SDimitry Andric }
393e8d8bef9SDimitry Andric }
394480093f4SDimitry Andric }
395480093f4SDimitry Andric }
396480093f4SDimitry Andric
397349cc55cSDimitry Andric if (Constant *C = Val->getAggregateElement(CIdx))
398349cc55cSDimitry Andric return C;
399349cc55cSDimitry Andric
400fe6060f1SDimitry Andric // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
401fe6060f1SDimitry Andric if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
402fe6060f1SDimitry Andric if (Constant *SplatVal = Val->getSplatValue())
403fe6060f1SDimitry Andric return SplatVal;
4045ffd83dbSDimitry Andric }
4055ffd83dbSDimitry Andric
406349cc55cSDimitry Andric return nullptr;
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric
ConstantFoldInsertElementInstruction(Constant * Val,Constant * Elt,Constant * Idx)4090b57cec5SDimitry Andric Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
4100b57cec5SDimitry Andric Constant *Elt,
4110b57cec5SDimitry Andric Constant *Idx) {
4120b57cec5SDimitry Andric if (isa<UndefValue>(Idx))
413e8d8bef9SDimitry Andric return PoisonValue::get(Val->getType());
4140b57cec5SDimitry Andric
41581ad6265SDimitry Andric // Inserting null into all zeros is still all zeros.
41681ad6265SDimitry Andric // TODO: This is true for undef and poison splats too.
41781ad6265SDimitry Andric if (isa<ConstantAggregateZero>(Val) && Elt->isNullValue())
41881ad6265SDimitry Andric return Val;
41981ad6265SDimitry Andric
4200b57cec5SDimitry Andric ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
4210b57cec5SDimitry Andric if (!CIdx) return nullptr;
4220b57cec5SDimitry Andric
423480093f4SDimitry Andric // Do not iterate on scalable vector. The num of elements is unknown at
424480093f4SDimitry Andric // compile-time.
4255ffd83dbSDimitry Andric if (isa<ScalableVectorType>(Val->getType()))
426480093f4SDimitry Andric return nullptr;
427480093f4SDimitry Andric
4285ffd83dbSDimitry Andric auto *ValTy = cast<FixedVectorType>(Val->getType());
4295ffd83dbSDimitry Andric
4305ffd83dbSDimitry Andric unsigned NumElts = ValTy->getNumElements();
4310b57cec5SDimitry Andric if (CIdx->uge(NumElts))
43228a41182SDimitry Andric return PoisonValue::get(Val->getType());
4330b57cec5SDimitry Andric
4340b57cec5SDimitry Andric SmallVector<Constant*, 16> Result;
4350b57cec5SDimitry Andric Result.reserve(NumElts);
4360b57cec5SDimitry Andric auto *Ty = Type::getInt32Ty(Val->getContext());
4370b57cec5SDimitry Andric uint64_t IdxVal = CIdx->getZExtValue();
4380b57cec5SDimitry Andric for (unsigned i = 0; i != NumElts; ++i) {
4390b57cec5SDimitry Andric if (i == IdxVal) {
4400b57cec5SDimitry Andric Result.push_back(Elt);
4410b57cec5SDimitry Andric continue;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric
4440b57cec5SDimitry Andric Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
4450b57cec5SDimitry Andric Result.push_back(C);
4460b57cec5SDimitry Andric }
4470b57cec5SDimitry Andric
4480b57cec5SDimitry Andric return ConstantVector::get(Result);
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric
ConstantFoldShuffleVectorInstruction(Constant * V1,Constant * V2,ArrayRef<int> Mask)4515ffd83dbSDimitry Andric Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,
4525ffd83dbSDimitry Andric ArrayRef<int> Mask) {
4535ffd83dbSDimitry Andric auto *V1VTy = cast<VectorType>(V1->getType());
4545ffd83dbSDimitry Andric unsigned MaskNumElts = Mask.size();
455e8d8bef9SDimitry Andric auto MaskEltCount =
456e8d8bef9SDimitry Andric ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
4575ffd83dbSDimitry Andric Type *EltTy = V1VTy->getElementType();
4580b57cec5SDimitry Andric
45906c3fb27SDimitry Andric // Poison shuffle mask -> poison value.
46006c3fb27SDimitry Andric if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
46106c3fb27SDimitry Andric return PoisonValue::get(VectorType::get(EltTy, MaskEltCount));
4625ffd83dbSDimitry Andric }
4630b57cec5SDimitry Andric
4645ffd83dbSDimitry Andric // If the mask is all zeros this is a splat, no need to go through all
4655ffd83dbSDimitry Andric // elements.
466349cc55cSDimitry Andric if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
4675ffd83dbSDimitry Andric Type *Ty = IntegerType::get(V1->getContext(), 32);
4685ffd83dbSDimitry Andric Constant *Elt =
4695ffd83dbSDimitry Andric ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));
470349cc55cSDimitry Andric
471349cc55cSDimitry Andric if (Elt->isNullValue()) {
472349cc55cSDimitry Andric auto *VTy = VectorType::get(EltTy, MaskEltCount);
473349cc55cSDimitry Andric return ConstantAggregateZero::get(VTy);
474349cc55cSDimitry Andric } else if (!MaskEltCount.isScalable())
4755ffd83dbSDimitry Andric return ConstantVector::getSplat(MaskEltCount, Elt);
4765ffd83dbSDimitry Andric }
477*0fca6ea1SDimitry Andric
478480093f4SDimitry Andric // Do not iterate on scalable vector. The num of elements is unknown at
479480093f4SDimitry Andric // compile-time.
4805ffd83dbSDimitry Andric if (isa<ScalableVectorType>(V1VTy))
481480093f4SDimitry Andric return nullptr;
482480093f4SDimitry Andric
483e8d8bef9SDimitry Andric unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
4840b57cec5SDimitry Andric
4850b57cec5SDimitry Andric // Loop over the shuffle mask, evaluating each element.
4860b57cec5SDimitry Andric SmallVector<Constant*, 32> Result;
4870b57cec5SDimitry Andric for (unsigned i = 0; i != MaskNumElts; ++i) {
4885ffd83dbSDimitry Andric int Elt = Mask[i];
4890b57cec5SDimitry Andric if (Elt == -1) {
4900b57cec5SDimitry Andric Result.push_back(UndefValue::get(EltTy));
4910b57cec5SDimitry Andric continue;
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric Constant *InElt;
4940b57cec5SDimitry Andric if (unsigned(Elt) >= SrcNumElts*2)
4950b57cec5SDimitry Andric InElt = UndefValue::get(EltTy);
4960b57cec5SDimitry Andric else if (unsigned(Elt) >= SrcNumElts) {
4970b57cec5SDimitry Andric Type *Ty = IntegerType::get(V2->getContext(), 32);
4980b57cec5SDimitry Andric InElt =
4990b57cec5SDimitry Andric ConstantExpr::getExtractElement(V2,
5000b57cec5SDimitry Andric ConstantInt::get(Ty, Elt - SrcNumElts));
5010b57cec5SDimitry Andric } else {
5020b57cec5SDimitry Andric Type *Ty = IntegerType::get(V1->getContext(), 32);
5030b57cec5SDimitry Andric InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric Result.push_back(InElt);
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric
5080b57cec5SDimitry Andric return ConstantVector::get(Result);
5090b57cec5SDimitry Andric }
5100b57cec5SDimitry Andric
ConstantFoldExtractValueInstruction(Constant * Agg,ArrayRef<unsigned> Idxs)5110b57cec5SDimitry Andric Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
5120b57cec5SDimitry Andric ArrayRef<unsigned> Idxs) {
5130b57cec5SDimitry Andric // Base case: no indices, so return the entire value.
5140b57cec5SDimitry Andric if (Idxs.empty())
5150b57cec5SDimitry Andric return Agg;
5160b57cec5SDimitry Andric
5170b57cec5SDimitry Andric if (Constant *C = Agg->getAggregateElement(Idxs[0]))
5180b57cec5SDimitry Andric return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
5190b57cec5SDimitry Andric
5200b57cec5SDimitry Andric return nullptr;
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric
ConstantFoldInsertValueInstruction(Constant * Agg,Constant * Val,ArrayRef<unsigned> Idxs)5230b57cec5SDimitry Andric Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
5240b57cec5SDimitry Andric Constant *Val,
5250b57cec5SDimitry Andric ArrayRef<unsigned> Idxs) {
5260b57cec5SDimitry Andric // Base case: no indices, so replace the entire value.
5270b57cec5SDimitry Andric if (Idxs.empty())
5280b57cec5SDimitry Andric return Val;
5290b57cec5SDimitry Andric
5300b57cec5SDimitry Andric unsigned NumElts;
5310b57cec5SDimitry Andric if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
5320b57cec5SDimitry Andric NumElts = ST->getNumElements();
5330b57cec5SDimitry Andric else
5345ffd83dbSDimitry Andric NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
5350b57cec5SDimitry Andric
5360b57cec5SDimitry Andric SmallVector<Constant*, 32> Result;
5370b57cec5SDimitry Andric for (unsigned i = 0; i != NumElts; ++i) {
5380b57cec5SDimitry Andric Constant *C = Agg->getAggregateElement(i);
5390b57cec5SDimitry Andric if (!C) return nullptr;
5400b57cec5SDimitry Andric
5410b57cec5SDimitry Andric if (Idxs[0] == i)
5420b57cec5SDimitry Andric C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
5430b57cec5SDimitry Andric
5440b57cec5SDimitry Andric Result.push_back(C);
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric
5470b57cec5SDimitry Andric if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
5480b57cec5SDimitry Andric return ConstantStruct::get(ST, Result);
5495ffd83dbSDimitry Andric return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
5500b57cec5SDimitry Andric }
5510b57cec5SDimitry Andric
ConstantFoldUnaryInstruction(unsigned Opcode,Constant * C)5520b57cec5SDimitry Andric Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
5530b57cec5SDimitry Andric assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
5540b57cec5SDimitry Andric
5555ffd83dbSDimitry Andric // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
5565ffd83dbSDimitry Andric // vectors are always evaluated per element.
5575ffd83dbSDimitry Andric bool IsScalableVector = isa<ScalableVectorType>(C->getType());
5585ffd83dbSDimitry Andric bool HasScalarUndefOrScalableVectorUndef =
5595ffd83dbSDimitry Andric (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
5600b57cec5SDimitry Andric
5615ffd83dbSDimitry Andric if (HasScalarUndefOrScalableVectorUndef) {
5620b57cec5SDimitry Andric switch (static_cast<Instruction::UnaryOps>(Opcode)) {
5630b57cec5SDimitry Andric case Instruction::FNeg:
5640b57cec5SDimitry Andric return C; // -undef -> undef
5650b57cec5SDimitry Andric case Instruction::UnaryOpsEnd:
5660b57cec5SDimitry Andric llvm_unreachable("Invalid UnaryOp");
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric }
5690b57cec5SDimitry Andric
5700b57cec5SDimitry Andric // Constant should not be UndefValue, unless these are vector constants.
5715ffd83dbSDimitry Andric assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
5720b57cec5SDimitry Andric // We only have FP UnaryOps right now.
5730b57cec5SDimitry Andric assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
5740b57cec5SDimitry Andric
5750b57cec5SDimitry Andric if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
5760b57cec5SDimitry Andric const APFloat &CV = CFP->getValueAPF();
5770b57cec5SDimitry Andric switch (Opcode) {
5780b57cec5SDimitry Andric default:
5790b57cec5SDimitry Andric break;
5800b57cec5SDimitry Andric case Instruction::FNeg:
5810b57cec5SDimitry Andric return ConstantFP::get(C->getContext(), neg(CV));
5820b57cec5SDimitry Andric }
5835ffd83dbSDimitry Andric } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
5845ffd83dbSDimitry Andric
5855ffd83dbSDimitry Andric Type *Ty = IntegerType::get(VTy->getContext(), 32);
5865ffd83dbSDimitry Andric // Fast path for splatted constants.
587bdd1243dSDimitry Andric if (Constant *Splat = C->getSplatValue())
588bdd1243dSDimitry Andric if (Constant *Elt = ConstantFoldUnaryInstruction(Opcode, Splat))
5895ffd83dbSDimitry Andric return ConstantVector::getSplat(VTy->getElementCount(), Elt);
5905ffd83dbSDimitry Andric
5910b57cec5SDimitry Andric // Fold each element and create a vector constant from those constants.
5920b57cec5SDimitry Andric SmallVector<Constant *, 16> Result;
5930b57cec5SDimitry Andric for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5940b57cec5SDimitry Andric Constant *ExtractIdx = ConstantInt::get(Ty, i);
5950b57cec5SDimitry Andric Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
596bdd1243dSDimitry Andric Constant *Res = ConstantFoldUnaryInstruction(Opcode, Elt);
597bdd1243dSDimitry Andric if (!Res)
598bdd1243dSDimitry Andric return nullptr;
599bdd1243dSDimitry Andric Result.push_back(Res);
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric
6020b57cec5SDimitry Andric return ConstantVector::get(Result);
6030b57cec5SDimitry Andric }
6040b57cec5SDimitry Andric
6050b57cec5SDimitry Andric // We don't know how to fold this.
6060b57cec5SDimitry Andric return nullptr;
6070b57cec5SDimitry Andric }
6080b57cec5SDimitry Andric
ConstantFoldBinaryInstruction(unsigned Opcode,Constant * C1,Constant * C2)6090b57cec5SDimitry Andric Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
6100b57cec5SDimitry Andric Constant *C2) {
6110b57cec5SDimitry Andric assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
6120b57cec5SDimitry Andric
613480093f4SDimitry Andric // Simplify BinOps with their identity values first. They are no-ops and we
614480093f4SDimitry Andric // can always return the other value, including undef or poison values.
6157a6dacacSDimitry Andric if (Constant *Identity = ConstantExpr::getBinOpIdentity(
6167a6dacacSDimitry Andric Opcode, C1->getType(), /*AllowRHSIdentity*/ false)) {
617480093f4SDimitry Andric if (C1 == Identity)
618480093f4SDimitry Andric return C2;
619480093f4SDimitry Andric if (C2 == Identity)
620480093f4SDimitry Andric return C1;
6217a6dacacSDimitry Andric } else if (Constant *Identity = ConstantExpr::getBinOpIdentity(
6227a6dacacSDimitry Andric Opcode, C1->getType(), /*AllowRHSIdentity*/ true)) {
6237a6dacacSDimitry Andric if (C2 == Identity)
6247a6dacacSDimitry Andric return C1;
625480093f4SDimitry Andric }
626480093f4SDimitry Andric
627e8d8bef9SDimitry Andric // Binary operations propagate poison.
628fe6060f1SDimitry Andric if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
629e8d8bef9SDimitry Andric return PoisonValue::get(C1->getType());
630e8d8bef9SDimitry Andric
6315ffd83dbSDimitry Andric // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
6325ffd83dbSDimitry Andric // vectors are always evaluated per element.
6335ffd83dbSDimitry Andric bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
6345ffd83dbSDimitry Andric bool HasScalarUndefOrScalableVectorUndef =
6355ffd83dbSDimitry Andric (!C1->getType()->isVectorTy() || IsScalableVector) &&
6360b57cec5SDimitry Andric (isa<UndefValue>(C1) || isa<UndefValue>(C2));
6375ffd83dbSDimitry Andric if (HasScalarUndefOrScalableVectorUndef) {
6380b57cec5SDimitry Andric switch (static_cast<Instruction::BinaryOps>(Opcode)) {
6390b57cec5SDimitry Andric case Instruction::Xor:
6400b57cec5SDimitry Andric if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
6410b57cec5SDimitry Andric // Handle undef ^ undef -> 0 special case. This is a common
6420b57cec5SDimitry Andric // idiom (misuse).
6430b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
644bdd1243dSDimitry Andric [[fallthrough]];
6450b57cec5SDimitry Andric case Instruction::Add:
6460b57cec5SDimitry Andric case Instruction::Sub:
6470b57cec5SDimitry Andric return UndefValue::get(C1->getType());
6480b57cec5SDimitry Andric case Instruction::And:
6490b57cec5SDimitry Andric if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
6500b57cec5SDimitry Andric return C1;
6510b57cec5SDimitry Andric return Constant::getNullValue(C1->getType()); // undef & X -> 0
6520b57cec5SDimitry Andric case Instruction::Mul: {
6530b57cec5SDimitry Andric // undef * undef -> undef
6540b57cec5SDimitry Andric if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
6550b57cec5SDimitry Andric return C1;
6560b57cec5SDimitry Andric const APInt *CV;
6570b57cec5SDimitry Andric // X * undef -> undef if X is odd
6580b57cec5SDimitry Andric if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
6590b57cec5SDimitry Andric if ((*CV)[0])
6600b57cec5SDimitry Andric return UndefValue::get(C1->getType());
6610b57cec5SDimitry Andric
6620b57cec5SDimitry Andric // X * undef -> 0 otherwise
6630b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric case Instruction::SDiv:
6660b57cec5SDimitry Andric case Instruction::UDiv:
66728a41182SDimitry Andric // X / undef -> poison
66828a41182SDimitry Andric // X / 0 -> poison
66928a41182SDimitry Andric if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
67028a41182SDimitry Andric return PoisonValue::get(C2->getType());
6710b57cec5SDimitry Andric // undef / X -> 0 otherwise
6720b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
6730b57cec5SDimitry Andric case Instruction::URem:
6740b57cec5SDimitry Andric case Instruction::SRem:
67528a41182SDimitry Andric // X % undef -> poison
67628a41182SDimitry Andric // X % 0 -> poison
67728a41182SDimitry Andric if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
67828a41182SDimitry Andric return PoisonValue::get(C2->getType());
6790b57cec5SDimitry Andric // undef % X -> 0 otherwise
6800b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
6810b57cec5SDimitry Andric case Instruction::Or: // X | undef -> -1
6820b57cec5SDimitry Andric if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
6830b57cec5SDimitry Andric return C1;
6840b57cec5SDimitry Andric return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
6850b57cec5SDimitry Andric case Instruction::LShr:
68628a41182SDimitry Andric // X >>l undef -> poison
6870b57cec5SDimitry Andric if (isa<UndefValue>(C2))
68828a41182SDimitry Andric return PoisonValue::get(C2->getType());
6890b57cec5SDimitry Andric // undef >>l X -> 0
6900b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
6910b57cec5SDimitry Andric case Instruction::AShr:
69228a41182SDimitry Andric // X >>a undef -> poison
6930b57cec5SDimitry Andric if (isa<UndefValue>(C2))
69428a41182SDimitry Andric return PoisonValue::get(C2->getType());
69528a41182SDimitry Andric // TODO: undef >>a X -> poison if the shift is exact
6960b57cec5SDimitry Andric // undef >>a X -> 0
6970b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
6980b57cec5SDimitry Andric case Instruction::Shl:
6990b57cec5SDimitry Andric // X << undef -> undef
7000b57cec5SDimitry Andric if (isa<UndefValue>(C2))
70128a41182SDimitry Andric return PoisonValue::get(C2->getType());
7020b57cec5SDimitry Andric // undef << X -> 0
7030b57cec5SDimitry Andric return Constant::getNullValue(C1->getType());
7040b57cec5SDimitry Andric case Instruction::FSub:
7055ffd83dbSDimitry Andric // -0.0 - undef --> undef (consistent with "fneg undef")
7065ffd83dbSDimitry Andric if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
7075ffd83dbSDimitry Andric return C2;
708bdd1243dSDimitry Andric [[fallthrough]];
7095ffd83dbSDimitry Andric case Instruction::FAdd:
7100b57cec5SDimitry Andric case Instruction::FMul:
7110b57cec5SDimitry Andric case Instruction::FDiv:
7120b57cec5SDimitry Andric case Instruction::FRem:
7130b57cec5SDimitry Andric // [any flop] undef, undef -> undef
7140b57cec5SDimitry Andric if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
7150b57cec5SDimitry Andric return C1;
7160b57cec5SDimitry Andric // [any flop] C, undef -> NaN
7170b57cec5SDimitry Andric // [any flop] undef, C -> NaN
7180b57cec5SDimitry Andric // We could potentially specialize NaN/Inf constants vs. 'normal'
7190b57cec5SDimitry Andric // constants (possibly differently depending on opcode and operand). This
7200b57cec5SDimitry Andric // would allow returning undef sometimes. But it is always safe to fold to
7210b57cec5SDimitry Andric // NaN because we can choose the undef operand as NaN, and any FP opcode
7220b57cec5SDimitry Andric // with a NaN operand will propagate NaN.
7230b57cec5SDimitry Andric return ConstantFP::getNaN(C1->getType());
7240b57cec5SDimitry Andric case Instruction::BinaryOpsEnd:
7250b57cec5SDimitry Andric llvm_unreachable("Invalid BinaryOp");
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric
7290b57cec5SDimitry Andric // Neither constant should be UndefValue, unless these are vector constants.
7305ffd83dbSDimitry Andric assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
7310b57cec5SDimitry Andric
7320b57cec5SDimitry Andric // Handle simplifications when the RHS is a constant int.
7330b57cec5SDimitry Andric if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
7340b57cec5SDimitry Andric switch (Opcode) {
7350b57cec5SDimitry Andric case Instruction::Mul:
7367a6dacacSDimitry Andric if (CI2->isZero())
7377a6dacacSDimitry Andric return C2; // X * 0 == 0
7380b57cec5SDimitry Andric break;
7390b57cec5SDimitry Andric case Instruction::UDiv:
7400b57cec5SDimitry Andric case Instruction::SDiv:
7410b57cec5SDimitry Andric if (CI2->isZero())
74228a41182SDimitry Andric return PoisonValue::get(CI2->getType()); // X / 0 == poison
7430b57cec5SDimitry Andric break;
7440b57cec5SDimitry Andric case Instruction::URem:
7450b57cec5SDimitry Andric case Instruction::SRem:
7460b57cec5SDimitry Andric if (CI2->isOne())
7470b57cec5SDimitry Andric return Constant::getNullValue(CI2->getType()); // X % 1 == 0
7480b57cec5SDimitry Andric if (CI2->isZero())
74928a41182SDimitry Andric return PoisonValue::get(CI2->getType()); // X % 0 == poison
7500b57cec5SDimitry Andric break;
7510b57cec5SDimitry Andric case Instruction::And:
7527a6dacacSDimitry Andric if (CI2->isZero())
7537a6dacacSDimitry Andric return C2; // X & 0 == 0
7540b57cec5SDimitry Andric
7550b57cec5SDimitry Andric if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
7560b57cec5SDimitry Andric // If and'ing the address of a global with a constant, fold it.
7570b57cec5SDimitry Andric if (CE1->getOpcode() == Instruction::PtrToInt &&
7580b57cec5SDimitry Andric isa<GlobalValue>(CE1->getOperand(0))) {
7590b57cec5SDimitry Andric GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
7600b57cec5SDimitry Andric
76106c3fb27SDimitry Andric Align GVAlign; // defaults to 1
7620b57cec5SDimitry Andric
7630b57cec5SDimitry Andric if (Module *TheModule = GV->getParent()) {
7645ffd83dbSDimitry Andric const DataLayout &DL = TheModule->getDataLayout();
7655ffd83dbSDimitry Andric GVAlign = GV->getPointerAlignment(DL);
7660b57cec5SDimitry Andric
7670b57cec5SDimitry Andric // If the function alignment is not specified then assume that it
7680b57cec5SDimitry Andric // is 4.
7690b57cec5SDimitry Andric // This is dangerous; on x86, the alignment of the pointer
7700b57cec5SDimitry Andric // corresponds to the alignment of the function, but might be less
7710b57cec5SDimitry Andric // than 4 if it isn't explicitly specified.
7720b57cec5SDimitry Andric // However, a fix for this behaviour was reverted because it
7730b57cec5SDimitry Andric // increased code size (see https://reviews.llvm.org/D55115)
7740b57cec5SDimitry Andric // FIXME: This code should be deleted once existing targets have
7750b57cec5SDimitry Andric // appropriate defaults
7765ffd83dbSDimitry Andric if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
7778bcb0991SDimitry Andric GVAlign = Align(4);
7785ffd83dbSDimitry Andric } else if (isa<GlobalVariable>(GV)) {
77906c3fb27SDimitry Andric GVAlign = cast<GlobalVariable>(GV)->getAlign().valueOrOne();
7800b57cec5SDimitry Andric }
7810b57cec5SDimitry Andric
78206c3fb27SDimitry Andric if (GVAlign > 1) {
783cb14a3feSDimitry Andric unsigned DstWidth = CI2->getBitWidth();
78406c3fb27SDimitry Andric unsigned SrcWidth = std::min(DstWidth, Log2(GVAlign));
7850b57cec5SDimitry Andric APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
7860b57cec5SDimitry Andric
7870b57cec5SDimitry Andric // If checking bits we know are clear, return zero.
7880b57cec5SDimitry Andric if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
7890b57cec5SDimitry Andric return Constant::getNullValue(CI2->getType());
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric }
7930b57cec5SDimitry Andric break;
7940b57cec5SDimitry Andric case Instruction::Or:
7950b57cec5SDimitry Andric if (CI2->isMinusOne())
7960b57cec5SDimitry Andric return C2; // X | -1 == -1
7970b57cec5SDimitry Andric break;
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric } else if (isa<ConstantInt>(C1)) {
8000b57cec5SDimitry Andric // If C1 is a ConstantInt and C2 is not, swap the operands.
8010b57cec5SDimitry Andric if (Instruction::isCommutative(Opcode))
8025f757f3fSDimitry Andric return ConstantExpr::isDesirableBinOp(Opcode)
8035f757f3fSDimitry Andric ? ConstantExpr::get(Opcode, C2, C1)
8045f757f3fSDimitry Andric : ConstantFoldBinaryInstruction(Opcode, C2, C1);
8050b57cec5SDimitry Andric }
8060b57cec5SDimitry Andric
8070b57cec5SDimitry Andric if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
8080b57cec5SDimitry Andric if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
8090b57cec5SDimitry Andric const APInt &C1V = CI1->getValue();
8100b57cec5SDimitry Andric const APInt &C2V = CI2->getValue();
8110b57cec5SDimitry Andric switch (Opcode) {
8120b57cec5SDimitry Andric default:
8130b57cec5SDimitry Andric break;
8140b57cec5SDimitry Andric case Instruction::Add:
8150b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V + C2V);
8160b57cec5SDimitry Andric case Instruction::Sub:
8170b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V - C2V);
8180b57cec5SDimitry Andric case Instruction::Mul:
8190b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V * C2V);
8200b57cec5SDimitry Andric case Instruction::UDiv:
8210b57cec5SDimitry Andric assert(!CI2->isZero() && "Div by zero handled above");
8220b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
8230b57cec5SDimitry Andric case Instruction::SDiv:
8240b57cec5SDimitry Andric assert(!CI2->isZero() && "Div by zero handled above");
825349cc55cSDimitry Andric if (C2V.isAllOnes() && C1V.isMinSignedValue())
82628a41182SDimitry Andric return PoisonValue::get(CI1->getType()); // MIN_INT / -1 -> poison
8270b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
8280b57cec5SDimitry Andric case Instruction::URem:
8290b57cec5SDimitry Andric assert(!CI2->isZero() && "Div by zero handled above");
8300b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
8310b57cec5SDimitry Andric case Instruction::SRem:
8320b57cec5SDimitry Andric assert(!CI2->isZero() && "Div by zero handled above");
833349cc55cSDimitry Andric if (C2V.isAllOnes() && C1V.isMinSignedValue())
83428a41182SDimitry Andric return PoisonValue::get(CI1->getType()); // MIN_INT % -1 -> poison
8350b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
8360b57cec5SDimitry Andric case Instruction::And:
8370b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V & C2V);
8380b57cec5SDimitry Andric case Instruction::Or:
8390b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V | C2V);
8400b57cec5SDimitry Andric case Instruction::Xor:
8410b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
8420b57cec5SDimitry Andric case Instruction::Shl:
8430b57cec5SDimitry Andric if (C2V.ult(C1V.getBitWidth()))
8440b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
84528a41182SDimitry Andric return PoisonValue::get(C1->getType()); // too big shift is poison
8460b57cec5SDimitry Andric case Instruction::LShr:
8470b57cec5SDimitry Andric if (C2V.ult(C1V.getBitWidth()))
8480b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
84928a41182SDimitry Andric return PoisonValue::get(C1->getType()); // too big shift is poison
8500b57cec5SDimitry Andric case Instruction::AShr:
8510b57cec5SDimitry Andric if (C2V.ult(C1V.getBitWidth()))
8520b57cec5SDimitry Andric return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
85328a41182SDimitry Andric return PoisonValue::get(C1->getType()); // too big shift is poison
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric }
8560b57cec5SDimitry Andric
8570b57cec5SDimitry Andric switch (Opcode) {
8580b57cec5SDimitry Andric case Instruction::SDiv:
8590b57cec5SDimitry Andric case Instruction::UDiv:
8600b57cec5SDimitry Andric case Instruction::URem:
8610b57cec5SDimitry Andric case Instruction::SRem:
8620b57cec5SDimitry Andric case Instruction::LShr:
8630b57cec5SDimitry Andric case Instruction::AShr:
8640b57cec5SDimitry Andric case Instruction::Shl:
8650b57cec5SDimitry Andric if (CI1->isZero()) return C1;
8660b57cec5SDimitry Andric break;
8670b57cec5SDimitry Andric default:
8680b57cec5SDimitry Andric break;
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
8710b57cec5SDimitry Andric if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
8720b57cec5SDimitry Andric const APFloat &C1V = CFP1->getValueAPF();
8730b57cec5SDimitry Andric const APFloat &C2V = CFP2->getValueAPF();
8740b57cec5SDimitry Andric APFloat C3V = C1V; // copy for modification
8750b57cec5SDimitry Andric switch (Opcode) {
8760b57cec5SDimitry Andric default:
8770b57cec5SDimitry Andric break;
8780b57cec5SDimitry Andric case Instruction::FAdd:
8790b57cec5SDimitry Andric (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
8800b57cec5SDimitry Andric return ConstantFP::get(C1->getContext(), C3V);
8810b57cec5SDimitry Andric case Instruction::FSub:
8820b57cec5SDimitry Andric (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
8830b57cec5SDimitry Andric return ConstantFP::get(C1->getContext(), C3V);
8840b57cec5SDimitry Andric case Instruction::FMul:
8850b57cec5SDimitry Andric (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
8860b57cec5SDimitry Andric return ConstantFP::get(C1->getContext(), C3V);
8870b57cec5SDimitry Andric case Instruction::FDiv:
8880b57cec5SDimitry Andric (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
8890b57cec5SDimitry Andric return ConstantFP::get(C1->getContext(), C3V);
8900b57cec5SDimitry Andric case Instruction::FRem:
8910b57cec5SDimitry Andric (void)C3V.mod(C2V);
8920b57cec5SDimitry Andric return ConstantFP::get(C1->getContext(), C3V);
8930b57cec5SDimitry Andric }
8940b57cec5SDimitry Andric }
895e8d8bef9SDimitry Andric } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
8965ffd83dbSDimitry Andric // Fast path for splatted constants.
8975ffd83dbSDimitry Andric if (Constant *C2Splat = C2->getSplatValue()) {
8985ffd83dbSDimitry Andric if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
89928a41182SDimitry Andric return PoisonValue::get(VTy);
9005ffd83dbSDimitry Andric if (Constant *C1Splat = C1->getSplatValue()) {
901753f127fSDimitry Andric Constant *Res =
902753f127fSDimitry Andric ConstantExpr::isDesirableBinOp(Opcode)
903753f127fSDimitry Andric ? ConstantExpr::get(Opcode, C1Splat, C2Splat)
904753f127fSDimitry Andric : ConstantFoldBinaryInstruction(Opcode, C1Splat, C2Splat);
905753f127fSDimitry Andric if (!Res)
906753f127fSDimitry Andric return nullptr;
907753f127fSDimitry Andric return ConstantVector::getSplat(VTy->getElementCount(), Res);
9085ffd83dbSDimitry Andric }
9095ffd83dbSDimitry Andric }
9105ffd83dbSDimitry Andric
911e8d8bef9SDimitry Andric if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
9120b57cec5SDimitry Andric // Fold each element and create a vector constant from those constants.
9130b57cec5SDimitry Andric SmallVector<Constant*, 16> Result;
914e8d8bef9SDimitry Andric Type *Ty = IntegerType::get(FVTy->getContext(), 32);
915e8d8bef9SDimitry Andric for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
9160b57cec5SDimitry Andric Constant *ExtractIdx = ConstantInt::get(Ty, i);
9170b57cec5SDimitry Andric Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
9180b57cec5SDimitry Andric Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
9190b57cec5SDimitry Andric
92028a41182SDimitry Andric // If any element of a divisor vector is zero, the whole op is poison.
9210b57cec5SDimitry Andric if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
92228a41182SDimitry Andric return PoisonValue::get(VTy);
9230b57cec5SDimitry Andric
924753f127fSDimitry Andric Constant *Res = ConstantExpr::isDesirableBinOp(Opcode)
925753f127fSDimitry Andric ? ConstantExpr::get(Opcode, LHS, RHS)
926753f127fSDimitry Andric : ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
927753f127fSDimitry Andric if (!Res)
928753f127fSDimitry Andric return nullptr;
929753f127fSDimitry Andric Result.push_back(Res);
9300b57cec5SDimitry Andric }
9310b57cec5SDimitry Andric
9320b57cec5SDimitry Andric return ConstantVector::get(Result);
9330b57cec5SDimitry Andric }
934e8d8bef9SDimitry Andric }
9350b57cec5SDimitry Andric
9360b57cec5SDimitry Andric if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
9370b57cec5SDimitry Andric // There are many possible foldings we could do here. We should probably
9380b57cec5SDimitry Andric // at least fold add of a pointer with an integer into the appropriate
9390b57cec5SDimitry Andric // getelementptr. This will improve alias analysis a bit.
9400b57cec5SDimitry Andric
9410b57cec5SDimitry Andric // Given ((a + b) + c), if (b + c) folds to something interesting, return
9420b57cec5SDimitry Andric // (a + (b + c)).
9430b57cec5SDimitry Andric if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
9440b57cec5SDimitry Andric Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
9450b57cec5SDimitry Andric if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
9460b57cec5SDimitry Andric return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric } else if (isa<ConstantExpr>(C2)) {
9490b57cec5SDimitry Andric // If C2 is a constant expr and C1 isn't, flop them around and fold the
9500b57cec5SDimitry Andric // other way if possible.
9510b57cec5SDimitry Andric if (Instruction::isCommutative(Opcode))
9520b57cec5SDimitry Andric return ConstantFoldBinaryInstruction(Opcode, C2, C1);
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric
9550b57cec5SDimitry Andric // i1 can be simplified in many cases.
9560b57cec5SDimitry Andric if (C1->getType()->isIntegerTy(1)) {
9570b57cec5SDimitry Andric switch (Opcode) {
9580b57cec5SDimitry Andric case Instruction::Add:
9590b57cec5SDimitry Andric case Instruction::Sub:
9600b57cec5SDimitry Andric return ConstantExpr::getXor(C1, C2);
9610b57cec5SDimitry Andric case Instruction::Shl:
9620b57cec5SDimitry Andric case Instruction::LShr:
9630b57cec5SDimitry Andric case Instruction::AShr:
9640b57cec5SDimitry Andric // We can assume that C2 == 0. If it were one the result would be
9650b57cec5SDimitry Andric // undefined because the shift value is as large as the bitwidth.
9660b57cec5SDimitry Andric return C1;
9670b57cec5SDimitry Andric case Instruction::SDiv:
9680b57cec5SDimitry Andric case Instruction::UDiv:
9690b57cec5SDimitry Andric // We can assume that C2 == 1. If it were zero the result would be
9700b57cec5SDimitry Andric // undefined through division by zero.
9710b57cec5SDimitry Andric return C1;
9720b57cec5SDimitry Andric case Instruction::URem:
9730b57cec5SDimitry Andric case Instruction::SRem:
9740b57cec5SDimitry Andric // We can assume that C2 == 1. If it were zero the result would be
9750b57cec5SDimitry Andric // undefined through division by zero.
9760b57cec5SDimitry Andric return ConstantInt::getFalse(C1->getContext());
9770b57cec5SDimitry Andric default:
9780b57cec5SDimitry Andric break;
9790b57cec5SDimitry Andric }
9800b57cec5SDimitry Andric }
9810b57cec5SDimitry Andric
9820b57cec5SDimitry Andric // We don't know how to fold this.
9830b57cec5SDimitry Andric return nullptr;
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric
areGlobalsPotentiallyEqual(const GlobalValue * GV1,const GlobalValue * GV2)9860b57cec5SDimitry Andric static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
9870b57cec5SDimitry Andric const GlobalValue *GV2) {
9880b57cec5SDimitry Andric auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
989eaeb601bSDimitry Andric if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
9900b57cec5SDimitry Andric return true;
9910b57cec5SDimitry Andric if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
9920b57cec5SDimitry Andric Type *Ty = GVar->getValueType();
9930b57cec5SDimitry Andric // A global with opaque type might end up being zero sized.
9940b57cec5SDimitry Andric if (!Ty->isSized())
9950b57cec5SDimitry Andric return true;
9960b57cec5SDimitry Andric // A global with an empty type might lie at the address of any other
9970b57cec5SDimitry Andric // global.
9980b57cec5SDimitry Andric if (Ty->isEmptyTy())
9990b57cec5SDimitry Andric return true;
10000b57cec5SDimitry Andric }
10010b57cec5SDimitry Andric return false;
10020b57cec5SDimitry Andric };
10030b57cec5SDimitry Andric // Don't try to decide equality of aliases.
10040b57cec5SDimitry Andric if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
10050b57cec5SDimitry Andric if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
10060b57cec5SDimitry Andric return ICmpInst::ICMP_NE;
10070b57cec5SDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
10080b57cec5SDimitry Andric }
10090b57cec5SDimitry Andric
10100b57cec5SDimitry Andric /// This function determines if there is anything we can decide about the two
10110b57cec5SDimitry Andric /// constants provided. This doesn't need to handle simple things like integer
10120b57cec5SDimitry Andric /// comparisons, but should instead handle ConstantExprs and GlobalValues.
10130b57cec5SDimitry Andric /// If we can determine that the two constants have a particular relation to
10140b57cec5SDimitry Andric /// each other, we should return the corresponding ICmp predicate, otherwise
10150b57cec5SDimitry Andric /// return ICmpInst::BAD_ICMP_PREDICATE.
evaluateICmpRelation(Constant * V1,Constant * V2)10165f757f3fSDimitry Andric static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2) {
10170b57cec5SDimitry Andric assert(V1->getType() == V2->getType() &&
10180b57cec5SDimitry Andric "Cannot compare different types of values!");
10190b57cec5SDimitry Andric if (V1 == V2) return ICmpInst::ICMP_EQ;
10200b57cec5SDimitry Andric
10215f757f3fSDimitry Andric // The following folds only apply to pointers.
10225f757f3fSDimitry Andric if (!V1->getType()->isPointerTy())
10235f757f3fSDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
10240b57cec5SDimitry Andric
10255f757f3fSDimitry Andric // To simplify this code we canonicalize the relation so that the first
10265f757f3fSDimitry Andric // operand is always the most "complex" of the two. We consider simple
10275f757f3fSDimitry Andric // constants (like ConstantPointerNull) to be the simplest, followed by
10285f757f3fSDimitry Andric // BlockAddress, GlobalValues, and ConstantExpr's (the most complex).
10295f757f3fSDimitry Andric auto GetComplexity = [](Constant *V) {
10305f757f3fSDimitry Andric if (isa<ConstantExpr>(V))
10315f757f3fSDimitry Andric return 3;
10325f757f3fSDimitry Andric if (isa<GlobalValue>(V))
10335f757f3fSDimitry Andric return 2;
10345f757f3fSDimitry Andric if (isa<BlockAddress>(V))
10355f757f3fSDimitry Andric return 1;
10365f757f3fSDimitry Andric return 0;
10375f757f3fSDimitry Andric };
10385f757f3fSDimitry Andric if (GetComplexity(V1) < GetComplexity(V2)) {
10395f757f3fSDimitry Andric ICmpInst::Predicate SwappedRelation = evaluateICmpRelation(V2, V1);
10405f757f3fSDimitry Andric if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
10415f757f3fSDimitry Andric return ICmpInst::getSwappedPredicate(SwappedRelation);
10420b57cec5SDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric
10455f757f3fSDimitry Andric if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
10465f757f3fSDimitry Andric // Now we know that the RHS is a BlockAddress or simple constant.
10475f757f3fSDimitry Andric if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
10485f757f3fSDimitry Andric // Block address in another function can't equal this one, but block
10495f757f3fSDimitry Andric // addresses in the current function might be the same if blocks are
10505f757f3fSDimitry Andric // empty.
10515f757f3fSDimitry Andric if (BA2->getFunction() != BA->getFunction())
10525f757f3fSDimitry Andric return ICmpInst::ICMP_NE;
10535f757f3fSDimitry Andric } else if (isa<ConstantPointerNull>(V2)) {
10545f757f3fSDimitry Andric return ICmpInst::ICMP_NE;
10555f757f3fSDimitry Andric }
10560b57cec5SDimitry Andric } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
10570b57cec5SDimitry Andric // Now we know that the RHS is a GlobalValue, BlockAddress or simple
10585f757f3fSDimitry Andric // constant.
10590b57cec5SDimitry Andric if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
10600b57cec5SDimitry Andric return areGlobalsPotentiallyEqual(GV, GV2);
10610b57cec5SDimitry Andric } else if (isa<BlockAddress>(V2)) {
10620b57cec5SDimitry Andric return ICmpInst::ICMP_NE; // Globals never equal labels.
10635f757f3fSDimitry Andric } else if (isa<ConstantPointerNull>(V2)) {
10640b57cec5SDimitry Andric // GlobalVals can never be null unless they have external weak linkage.
10650b57cec5SDimitry Andric // We don't try to evaluate aliases here.
10660b57cec5SDimitry Andric // NOTE: We should not be doing this constant folding if null pointer
10670b57cec5SDimitry Andric // is considered valid for the function. But currently there is no way to
10680b57cec5SDimitry Andric // query it from the Constant type.
10690b57cec5SDimitry Andric if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
10700b57cec5SDimitry Andric !NullPointerIsDefined(nullptr /* F */,
10710b57cec5SDimitry Andric GV->getType()->getAddressSpace()))
1072fe6060f1SDimitry Andric return ICmpInst::ICMP_UGT;
10730b57cec5SDimitry Andric }
1074*0fca6ea1SDimitry Andric } else if (auto *CE1 = dyn_cast<ConstantExpr>(V1)) {
10750b57cec5SDimitry Andric // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
10760b57cec5SDimitry Andric // constantexpr, a global, block address, or a simple constant.
10770b57cec5SDimitry Andric Constant *CE1Op0 = CE1->getOperand(0);
10780b57cec5SDimitry Andric
10790b57cec5SDimitry Andric switch (CE1->getOpcode()) {
10800b57cec5SDimitry Andric case Instruction::GetElementPtr: {
10810b57cec5SDimitry Andric GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
10820b57cec5SDimitry Andric // Ok, since this is a getelementptr, we know that the constant has a
10830b57cec5SDimitry Andric // pointer type. Check the various cases.
10840b57cec5SDimitry Andric if (isa<ConstantPointerNull>(V2)) {
10850b57cec5SDimitry Andric // If we are comparing a GEP to a null pointer, check to see if the base
10860b57cec5SDimitry Andric // of the GEP equals the null pointer.
10870b57cec5SDimitry Andric if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
10880b57cec5SDimitry Andric // If its not weak linkage, the GVal must have a non-zero address
10890b57cec5SDimitry Andric // so the result is greater-than
109004eeddc0SDimitry Andric if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())
1091fe6060f1SDimitry Andric return ICmpInst::ICMP_UGT;
10920b57cec5SDimitry Andric }
10930b57cec5SDimitry Andric } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
109404eeddc0SDimitry Andric if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
109504eeddc0SDimitry Andric if (GV != GV2) {
10960b57cec5SDimitry Andric if (CE1GEP->hasAllZeroIndices())
10970b57cec5SDimitry Andric return areGlobalsPotentiallyEqual(GV, GV2);
10980b57cec5SDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric }
110104eeddc0SDimitry Andric } else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {
11020b57cec5SDimitry Andric // By far the most common case to handle is when the base pointers are
11030b57cec5SDimitry Andric // obviously to the same global.
110404eeddc0SDimitry Andric const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());
11050b57cec5SDimitry Andric if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
11060b57cec5SDimitry Andric // Don't know relative ordering, but check for inequality.
11070b57cec5SDimitry Andric if (CE1Op0 != CE2Op0) {
11080b57cec5SDimitry Andric if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
11090b57cec5SDimitry Andric return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
11100b57cec5SDimitry Andric cast<GlobalValue>(CE2Op0));
11110b57cec5SDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
11120b57cec5SDimitry Andric }
11130b57cec5SDimitry Andric }
11140b57cec5SDimitry Andric }
11150b57cec5SDimitry Andric break;
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric default:
11180b57cec5SDimitry Andric break;
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric
11220b57cec5SDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
11230b57cec5SDimitry Andric }
11240b57cec5SDimitry Andric
ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,Constant * C1,Constant * C2)112504eeddc0SDimitry Andric Constant *llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,
11260b57cec5SDimitry Andric Constant *C1, Constant *C2) {
11270b57cec5SDimitry Andric Type *ResultTy;
11280b57cec5SDimitry Andric if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
11290b57cec5SDimitry Andric ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
11305ffd83dbSDimitry Andric VT->getElementCount());
11310b57cec5SDimitry Andric else
11320b57cec5SDimitry Andric ResultTy = Type::getInt1Ty(C1->getContext());
11330b57cec5SDimitry Andric
11340b57cec5SDimitry Andric // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
113504eeddc0SDimitry Andric if (Predicate == FCmpInst::FCMP_FALSE)
11360b57cec5SDimitry Andric return Constant::getNullValue(ResultTy);
11370b57cec5SDimitry Andric
113804eeddc0SDimitry Andric if (Predicate == FCmpInst::FCMP_TRUE)
11390b57cec5SDimitry Andric return Constant::getAllOnesValue(ResultTy);
11400b57cec5SDimitry Andric
11410b57cec5SDimitry Andric // Handle some degenerate cases first
1142e8d8bef9SDimitry Andric if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
1143e8d8bef9SDimitry Andric return PoisonValue::get(ResultTy);
1144e8d8bef9SDimitry Andric
11450b57cec5SDimitry Andric if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
11460b57cec5SDimitry Andric bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
11470b57cec5SDimitry Andric // For EQ and NE, we can always pick a value for the undef to make the
11480b57cec5SDimitry Andric // predicate pass or fail, so we can return undef.
11490b57cec5SDimitry Andric // Also, if both operands are undef, we can return undef for int comparison.
11500b57cec5SDimitry Andric if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
11510b57cec5SDimitry Andric return UndefValue::get(ResultTy);
11520b57cec5SDimitry Andric
11530b57cec5SDimitry Andric // Otherwise, for integer compare, pick the same value as the non-undef
11540b57cec5SDimitry Andric // operand, and fold it to true or false.
11550b57cec5SDimitry Andric if (isIntegerPredicate)
11560b57cec5SDimitry Andric return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
11570b57cec5SDimitry Andric
11580b57cec5SDimitry Andric // Choosing NaN for the undef will always make unordered comparison succeed
11590b57cec5SDimitry Andric // and ordered comparison fails.
11600b57cec5SDimitry Andric return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric
1163bdd1243dSDimitry Andric if (C2->isNullValue()) {
1164fe6060f1SDimitry Andric // The caller is expected to commute the operands if the constant expression
1165fe6060f1SDimitry Andric // is C2.
1166fe6060f1SDimitry Andric // C1 >= 0 --> true
116704eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_UGE)
1168fe6060f1SDimitry Andric return Constant::getAllOnesValue(ResultTy);
1169fe6060f1SDimitry Andric // C1 < 0 --> false
117004eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_ULT)
1171fe6060f1SDimitry Andric return Constant::getNullValue(ResultTy);
1172fe6060f1SDimitry Andric }
1173fe6060f1SDimitry Andric
11740b57cec5SDimitry Andric // If the comparison is a comparison between two i1's, simplify it.
11750b57cec5SDimitry Andric if (C1->getType()->isIntegerTy(1)) {
117604eeddc0SDimitry Andric switch (Predicate) {
11770b57cec5SDimitry Andric case ICmpInst::ICMP_EQ:
11780b57cec5SDimitry Andric if (isa<ConstantInt>(C2))
11790b57cec5SDimitry Andric return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
11800b57cec5SDimitry Andric return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
11810b57cec5SDimitry Andric case ICmpInst::ICMP_NE:
11820b57cec5SDimitry Andric return ConstantExpr::getXor(C1, C2);
11830b57cec5SDimitry Andric default:
11840b57cec5SDimitry Andric break;
11850b57cec5SDimitry Andric }
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric
11880b57cec5SDimitry Andric if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
11890b57cec5SDimitry Andric const APInt &V1 = cast<ConstantInt>(C1)->getValue();
11900b57cec5SDimitry Andric const APInt &V2 = cast<ConstantInt>(C2)->getValue();
119104eeddc0SDimitry Andric return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));
11920b57cec5SDimitry Andric } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
11930b57cec5SDimitry Andric const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
11940b57cec5SDimitry Andric const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
11950eae32dcSDimitry Andric return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));
11965ffd83dbSDimitry Andric } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
11975ffd83dbSDimitry Andric
11985ffd83dbSDimitry Andric // Fast path for splatted constants.
11995ffd83dbSDimitry Andric if (Constant *C1Splat = C1->getSplatValue())
12005ffd83dbSDimitry Andric if (Constant *C2Splat = C2->getSplatValue())
1201*0fca6ea1SDimitry Andric if (Constant *Elt =
1202*0fca6ea1SDimitry Andric ConstantFoldCompareInstruction(Predicate, C1Splat, C2Splat))
1203*0fca6ea1SDimitry Andric return ConstantVector::getSplat(C1VTy->getElementCount(), Elt);
12045ffd83dbSDimitry Andric
1205e8d8bef9SDimitry Andric // Do not iterate on scalable vector. The number of elements is unknown at
1206e8d8bef9SDimitry Andric // compile-time.
1207e8d8bef9SDimitry Andric if (isa<ScalableVectorType>(C1VTy))
1208e8d8bef9SDimitry Andric return nullptr;
1209e8d8bef9SDimitry Andric
12100b57cec5SDimitry Andric // If we can constant fold the comparison of each element, constant fold
12110b57cec5SDimitry Andric // the whole vector comparison.
12120b57cec5SDimitry Andric SmallVector<Constant*, 4> ResElts;
12130b57cec5SDimitry Andric Type *Ty = IntegerType::get(C1->getContext(), 32);
12140b57cec5SDimitry Andric // Compare the elements, producing an i1 result or constant expr.
1215e8d8bef9SDimitry Andric for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
1216e8d8bef9SDimitry Andric I != E; ++I) {
12170b57cec5SDimitry Andric Constant *C1E =
1218e8d8bef9SDimitry Andric ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));
12190b57cec5SDimitry Andric Constant *C2E =
1220e8d8bef9SDimitry Andric ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));
1221*0fca6ea1SDimitry Andric Constant *Elt = ConstantFoldCompareInstruction(Predicate, C1E, C2E);
1222*0fca6ea1SDimitry Andric if (!Elt)
1223*0fca6ea1SDimitry Andric return nullptr;
12240b57cec5SDimitry Andric
1225*0fca6ea1SDimitry Andric ResElts.push_back(Elt);
12260b57cec5SDimitry Andric }
12270b57cec5SDimitry Andric
12280b57cec5SDimitry Andric return ConstantVector::get(ResElts);
12290b57cec5SDimitry Andric }
12300b57cec5SDimitry Andric
12315f757f3fSDimitry Andric if (C1->getType()->isFPOrFPVectorTy()) {
12325f757f3fSDimitry Andric if (C1 == C2) {
12335f757f3fSDimitry Andric // We know that C1 == C2 || isUnordered(C1, C2).
123404eeddc0SDimitry Andric if (Predicate == FCmpInst::FCMP_ONE)
12355f757f3fSDimitry Andric return ConstantInt::getFalse(ResultTy);
123604eeddc0SDimitry Andric else if (Predicate == FCmpInst::FCMP_UEQ)
12375f757f3fSDimitry Andric return ConstantInt::getTrue(ResultTy);
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric } else {
12400b57cec5SDimitry Andric // Evaluate the relation between the two constants, per the predicate.
12410b57cec5SDimitry Andric int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
12425f757f3fSDimitry Andric switch (evaluateICmpRelation(C1, C2)) {
12430b57cec5SDimitry Andric default: llvm_unreachable("Unknown relational!");
12440b57cec5SDimitry Andric case ICmpInst::BAD_ICMP_PREDICATE:
12450b57cec5SDimitry Andric break; // Couldn't determine anything about these constants.
12460b57cec5SDimitry Andric case ICmpInst::ICMP_EQ: // We know the constants are equal!
12470b57cec5SDimitry Andric // If we know the constants are equal, we can decide the result of this
12480b57cec5SDimitry Andric // computation precisely.
124904eeddc0SDimitry Andric Result = ICmpInst::isTrueWhenEqual(Predicate);
12500b57cec5SDimitry Andric break;
12510b57cec5SDimitry Andric case ICmpInst::ICMP_ULT:
125204eeddc0SDimitry Andric switch (Predicate) {
12530b57cec5SDimitry Andric case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
12540b57cec5SDimitry Andric Result = 1; break;
12550b57cec5SDimitry Andric case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
12560b57cec5SDimitry Andric Result = 0; break;
125704eeddc0SDimitry Andric default:
125804eeddc0SDimitry Andric break;
12590b57cec5SDimitry Andric }
12600b57cec5SDimitry Andric break;
12610b57cec5SDimitry Andric case ICmpInst::ICMP_SLT:
126204eeddc0SDimitry Andric switch (Predicate) {
12630b57cec5SDimitry Andric case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
12640b57cec5SDimitry Andric Result = 1; break;
12650b57cec5SDimitry Andric case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
12660b57cec5SDimitry Andric Result = 0; break;
126704eeddc0SDimitry Andric default:
126804eeddc0SDimitry Andric break;
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric break;
12710b57cec5SDimitry Andric case ICmpInst::ICMP_UGT:
127204eeddc0SDimitry Andric switch (Predicate) {
12730b57cec5SDimitry Andric case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
12740b57cec5SDimitry Andric Result = 1; break;
12750b57cec5SDimitry Andric case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
12760b57cec5SDimitry Andric Result = 0; break;
127704eeddc0SDimitry Andric default:
127804eeddc0SDimitry Andric break;
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric break;
12810b57cec5SDimitry Andric case ICmpInst::ICMP_SGT:
128204eeddc0SDimitry Andric switch (Predicate) {
12830b57cec5SDimitry Andric case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
12840b57cec5SDimitry Andric Result = 1; break;
12850b57cec5SDimitry Andric case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
12860b57cec5SDimitry Andric Result = 0; break;
128704eeddc0SDimitry Andric default:
128804eeddc0SDimitry Andric break;
12890b57cec5SDimitry Andric }
12900b57cec5SDimitry Andric break;
12910b57cec5SDimitry Andric case ICmpInst::ICMP_ULE:
129204eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_UGT)
129304eeddc0SDimitry Andric Result = 0;
129404eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)
129504eeddc0SDimitry Andric Result = 1;
12960b57cec5SDimitry Andric break;
12970b57cec5SDimitry Andric case ICmpInst::ICMP_SLE:
129804eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_SGT)
129904eeddc0SDimitry Andric Result = 0;
130004eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)
130104eeddc0SDimitry Andric Result = 1;
13020b57cec5SDimitry Andric break;
13030b57cec5SDimitry Andric case ICmpInst::ICMP_UGE:
130404eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_ULT)
130504eeddc0SDimitry Andric Result = 0;
130604eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)
130704eeddc0SDimitry Andric Result = 1;
13080b57cec5SDimitry Andric break;
13090b57cec5SDimitry Andric case ICmpInst::ICMP_SGE:
131004eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_SLT)
131104eeddc0SDimitry Andric Result = 0;
131204eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)
131304eeddc0SDimitry Andric Result = 1;
13140b57cec5SDimitry Andric break;
13150b57cec5SDimitry Andric case ICmpInst::ICMP_NE:
131604eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_EQ)
131704eeddc0SDimitry Andric Result = 0;
131804eeddc0SDimitry Andric if (Predicate == ICmpInst::ICMP_NE)
131904eeddc0SDimitry Andric Result = 1;
13200b57cec5SDimitry Andric break;
13210b57cec5SDimitry Andric }
13220b57cec5SDimitry Andric
13230b57cec5SDimitry Andric // If we evaluated the result, return it now.
13240b57cec5SDimitry Andric if (Result != -1)
13250b57cec5SDimitry Andric return ConstantInt::get(ResultTy, Result);
13260b57cec5SDimitry Andric
13270b57cec5SDimitry Andric if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
13280b57cec5SDimitry Andric (C1->isNullValue() && !C2->isNullValue())) {
13290b57cec5SDimitry Andric // If C2 is a constant expr and C1 isn't, flip them around and fold the
13300b57cec5SDimitry Andric // other way if possible.
13310b57cec5SDimitry Andric // Also, if C1 is null and C2 isn't, flip them around.
133204eeddc0SDimitry Andric Predicate = ICmpInst::getSwappedPredicate(Predicate);
1333*0fca6ea1SDimitry Andric return ConstantFoldCompareInstruction(Predicate, C2, C1);
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric return nullptr;
13370b57cec5SDimitry Andric }
13380b57cec5SDimitry Andric
ConstantFoldGetElementPtr(Type * PointeeTy,Constant * C,std::optional<ConstantRange> InRange,ArrayRef<Value * > Idxs)13390b57cec5SDimitry Andric Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
1340*0fca6ea1SDimitry Andric std::optional<ConstantRange> InRange,
13410b57cec5SDimitry Andric ArrayRef<Value *> Idxs) {
13420b57cec5SDimitry Andric if (Idxs.empty()) return C;
13430b57cec5SDimitry Andric
13440b57cec5SDimitry Andric Type *GEPTy = GetElementPtrInst::getGEPReturnType(
134506c3fb27SDimitry Andric C, ArrayRef((Value *const *)Idxs.data(), Idxs.size()));
13460b57cec5SDimitry Andric
1347e8d8bef9SDimitry Andric if (isa<PoisonValue>(C))
1348e8d8bef9SDimitry Andric return PoisonValue::get(GEPTy);
1349e8d8bef9SDimitry Andric
13500b57cec5SDimitry Andric if (isa<UndefValue>(C))
1351*0fca6ea1SDimitry Andric return UndefValue::get(GEPTy);
13520b57cec5SDimitry Andric
135381ad6265SDimitry Andric auto IsNoOp = [&]() {
1354bdd1243dSDimitry Andric // Avoid losing inrange information.
1355*0fca6ea1SDimitry Andric if (InRange)
1356bdd1243dSDimitry Andric return false;
1357bdd1243dSDimitry Andric
135881ad6265SDimitry Andric return all_of(Idxs, [](Value *Idx) {
135981ad6265SDimitry Andric Constant *IdxC = cast<Constant>(Idx);
136081ad6265SDimitry Andric return IdxC->isNullValue() || isa<UndefValue>(IdxC);
136181ad6265SDimitry Andric });
136281ad6265SDimitry Andric };
136381ad6265SDimitry Andric if (IsNoOp())
13640b57cec5SDimitry Andric return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
13650b57cec5SDimitry Andric ? ConstantVector::getSplat(
13665ffd83dbSDimitry Andric cast<VectorType>(GEPTy)->getElementCount(), C)
13670b57cec5SDimitry Andric : C;
13680b57cec5SDimitry Andric
13690b57cec5SDimitry Andric return nullptr;
13700b57cec5SDimitry Andric }
1371