xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
10b57cec5SDimitry Andric //===-- llvm/CodeGen/GlobalISel/LegalizerHelper.cpp -----------------------===//
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 /// \file This file implements the LegalizerHelper class to legalize
100b57cec5SDimitry Andric /// individual instructions and the LegalizeMachineIR wrapper pass for the
110b57cec5SDimitry Andric /// primary legalization.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
160b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/CallLowering.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
19*fe6060f1SDimitry Andric #include "llvm/CodeGen/GlobalISel/LostDebugLocObserver.h"
20e8d8bef9SDimitry Andric #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
21*fe6060f1SDimitry Andric #include "llvm/CodeGen/GlobalISel/Utils.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
238bcb0991SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
26*fe6060f1SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
28*fe6060f1SDimitry Andric #include "llvm/IR/Instructions.h"
290b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
300b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
310b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric #define DEBUG_TYPE "legalizer"
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric using namespace LegalizeActions;
37e8d8bef9SDimitry Andric using namespace MIPatternMatch;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric /// Try to break down \p OrigTy into \p NarrowTy sized pieces.
400b57cec5SDimitry Andric ///
410b57cec5SDimitry Andric /// Returns the number of \p NarrowTy elements needed to reconstruct \p OrigTy,
420b57cec5SDimitry Andric /// with any leftover piece as type \p LeftoverTy
430b57cec5SDimitry Andric ///
440b57cec5SDimitry Andric /// Returns -1 in the first element of the pair if the breakdown is not
450b57cec5SDimitry Andric /// satisfiable.
460b57cec5SDimitry Andric static std::pair<int, int>
470b57cec5SDimitry Andric getNarrowTypeBreakDown(LLT OrigTy, LLT NarrowTy, LLT &LeftoverTy) {
480b57cec5SDimitry Andric   assert(!LeftoverTy.isValid() && "this is an out argument");
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   unsigned Size = OrigTy.getSizeInBits();
510b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
520b57cec5SDimitry Andric   unsigned NumParts = Size / NarrowSize;
530b57cec5SDimitry Andric   unsigned LeftoverSize = Size - NumParts * NarrowSize;
540b57cec5SDimitry Andric   assert(Size > NarrowSize);
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric   if (LeftoverSize == 0)
570b57cec5SDimitry Andric     return {NumParts, 0};
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric   if (NarrowTy.isVector()) {
600b57cec5SDimitry Andric     unsigned EltSize = OrigTy.getScalarSizeInBits();
610b57cec5SDimitry Andric     if (LeftoverSize % EltSize != 0)
620b57cec5SDimitry Andric       return {-1, -1};
63*fe6060f1SDimitry Andric     LeftoverTy = LLT::scalarOrVector(
64*fe6060f1SDimitry Andric         ElementCount::getFixed(LeftoverSize / EltSize), EltSize);
650b57cec5SDimitry Andric   } else {
660b57cec5SDimitry Andric     LeftoverTy = LLT::scalar(LeftoverSize);
670b57cec5SDimitry Andric   }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric   int NumLeftover = LeftoverSize / LeftoverTy.getSizeInBits();
700b57cec5SDimitry Andric   return std::make_pair(NumParts, NumLeftover);
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric 
735ffd83dbSDimitry Andric static Type *getFloatTypeForLLT(LLVMContext &Ctx, LLT Ty) {
745ffd83dbSDimitry Andric 
755ffd83dbSDimitry Andric   if (!Ty.isScalar())
765ffd83dbSDimitry Andric     return nullptr;
775ffd83dbSDimitry Andric 
785ffd83dbSDimitry Andric   switch (Ty.getSizeInBits()) {
795ffd83dbSDimitry Andric   case 16:
805ffd83dbSDimitry Andric     return Type::getHalfTy(Ctx);
815ffd83dbSDimitry Andric   case 32:
825ffd83dbSDimitry Andric     return Type::getFloatTy(Ctx);
835ffd83dbSDimitry Andric   case 64:
845ffd83dbSDimitry Andric     return Type::getDoubleTy(Ctx);
85e8d8bef9SDimitry Andric   case 80:
86e8d8bef9SDimitry Andric     return Type::getX86_FP80Ty(Ctx);
875ffd83dbSDimitry Andric   case 128:
885ffd83dbSDimitry Andric     return Type::getFP128Ty(Ctx);
895ffd83dbSDimitry Andric   default:
905ffd83dbSDimitry Andric     return nullptr;
915ffd83dbSDimitry Andric   }
925ffd83dbSDimitry Andric }
935ffd83dbSDimitry Andric 
940b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF,
950b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
960b57cec5SDimitry Andric                                  MachineIRBuilder &Builder)
975ffd83dbSDimitry Andric     : MIRBuilder(Builder), Observer(Observer), MRI(MF.getRegInfo()),
98e8d8bef9SDimitry Andric       LI(*MF.getSubtarget().getLegalizerInfo()),
99e8d8bef9SDimitry Andric       TLI(*MF.getSubtarget().getTargetLowering()) { }
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF, const LegalizerInfo &LI,
1020b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
1030b57cec5SDimitry Andric                                  MachineIRBuilder &B)
104e8d8bef9SDimitry Andric   : MIRBuilder(B), Observer(Observer), MRI(MF.getRegInfo()), LI(LI),
105e8d8bef9SDimitry Andric     TLI(*MF.getSubtarget().getTargetLowering()) { }
106e8d8bef9SDimitry Andric 
1070b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
108*fe6060f1SDimitry Andric LegalizerHelper::legalizeInstrStep(MachineInstr &MI,
109*fe6060f1SDimitry Andric                                    LostDebugLocObserver &LocObserver) {
1105ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "Legalizing: " << MI);
1115ffd83dbSDimitry Andric 
1125ffd83dbSDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INTRINSIC ||
1150b57cec5SDimitry Andric       MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS)
1165ffd83dbSDimitry Andric     return LI.legalizeIntrinsic(*this, MI) ? Legalized : UnableToLegalize;
1170b57cec5SDimitry Andric   auto Step = LI.getAction(MI, MRI);
1180b57cec5SDimitry Andric   switch (Step.Action) {
1190b57cec5SDimitry Andric   case Legal:
1200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Already legal\n");
1210b57cec5SDimitry Andric     return AlreadyLegal;
1220b57cec5SDimitry Andric   case Libcall:
1230b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Convert to libcall\n");
124*fe6060f1SDimitry Andric     return libcall(MI, LocObserver);
1250b57cec5SDimitry Andric   case NarrowScalar:
1260b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Narrow scalar\n");
1270b57cec5SDimitry Andric     return narrowScalar(MI, Step.TypeIdx, Step.NewType);
1280b57cec5SDimitry Andric   case WidenScalar:
1290b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Widen scalar\n");
1300b57cec5SDimitry Andric     return widenScalar(MI, Step.TypeIdx, Step.NewType);
1315ffd83dbSDimitry Andric   case Bitcast:
1325ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << ".. Bitcast type\n");
1335ffd83dbSDimitry Andric     return bitcast(MI, Step.TypeIdx, Step.NewType);
1340b57cec5SDimitry Andric   case Lower:
1350b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Lower\n");
1360b57cec5SDimitry Andric     return lower(MI, Step.TypeIdx, Step.NewType);
1370b57cec5SDimitry Andric   case FewerElements:
1380b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Reduce number of elements\n");
1390b57cec5SDimitry Andric     return fewerElementsVector(MI, Step.TypeIdx, Step.NewType);
1400b57cec5SDimitry Andric   case MoreElements:
1410b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Increase number of elements\n");
1420b57cec5SDimitry Andric     return moreElementsVector(MI, Step.TypeIdx, Step.NewType);
1430b57cec5SDimitry Andric   case Custom:
1440b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Custom legalization\n");
1455ffd83dbSDimitry Andric     return LI.legalizeCustom(*this, MI) ? Legalized : UnableToLegalize;
1460b57cec5SDimitry Andric   default:
1470b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Unable to legalize\n");
1480b57cec5SDimitry Andric     return UnableToLegalize;
1490b57cec5SDimitry Andric   }
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric void LegalizerHelper::extractParts(Register Reg, LLT Ty, int NumParts,
1530b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &VRegs) {
1540b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i)
1550b57cec5SDimitry Andric     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
1560b57cec5SDimitry Andric   MIRBuilder.buildUnmerge(VRegs, Reg);
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric bool LegalizerHelper::extractParts(Register Reg, LLT RegTy,
1600b57cec5SDimitry Andric                                    LLT MainTy, LLT &LeftoverTy,
1610b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &VRegs,
1620b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &LeftoverRegs) {
1630b57cec5SDimitry Andric   assert(!LeftoverTy.isValid() && "this is an out argument");
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   unsigned RegSize = RegTy.getSizeInBits();
1660b57cec5SDimitry Andric   unsigned MainSize = MainTy.getSizeInBits();
1670b57cec5SDimitry Andric   unsigned NumParts = RegSize / MainSize;
1680b57cec5SDimitry Andric   unsigned LeftoverSize = RegSize - NumParts * MainSize;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   // Use an unmerge when possible.
1710b57cec5SDimitry Andric   if (LeftoverSize == 0) {
1720b57cec5SDimitry Andric     for (unsigned I = 0; I < NumParts; ++I)
1730b57cec5SDimitry Andric       VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
1740b57cec5SDimitry Andric     MIRBuilder.buildUnmerge(VRegs, Reg);
1750b57cec5SDimitry Andric     return true;
1760b57cec5SDimitry Andric   }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   if (MainTy.isVector()) {
1790b57cec5SDimitry Andric     unsigned EltSize = MainTy.getScalarSizeInBits();
1800b57cec5SDimitry Andric     if (LeftoverSize % EltSize != 0)
1810b57cec5SDimitry Andric       return false;
182*fe6060f1SDimitry Andric     LeftoverTy = LLT::scalarOrVector(
183*fe6060f1SDimitry Andric         ElementCount::getFixed(LeftoverSize / EltSize), EltSize);
1840b57cec5SDimitry Andric   } else {
1850b57cec5SDimitry Andric     LeftoverTy = LLT::scalar(LeftoverSize);
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   // For irregular sizes, extract the individual parts.
1890b57cec5SDimitry Andric   for (unsigned I = 0; I != NumParts; ++I) {
1900b57cec5SDimitry Andric     Register NewReg = MRI.createGenericVirtualRegister(MainTy);
1910b57cec5SDimitry Andric     VRegs.push_back(NewReg);
1920b57cec5SDimitry Andric     MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
1930b57cec5SDimitry Andric   }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
1960b57cec5SDimitry Andric        Offset += LeftoverSize) {
1970b57cec5SDimitry Andric     Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
1980b57cec5SDimitry Andric     LeftoverRegs.push_back(NewReg);
1990b57cec5SDimitry Andric     MIRBuilder.buildExtract(NewReg, Reg, Offset);
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   return true;
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric void LegalizerHelper::insertParts(Register DstReg,
2060b57cec5SDimitry Andric                                   LLT ResultTy, LLT PartTy,
2070b57cec5SDimitry Andric                                   ArrayRef<Register> PartRegs,
2080b57cec5SDimitry Andric                                   LLT LeftoverTy,
2090b57cec5SDimitry Andric                                   ArrayRef<Register> LeftoverRegs) {
2100b57cec5SDimitry Andric   if (!LeftoverTy.isValid()) {
2110b57cec5SDimitry Andric     assert(LeftoverRegs.empty());
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     if (!ResultTy.isVector()) {
2140b57cec5SDimitry Andric       MIRBuilder.buildMerge(DstReg, PartRegs);
2150b57cec5SDimitry Andric       return;
2160b57cec5SDimitry Andric     }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric     if (PartTy.isVector())
2190b57cec5SDimitry Andric       MIRBuilder.buildConcatVectors(DstReg, PartRegs);
2200b57cec5SDimitry Andric     else
2210b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, PartRegs);
2220b57cec5SDimitry Andric     return;
2230b57cec5SDimitry Andric   }
2240b57cec5SDimitry Andric 
225*fe6060f1SDimitry Andric   SmallVector<Register> GCDRegs;
226*fe6060f1SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(ResultTy, LeftoverTy), PartTy);
227*fe6060f1SDimitry Andric   for (auto PartReg : concat<const Register>(PartRegs, LeftoverRegs))
228*fe6060f1SDimitry Andric     extractGCDType(GCDRegs, GCDTy, PartReg);
229*fe6060f1SDimitry Andric   LLT ResultLCMTy = buildLCMMergePieces(ResultTy, LeftoverTy, GCDTy, GCDRegs);
230*fe6060f1SDimitry Andric   buildWidenedRemergeToDst(DstReg, ResultLCMTy, GCDRegs);
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric 
233e8d8bef9SDimitry Andric /// Append the result registers of G_UNMERGE_VALUES \p MI to \p Regs.
2345ffd83dbSDimitry Andric static void getUnmergeResults(SmallVectorImpl<Register> &Regs,
2355ffd83dbSDimitry Andric                               const MachineInstr &MI) {
2365ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES);
2375ffd83dbSDimitry Andric 
238e8d8bef9SDimitry Andric   const int StartIdx = Regs.size();
2395ffd83dbSDimitry Andric   const int NumResults = MI.getNumOperands() - 1;
240e8d8bef9SDimitry Andric   Regs.resize(Regs.size() + NumResults);
2415ffd83dbSDimitry Andric   for (int I = 0; I != NumResults; ++I)
242e8d8bef9SDimitry Andric     Regs[StartIdx + I] = MI.getOperand(I).getReg();
2435ffd83dbSDimitry Andric }
2445ffd83dbSDimitry Andric 
245e8d8bef9SDimitry Andric void LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts,
246e8d8bef9SDimitry Andric                                      LLT GCDTy, Register SrcReg) {
2475ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2485ffd83dbSDimitry Andric   if (SrcTy == GCDTy) {
2495ffd83dbSDimitry Andric     // If the source already evenly divides the result type, we don't need to do
2505ffd83dbSDimitry Andric     // anything.
2515ffd83dbSDimitry Andric     Parts.push_back(SrcReg);
2525ffd83dbSDimitry Andric   } else {
2535ffd83dbSDimitry Andric     // Need to split into common type sized pieces.
2545ffd83dbSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
2555ffd83dbSDimitry Andric     getUnmergeResults(Parts, *Unmerge);
2565ffd83dbSDimitry Andric   }
257e8d8bef9SDimitry Andric }
2585ffd83dbSDimitry Andric 
259e8d8bef9SDimitry Andric LLT LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts, LLT DstTy,
260e8d8bef9SDimitry Andric                                     LLT NarrowTy, Register SrcReg) {
261e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
262e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
263e8d8bef9SDimitry Andric   extractGCDType(Parts, GCDTy, SrcReg);
2645ffd83dbSDimitry Andric   return GCDTy;
2655ffd83dbSDimitry Andric }
2665ffd83dbSDimitry Andric 
2675ffd83dbSDimitry Andric LLT LegalizerHelper::buildLCMMergePieces(LLT DstTy, LLT NarrowTy, LLT GCDTy,
2685ffd83dbSDimitry Andric                                          SmallVectorImpl<Register> &VRegs,
2695ffd83dbSDimitry Andric                                          unsigned PadStrategy) {
2705ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(DstTy, NarrowTy);
2715ffd83dbSDimitry Andric 
2725ffd83dbSDimitry Andric   int NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
2735ffd83dbSDimitry Andric   int NumSubParts = NarrowTy.getSizeInBits() / GCDTy.getSizeInBits();
2745ffd83dbSDimitry Andric   int NumOrigSrc = VRegs.size();
2755ffd83dbSDimitry Andric 
2765ffd83dbSDimitry Andric   Register PadReg;
2775ffd83dbSDimitry Andric 
2785ffd83dbSDimitry Andric   // Get a value we can use to pad the source value if the sources won't evenly
2795ffd83dbSDimitry Andric   // cover the result type.
2805ffd83dbSDimitry Andric   if (NumOrigSrc < NumParts * NumSubParts) {
2815ffd83dbSDimitry Andric     if (PadStrategy == TargetOpcode::G_ZEXT)
2825ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildConstant(GCDTy, 0).getReg(0);
2835ffd83dbSDimitry Andric     else if (PadStrategy == TargetOpcode::G_ANYEXT)
2845ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
2855ffd83dbSDimitry Andric     else {
2865ffd83dbSDimitry Andric       assert(PadStrategy == TargetOpcode::G_SEXT);
2875ffd83dbSDimitry Andric 
2885ffd83dbSDimitry Andric       // Shift the sign bit of the low register through the high register.
2895ffd83dbSDimitry Andric       auto ShiftAmt =
2905ffd83dbSDimitry Andric         MIRBuilder.buildConstant(LLT::scalar(64), GCDTy.getSizeInBits() - 1);
2915ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildAShr(GCDTy, VRegs.back(), ShiftAmt).getReg(0);
2925ffd83dbSDimitry Andric     }
2935ffd83dbSDimitry Andric   }
2945ffd83dbSDimitry Andric 
2955ffd83dbSDimitry Andric   // Registers for the final merge to be produced.
2965ffd83dbSDimitry Andric   SmallVector<Register, 4> Remerge(NumParts);
2975ffd83dbSDimitry Andric 
2985ffd83dbSDimitry Andric   // Registers needed for intermediate merges, which will be merged into a
2995ffd83dbSDimitry Andric   // source for Remerge.
3005ffd83dbSDimitry Andric   SmallVector<Register, 4> SubMerge(NumSubParts);
3015ffd83dbSDimitry Andric 
3025ffd83dbSDimitry Andric   // Once we've fully read off the end of the original source bits, we can reuse
3035ffd83dbSDimitry Andric   // the same high bits for remaining padding elements.
3045ffd83dbSDimitry Andric   Register AllPadReg;
3055ffd83dbSDimitry Andric 
3065ffd83dbSDimitry Andric   // Build merges to the LCM type to cover the original result type.
3075ffd83dbSDimitry Andric   for (int I = 0; I != NumParts; ++I) {
3085ffd83dbSDimitry Andric     bool AllMergePartsArePadding = true;
3095ffd83dbSDimitry Andric 
3105ffd83dbSDimitry Andric     // Build the requested merges to the requested type.
3115ffd83dbSDimitry Andric     for (int J = 0; J != NumSubParts; ++J) {
3125ffd83dbSDimitry Andric       int Idx = I * NumSubParts + J;
3135ffd83dbSDimitry Andric       if (Idx >= NumOrigSrc) {
3145ffd83dbSDimitry Andric         SubMerge[J] = PadReg;
3155ffd83dbSDimitry Andric         continue;
3165ffd83dbSDimitry Andric       }
3175ffd83dbSDimitry Andric 
3185ffd83dbSDimitry Andric       SubMerge[J] = VRegs[Idx];
3195ffd83dbSDimitry Andric 
3205ffd83dbSDimitry Andric       // There are meaningful bits here we can't reuse later.
3215ffd83dbSDimitry Andric       AllMergePartsArePadding = false;
3225ffd83dbSDimitry Andric     }
3235ffd83dbSDimitry Andric 
3245ffd83dbSDimitry Andric     // If we've filled up a complete piece with padding bits, we can directly
3255ffd83dbSDimitry Andric     // emit the natural sized constant if applicable, rather than a merge of
3265ffd83dbSDimitry Andric     // smaller constants.
3275ffd83dbSDimitry Andric     if (AllMergePartsArePadding && !AllPadReg) {
3285ffd83dbSDimitry Andric       if (PadStrategy == TargetOpcode::G_ANYEXT)
3295ffd83dbSDimitry Andric         AllPadReg = MIRBuilder.buildUndef(NarrowTy).getReg(0);
3305ffd83dbSDimitry Andric       else if (PadStrategy == TargetOpcode::G_ZEXT)
3315ffd83dbSDimitry Andric         AllPadReg = MIRBuilder.buildConstant(NarrowTy, 0).getReg(0);
3325ffd83dbSDimitry Andric 
3335ffd83dbSDimitry Andric       // If this is a sign extension, we can't materialize a trivial constant
3345ffd83dbSDimitry Andric       // with the right type and have to produce a merge.
3355ffd83dbSDimitry Andric     }
3365ffd83dbSDimitry Andric 
3375ffd83dbSDimitry Andric     if (AllPadReg) {
3385ffd83dbSDimitry Andric       // Avoid creating additional instructions if we're just adding additional
3395ffd83dbSDimitry Andric       // copies of padding bits.
3405ffd83dbSDimitry Andric       Remerge[I] = AllPadReg;
3415ffd83dbSDimitry Andric       continue;
3425ffd83dbSDimitry Andric     }
3435ffd83dbSDimitry Andric 
3445ffd83dbSDimitry Andric     if (NumSubParts == 1)
3455ffd83dbSDimitry Andric       Remerge[I] = SubMerge[0];
3465ffd83dbSDimitry Andric     else
3475ffd83dbSDimitry Andric       Remerge[I] = MIRBuilder.buildMerge(NarrowTy, SubMerge).getReg(0);
3485ffd83dbSDimitry Andric 
3495ffd83dbSDimitry Andric     // In the sign extend padding case, re-use the first all-signbit merge.
3505ffd83dbSDimitry Andric     if (AllMergePartsArePadding && !AllPadReg)
3515ffd83dbSDimitry Andric       AllPadReg = Remerge[I];
3525ffd83dbSDimitry Andric   }
3535ffd83dbSDimitry Andric 
3545ffd83dbSDimitry Andric   VRegs = std::move(Remerge);
3555ffd83dbSDimitry Andric   return LCMTy;
3565ffd83dbSDimitry Andric }
3575ffd83dbSDimitry Andric 
3585ffd83dbSDimitry Andric void LegalizerHelper::buildWidenedRemergeToDst(Register DstReg, LLT LCMTy,
3595ffd83dbSDimitry Andric                                                ArrayRef<Register> RemergeRegs) {
3605ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3615ffd83dbSDimitry Andric 
3625ffd83dbSDimitry Andric   // Create the merge to the widened source, and extract the relevant bits into
3635ffd83dbSDimitry Andric   // the result.
3645ffd83dbSDimitry Andric 
3655ffd83dbSDimitry Andric   if (DstTy == LCMTy) {
3665ffd83dbSDimitry Andric     MIRBuilder.buildMerge(DstReg, RemergeRegs);
3675ffd83dbSDimitry Andric     return;
3685ffd83dbSDimitry Andric   }
3695ffd83dbSDimitry Andric 
3705ffd83dbSDimitry Andric   auto Remerge = MIRBuilder.buildMerge(LCMTy, RemergeRegs);
3715ffd83dbSDimitry Andric   if (DstTy.isScalar() && LCMTy.isScalar()) {
3725ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(DstReg, Remerge);
3735ffd83dbSDimitry Andric     return;
3745ffd83dbSDimitry Andric   }
3755ffd83dbSDimitry Andric 
3765ffd83dbSDimitry Andric   if (LCMTy.isVector()) {
377e8d8bef9SDimitry Andric     unsigned NumDefs = LCMTy.getSizeInBits() / DstTy.getSizeInBits();
378e8d8bef9SDimitry Andric     SmallVector<Register, 8> UnmergeDefs(NumDefs);
379e8d8bef9SDimitry Andric     UnmergeDefs[0] = DstReg;
380e8d8bef9SDimitry Andric     for (unsigned I = 1; I != NumDefs; ++I)
381e8d8bef9SDimitry Andric       UnmergeDefs[I] = MRI.createGenericVirtualRegister(DstTy);
382e8d8bef9SDimitry Andric 
383e8d8bef9SDimitry Andric     MIRBuilder.buildUnmerge(UnmergeDefs,
384e8d8bef9SDimitry Andric                             MIRBuilder.buildMerge(LCMTy, RemergeRegs));
3855ffd83dbSDimitry Andric     return;
3865ffd83dbSDimitry Andric   }
3875ffd83dbSDimitry Andric 
3885ffd83dbSDimitry Andric   llvm_unreachable("unhandled case");
3895ffd83dbSDimitry Andric }
3905ffd83dbSDimitry Andric 
3910b57cec5SDimitry Andric static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size) {
392e8d8bef9SDimitry Andric #define RTLIBCASE_INT(LibcallPrefix)                                           \
3935ffd83dbSDimitry Andric   do {                                                                         \
3945ffd83dbSDimitry Andric     switch (Size) {                                                            \
3955ffd83dbSDimitry Andric     case 32:                                                                   \
3965ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
3975ffd83dbSDimitry Andric     case 64:                                                                   \
3985ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
3995ffd83dbSDimitry Andric     case 128:                                                                  \
4005ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
4015ffd83dbSDimitry Andric     default:                                                                   \
4025ffd83dbSDimitry Andric       llvm_unreachable("unexpected size");                                     \
4035ffd83dbSDimitry Andric     }                                                                          \
4045ffd83dbSDimitry Andric   } while (0)
4055ffd83dbSDimitry Andric 
406e8d8bef9SDimitry Andric #define RTLIBCASE(LibcallPrefix)                                               \
407e8d8bef9SDimitry Andric   do {                                                                         \
408e8d8bef9SDimitry Andric     switch (Size) {                                                            \
409e8d8bef9SDimitry Andric     case 32:                                                                   \
410e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
411e8d8bef9SDimitry Andric     case 64:                                                                   \
412e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
413e8d8bef9SDimitry Andric     case 80:                                                                   \
414e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##80;                                         \
415e8d8bef9SDimitry Andric     case 128:                                                                  \
416e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
417e8d8bef9SDimitry Andric     default:                                                                   \
418e8d8bef9SDimitry Andric       llvm_unreachable("unexpected size");                                     \
419e8d8bef9SDimitry Andric     }                                                                          \
420e8d8bef9SDimitry Andric   } while (0)
4215ffd83dbSDimitry Andric 
4220b57cec5SDimitry Andric   switch (Opcode) {
4230b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
424e8d8bef9SDimitry Andric     RTLIBCASE_INT(SDIV_I);
4250b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
426e8d8bef9SDimitry Andric     RTLIBCASE_INT(UDIV_I);
4270b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
428e8d8bef9SDimitry Andric     RTLIBCASE_INT(SREM_I);
4290b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
430e8d8bef9SDimitry Andric     RTLIBCASE_INT(UREM_I);
4310b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
432e8d8bef9SDimitry Andric     RTLIBCASE_INT(CTLZ_I);
4330b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
4345ffd83dbSDimitry Andric     RTLIBCASE(ADD_F);
4350b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
4365ffd83dbSDimitry Andric     RTLIBCASE(SUB_F);
4370b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
4385ffd83dbSDimitry Andric     RTLIBCASE(MUL_F);
4390b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
4405ffd83dbSDimitry Andric     RTLIBCASE(DIV_F);
4410b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
4425ffd83dbSDimitry Andric     RTLIBCASE(EXP_F);
4430b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
4445ffd83dbSDimitry Andric     RTLIBCASE(EXP2_F);
4450b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
4465ffd83dbSDimitry Andric     RTLIBCASE(REM_F);
4470b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
4485ffd83dbSDimitry Andric     RTLIBCASE(POW_F);
4490b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
4505ffd83dbSDimitry Andric     RTLIBCASE(FMA_F);
4510b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
4525ffd83dbSDimitry Andric     RTLIBCASE(SIN_F);
4530b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
4545ffd83dbSDimitry Andric     RTLIBCASE(COS_F);
4550b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
4565ffd83dbSDimitry Andric     RTLIBCASE(LOG10_F);
4570b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
4585ffd83dbSDimitry Andric     RTLIBCASE(LOG_F);
4590b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
4605ffd83dbSDimitry Andric     RTLIBCASE(LOG2_F);
4610b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
4625ffd83dbSDimitry Andric     RTLIBCASE(CEIL_F);
4630b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
4645ffd83dbSDimitry Andric     RTLIBCASE(FLOOR_F);
4655ffd83dbSDimitry Andric   case TargetOpcode::G_FMINNUM:
4665ffd83dbSDimitry Andric     RTLIBCASE(FMIN_F);
4675ffd83dbSDimitry Andric   case TargetOpcode::G_FMAXNUM:
4685ffd83dbSDimitry Andric     RTLIBCASE(FMAX_F);
4695ffd83dbSDimitry Andric   case TargetOpcode::G_FSQRT:
4705ffd83dbSDimitry Andric     RTLIBCASE(SQRT_F);
4715ffd83dbSDimitry Andric   case TargetOpcode::G_FRINT:
4725ffd83dbSDimitry Andric     RTLIBCASE(RINT_F);
4735ffd83dbSDimitry Andric   case TargetOpcode::G_FNEARBYINT:
4745ffd83dbSDimitry Andric     RTLIBCASE(NEARBYINT_F);
475e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
476e8d8bef9SDimitry Andric     RTLIBCASE(ROUNDEVEN_F);
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric   llvm_unreachable("Unknown libcall function");
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4818bcb0991SDimitry Andric /// True if an instruction is in tail position in its caller. Intended for
4828bcb0991SDimitry Andric /// legalizing libcalls as tail calls when possible.
483*fe6060f1SDimitry Andric static bool isLibCallInTailPosition(MachineInstr &MI,
484*fe6060f1SDimitry Andric                                     const TargetInstrInfo &TII,
485*fe6060f1SDimitry Andric                                     MachineRegisterInfo &MRI) {
4865ffd83dbSDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
4875ffd83dbSDimitry Andric   const Function &F = MBB.getParent()->getFunction();
4888bcb0991SDimitry Andric 
4898bcb0991SDimitry Andric   // Conservatively require the attributes of the call to match those of
4908bcb0991SDimitry Andric   // the return. Ignore NoAlias and NonNull because they don't affect the
4918bcb0991SDimitry Andric   // call sequence.
4928bcb0991SDimitry Andric   AttributeList CallerAttrs = F.getAttributes();
4938bcb0991SDimitry Andric   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
4948bcb0991SDimitry Andric           .removeAttribute(Attribute::NoAlias)
4958bcb0991SDimitry Andric           .removeAttribute(Attribute::NonNull)
4968bcb0991SDimitry Andric           .hasAttributes())
4978bcb0991SDimitry Andric     return false;
4988bcb0991SDimitry Andric 
4998bcb0991SDimitry Andric   // It's not safe to eliminate the sign / zero extension of the return value.
5008bcb0991SDimitry Andric   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
5018bcb0991SDimitry Andric       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
5028bcb0991SDimitry Andric     return false;
5038bcb0991SDimitry Andric 
504*fe6060f1SDimitry Andric   // Only tail call if the following instruction is a standard return or if we
505*fe6060f1SDimitry Andric   // have a `thisreturn` callee, and a sequence like:
506*fe6060f1SDimitry Andric   //
507*fe6060f1SDimitry Andric   //   G_MEMCPY %0, %1, %2
508*fe6060f1SDimitry Andric   //   $x0 = COPY %0
509*fe6060f1SDimitry Andric   //   RET_ReallyLR implicit $x0
5105ffd83dbSDimitry Andric   auto Next = next_nodbg(MI.getIterator(), MBB.instr_end());
511*fe6060f1SDimitry Andric   if (Next != MBB.instr_end() && Next->isCopy()) {
512*fe6060f1SDimitry Andric     switch (MI.getOpcode()) {
513*fe6060f1SDimitry Andric     default:
514*fe6060f1SDimitry Andric       llvm_unreachable("unsupported opcode");
515*fe6060f1SDimitry Andric     case TargetOpcode::G_BZERO:
516*fe6060f1SDimitry Andric       return false;
517*fe6060f1SDimitry Andric     case TargetOpcode::G_MEMCPY:
518*fe6060f1SDimitry Andric     case TargetOpcode::G_MEMMOVE:
519*fe6060f1SDimitry Andric     case TargetOpcode::G_MEMSET:
520*fe6060f1SDimitry Andric       break;
521*fe6060f1SDimitry Andric     }
522*fe6060f1SDimitry Andric 
523*fe6060f1SDimitry Andric     Register VReg = MI.getOperand(0).getReg();
524*fe6060f1SDimitry Andric     if (!VReg.isVirtual() || VReg != Next->getOperand(1).getReg())
525*fe6060f1SDimitry Andric       return false;
526*fe6060f1SDimitry Andric 
527*fe6060f1SDimitry Andric     Register PReg = Next->getOperand(0).getReg();
528*fe6060f1SDimitry Andric     if (!PReg.isPhysical())
529*fe6060f1SDimitry Andric       return false;
530*fe6060f1SDimitry Andric 
531*fe6060f1SDimitry Andric     auto Ret = next_nodbg(Next, MBB.instr_end());
532*fe6060f1SDimitry Andric     if (Ret == MBB.instr_end() || !Ret->isReturn())
533*fe6060f1SDimitry Andric       return false;
534*fe6060f1SDimitry Andric 
535*fe6060f1SDimitry Andric     if (Ret->getNumImplicitOperands() != 1)
536*fe6060f1SDimitry Andric       return false;
537*fe6060f1SDimitry Andric 
538*fe6060f1SDimitry Andric     if (PReg != Ret->getOperand(0).getReg())
539*fe6060f1SDimitry Andric       return false;
540*fe6060f1SDimitry Andric 
541*fe6060f1SDimitry Andric     // Skip over the COPY that we just validated.
542*fe6060f1SDimitry Andric     Next = Ret;
543*fe6060f1SDimitry Andric   }
544*fe6060f1SDimitry Andric 
5455ffd83dbSDimitry Andric   if (Next == MBB.instr_end() || TII.isTailCall(*Next) || !Next->isReturn())
5468bcb0991SDimitry Andric     return false;
5478bcb0991SDimitry Andric 
5488bcb0991SDimitry Andric   return true;
5498bcb0991SDimitry Andric }
5508bcb0991SDimitry Andric 
5510b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
5525ffd83dbSDimitry Andric llvm::createLibcall(MachineIRBuilder &MIRBuilder, const char *Name,
5530b57cec5SDimitry Andric                     const CallLowering::ArgInfo &Result,
5545ffd83dbSDimitry Andric                     ArrayRef<CallLowering::ArgInfo> Args,
5555ffd83dbSDimitry Andric                     const CallingConv::ID CC) {
5560b57cec5SDimitry Andric   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
5570b57cec5SDimitry Andric 
5588bcb0991SDimitry Andric   CallLowering::CallLoweringInfo Info;
5595ffd83dbSDimitry Andric   Info.CallConv = CC;
5608bcb0991SDimitry Andric   Info.Callee = MachineOperand::CreateES(Name);
5618bcb0991SDimitry Andric   Info.OrigRet = Result;
5628bcb0991SDimitry Andric   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
5638bcb0991SDimitry Andric   if (!CLI.lowerCall(MIRBuilder, Info))
5640b57cec5SDimitry Andric     return LegalizerHelper::UnableToLegalize;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   return LegalizerHelper::Legalized;
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric 
5695ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
5705ffd83dbSDimitry Andric llvm::createLibcall(MachineIRBuilder &MIRBuilder, RTLIB::Libcall Libcall,
5715ffd83dbSDimitry Andric                     const CallLowering::ArgInfo &Result,
5725ffd83dbSDimitry Andric                     ArrayRef<CallLowering::ArgInfo> Args) {
5735ffd83dbSDimitry Andric   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
5745ffd83dbSDimitry Andric   const char *Name = TLI.getLibcallName(Libcall);
5755ffd83dbSDimitry Andric   const CallingConv::ID CC = TLI.getLibcallCallingConv(Libcall);
5765ffd83dbSDimitry Andric   return createLibcall(MIRBuilder, Name, Result, Args, CC);
5775ffd83dbSDimitry Andric }
5785ffd83dbSDimitry Andric 
5790b57cec5SDimitry Andric // Useful for libcalls where all operands have the same type.
5800b57cec5SDimitry Andric static LegalizerHelper::LegalizeResult
5810b57cec5SDimitry Andric simpleLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, unsigned Size,
5820b57cec5SDimitry Andric               Type *OpType) {
5830b57cec5SDimitry Andric   auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
5840b57cec5SDimitry Andric 
585*fe6060f1SDimitry Andric   // FIXME: What does the original arg index mean here?
5860b57cec5SDimitry Andric   SmallVector<CallLowering::ArgInfo, 3> Args;
5870b57cec5SDimitry Andric   for (unsigned i = 1; i < MI.getNumOperands(); i++)
588*fe6060f1SDimitry Andric     Args.push_back({MI.getOperand(i).getReg(), OpType, 0});
589*fe6060f1SDimitry Andric   return createLibcall(MIRBuilder, Libcall,
590*fe6060f1SDimitry Andric                        {MI.getOperand(0).getReg(), OpType, 0}, Args);
5910b57cec5SDimitry Andric }
5920b57cec5SDimitry Andric 
5938bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
5948bcb0991SDimitry Andric llvm::createMemLibcall(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
595*fe6060f1SDimitry Andric                        MachineInstr &MI, LostDebugLocObserver &LocObserver) {
5968bcb0991SDimitry Andric   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
5978bcb0991SDimitry Andric 
5988bcb0991SDimitry Andric   SmallVector<CallLowering::ArgInfo, 3> Args;
5998bcb0991SDimitry Andric   // Add all the args, except for the last which is an imm denoting 'tail'.
600e8d8bef9SDimitry Andric   for (unsigned i = 0; i < MI.getNumOperands() - 1; ++i) {
6018bcb0991SDimitry Andric     Register Reg = MI.getOperand(i).getReg();
6028bcb0991SDimitry Andric 
6038bcb0991SDimitry Andric     // Need derive an IR type for call lowering.
6048bcb0991SDimitry Andric     LLT OpLLT = MRI.getType(Reg);
6058bcb0991SDimitry Andric     Type *OpTy = nullptr;
6068bcb0991SDimitry Andric     if (OpLLT.isPointer())
6078bcb0991SDimitry Andric       OpTy = Type::getInt8PtrTy(Ctx, OpLLT.getAddressSpace());
6088bcb0991SDimitry Andric     else
6098bcb0991SDimitry Andric       OpTy = IntegerType::get(Ctx, OpLLT.getSizeInBits());
610*fe6060f1SDimitry Andric     Args.push_back({Reg, OpTy, 0});
6118bcb0991SDimitry Andric   }
6128bcb0991SDimitry Andric 
6138bcb0991SDimitry Andric   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
6148bcb0991SDimitry Andric   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
6158bcb0991SDimitry Andric   RTLIB::Libcall RTLibcall;
616*fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
617*fe6060f1SDimitry Andric   switch (Opc) {
618*fe6060f1SDimitry Andric   case TargetOpcode::G_BZERO:
619*fe6060f1SDimitry Andric     RTLibcall = RTLIB::BZERO;
620*fe6060f1SDimitry Andric     break;
621e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
6228bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMCPY;
623*fe6060f1SDimitry Andric     Args[0].Flags[0].setReturned();
6248bcb0991SDimitry Andric     break;
625e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
6268bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMMOVE;
627*fe6060f1SDimitry Andric     Args[0].Flags[0].setReturned();
6288bcb0991SDimitry Andric     break;
629e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET:
630e8d8bef9SDimitry Andric     RTLibcall = RTLIB::MEMSET;
631*fe6060f1SDimitry Andric     Args[0].Flags[0].setReturned();
632e8d8bef9SDimitry Andric     break;
6338bcb0991SDimitry Andric   default:
634*fe6060f1SDimitry Andric     llvm_unreachable("unsupported opcode");
6358bcb0991SDimitry Andric   }
6368bcb0991SDimitry Andric   const char *Name = TLI.getLibcallName(RTLibcall);
6378bcb0991SDimitry Andric 
638*fe6060f1SDimitry Andric   // Unsupported libcall on the target.
639*fe6060f1SDimitry Andric   if (!Name) {
640*fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << ".. .. Could not find libcall name for "
641*fe6060f1SDimitry Andric                       << MIRBuilder.getTII().getName(Opc) << "\n");
642*fe6060f1SDimitry Andric     return LegalizerHelper::UnableToLegalize;
643*fe6060f1SDimitry Andric   }
644*fe6060f1SDimitry Andric 
6458bcb0991SDimitry Andric   CallLowering::CallLoweringInfo Info;
6468bcb0991SDimitry Andric   Info.CallConv = TLI.getLibcallCallingConv(RTLibcall);
6478bcb0991SDimitry Andric   Info.Callee = MachineOperand::CreateES(Name);
648*fe6060f1SDimitry Andric   Info.OrigRet = CallLowering::ArgInfo({0}, Type::getVoidTy(Ctx), 0);
649e8d8bef9SDimitry Andric   Info.IsTailCall = MI.getOperand(MI.getNumOperands() - 1).getImm() &&
650*fe6060f1SDimitry Andric                     isLibCallInTailPosition(MI, MIRBuilder.getTII(), MRI);
6518bcb0991SDimitry Andric 
6528bcb0991SDimitry Andric   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
6538bcb0991SDimitry Andric   if (!CLI.lowerCall(MIRBuilder, Info))
6548bcb0991SDimitry Andric     return LegalizerHelper::UnableToLegalize;
6558bcb0991SDimitry Andric 
6568bcb0991SDimitry Andric   if (Info.LoweredTailCall) {
6578bcb0991SDimitry Andric     assert(Info.IsTailCall && "Lowered tail call when it wasn't a tail call?");
658*fe6060f1SDimitry Andric 
659*fe6060f1SDimitry Andric     // Check debug locations before removing the return.
660*fe6060f1SDimitry Andric     LocObserver.checkpoint(true);
661*fe6060f1SDimitry Andric 
6625ffd83dbSDimitry Andric     // We must have a return following the call (or debug insts) to get past
6638bcb0991SDimitry Andric     // isLibCallInTailPosition.
6645ffd83dbSDimitry Andric     do {
6655ffd83dbSDimitry Andric       MachineInstr *Next = MI.getNextNode();
666*fe6060f1SDimitry Andric       assert(Next &&
667*fe6060f1SDimitry Andric              (Next->isCopy() || Next->isReturn() || Next->isDebugInstr()) &&
6685ffd83dbSDimitry Andric              "Expected instr following MI to be return or debug inst?");
6698bcb0991SDimitry Andric       // We lowered a tail call, so the call is now the return from the block.
6708bcb0991SDimitry Andric       // Delete the old return.
6715ffd83dbSDimitry Andric       Next->eraseFromParent();
6725ffd83dbSDimitry Andric     } while (MI.getNextNode());
673*fe6060f1SDimitry Andric 
674*fe6060f1SDimitry Andric     // We expect to lose the debug location from the return.
675*fe6060f1SDimitry Andric     LocObserver.checkpoint(false);
6768bcb0991SDimitry Andric   }
6778bcb0991SDimitry Andric 
6788bcb0991SDimitry Andric   return LegalizerHelper::Legalized;
6798bcb0991SDimitry Andric }
6808bcb0991SDimitry Andric 
6810b57cec5SDimitry Andric static RTLIB::Libcall getConvRTLibDesc(unsigned Opcode, Type *ToType,
6820b57cec5SDimitry Andric                                        Type *FromType) {
6830b57cec5SDimitry Andric   auto ToMVT = MVT::getVT(ToType);
6840b57cec5SDimitry Andric   auto FromMVT = MVT::getVT(FromType);
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   switch (Opcode) {
6870b57cec5SDimitry Andric   case TargetOpcode::G_FPEXT:
6880b57cec5SDimitry Andric     return RTLIB::getFPEXT(FromMVT, ToMVT);
6890b57cec5SDimitry Andric   case TargetOpcode::G_FPTRUNC:
6900b57cec5SDimitry Andric     return RTLIB::getFPROUND(FromMVT, ToMVT);
6910b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
6920b57cec5SDimitry Andric     return RTLIB::getFPTOSINT(FromMVT, ToMVT);
6930b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
6940b57cec5SDimitry Andric     return RTLIB::getFPTOUINT(FromMVT, ToMVT);
6950b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
6960b57cec5SDimitry Andric     return RTLIB::getSINTTOFP(FromMVT, ToMVT);
6970b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
6980b57cec5SDimitry Andric     return RTLIB::getUINTTOFP(FromMVT, ToMVT);
6990b57cec5SDimitry Andric   }
7000b57cec5SDimitry Andric   llvm_unreachable("Unsupported libcall function");
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric static LegalizerHelper::LegalizeResult
7040b57cec5SDimitry Andric conversionLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, Type *ToType,
7050b57cec5SDimitry Andric                   Type *FromType) {
7060b57cec5SDimitry Andric   RTLIB::Libcall Libcall = getConvRTLibDesc(MI.getOpcode(), ToType, FromType);
707*fe6060f1SDimitry Andric   return createLibcall(MIRBuilder, Libcall,
708*fe6060f1SDimitry Andric                        {MI.getOperand(0).getReg(), ToType, 0},
709*fe6060f1SDimitry Andric                        {{MI.getOperand(1).getReg(), FromType, 0}});
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
713*fe6060f1SDimitry Andric LegalizerHelper::libcall(MachineInstr &MI, LostDebugLocObserver &LocObserver) {
7140b57cec5SDimitry Andric   LLT LLTy = MRI.getType(MI.getOperand(0).getReg());
7150b57cec5SDimitry Andric   unsigned Size = LLTy.getSizeInBits();
7160b57cec5SDimitry Andric   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   switch (MI.getOpcode()) {
7190b57cec5SDimitry Andric   default:
7200b57cec5SDimitry Andric     return UnableToLegalize;
7210b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
7220b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
7230b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
7240b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
7250b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
7260b57cec5SDimitry Andric     Type *HLTy = IntegerType::get(Ctx, Size);
7270b57cec5SDimitry Andric     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
7280b57cec5SDimitry Andric     if (Status != Legalized)
7290b57cec5SDimitry Andric       return Status;
7300b57cec5SDimitry Andric     break;
7310b57cec5SDimitry Andric   }
7320b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
7330b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
7340b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
7350b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
7360b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
7370b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
7380b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
7390b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
7400b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
7410b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
7420b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
7430b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
7440b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
7450b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
7460b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
7475ffd83dbSDimitry Andric   case TargetOpcode::G_FFLOOR:
7485ffd83dbSDimitry Andric   case TargetOpcode::G_FMINNUM:
7495ffd83dbSDimitry Andric   case TargetOpcode::G_FMAXNUM:
7505ffd83dbSDimitry Andric   case TargetOpcode::G_FSQRT:
7515ffd83dbSDimitry Andric   case TargetOpcode::G_FRINT:
752e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
753e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
7545ffd83dbSDimitry Andric     Type *HLTy = getFloatTypeForLLT(Ctx, LLTy);
755e8d8bef9SDimitry Andric     if (!HLTy || (Size != 32 && Size != 64 && Size != 80 && Size != 128)) {
756e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "No libcall available for type " << LLTy << ".\n");
7570b57cec5SDimitry Andric       return UnableToLegalize;
7580b57cec5SDimitry Andric     }
7590b57cec5SDimitry Andric     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
7600b57cec5SDimitry Andric     if (Status != Legalized)
7610b57cec5SDimitry Andric       return Status;
7620b57cec5SDimitry Andric     break;
7630b57cec5SDimitry Andric   }
7645ffd83dbSDimitry Andric   case TargetOpcode::G_FPEXT:
7650b57cec5SDimitry Andric   case TargetOpcode::G_FPTRUNC: {
7665ffd83dbSDimitry Andric     Type *FromTy = getFloatTypeForLLT(Ctx,  MRI.getType(MI.getOperand(1).getReg()));
7675ffd83dbSDimitry Andric     Type *ToTy = getFloatTypeForLLT(Ctx, MRI.getType(MI.getOperand(0).getReg()));
7685ffd83dbSDimitry Andric     if (!FromTy || !ToTy)
7690b57cec5SDimitry Andric       return UnableToLegalize;
7705ffd83dbSDimitry Andric     LegalizeResult Status = conversionLibcall(MI, MIRBuilder, ToTy, FromTy );
7710b57cec5SDimitry Andric     if (Status != Legalized)
7720b57cec5SDimitry Andric       return Status;
7730b57cec5SDimitry Andric     break;
7740b57cec5SDimitry Andric   }
7750b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
7760b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI: {
7770b57cec5SDimitry Andric     // FIXME: Support other types
7780b57cec5SDimitry Andric     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
7790b57cec5SDimitry Andric     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
7800b57cec5SDimitry Andric     if ((ToSize != 32 && ToSize != 64) || (FromSize != 32 && FromSize != 64))
7810b57cec5SDimitry Andric       return UnableToLegalize;
7820b57cec5SDimitry Andric     LegalizeResult Status = conversionLibcall(
7830b57cec5SDimitry Andric         MI, MIRBuilder,
7840b57cec5SDimitry Andric         ToSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx),
7850b57cec5SDimitry Andric         FromSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx));
7860b57cec5SDimitry Andric     if (Status != Legalized)
7870b57cec5SDimitry Andric       return Status;
7880b57cec5SDimitry Andric     break;
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
7910b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP: {
7920b57cec5SDimitry Andric     // FIXME: Support other types
7930b57cec5SDimitry Andric     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
7940b57cec5SDimitry Andric     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
7950b57cec5SDimitry Andric     if ((FromSize != 32 && FromSize != 64) || (ToSize != 32 && ToSize != 64))
7960b57cec5SDimitry Andric       return UnableToLegalize;
7970b57cec5SDimitry Andric     LegalizeResult Status = conversionLibcall(
7980b57cec5SDimitry Andric         MI, MIRBuilder,
7990b57cec5SDimitry Andric         ToSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx),
8000b57cec5SDimitry Andric         FromSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx));
8010b57cec5SDimitry Andric     if (Status != Legalized)
8020b57cec5SDimitry Andric       return Status;
8030b57cec5SDimitry Andric     break;
8040b57cec5SDimitry Andric   }
805*fe6060f1SDimitry Andric   case TargetOpcode::G_BZERO:
806e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
807e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
808e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET: {
809*fe6060f1SDimitry Andric     LegalizeResult Result =
810*fe6060f1SDimitry Andric         createMemLibcall(MIRBuilder, *MIRBuilder.getMRI(), MI, LocObserver);
811*fe6060f1SDimitry Andric     if (Result != Legalized)
812*fe6060f1SDimitry Andric       return Result;
813e8d8bef9SDimitry Andric     MI.eraseFromParent();
814e8d8bef9SDimitry Andric     return Result;
815e8d8bef9SDimitry Andric   }
8160b57cec5SDimitry Andric   }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   MI.eraseFromParent();
8190b57cec5SDimitry Andric   return Legalized;
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::narrowScalar(MachineInstr &MI,
8230b57cec5SDimitry Andric                                                               unsigned TypeIdx,
8240b57cec5SDimitry Andric                                                               LLT NarrowTy) {
8250b57cec5SDimitry Andric   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
8260b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   switch (MI.getOpcode()) {
8290b57cec5SDimitry Andric   default:
8300b57cec5SDimitry Andric     return UnableToLegalize;
8310b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
8325ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
8335ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
8345ffd83dbSDimitry Andric 
8355ffd83dbSDimitry Andric     // If SizeOp0 is not an exact multiple of NarrowSize, emit
8365ffd83dbSDimitry Andric     // G_ANYEXT(G_IMPLICIT_DEF). Cast result to vector if needed.
8375ffd83dbSDimitry Andric     // FIXME: Although this would also be legal for the general case, it causes
8385ffd83dbSDimitry Andric     //  a lot of regressions in the emitted code (superfluous COPYs, artifact
8395ffd83dbSDimitry Andric     //  combines not being hit). This seems to be a problem related to the
8405ffd83dbSDimitry Andric     //  artifact combiner.
8415ffd83dbSDimitry Andric     if (SizeOp0 % NarrowSize != 0) {
8425ffd83dbSDimitry Andric       LLT ImplicitTy = NarrowTy;
8435ffd83dbSDimitry Andric       if (DstTy.isVector())
844*fe6060f1SDimitry Andric         ImplicitTy = LLT::vector(DstTy.getElementCount(), ImplicitTy);
8455ffd83dbSDimitry Andric 
8465ffd83dbSDimitry Andric       Register ImplicitReg = MIRBuilder.buildUndef(ImplicitTy).getReg(0);
8475ffd83dbSDimitry Andric       MIRBuilder.buildAnyExt(DstReg, ImplicitReg);
8485ffd83dbSDimitry Andric 
8495ffd83dbSDimitry Andric       MI.eraseFromParent();
8505ffd83dbSDimitry Andric       return Legalized;
8515ffd83dbSDimitry Andric     }
8525ffd83dbSDimitry Andric 
8530b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric     SmallVector<Register, 2> DstRegs;
8560b57cec5SDimitry Andric     for (int i = 0; i < NumParts; ++i)
8575ffd83dbSDimitry Andric       DstRegs.push_back(MIRBuilder.buildUndef(NarrowTy).getReg(0));
8580b57cec5SDimitry Andric 
8595ffd83dbSDimitry Andric     if (DstTy.isVector())
8600b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, DstRegs);
8610b57cec5SDimitry Andric     else
8620b57cec5SDimitry Andric       MIRBuilder.buildMerge(DstReg, DstRegs);
8630b57cec5SDimitry Andric     MI.eraseFromParent();
8640b57cec5SDimitry Andric     return Legalized;
8650b57cec5SDimitry Andric   }
8660b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
8670b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
8680b57cec5SDimitry Andric     const APInt &Val = MI.getOperand(1).getCImm()->getValue();
8690b57cec5SDimitry Andric     unsigned TotalSize = Ty.getSizeInBits();
8700b57cec5SDimitry Andric     unsigned NarrowSize = NarrowTy.getSizeInBits();
8710b57cec5SDimitry Andric     int NumParts = TotalSize / NarrowSize;
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric     SmallVector<Register, 4> PartRegs;
8740b57cec5SDimitry Andric     for (int I = 0; I != NumParts; ++I) {
8750b57cec5SDimitry Andric       unsigned Offset = I * NarrowSize;
8760b57cec5SDimitry Andric       auto K = MIRBuilder.buildConstant(NarrowTy,
8770b57cec5SDimitry Andric                                         Val.lshr(Offset).trunc(NarrowSize));
8780b57cec5SDimitry Andric       PartRegs.push_back(K.getReg(0));
8790b57cec5SDimitry Andric     }
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric     LLT LeftoverTy;
8820b57cec5SDimitry Andric     unsigned LeftoverBits = TotalSize - NumParts * NarrowSize;
8830b57cec5SDimitry Andric     SmallVector<Register, 1> LeftoverRegs;
8840b57cec5SDimitry Andric     if (LeftoverBits != 0) {
8850b57cec5SDimitry Andric       LeftoverTy = LLT::scalar(LeftoverBits);
8860b57cec5SDimitry Andric       auto K = MIRBuilder.buildConstant(
8870b57cec5SDimitry Andric         LeftoverTy,
8880b57cec5SDimitry Andric         Val.lshr(NumParts * NarrowSize).trunc(LeftoverBits));
8890b57cec5SDimitry Andric       LeftoverRegs.push_back(K.getReg(0));
8900b57cec5SDimitry Andric     }
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric     insertParts(MI.getOperand(0).getReg(),
8930b57cec5SDimitry Andric                 Ty, NarrowTy, PartRegs, LeftoverTy, LeftoverRegs);
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric     MI.eraseFromParent();
8960b57cec5SDimitry Andric     return Legalized;
8970b57cec5SDimitry Andric   }
8985ffd83dbSDimitry Andric   case TargetOpcode::G_SEXT:
8995ffd83dbSDimitry Andric   case TargetOpcode::G_ZEXT:
9005ffd83dbSDimitry Andric   case TargetOpcode::G_ANYEXT:
9015ffd83dbSDimitry Andric     return narrowScalarExt(MI, TypeIdx, NarrowTy);
9028bcb0991SDimitry Andric   case TargetOpcode::G_TRUNC: {
9038bcb0991SDimitry Andric     if (TypeIdx != 1)
9048bcb0991SDimitry Andric       return UnableToLegalize;
9058bcb0991SDimitry Andric 
9068bcb0991SDimitry Andric     uint64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
9078bcb0991SDimitry Andric     if (NarrowTy.getSizeInBits() * 2 != SizeOp1) {
9088bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Can't narrow trunc to type " << NarrowTy << "\n");
9098bcb0991SDimitry Andric       return UnableToLegalize;
9108bcb0991SDimitry Andric     }
9118bcb0991SDimitry Andric 
9125ffd83dbSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
9135ffd83dbSDimitry Andric     MIRBuilder.buildCopy(MI.getOperand(0), Unmerge.getReg(0));
9148bcb0991SDimitry Andric     MI.eraseFromParent();
9158bcb0991SDimitry Andric     return Legalized;
9168bcb0991SDimitry Andric   }
9178bcb0991SDimitry Andric 
9185ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
9195ffd83dbSDimitry Andric     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
920*fe6060f1SDimitry Andric   case TargetOpcode::G_ADD:
921*fe6060f1SDimitry Andric   case TargetOpcode::G_SUB:
922*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDO:
923*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBO:
924*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
925*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
926*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDO:
927*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBO:
928*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
929*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
930*fe6060f1SDimitry Andric     return narrowScalarAddSub(MI, TypeIdx, NarrowTy);
9310b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
9320b57cec5SDimitry Andric   case TargetOpcode::G_UMULH:
9330b57cec5SDimitry Andric     return narrowScalarMul(MI, NarrowTy);
9340b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
9350b57cec5SDimitry Andric     return narrowScalarExtract(MI, TypeIdx, NarrowTy);
9360b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
9370b57cec5SDimitry Andric     return narrowScalarInsert(MI, TypeIdx, NarrowTy);
9380b57cec5SDimitry Andric   case TargetOpcode::G_LOAD: {
939*fe6060f1SDimitry Andric     auto &LoadMI = cast<GLoad>(MI);
940*fe6060f1SDimitry Andric     Register DstReg = LoadMI.getDstReg();
9410b57cec5SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
9420b57cec5SDimitry Andric     if (DstTy.isVector())
9430b57cec5SDimitry Andric       return UnableToLegalize;
9440b57cec5SDimitry Andric 
945*fe6060f1SDimitry Andric     if (8 * LoadMI.getMemSize() != DstTy.getSizeInBits()) {
9460b57cec5SDimitry Andric       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
947*fe6060f1SDimitry Andric       MIRBuilder.buildLoad(TmpReg, LoadMI.getPointerReg(), LoadMI.getMMO());
9480b57cec5SDimitry Andric       MIRBuilder.buildAnyExt(DstReg, TmpReg);
949*fe6060f1SDimitry Andric       LoadMI.eraseFromParent();
9500b57cec5SDimitry Andric       return Legalized;
9510b57cec5SDimitry Andric     }
9520b57cec5SDimitry Andric 
953*fe6060f1SDimitry Andric     return reduceLoadStoreWidth(LoadMI, TypeIdx, NarrowTy);
9540b57cec5SDimitry Andric   }
9550b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
9560b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD: {
957*fe6060f1SDimitry Andric     auto &LoadMI = cast<GExtLoad>(MI);
958*fe6060f1SDimitry Andric     Register DstReg = LoadMI.getDstReg();
959*fe6060f1SDimitry Andric     Register PtrReg = LoadMI.getPointerReg();
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric     Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
962*fe6060f1SDimitry Andric     auto &MMO = LoadMI.getMMO();
963e8d8bef9SDimitry Andric     unsigned MemSize = MMO.getSizeInBits();
964e8d8bef9SDimitry Andric 
965e8d8bef9SDimitry Andric     if (MemSize == NarrowSize) {
9660b57cec5SDimitry Andric       MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
967e8d8bef9SDimitry Andric     } else if (MemSize < NarrowSize) {
968*fe6060f1SDimitry Andric       MIRBuilder.buildLoadInstr(LoadMI.getOpcode(), TmpReg, PtrReg, MMO);
969e8d8bef9SDimitry Andric     } else if (MemSize > NarrowSize) {
970e8d8bef9SDimitry Andric       // FIXME: Need to split the load.
971e8d8bef9SDimitry Andric       return UnableToLegalize;
9720b57cec5SDimitry Andric     }
9730b57cec5SDimitry Andric 
974*fe6060f1SDimitry Andric     if (isa<GZExtLoad>(LoadMI))
9750b57cec5SDimitry Andric       MIRBuilder.buildZExt(DstReg, TmpReg);
9760b57cec5SDimitry Andric     else
9770b57cec5SDimitry Andric       MIRBuilder.buildSExt(DstReg, TmpReg);
9780b57cec5SDimitry Andric 
979*fe6060f1SDimitry Andric     LoadMI.eraseFromParent();
9800b57cec5SDimitry Andric     return Legalized;
9810b57cec5SDimitry Andric   }
9820b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
983*fe6060f1SDimitry Andric     auto &StoreMI = cast<GStore>(MI);
9840b57cec5SDimitry Andric 
985*fe6060f1SDimitry Andric     Register SrcReg = StoreMI.getValueReg();
9860b57cec5SDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
9870b57cec5SDimitry Andric     if (SrcTy.isVector())
9880b57cec5SDimitry Andric       return UnableToLegalize;
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
9910b57cec5SDimitry Andric     unsigned HandledSize = NumParts * NarrowTy.getSizeInBits();
9920b57cec5SDimitry Andric     unsigned LeftoverBits = SrcTy.getSizeInBits() - HandledSize;
9930b57cec5SDimitry Andric     if (SrcTy.isVector() && LeftoverBits != 0)
9940b57cec5SDimitry Andric       return UnableToLegalize;
9950b57cec5SDimitry Andric 
996*fe6060f1SDimitry Andric     if (8 * StoreMI.getMemSize() != SrcTy.getSizeInBits()) {
9970b57cec5SDimitry Andric       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
9980b57cec5SDimitry Andric       MIRBuilder.buildTrunc(TmpReg, SrcReg);
999*fe6060f1SDimitry Andric       MIRBuilder.buildStore(TmpReg, StoreMI.getPointerReg(), StoreMI.getMMO());
1000*fe6060f1SDimitry Andric       StoreMI.eraseFromParent();
10010b57cec5SDimitry Andric       return Legalized;
10020b57cec5SDimitry Andric     }
10030b57cec5SDimitry Andric 
1004*fe6060f1SDimitry Andric     return reduceLoadStoreWidth(StoreMI, 0, NarrowTy);
10050b57cec5SDimitry Andric   }
10060b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
10070b57cec5SDimitry Andric     return narrowScalarSelect(MI, TypeIdx, NarrowTy);
10080b57cec5SDimitry Andric   case TargetOpcode::G_AND:
10090b57cec5SDimitry Andric   case TargetOpcode::G_OR:
10100b57cec5SDimitry Andric   case TargetOpcode::G_XOR: {
10110b57cec5SDimitry Andric     // Legalize bitwise operation:
10120b57cec5SDimitry Andric     // A = BinOp<Ty> B, C
10130b57cec5SDimitry Andric     // into:
10140b57cec5SDimitry Andric     // B1, ..., BN = G_UNMERGE_VALUES B
10150b57cec5SDimitry Andric     // C1, ..., CN = G_UNMERGE_VALUES C
10160b57cec5SDimitry Andric     // A1 = BinOp<Ty/N> B1, C2
10170b57cec5SDimitry Andric     // ...
10180b57cec5SDimitry Andric     // AN = BinOp<Ty/N> BN, CN
10190b57cec5SDimitry Andric     // A = G_MERGE_VALUES A1, ..., AN
10200b57cec5SDimitry Andric     return narrowScalarBasic(MI, TypeIdx, NarrowTy);
10210b57cec5SDimitry Andric   }
10220b57cec5SDimitry Andric   case TargetOpcode::G_SHL:
10230b57cec5SDimitry Andric   case TargetOpcode::G_LSHR:
10240b57cec5SDimitry Andric   case TargetOpcode::G_ASHR:
10250b57cec5SDimitry Andric     return narrowScalarShift(MI, TypeIdx, NarrowTy);
10260b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
10270b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
10280b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
10290b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
10300b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP:
10315ffd83dbSDimitry Andric     if (TypeIdx == 1)
10325ffd83dbSDimitry Andric       switch (MI.getOpcode()) {
10335ffd83dbSDimitry Andric       case TargetOpcode::G_CTLZ:
10345ffd83dbSDimitry Andric       case TargetOpcode::G_CTLZ_ZERO_UNDEF:
10355ffd83dbSDimitry Andric         return narrowScalarCTLZ(MI, TypeIdx, NarrowTy);
10365ffd83dbSDimitry Andric       case TargetOpcode::G_CTTZ:
10375ffd83dbSDimitry Andric       case TargetOpcode::G_CTTZ_ZERO_UNDEF:
10385ffd83dbSDimitry Andric         return narrowScalarCTTZ(MI, TypeIdx, NarrowTy);
10395ffd83dbSDimitry Andric       case TargetOpcode::G_CTPOP:
10405ffd83dbSDimitry Andric         return narrowScalarCTPOP(MI, TypeIdx, NarrowTy);
10415ffd83dbSDimitry Andric       default:
10425ffd83dbSDimitry Andric         return UnableToLegalize;
10435ffd83dbSDimitry Andric       }
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric     Observer.changingInstr(MI);
10460b57cec5SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
10470b57cec5SDimitry Andric     Observer.changedInstr(MI);
10480b57cec5SDimitry Andric     return Legalized;
10490b57cec5SDimitry Andric   case TargetOpcode::G_INTTOPTR:
10500b57cec5SDimitry Andric     if (TypeIdx != 1)
10510b57cec5SDimitry Andric       return UnableToLegalize;
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric     Observer.changingInstr(MI);
10540b57cec5SDimitry Andric     narrowScalarSrc(MI, NarrowTy, 1);
10550b57cec5SDimitry Andric     Observer.changedInstr(MI);
10560b57cec5SDimitry Andric     return Legalized;
10570b57cec5SDimitry Andric   case TargetOpcode::G_PTRTOINT:
10580b57cec5SDimitry Andric     if (TypeIdx != 0)
10590b57cec5SDimitry Andric       return UnableToLegalize;
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric     Observer.changingInstr(MI);
10620b57cec5SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
10630b57cec5SDimitry Andric     Observer.changedInstr(MI);
10640b57cec5SDimitry Andric     return Legalized;
10650b57cec5SDimitry Andric   case TargetOpcode::G_PHI: {
1066d409305fSDimitry Andric     // FIXME: add support for when SizeOp0 isn't an exact multiple of
1067d409305fSDimitry Andric     // NarrowSize.
1068d409305fSDimitry Andric     if (SizeOp0 % NarrowSize != 0)
1069d409305fSDimitry Andric       return UnableToLegalize;
1070d409305fSDimitry Andric 
10710b57cec5SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
10725ffd83dbSDimitry Andric     SmallVector<Register, 2> DstRegs(NumParts);
10735ffd83dbSDimitry Andric     SmallVector<SmallVector<Register, 2>, 2> SrcRegs(MI.getNumOperands() / 2);
10740b57cec5SDimitry Andric     Observer.changingInstr(MI);
10750b57cec5SDimitry Andric     for (unsigned i = 1; i < MI.getNumOperands(); i += 2) {
10760b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(i + 1).getMBB();
10770b57cec5SDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
10780b57cec5SDimitry Andric       extractParts(MI.getOperand(i).getReg(), NarrowTy, NumParts,
10790b57cec5SDimitry Andric                    SrcRegs[i / 2]);
10800b57cec5SDimitry Andric     }
10810b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
10820b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, MI);
10830b57cec5SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
10840b57cec5SDimitry Andric       DstRegs[i] = MRI.createGenericVirtualRegister(NarrowTy);
10850b57cec5SDimitry Andric       MachineInstrBuilder MIB =
10860b57cec5SDimitry Andric           MIRBuilder.buildInstr(TargetOpcode::G_PHI).addDef(DstRegs[i]);
10870b57cec5SDimitry Andric       for (unsigned j = 1; j < MI.getNumOperands(); j += 2)
10880b57cec5SDimitry Andric         MIB.addUse(SrcRegs[j / 2][i]).add(MI.getOperand(j + 1));
10890b57cec5SDimitry Andric     }
10908bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MBB, MBB.getFirstNonPHI());
10915ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
10920b57cec5SDimitry Andric     Observer.changedInstr(MI);
10930b57cec5SDimitry Andric     MI.eraseFromParent();
10940b57cec5SDimitry Andric     return Legalized;
10950b57cec5SDimitry Andric   }
10960b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
10970b57cec5SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
10980b57cec5SDimitry Andric     if (TypeIdx != 2)
10990b57cec5SDimitry Andric       return UnableToLegalize;
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric     int OpIdx = MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
11020b57cec5SDimitry Andric     Observer.changingInstr(MI);
11030b57cec5SDimitry Andric     narrowScalarSrc(MI, NarrowTy, OpIdx);
11040b57cec5SDimitry Andric     Observer.changedInstr(MI);
11050b57cec5SDimitry Andric     return Legalized;
11060b57cec5SDimitry Andric   }
11070b57cec5SDimitry Andric   case TargetOpcode::G_ICMP: {
1108*fe6060f1SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
1109*fe6060f1SDimitry Andric     LLT SrcTy = MRI.getType(LHS);
1110*fe6060f1SDimitry Andric     uint64_t SrcSize = SrcTy.getSizeInBits();
11110b57cec5SDimitry Andric     CmpInst::Predicate Pred =
11120b57cec5SDimitry Andric         static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
11130b57cec5SDimitry Andric 
1114*fe6060f1SDimitry Andric     // TODO: Handle the non-equality case for weird sizes.
1115*fe6060f1SDimitry Andric     if (NarrowSize * 2 != SrcSize && !ICmpInst::isEquality(Pred))
1116*fe6060f1SDimitry Andric       return UnableToLegalize;
1117*fe6060f1SDimitry Andric 
1118*fe6060f1SDimitry Andric     LLT LeftoverTy; // Example: s88 -> s64 (NarrowTy) + s24 (leftover)
1119*fe6060f1SDimitry Andric     SmallVector<Register, 4> LHSPartRegs, LHSLeftoverRegs;
1120*fe6060f1SDimitry Andric     if (!extractParts(LHS, SrcTy, NarrowTy, LeftoverTy, LHSPartRegs,
1121*fe6060f1SDimitry Andric                       LHSLeftoverRegs))
1122*fe6060f1SDimitry Andric       return UnableToLegalize;
1123*fe6060f1SDimitry Andric 
1124*fe6060f1SDimitry Andric     LLT Unused; // Matches LeftoverTy; G_ICMP LHS and RHS are the same type.
1125*fe6060f1SDimitry Andric     SmallVector<Register, 4> RHSPartRegs, RHSLeftoverRegs;
1126*fe6060f1SDimitry Andric     if (!extractParts(MI.getOperand(3).getReg(), SrcTy, NarrowTy, Unused,
1127*fe6060f1SDimitry Andric                       RHSPartRegs, RHSLeftoverRegs))
1128*fe6060f1SDimitry Andric       return UnableToLegalize;
1129*fe6060f1SDimitry Andric 
1130*fe6060f1SDimitry Andric     // We now have the LHS and RHS of the compare split into narrow-type
1131*fe6060f1SDimitry Andric     // registers, plus potentially some leftover type.
1132*fe6060f1SDimitry Andric     Register Dst = MI.getOperand(0).getReg();
1133*fe6060f1SDimitry Andric     LLT ResTy = MRI.getType(Dst);
1134*fe6060f1SDimitry Andric     if (ICmpInst::isEquality(Pred)) {
1135*fe6060f1SDimitry Andric       // For each part on the LHS and RHS, keep track of the result of XOR-ing
1136*fe6060f1SDimitry Andric       // them together. For each equal part, the result should be all 0s. For
1137*fe6060f1SDimitry Andric       // each non-equal part, we'll get at least one 1.
1138*fe6060f1SDimitry Andric       auto Zero = MIRBuilder.buildConstant(NarrowTy, 0);
1139*fe6060f1SDimitry Andric       SmallVector<Register, 4> Xors;
1140*fe6060f1SDimitry Andric       for (auto LHSAndRHS : zip(LHSPartRegs, RHSPartRegs)) {
1141*fe6060f1SDimitry Andric         auto LHS = std::get<0>(LHSAndRHS);
1142*fe6060f1SDimitry Andric         auto RHS = std::get<1>(LHSAndRHS);
1143*fe6060f1SDimitry Andric         auto Xor = MIRBuilder.buildXor(NarrowTy, LHS, RHS).getReg(0);
1144*fe6060f1SDimitry Andric         Xors.push_back(Xor);
1145*fe6060f1SDimitry Andric       }
1146*fe6060f1SDimitry Andric 
1147*fe6060f1SDimitry Andric       // Build a G_XOR for each leftover register. Each G_XOR must be widened
1148*fe6060f1SDimitry Andric       // to the desired narrow type so that we can OR them together later.
1149*fe6060f1SDimitry Andric       SmallVector<Register, 4> WidenedXors;
1150*fe6060f1SDimitry Andric       for (auto LHSAndRHS : zip(LHSLeftoverRegs, RHSLeftoverRegs)) {
1151*fe6060f1SDimitry Andric         auto LHS = std::get<0>(LHSAndRHS);
1152*fe6060f1SDimitry Andric         auto RHS = std::get<1>(LHSAndRHS);
1153*fe6060f1SDimitry Andric         auto Xor = MIRBuilder.buildXor(LeftoverTy, LHS, RHS).getReg(0);
1154*fe6060f1SDimitry Andric         LLT GCDTy = extractGCDType(WidenedXors, NarrowTy, LeftoverTy, Xor);
1155*fe6060f1SDimitry Andric         buildLCMMergePieces(LeftoverTy, NarrowTy, GCDTy, WidenedXors,
1156*fe6060f1SDimitry Andric                             /* PadStrategy = */ TargetOpcode::G_ZEXT);
1157*fe6060f1SDimitry Andric         Xors.insert(Xors.end(), WidenedXors.begin(), WidenedXors.end());
1158*fe6060f1SDimitry Andric       }
1159*fe6060f1SDimitry Andric 
1160*fe6060f1SDimitry Andric       // Now, for each part we broke up, we know if they are equal/not equal
1161*fe6060f1SDimitry Andric       // based off the G_XOR. We can OR these all together and compare against
1162*fe6060f1SDimitry Andric       // 0 to get the result.
1163*fe6060f1SDimitry Andric       assert(Xors.size() >= 2 && "Should have gotten at least two Xors?");
1164*fe6060f1SDimitry Andric       auto Or = MIRBuilder.buildOr(NarrowTy, Xors[0], Xors[1]);
1165*fe6060f1SDimitry Andric       for (unsigned I = 2, E = Xors.size(); I < E; ++I)
1166*fe6060f1SDimitry Andric         Or = MIRBuilder.buildOr(NarrowTy, Or, Xors[I]);
1167*fe6060f1SDimitry Andric       MIRBuilder.buildICmp(Pred, Dst, Or, Zero);
11680b57cec5SDimitry Andric     } else {
1169*fe6060f1SDimitry Andric       // TODO: Handle non-power-of-two types.
1170*fe6060f1SDimitry Andric       assert(LHSPartRegs.size() == 2 && "Expected exactly 2 LHS part regs?");
1171*fe6060f1SDimitry Andric       assert(RHSPartRegs.size() == 2 && "Expected exactly 2 RHS part regs?");
1172*fe6060f1SDimitry Andric       Register LHSL = LHSPartRegs[0];
1173*fe6060f1SDimitry Andric       Register LHSH = LHSPartRegs[1];
1174*fe6060f1SDimitry Andric       Register RHSL = RHSPartRegs[0];
1175*fe6060f1SDimitry Andric       Register RHSH = RHSPartRegs[1];
11768bcb0991SDimitry Andric       MachineInstrBuilder CmpH = MIRBuilder.buildICmp(Pred, ResTy, LHSH, RHSH);
11770b57cec5SDimitry Andric       MachineInstrBuilder CmpHEQ =
11788bcb0991SDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, ResTy, LHSH, RHSH);
11790b57cec5SDimitry Andric       MachineInstrBuilder CmpLU = MIRBuilder.buildICmp(
11808bcb0991SDimitry Andric           ICmpInst::getUnsignedPredicate(Pred), ResTy, LHSL, RHSL);
1181*fe6060f1SDimitry Andric       MIRBuilder.buildSelect(Dst, CmpHEQ, CmpLU, CmpH);
11820b57cec5SDimitry Andric     }
11830b57cec5SDimitry Andric     MI.eraseFromParent();
11840b57cec5SDimitry Andric     return Legalized;
11850b57cec5SDimitry Andric   }
11868bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
11878bcb0991SDimitry Andric     if (TypeIdx != 0)
11888bcb0991SDimitry Andric       return UnableToLegalize;
11898bcb0991SDimitry Andric 
11908bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
11918bcb0991SDimitry Andric 
11928bcb0991SDimitry Andric     // So long as the new type has more bits than the bits we're extending we
11938bcb0991SDimitry Andric     // don't need to break it apart.
11948bcb0991SDimitry Andric     if (NarrowTy.getScalarSizeInBits() >= SizeInBits) {
11958bcb0991SDimitry Andric       Observer.changingInstr(MI);
11968bcb0991SDimitry Andric       // We don't lose any non-extension bits by truncating the src and
11978bcb0991SDimitry Andric       // sign-extending the dst.
11988bcb0991SDimitry Andric       MachineOperand &MO1 = MI.getOperand(1);
11995ffd83dbSDimitry Andric       auto TruncMIB = MIRBuilder.buildTrunc(NarrowTy, MO1);
12005ffd83dbSDimitry Andric       MO1.setReg(TruncMIB.getReg(0));
12018bcb0991SDimitry Andric 
12028bcb0991SDimitry Andric       MachineOperand &MO2 = MI.getOperand(0);
12038bcb0991SDimitry Andric       Register DstExt = MRI.createGenericVirtualRegister(NarrowTy);
12048bcb0991SDimitry Andric       MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
12055ffd83dbSDimitry Andric       MIRBuilder.buildSExt(MO2, DstExt);
12068bcb0991SDimitry Andric       MO2.setReg(DstExt);
12078bcb0991SDimitry Andric       Observer.changedInstr(MI);
12088bcb0991SDimitry Andric       return Legalized;
12098bcb0991SDimitry Andric     }
12108bcb0991SDimitry Andric 
12118bcb0991SDimitry Andric     // Break it apart. Components below the extension point are unmodified. The
12128bcb0991SDimitry Andric     // component containing the extension point becomes a narrower SEXT_INREG.
12138bcb0991SDimitry Andric     // Components above it are ashr'd from the component containing the
12148bcb0991SDimitry Andric     // extension point.
12158bcb0991SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
12168bcb0991SDimitry Andric       return UnableToLegalize;
12178bcb0991SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
12188bcb0991SDimitry Andric 
12198bcb0991SDimitry Andric     // List the registers where the destination will be scattered.
12208bcb0991SDimitry Andric     SmallVector<Register, 2> DstRegs;
12218bcb0991SDimitry Andric     // List the registers where the source will be split.
12228bcb0991SDimitry Andric     SmallVector<Register, 2> SrcRegs;
12238bcb0991SDimitry Andric 
12248bcb0991SDimitry Andric     // Create all the temporary registers.
12258bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
12268bcb0991SDimitry Andric       Register SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
12278bcb0991SDimitry Andric 
12288bcb0991SDimitry Andric       SrcRegs.push_back(SrcReg);
12298bcb0991SDimitry Andric     }
12308bcb0991SDimitry Andric 
12318bcb0991SDimitry Andric     // Explode the big arguments into smaller chunks.
12325ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge(SrcRegs, MI.getOperand(1));
12338bcb0991SDimitry Andric 
12348bcb0991SDimitry Andric     Register AshrCstReg =
12358bcb0991SDimitry Andric         MIRBuilder.buildConstant(NarrowTy, NarrowTy.getScalarSizeInBits() - 1)
12365ffd83dbSDimitry Andric             .getReg(0);
12378bcb0991SDimitry Andric     Register FullExtensionReg = 0;
12388bcb0991SDimitry Andric     Register PartialExtensionReg = 0;
12398bcb0991SDimitry Andric 
12408bcb0991SDimitry Andric     // Do the operation on each small part.
12418bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
12428bcb0991SDimitry Andric       if ((i + 1) * NarrowTy.getScalarSizeInBits() < SizeInBits)
12438bcb0991SDimitry Andric         DstRegs.push_back(SrcRegs[i]);
12448bcb0991SDimitry Andric       else if (i * NarrowTy.getScalarSizeInBits() > SizeInBits) {
12458bcb0991SDimitry Andric         assert(PartialExtensionReg &&
12468bcb0991SDimitry Andric                "Expected to visit partial extension before full");
12478bcb0991SDimitry Andric         if (FullExtensionReg) {
12488bcb0991SDimitry Andric           DstRegs.push_back(FullExtensionReg);
12498bcb0991SDimitry Andric           continue;
12508bcb0991SDimitry Andric         }
12515ffd83dbSDimitry Andric         DstRegs.push_back(
12525ffd83dbSDimitry Andric             MIRBuilder.buildAShr(NarrowTy, PartialExtensionReg, AshrCstReg)
12535ffd83dbSDimitry Andric                 .getReg(0));
12548bcb0991SDimitry Andric         FullExtensionReg = DstRegs.back();
12558bcb0991SDimitry Andric       } else {
12568bcb0991SDimitry Andric         DstRegs.push_back(
12578bcb0991SDimitry Andric             MIRBuilder
12588bcb0991SDimitry Andric                 .buildInstr(
12598bcb0991SDimitry Andric                     TargetOpcode::G_SEXT_INREG, {NarrowTy},
12608bcb0991SDimitry Andric                     {SrcRegs[i], SizeInBits % NarrowTy.getScalarSizeInBits()})
12615ffd83dbSDimitry Andric                 .getReg(0));
12628bcb0991SDimitry Andric         PartialExtensionReg = DstRegs.back();
12638bcb0991SDimitry Andric       }
12648bcb0991SDimitry Andric     }
12658bcb0991SDimitry Andric 
12668bcb0991SDimitry Andric     // Gather the destination registers into the final destination.
12678bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
12688bcb0991SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
12698bcb0991SDimitry Andric     MI.eraseFromParent();
12708bcb0991SDimitry Andric     return Legalized;
12718bcb0991SDimitry Andric   }
1272480093f4SDimitry Andric   case TargetOpcode::G_BSWAP:
1273480093f4SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
1274480093f4SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
1275480093f4SDimitry Andric       return UnableToLegalize;
1276480093f4SDimitry Andric 
1277480093f4SDimitry Andric     Observer.changingInstr(MI);
1278480093f4SDimitry Andric     SmallVector<Register, 2> SrcRegs, DstRegs;
1279480093f4SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
1280480093f4SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
1281480093f4SDimitry Andric 
1282480093f4SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
1283480093f4SDimitry Andric       auto DstPart = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
1284480093f4SDimitry Andric                                            {SrcRegs[NumParts - 1 - i]});
1285480093f4SDimitry Andric       DstRegs.push_back(DstPart.getReg(0));
1286480093f4SDimitry Andric     }
1287480093f4SDimitry Andric 
12885ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
1289480093f4SDimitry Andric 
1290480093f4SDimitry Andric     Observer.changedInstr(MI);
1291480093f4SDimitry Andric     MI.eraseFromParent();
1292480093f4SDimitry Andric     return Legalized;
1293480093f4SDimitry Andric   }
1294e8d8bef9SDimitry Andric   case TargetOpcode::G_PTR_ADD:
12955ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
12965ffd83dbSDimitry Andric     if (TypeIdx != 1)
12975ffd83dbSDimitry Andric       return UnableToLegalize;
12985ffd83dbSDimitry Andric     Observer.changingInstr(MI);
12995ffd83dbSDimitry Andric     narrowScalarSrc(MI, NarrowTy, 2);
13005ffd83dbSDimitry Andric     Observer.changedInstr(MI);
13015ffd83dbSDimitry Andric     return Legalized;
13020b57cec5SDimitry Andric   }
130323408297SDimitry Andric   case TargetOpcode::G_FPTOUI:
130423408297SDimitry Andric   case TargetOpcode::G_FPTOSI:
130523408297SDimitry Andric     return narrowScalarFPTOI(MI, TypeIdx, NarrowTy);
1306e8d8bef9SDimitry Andric   case TargetOpcode::G_FPEXT:
1307e8d8bef9SDimitry Andric     if (TypeIdx != 0)
1308e8d8bef9SDimitry Andric       return UnableToLegalize;
1309e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
1310e8d8bef9SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_FPEXT);
1311e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
1312e8d8bef9SDimitry Andric     return Legalized;
13130b57cec5SDimitry Andric   }
13145ffd83dbSDimitry Andric }
13155ffd83dbSDimitry Andric 
13165ffd83dbSDimitry Andric Register LegalizerHelper::coerceToScalar(Register Val) {
13175ffd83dbSDimitry Andric   LLT Ty = MRI.getType(Val);
13185ffd83dbSDimitry Andric   if (Ty.isScalar())
13195ffd83dbSDimitry Andric     return Val;
13205ffd83dbSDimitry Andric 
13215ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
13225ffd83dbSDimitry Andric   LLT NewTy = LLT::scalar(Ty.getSizeInBits());
13235ffd83dbSDimitry Andric   if (Ty.isPointer()) {
13245ffd83dbSDimitry Andric     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
13255ffd83dbSDimitry Andric       return Register();
13265ffd83dbSDimitry Andric     return MIRBuilder.buildPtrToInt(NewTy, Val).getReg(0);
13275ffd83dbSDimitry Andric   }
13285ffd83dbSDimitry Andric 
13295ffd83dbSDimitry Andric   Register NewVal = Val;
13305ffd83dbSDimitry Andric 
13315ffd83dbSDimitry Andric   assert(Ty.isVector());
13325ffd83dbSDimitry Andric   LLT EltTy = Ty.getElementType();
13335ffd83dbSDimitry Andric   if (EltTy.isPointer())
13345ffd83dbSDimitry Andric     NewVal = MIRBuilder.buildPtrToInt(NewTy, NewVal).getReg(0);
13355ffd83dbSDimitry Andric   return MIRBuilder.buildBitcast(NewTy, NewVal).getReg(0);
13365ffd83dbSDimitry Andric }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric void LegalizerHelper::widenScalarSrc(MachineInstr &MI, LLT WideTy,
13390b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned ExtOpcode) {
13400b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13415ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MO});
13425ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
13430b57cec5SDimitry Andric }
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric void LegalizerHelper::narrowScalarSrc(MachineInstr &MI, LLT NarrowTy,
13460b57cec5SDimitry Andric                                       unsigned OpIdx) {
13470b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13485ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildTrunc(NarrowTy, MO);
13495ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
13500b57cec5SDimitry Andric }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric void LegalizerHelper::widenScalarDst(MachineInstr &MI, LLT WideTy,
13530b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned TruncOpcode) {
13540b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13550b57cec5SDimitry Andric   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
13560b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13575ffd83dbSDimitry Andric   MIRBuilder.buildInstr(TruncOpcode, {MO}, {DstExt});
13580b57cec5SDimitry Andric   MO.setReg(DstExt);
13590b57cec5SDimitry Andric }
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric void LegalizerHelper::narrowScalarDst(MachineInstr &MI, LLT NarrowTy,
13620b57cec5SDimitry Andric                                       unsigned OpIdx, unsigned ExtOpcode) {
13630b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13640b57cec5SDimitry Andric   Register DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
13650b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13665ffd83dbSDimitry Andric   MIRBuilder.buildInstr(ExtOpcode, {MO}, {DstTrunc});
13670b57cec5SDimitry Andric   MO.setReg(DstTrunc);
13680b57cec5SDimitry Andric }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorDst(MachineInstr &MI, LLT WideTy,
13710b57cec5SDimitry Andric                                             unsigned OpIdx) {
13720b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13730b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1374e8d8bef9SDimitry Andric   MO.setReg(widenWithUnmerge(WideTy, MO.getReg()));
13750b57cec5SDimitry Andric }
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorSrc(MachineInstr &MI, LLT MoreTy,
13780b57cec5SDimitry Andric                                             unsigned OpIdx) {
13790b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric   LLT OldTy = MRI.getType(MO.getReg());
13820b57cec5SDimitry Andric   unsigned OldElts = OldTy.getNumElements();
13830b57cec5SDimitry Andric   unsigned NewElts = MoreTy.getNumElements();
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   unsigned NumParts = NewElts / OldElts;
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric   // Use concat_vectors if the result is a multiple of the number of elements.
13880b57cec5SDimitry Andric   if (NumParts * OldElts == NewElts) {
13890b57cec5SDimitry Andric     SmallVector<Register, 8> Parts;
13900b57cec5SDimitry Andric     Parts.push_back(MO.getReg());
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric     Register ImpDef = MIRBuilder.buildUndef(OldTy).getReg(0);
13930b57cec5SDimitry Andric     for (unsigned I = 1; I != NumParts; ++I)
13940b57cec5SDimitry Andric       Parts.push_back(ImpDef);
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric     auto Concat = MIRBuilder.buildConcatVectors(MoreTy, Parts);
13970b57cec5SDimitry Andric     MO.setReg(Concat.getReg(0));
13980b57cec5SDimitry Andric     return;
13990b57cec5SDimitry Andric   }
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric   Register MoreReg = MRI.createGenericVirtualRegister(MoreTy);
14020b57cec5SDimitry Andric   Register ImpDef = MIRBuilder.buildUndef(MoreTy).getReg(0);
14030b57cec5SDimitry Andric   MIRBuilder.buildInsert(MoreReg, ImpDef, MO.getReg(), 0);
14040b57cec5SDimitry Andric   MO.setReg(MoreReg);
14050b57cec5SDimitry Andric }
14060b57cec5SDimitry Andric 
14075ffd83dbSDimitry Andric void LegalizerHelper::bitcastSrc(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
14085ffd83dbSDimitry Andric   MachineOperand &Op = MI.getOperand(OpIdx);
14095ffd83dbSDimitry Andric   Op.setReg(MIRBuilder.buildBitcast(CastTy, Op).getReg(0));
14105ffd83dbSDimitry Andric }
14115ffd83dbSDimitry Andric 
14125ffd83dbSDimitry Andric void LegalizerHelper::bitcastDst(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
14135ffd83dbSDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14145ffd83dbSDimitry Andric   Register CastDst = MRI.createGenericVirtualRegister(CastTy);
14155ffd83dbSDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
14165ffd83dbSDimitry Andric   MIRBuilder.buildBitcast(MO, CastDst);
14175ffd83dbSDimitry Andric   MO.setReg(CastDst);
14185ffd83dbSDimitry Andric }
14195ffd83dbSDimitry Andric 
14200b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
14210b57cec5SDimitry Andric LegalizerHelper::widenScalarMergeValues(MachineInstr &MI, unsigned TypeIdx,
14220b57cec5SDimitry Andric                                         LLT WideTy) {
14230b57cec5SDimitry Andric   if (TypeIdx != 1)
14240b57cec5SDimitry Andric     return UnableToLegalize;
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
14270b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
14280b57cec5SDimitry Andric   if (DstTy.isVector())
14290b57cec5SDimitry Andric     return UnableToLegalize;
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
14320b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src1);
14330b57cec5SDimitry Andric   const int DstSize = DstTy.getSizeInBits();
14340b57cec5SDimitry Andric   const int SrcSize = SrcTy.getSizeInBits();
14350b57cec5SDimitry Andric   const int WideSize = WideTy.getSizeInBits();
14360b57cec5SDimitry Andric   const int NumMerge = (DstSize + WideSize - 1) / WideSize;
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   unsigned NumOps = MI.getNumOperands();
14390b57cec5SDimitry Andric   unsigned NumSrc = MI.getNumOperands() - 1;
14400b57cec5SDimitry Andric   unsigned PartSize = DstTy.getSizeInBits() / NumSrc;
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric   if (WideSize >= DstSize) {
14430b57cec5SDimitry Andric     // Directly pack the bits in the target type.
14440b57cec5SDimitry Andric     Register ResultReg = MIRBuilder.buildZExt(WideTy, Src1).getReg(0);
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric     for (unsigned I = 2; I != NumOps; ++I) {
14470b57cec5SDimitry Andric       const unsigned Offset = (I - 1) * PartSize;
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric       Register SrcReg = MI.getOperand(I).getReg();
14500b57cec5SDimitry Andric       assert(MRI.getType(SrcReg) == LLT::scalar(PartSize));
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric       auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
14530b57cec5SDimitry Andric 
14548bcb0991SDimitry Andric       Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
14550b57cec5SDimitry Andric         MRI.createGenericVirtualRegister(WideTy);
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
14580b57cec5SDimitry Andric       auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
14590b57cec5SDimitry Andric       MIRBuilder.buildOr(NextResult, ResultReg, Shl);
14600b57cec5SDimitry Andric       ResultReg = NextResult;
14610b57cec5SDimitry Andric     }
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric     if (WideSize > DstSize)
14640b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg, ResultReg);
14658bcb0991SDimitry Andric     else if (DstTy.isPointer())
14668bcb0991SDimitry Andric       MIRBuilder.buildIntToPtr(DstReg, ResultReg);
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric     MI.eraseFromParent();
14690b57cec5SDimitry Andric     return Legalized;
14700b57cec5SDimitry Andric   }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   // Unmerge the original values to the GCD type, and recombine to the next
14730b57cec5SDimitry Andric   // multiple greater than the original type.
14740b57cec5SDimitry Andric   //
14750b57cec5SDimitry Andric   // %3:_(s12) = G_MERGE_VALUES %0:_(s4), %1:_(s4), %2:_(s4) -> s6
14760b57cec5SDimitry Andric   // %4:_(s2), %5:_(s2) = G_UNMERGE_VALUES %0
14770b57cec5SDimitry Andric   // %6:_(s2), %7:_(s2) = G_UNMERGE_VALUES %1
14780b57cec5SDimitry Andric   // %8:_(s2), %9:_(s2) = G_UNMERGE_VALUES %2
14790b57cec5SDimitry Andric   // %10:_(s6) = G_MERGE_VALUES %4, %5, %6
14800b57cec5SDimitry Andric   // %11:_(s6) = G_MERGE_VALUES %7, %8, %9
14810b57cec5SDimitry Andric   // %12:_(s12) = G_MERGE_VALUES %10, %11
14820b57cec5SDimitry Andric   //
14830b57cec5SDimitry Andric   // Padding with undef if necessary:
14840b57cec5SDimitry Andric   //
14850b57cec5SDimitry Andric   // %2:_(s8) = G_MERGE_VALUES %0:_(s4), %1:_(s4) -> s6
14860b57cec5SDimitry Andric   // %3:_(s2), %4:_(s2) = G_UNMERGE_VALUES %0
14870b57cec5SDimitry Andric   // %5:_(s2), %6:_(s2) = G_UNMERGE_VALUES %1
14880b57cec5SDimitry Andric   // %7:_(s2) = G_IMPLICIT_DEF
14890b57cec5SDimitry Andric   // %8:_(s6) = G_MERGE_VALUES %3, %4, %5
14900b57cec5SDimitry Andric   // %9:_(s6) = G_MERGE_VALUES %6, %7, %7
14910b57cec5SDimitry Andric   // %10:_(s12) = G_MERGE_VALUES %8, %9
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric   const int GCD = greatestCommonDivisor(SrcSize, WideSize);
14940b57cec5SDimitry Andric   LLT GCDTy = LLT::scalar(GCD);
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric   SmallVector<Register, 8> Parts;
14970b57cec5SDimitry Andric   SmallVector<Register, 8> NewMergeRegs;
14980b57cec5SDimitry Andric   SmallVector<Register, 8> Unmerges;
14990b57cec5SDimitry Andric   LLT WideDstTy = LLT::scalar(NumMerge * WideSize);
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   // Decompose the original operands if they don't evenly divide.
15020b57cec5SDimitry Andric   for (int I = 1, E = MI.getNumOperands(); I != E; ++I) {
15030b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
15040b57cec5SDimitry Andric     if (GCD == SrcSize) {
15050b57cec5SDimitry Andric       Unmerges.push_back(SrcReg);
15060b57cec5SDimitry Andric     } else {
15070b57cec5SDimitry Andric       auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
15080b57cec5SDimitry Andric       for (int J = 0, JE = Unmerge->getNumOperands() - 1; J != JE; ++J)
15090b57cec5SDimitry Andric         Unmerges.push_back(Unmerge.getReg(J));
15100b57cec5SDimitry Andric     }
15110b57cec5SDimitry Andric   }
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric   // Pad with undef to the next size that is a multiple of the requested size.
15140b57cec5SDimitry Andric   if (static_cast<int>(Unmerges.size()) != NumMerge * WideSize) {
15150b57cec5SDimitry Andric     Register UndefReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
15160b57cec5SDimitry Andric     for (int I = Unmerges.size(); I != NumMerge * WideSize; ++I)
15170b57cec5SDimitry Andric       Unmerges.push_back(UndefReg);
15180b57cec5SDimitry Andric   }
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric   const int PartsPerGCD = WideSize / GCD;
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric   // Build merges of each piece.
15230b57cec5SDimitry Andric   ArrayRef<Register> Slicer(Unmerges);
15240b57cec5SDimitry Andric   for (int I = 0; I != NumMerge; ++I, Slicer = Slicer.drop_front(PartsPerGCD)) {
15250b57cec5SDimitry Andric     auto Merge = MIRBuilder.buildMerge(WideTy, Slicer.take_front(PartsPerGCD));
15260b57cec5SDimitry Andric     NewMergeRegs.push_back(Merge.getReg(0));
15270b57cec5SDimitry Andric   }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric   // A truncate may be necessary if the requested type doesn't evenly divide the
15300b57cec5SDimitry Andric   // original result type.
15310b57cec5SDimitry Andric   if (DstTy.getSizeInBits() == WideDstTy.getSizeInBits()) {
15320b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, NewMergeRegs);
15330b57cec5SDimitry Andric   } else {
15340b57cec5SDimitry Andric     auto FinalMerge = MIRBuilder.buildMerge(WideDstTy, NewMergeRegs);
15350b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, FinalMerge.getReg(0));
15360b57cec5SDimitry Andric   }
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric   MI.eraseFromParent();
15390b57cec5SDimitry Andric   return Legalized;
15400b57cec5SDimitry Andric }
15410b57cec5SDimitry Andric 
1542e8d8bef9SDimitry Andric Register LegalizerHelper::widenWithUnmerge(LLT WideTy, Register OrigReg) {
1543e8d8bef9SDimitry Andric   Register WideReg = MRI.createGenericVirtualRegister(WideTy);
1544e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(OrigReg);
1545e8d8bef9SDimitry Andric   LLT LCMTy = getLCMType(WideTy, OrigTy);
1546e8d8bef9SDimitry Andric 
1547e8d8bef9SDimitry Andric   const int NumMergeParts = LCMTy.getSizeInBits() / WideTy.getSizeInBits();
1548e8d8bef9SDimitry Andric   const int NumUnmergeParts = LCMTy.getSizeInBits() / OrigTy.getSizeInBits();
1549e8d8bef9SDimitry Andric 
1550e8d8bef9SDimitry Andric   Register UnmergeSrc = WideReg;
1551e8d8bef9SDimitry Andric 
1552e8d8bef9SDimitry Andric   // Create a merge to the LCM type, padding with undef
1553e8d8bef9SDimitry Andric   // %0:_(<3 x s32>) = G_FOO => <4 x s32>
1554e8d8bef9SDimitry Andric   // =>
1555e8d8bef9SDimitry Andric   // %1:_(<4 x s32>) = G_FOO
1556e8d8bef9SDimitry Andric   // %2:_(<4 x s32>) = G_IMPLICIT_DEF
1557e8d8bef9SDimitry Andric   // %3:_(<12 x s32>) = G_CONCAT_VECTORS %1, %2, %2
1558e8d8bef9SDimitry Andric   // %0:_(<3 x s32>), %4:_, %5:_, %6:_ = G_UNMERGE_VALUES %3
1559e8d8bef9SDimitry Andric   if (NumMergeParts > 1) {
1560e8d8bef9SDimitry Andric     Register Undef = MIRBuilder.buildUndef(WideTy).getReg(0);
1561e8d8bef9SDimitry Andric     SmallVector<Register, 8> MergeParts(NumMergeParts, Undef);
1562e8d8bef9SDimitry Andric     MergeParts[0] = WideReg;
1563e8d8bef9SDimitry Andric     UnmergeSrc = MIRBuilder.buildMerge(LCMTy, MergeParts).getReg(0);
1564e8d8bef9SDimitry Andric   }
1565e8d8bef9SDimitry Andric 
1566e8d8bef9SDimitry Andric   // Unmerge to the original register and pad with dead defs.
1567e8d8bef9SDimitry Andric   SmallVector<Register, 8> UnmergeResults(NumUnmergeParts);
1568e8d8bef9SDimitry Andric   UnmergeResults[0] = OrigReg;
1569e8d8bef9SDimitry Andric   for (int I = 1; I != NumUnmergeParts; ++I)
1570e8d8bef9SDimitry Andric     UnmergeResults[I] = MRI.createGenericVirtualRegister(OrigTy);
1571e8d8bef9SDimitry Andric 
1572e8d8bef9SDimitry Andric   MIRBuilder.buildUnmerge(UnmergeResults, UnmergeSrc);
1573e8d8bef9SDimitry Andric   return WideReg;
1574e8d8bef9SDimitry Andric }
1575e8d8bef9SDimitry Andric 
15760b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
15770b57cec5SDimitry Andric LegalizerHelper::widenScalarUnmergeValues(MachineInstr &MI, unsigned TypeIdx,
15780b57cec5SDimitry Andric                                           LLT WideTy) {
15790b57cec5SDimitry Andric   if (TypeIdx != 0)
15800b57cec5SDimitry Andric     return UnableToLegalize;
15810b57cec5SDimitry Andric 
15825ffd83dbSDimitry Andric   int NumDst = MI.getNumOperands() - 1;
15830b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
15840b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
15855ffd83dbSDimitry Andric   if (SrcTy.isVector())
15860b57cec5SDimitry Andric     return UnableToLegalize;
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
15890b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
15900b57cec5SDimitry Andric   if (!DstTy.isScalar())
15910b57cec5SDimitry Andric     return UnableToLegalize;
15920b57cec5SDimitry Andric 
15935ffd83dbSDimitry Andric   if (WideTy.getSizeInBits() >= SrcTy.getSizeInBits()) {
15945ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
15955ffd83dbSDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
15965ffd83dbSDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace())) {
15975ffd83dbSDimitry Andric         LLVM_DEBUG(
15985ffd83dbSDimitry Andric             dbgs() << "Not casting non-integral address space integer\n");
15995ffd83dbSDimitry Andric         return UnableToLegalize;
16000b57cec5SDimitry Andric       }
16010b57cec5SDimitry Andric 
16025ffd83dbSDimitry Andric       SrcTy = LLT::scalar(SrcTy.getSizeInBits());
16035ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildPtrToInt(SrcTy, SrcReg).getReg(0);
16045ffd83dbSDimitry Andric     }
16050b57cec5SDimitry Andric 
16065ffd83dbSDimitry Andric     // Widen SrcTy to WideTy. This does not affect the result, but since the
16075ffd83dbSDimitry Andric     // user requested this size, it is probably better handled than SrcTy and
16085ffd83dbSDimitry Andric     // should reduce the total number of legalization artifacts
16095ffd83dbSDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
16105ffd83dbSDimitry Andric       SrcTy = WideTy;
16115ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
16125ffd83dbSDimitry Andric     }
16130b57cec5SDimitry Andric 
16145ffd83dbSDimitry Andric     // Theres no unmerge type to target. Directly extract the bits from the
16155ffd83dbSDimitry Andric     // source type
16165ffd83dbSDimitry Andric     unsigned DstSize = DstTy.getSizeInBits();
16170b57cec5SDimitry Andric 
16185ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
16195ffd83dbSDimitry Andric     for (int I = 1; I != NumDst; ++I) {
16205ffd83dbSDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcTy, DstSize * I);
16215ffd83dbSDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcTy, SrcReg, ShiftAmt);
16225ffd83dbSDimitry Andric       MIRBuilder.buildTrunc(MI.getOperand(I), Shr);
16235ffd83dbSDimitry Andric     }
16245ffd83dbSDimitry Andric 
16255ffd83dbSDimitry Andric     MI.eraseFromParent();
16265ffd83dbSDimitry Andric     return Legalized;
16275ffd83dbSDimitry Andric   }
16285ffd83dbSDimitry Andric 
16295ffd83dbSDimitry Andric   // Extend the source to a wider type.
16305ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(SrcTy, WideTy);
16315ffd83dbSDimitry Andric 
16325ffd83dbSDimitry Andric   Register WideSrc = SrcReg;
16335ffd83dbSDimitry Andric   if (LCMTy.getSizeInBits() != SrcTy.getSizeInBits()) {
16345ffd83dbSDimitry Andric     // TODO: If this is an integral address space, cast to integer and anyext.
16355ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
16365ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Widening pointer source types not implemented\n");
16375ffd83dbSDimitry Andric       return UnableToLegalize;
16385ffd83dbSDimitry Andric     }
16395ffd83dbSDimitry Andric 
16405ffd83dbSDimitry Andric     WideSrc = MIRBuilder.buildAnyExt(LCMTy, WideSrc).getReg(0);
16415ffd83dbSDimitry Andric   }
16425ffd83dbSDimitry Andric 
16435ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(WideTy, WideSrc);
16445ffd83dbSDimitry Andric 
1645e8d8bef9SDimitry Andric   // Create a sequence of unmerges and merges to the original results. Since we
1646e8d8bef9SDimitry Andric   // may have widened the source, we will need to pad the results with dead defs
1647e8d8bef9SDimitry Andric   // to cover the source register.
1648e8d8bef9SDimitry Andric   // e.g. widen s48 to s64:
1649e8d8bef9SDimitry Andric   // %1:_(s48), %2:_(s48) = G_UNMERGE_VALUES %0:_(s96)
16505ffd83dbSDimitry Andric   //
16515ffd83dbSDimitry Andric   // =>
1652e8d8bef9SDimitry Andric   //  %4:_(s192) = G_ANYEXT %0:_(s96)
1653e8d8bef9SDimitry Andric   //  %5:_(s64), %6, %7 = G_UNMERGE_VALUES %4 ; Requested unmerge
1654e8d8bef9SDimitry Andric   //  ; unpack to GCD type, with extra dead defs
1655e8d8bef9SDimitry Andric   //  %8:_(s16), %9, %10, %11 = G_UNMERGE_VALUES %5:_(s64)
1656e8d8bef9SDimitry Andric   //  %12:_(s16), %13, dead %14, dead %15 = G_UNMERGE_VALUES %6:_(s64)
1657e8d8bef9SDimitry Andric   //  dead %16:_(s16), dead %17, dead %18, dead %18 = G_UNMERGE_VALUES %7:_(s64)
1658e8d8bef9SDimitry Andric   //  %1:_(s48) = G_MERGE_VALUES %8:_(s16), %9, %10   ; Remerge to destination
1659e8d8bef9SDimitry Andric   //  %2:_(s48) = G_MERGE_VALUES %11:_(s16), %12, %13 ; Remerge to destination
1660e8d8bef9SDimitry Andric   const LLT GCDTy = getGCDType(WideTy, DstTy);
16615ffd83dbSDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
1662e8d8bef9SDimitry Andric   const int PartsPerRemerge = DstTy.getSizeInBits() / GCDTy.getSizeInBits();
1663e8d8bef9SDimitry Andric 
1664e8d8bef9SDimitry Andric   // Directly unmerge to the destination without going through a GCD type
1665e8d8bef9SDimitry Andric   // if possible
1666e8d8bef9SDimitry Andric   if (PartsPerRemerge == 1) {
16675ffd83dbSDimitry Andric     const int PartsPerUnmerge = WideTy.getSizeInBits() / DstTy.getSizeInBits();
16685ffd83dbSDimitry Andric 
16695ffd83dbSDimitry Andric     for (int I = 0; I != NumUnmerge; ++I) {
16705ffd83dbSDimitry Andric       auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
16715ffd83dbSDimitry Andric 
16725ffd83dbSDimitry Andric       for (int J = 0; J != PartsPerUnmerge; ++J) {
16735ffd83dbSDimitry Andric         int Idx = I * PartsPerUnmerge + J;
16745ffd83dbSDimitry Andric         if (Idx < NumDst)
16755ffd83dbSDimitry Andric           MIB.addDef(MI.getOperand(Idx).getReg());
16765ffd83dbSDimitry Andric         else {
16775ffd83dbSDimitry Andric           // Create dead def for excess components.
16785ffd83dbSDimitry Andric           MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
16795ffd83dbSDimitry Andric         }
16805ffd83dbSDimitry Andric       }
16815ffd83dbSDimitry Andric 
16825ffd83dbSDimitry Andric       MIB.addUse(Unmerge.getReg(I));
16835ffd83dbSDimitry Andric     }
1684e8d8bef9SDimitry Andric   } else {
1685e8d8bef9SDimitry Andric     SmallVector<Register, 16> Parts;
1686e8d8bef9SDimitry Andric     for (int J = 0; J != NumUnmerge; ++J)
1687e8d8bef9SDimitry Andric       extractGCDType(Parts, GCDTy, Unmerge.getReg(J));
1688e8d8bef9SDimitry Andric 
1689e8d8bef9SDimitry Andric     SmallVector<Register, 8> RemergeParts;
1690e8d8bef9SDimitry Andric     for (int I = 0; I != NumDst; ++I) {
1691e8d8bef9SDimitry Andric       for (int J = 0; J < PartsPerRemerge; ++J) {
1692e8d8bef9SDimitry Andric         const int Idx = I * PartsPerRemerge + J;
1693e8d8bef9SDimitry Andric         RemergeParts.emplace_back(Parts[Idx]);
1694e8d8bef9SDimitry Andric       }
1695e8d8bef9SDimitry Andric 
1696e8d8bef9SDimitry Andric       MIRBuilder.buildMerge(MI.getOperand(I).getReg(), RemergeParts);
1697e8d8bef9SDimitry Andric       RemergeParts.clear();
1698e8d8bef9SDimitry Andric     }
1699e8d8bef9SDimitry Andric   }
17005ffd83dbSDimitry Andric 
17015ffd83dbSDimitry Andric   MI.eraseFromParent();
17020b57cec5SDimitry Andric   return Legalized;
17030b57cec5SDimitry Andric }
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
17060b57cec5SDimitry Andric LegalizerHelper::widenScalarExtract(MachineInstr &MI, unsigned TypeIdx,
17070b57cec5SDimitry Andric                                     LLT WideTy) {
17080b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
17090b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
17100b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
17130b57cec5SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   if (TypeIdx == 0) {
17160b57cec5SDimitry Andric     if (SrcTy.isVector() || DstTy.isVector())
17170b57cec5SDimitry Andric       return UnableToLegalize;
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric     SrcOp Src(SrcReg);
17200b57cec5SDimitry Andric     if (SrcTy.isPointer()) {
17210b57cec5SDimitry Andric       // Extracts from pointers can be handled only if they are really just
17220b57cec5SDimitry Andric       // simple integers.
17230b57cec5SDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
17240b57cec5SDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace()))
17250b57cec5SDimitry Andric         return UnableToLegalize;
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric       LLT SrcAsIntTy = LLT::scalar(SrcTy.getSizeInBits());
17280b57cec5SDimitry Andric       Src = MIRBuilder.buildPtrToInt(SrcAsIntTy, Src);
17290b57cec5SDimitry Andric       SrcTy = SrcAsIntTy;
17300b57cec5SDimitry Andric     }
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric     if (DstTy.isPointer())
17330b57cec5SDimitry Andric       return UnableToLegalize;
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric     if (Offset == 0) {
17360b57cec5SDimitry Andric       // Avoid a shift in the degenerate case.
17370b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg,
17380b57cec5SDimitry Andric                             MIRBuilder.buildAnyExtOrTrunc(WideTy, Src));
17390b57cec5SDimitry Andric       MI.eraseFromParent();
17400b57cec5SDimitry Andric       return Legalized;
17410b57cec5SDimitry Andric     }
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric     // Do a shift in the source type.
17440b57cec5SDimitry Andric     LLT ShiftTy = SrcTy;
17450b57cec5SDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
17460b57cec5SDimitry Andric       Src = MIRBuilder.buildAnyExt(WideTy, Src);
17470b57cec5SDimitry Andric       ShiftTy = WideTy;
1748e8d8bef9SDimitry Andric     }
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric     auto LShr = MIRBuilder.buildLShr(
17510b57cec5SDimitry Andric       ShiftTy, Src, MIRBuilder.buildConstant(ShiftTy, Offset));
17520b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, LShr);
17530b57cec5SDimitry Andric     MI.eraseFromParent();
17540b57cec5SDimitry Andric     return Legalized;
17550b57cec5SDimitry Andric   }
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   if (SrcTy.isScalar()) {
17580b57cec5SDimitry Andric     Observer.changingInstr(MI);
17590b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17600b57cec5SDimitry Andric     Observer.changedInstr(MI);
17610b57cec5SDimitry Andric     return Legalized;
17620b57cec5SDimitry Andric   }
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric   if (!SrcTy.isVector())
17650b57cec5SDimitry Andric     return UnableToLegalize;
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   if (DstTy != SrcTy.getElementType())
17680b57cec5SDimitry Andric     return UnableToLegalize;
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   if (Offset % SrcTy.getScalarSizeInBits() != 0)
17710b57cec5SDimitry Andric     return UnableToLegalize;
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   Observer.changingInstr(MI);
17740b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric   MI.getOperand(2).setImm((WideTy.getSizeInBits() / SrcTy.getSizeInBits()) *
17770b57cec5SDimitry Andric                           Offset);
17780b57cec5SDimitry Andric   widenScalarDst(MI, WideTy.getScalarType(), 0);
17790b57cec5SDimitry Andric   Observer.changedInstr(MI);
17800b57cec5SDimitry Andric   return Legalized;
17810b57cec5SDimitry Andric }
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
17840b57cec5SDimitry Andric LegalizerHelper::widenScalarInsert(MachineInstr &MI, unsigned TypeIdx,
17850b57cec5SDimitry Andric                                    LLT WideTy) {
1786e8d8bef9SDimitry Andric   if (TypeIdx != 0 || WideTy.isVector())
17870b57cec5SDimitry Andric     return UnableToLegalize;
17880b57cec5SDimitry Andric   Observer.changingInstr(MI);
17890b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17900b57cec5SDimitry Andric   widenScalarDst(MI, WideTy);
17910b57cec5SDimitry Andric   Observer.changedInstr(MI);
17920b57cec5SDimitry Andric   return Legalized;
17930b57cec5SDimitry Andric }
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
1796*fe6060f1SDimitry Andric LegalizerHelper::widenScalarAddSubOverflow(MachineInstr &MI, unsigned TypeIdx,
1797e8d8bef9SDimitry Andric                                            LLT WideTy) {
1798e8d8bef9SDimitry Andric   if (TypeIdx == 1)
1799e8d8bef9SDimitry Andric     return UnableToLegalize; // TODO
1800*fe6060f1SDimitry Andric 
1801*fe6060f1SDimitry Andric   unsigned Opcode;
1802*fe6060f1SDimitry Andric   unsigned ExtOpcode;
1803*fe6060f1SDimitry Andric   Optional<Register> CarryIn = None;
1804*fe6060f1SDimitry Andric   switch (MI.getOpcode()) {
1805*fe6060f1SDimitry Andric   default:
1806*fe6060f1SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1807*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDO:
1808*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_ADD;
1809*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1810*fe6060f1SDimitry Andric     break;
1811*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBO:
1812*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_SUB;
1813*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1814*fe6060f1SDimitry Andric     break;
1815*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDO:
1816*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_ADD;
1817*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1818*fe6060f1SDimitry Andric     break;
1819*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBO:
1820*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_SUB;
1821*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1822*fe6060f1SDimitry Andric     break;
1823*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
1824*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_UADDE;
1825*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1826*fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1827*fe6060f1SDimitry Andric     break;
1828*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
1829*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_USUBE;
1830*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1831*fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1832*fe6060f1SDimitry Andric     break;
1833*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
1834*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_UADDE;
1835*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1836*fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1837*fe6060f1SDimitry Andric     break;
1838*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
1839*fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_USUBE;
1840*fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1841*fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1842*fe6060f1SDimitry Andric     break;
1843*fe6060f1SDimitry Andric   }
1844*fe6060f1SDimitry Andric 
1845e8d8bef9SDimitry Andric   auto LHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(2)});
1846e8d8bef9SDimitry Andric   auto RHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(3)});
1847e8d8bef9SDimitry Andric   // Do the arithmetic in the larger type.
1848*fe6060f1SDimitry Andric   Register NewOp;
1849*fe6060f1SDimitry Andric   if (CarryIn) {
1850*fe6060f1SDimitry Andric     LLT CarryOutTy = MRI.getType(MI.getOperand(1).getReg());
1851*fe6060f1SDimitry Andric     NewOp = MIRBuilder
1852*fe6060f1SDimitry Andric                 .buildInstr(Opcode, {WideTy, CarryOutTy},
1853*fe6060f1SDimitry Andric                             {LHSExt, RHSExt, *CarryIn})
1854*fe6060f1SDimitry Andric                 .getReg(0);
1855*fe6060f1SDimitry Andric   } else {
1856*fe6060f1SDimitry Andric     NewOp = MIRBuilder.buildInstr(Opcode, {WideTy}, {LHSExt, RHSExt}).getReg(0);
1857*fe6060f1SDimitry Andric   }
1858e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(MI.getOperand(0).getReg());
1859e8d8bef9SDimitry Andric   auto TruncOp = MIRBuilder.buildTrunc(OrigTy, NewOp);
1860e8d8bef9SDimitry Andric   auto ExtOp = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {TruncOp});
1861e8d8bef9SDimitry Andric   // There is no overflow if the ExtOp is the same as NewOp.
1862e8d8bef9SDimitry Andric   MIRBuilder.buildICmp(CmpInst::ICMP_NE, MI.getOperand(1), NewOp, ExtOp);
1863e8d8bef9SDimitry Andric   // Now trunc the NewOp to the original result.
1864e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(MI.getOperand(0), NewOp);
1865e8d8bef9SDimitry Andric   MI.eraseFromParent();
1866e8d8bef9SDimitry Andric   return Legalized;
1867e8d8bef9SDimitry Andric }
1868e8d8bef9SDimitry Andric 
1869e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
1870e8d8bef9SDimitry Andric LegalizerHelper::widenScalarAddSubShlSat(MachineInstr &MI, unsigned TypeIdx,
18715ffd83dbSDimitry Andric                                          LLT WideTy) {
18725ffd83dbSDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SADDSAT ||
1873e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSUBSAT ||
1874e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSHLSAT;
1875e8d8bef9SDimitry Andric   bool IsShift = MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
1876e8d8bef9SDimitry Andric                  MI.getOpcode() == TargetOpcode::G_USHLSAT;
18775ffd83dbSDimitry Andric   // We can convert this to:
18785ffd83dbSDimitry Andric   //   1. Any extend iN to iM
18795ffd83dbSDimitry Andric   //   2. SHL by M-N
1880e8d8bef9SDimitry Andric   //   3. [US][ADD|SUB|SHL]SAT
18815ffd83dbSDimitry Andric   //   4. L/ASHR by M-N
18825ffd83dbSDimitry Andric   //
18835ffd83dbSDimitry Andric   // It may be more efficient to lower this to a min and a max operation in
18845ffd83dbSDimitry Andric   // the higher precision arithmetic if the promoted operation isn't legal,
18855ffd83dbSDimitry Andric   // but this decision is up to the target's lowering request.
18865ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
18870b57cec5SDimitry Andric 
18885ffd83dbSDimitry Andric   unsigned NewBits = WideTy.getScalarSizeInBits();
18895ffd83dbSDimitry Andric   unsigned SHLAmount = NewBits - MRI.getType(DstReg).getScalarSizeInBits();
18905ffd83dbSDimitry Andric 
1891e8d8bef9SDimitry Andric   // Shifts must zero-extend the RHS to preserve the unsigned quantity, and
1892e8d8bef9SDimitry Andric   // must not left shift the RHS to preserve the shift amount.
18935ffd83dbSDimitry Andric   auto LHS = MIRBuilder.buildAnyExt(WideTy, MI.getOperand(1));
1894e8d8bef9SDimitry Andric   auto RHS = IsShift ? MIRBuilder.buildZExt(WideTy, MI.getOperand(2))
1895e8d8bef9SDimitry Andric                      : MIRBuilder.buildAnyExt(WideTy, MI.getOperand(2));
18965ffd83dbSDimitry Andric   auto ShiftK = MIRBuilder.buildConstant(WideTy, SHLAmount);
18975ffd83dbSDimitry Andric   auto ShiftL = MIRBuilder.buildShl(WideTy, LHS, ShiftK);
1898e8d8bef9SDimitry Andric   auto ShiftR = IsShift ? RHS : MIRBuilder.buildShl(WideTy, RHS, ShiftK);
18995ffd83dbSDimitry Andric 
19005ffd83dbSDimitry Andric   auto WideInst = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy},
19015ffd83dbSDimitry Andric                                         {ShiftL, ShiftR}, MI.getFlags());
19025ffd83dbSDimitry Andric 
19035ffd83dbSDimitry Andric   // Use a shift that will preserve the number of sign bits when the trunc is
19045ffd83dbSDimitry Andric   // folded away.
19055ffd83dbSDimitry Andric   auto Result = IsSigned ? MIRBuilder.buildAShr(WideTy, WideInst, ShiftK)
19065ffd83dbSDimitry Andric                          : MIRBuilder.buildLShr(WideTy, WideInst, ShiftK);
19075ffd83dbSDimitry Andric 
19085ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(DstReg, Result);
19095ffd83dbSDimitry Andric   MI.eraseFromParent();
19105ffd83dbSDimitry Andric   return Legalized;
19115ffd83dbSDimitry Andric }
19125ffd83dbSDimitry Andric 
19135ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
1914*fe6060f1SDimitry Andric LegalizerHelper::widenScalarMulo(MachineInstr &MI, unsigned TypeIdx,
1915*fe6060f1SDimitry Andric                                  LLT WideTy) {
1916*fe6060f1SDimitry Andric   if (TypeIdx == 1)
1917*fe6060f1SDimitry Andric     return UnableToLegalize;
1918*fe6060f1SDimitry Andric 
1919*fe6060f1SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SMULO;
1920*fe6060f1SDimitry Andric   Register Result = MI.getOperand(0).getReg();
1921*fe6060f1SDimitry Andric   Register OriginalOverflow = MI.getOperand(1).getReg();
1922*fe6060f1SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
1923*fe6060f1SDimitry Andric   Register RHS = MI.getOperand(3).getReg();
1924*fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(LHS);
1925*fe6060f1SDimitry Andric   LLT OverflowTy = MRI.getType(OriginalOverflow);
1926*fe6060f1SDimitry Andric   unsigned SrcBitWidth = SrcTy.getScalarSizeInBits();
1927*fe6060f1SDimitry Andric 
1928*fe6060f1SDimitry Andric   // To determine if the result overflowed in the larger type, we extend the
1929*fe6060f1SDimitry Andric   // input to the larger type, do the multiply (checking if it overflows),
1930*fe6060f1SDimitry Andric   // then also check the high bits of the result to see if overflow happened
1931*fe6060f1SDimitry Andric   // there.
1932*fe6060f1SDimitry Andric   unsigned ExtOp = IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
1933*fe6060f1SDimitry Andric   auto LeftOperand = MIRBuilder.buildInstr(ExtOp, {WideTy}, {LHS});
1934*fe6060f1SDimitry Andric   auto RightOperand = MIRBuilder.buildInstr(ExtOp, {WideTy}, {RHS});
1935*fe6060f1SDimitry Andric 
1936*fe6060f1SDimitry Andric   auto Mulo = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy, OverflowTy},
1937*fe6060f1SDimitry Andric                                     {LeftOperand, RightOperand});
1938*fe6060f1SDimitry Andric   auto Mul = Mulo->getOperand(0);
1939*fe6060f1SDimitry Andric   MIRBuilder.buildTrunc(Result, Mul);
1940*fe6060f1SDimitry Andric 
1941*fe6060f1SDimitry Andric   MachineInstrBuilder ExtResult;
1942*fe6060f1SDimitry Andric   // Overflow occurred if it occurred in the larger type, or if the high part
1943*fe6060f1SDimitry Andric   // of the result does not zero/sign-extend the low part.  Check this second
1944*fe6060f1SDimitry Andric   // possibility first.
1945*fe6060f1SDimitry Andric   if (IsSigned) {
1946*fe6060f1SDimitry Andric     // For signed, overflow occurred when the high part does not sign-extend
1947*fe6060f1SDimitry Andric     // the low part.
1948*fe6060f1SDimitry Andric     ExtResult = MIRBuilder.buildSExtInReg(WideTy, Mul, SrcBitWidth);
1949*fe6060f1SDimitry Andric   } else {
1950*fe6060f1SDimitry Andric     // Unsigned overflow occurred when the high part does not zero-extend the
1951*fe6060f1SDimitry Andric     // low part.
1952*fe6060f1SDimitry Andric     ExtResult = MIRBuilder.buildZExtInReg(WideTy, Mul, SrcBitWidth);
1953*fe6060f1SDimitry Andric   }
1954*fe6060f1SDimitry Andric 
1955*fe6060f1SDimitry Andric   // Multiplication cannot overflow if the WideTy is >= 2 * original width,
1956*fe6060f1SDimitry Andric   // so we don't need to check the overflow result of larger type Mulo.
1957*fe6060f1SDimitry Andric   if (WideTy.getScalarSizeInBits() < 2 * SrcBitWidth) {
1958*fe6060f1SDimitry Andric     auto Overflow =
1959*fe6060f1SDimitry Andric         MIRBuilder.buildICmp(CmpInst::ICMP_NE, OverflowTy, Mul, ExtResult);
1960*fe6060f1SDimitry Andric     // Finally check if the multiplication in the larger type itself overflowed.
1961*fe6060f1SDimitry Andric     MIRBuilder.buildOr(OriginalOverflow, Mulo->getOperand(1), Overflow);
1962*fe6060f1SDimitry Andric   } else {
1963*fe6060f1SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_NE, OriginalOverflow, Mul, ExtResult);
1964*fe6060f1SDimitry Andric   }
1965*fe6060f1SDimitry Andric   MI.eraseFromParent();
1966*fe6060f1SDimitry Andric   return Legalized;
1967*fe6060f1SDimitry Andric }
1968*fe6060f1SDimitry Andric 
1969*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
19705ffd83dbSDimitry Andric LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
19710b57cec5SDimitry Andric   switch (MI.getOpcode()) {
19720b57cec5SDimitry Andric   default:
19730b57cec5SDimitry Andric     return UnableToLegalize;
1974*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_XCHG:
1975*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_ADD:
1976*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_SUB:
1977*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_AND:
1978*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_OR:
1979*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_XOR:
1980*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_MIN:
1981*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_MAX:
1982*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_UMIN:
1983*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_UMAX:
1984*fe6060f1SDimitry Andric     assert(TypeIdx == 0 && "atomicrmw with second scalar type");
1985*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
1986*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
1987*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 0);
1988*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
1989*fe6060f1SDimitry Andric     return Legalized;
1990*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG:
1991*fe6060f1SDimitry Andric     assert(TypeIdx == 0 && "G_ATOMIC_CMPXCHG with second scalar type");
1992*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
1993*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
1994*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
1995*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 0);
1996*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
1997*fe6060f1SDimitry Andric     return Legalized;
1998*fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS:
1999*fe6060f1SDimitry Andric     if (TypeIdx == 0) {
2000*fe6060f1SDimitry Andric       Observer.changingInstr(MI);
2001*fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
2002*fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 4, TargetOpcode::G_ANYEXT);
2003*fe6060f1SDimitry Andric       widenScalarDst(MI, WideTy, 0);
2004*fe6060f1SDimitry Andric       Observer.changedInstr(MI);
2005*fe6060f1SDimitry Andric       return Legalized;
2006*fe6060f1SDimitry Andric     }
2007*fe6060f1SDimitry Andric     assert(TypeIdx == 1 &&
2008*fe6060f1SDimitry Andric            "G_ATOMIC_CMPXCHG_WITH_SUCCESS with third scalar type");
2009*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2010*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 1);
2011*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2012*fe6060f1SDimitry Andric     return Legalized;
20130b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
20140b57cec5SDimitry Andric     return widenScalarExtract(MI, TypeIdx, WideTy);
20150b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
20160b57cec5SDimitry Andric     return widenScalarInsert(MI, TypeIdx, WideTy);
20170b57cec5SDimitry Andric   case TargetOpcode::G_MERGE_VALUES:
20180b57cec5SDimitry Andric     return widenScalarMergeValues(MI, TypeIdx, WideTy);
20190b57cec5SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES:
20200b57cec5SDimitry Andric     return widenScalarUnmergeValues(MI, TypeIdx, WideTy);
2021e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
2022e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
20230b57cec5SDimitry Andric   case TargetOpcode::G_UADDO:
2024e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBO:
2025*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
2026*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
2027*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
2028*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
2029*fe6060f1SDimitry Andric     return widenScalarAddSubOverflow(MI, TypeIdx, WideTy);
2030*fe6060f1SDimitry Andric   case TargetOpcode::G_UMULO:
2031*fe6060f1SDimitry Andric   case TargetOpcode::G_SMULO:
2032*fe6060f1SDimitry Andric     return widenScalarMulo(MI, TypeIdx, WideTy);
20335ffd83dbSDimitry Andric   case TargetOpcode::G_SADDSAT:
20345ffd83dbSDimitry Andric   case TargetOpcode::G_SSUBSAT:
2035e8d8bef9SDimitry Andric   case TargetOpcode::G_SSHLSAT:
20365ffd83dbSDimitry Andric   case TargetOpcode::G_UADDSAT:
20375ffd83dbSDimitry Andric   case TargetOpcode::G_USUBSAT:
2038e8d8bef9SDimitry Andric   case TargetOpcode::G_USHLSAT:
2039e8d8bef9SDimitry Andric     return widenScalarAddSubShlSat(MI, TypeIdx, WideTy);
20400b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
20410b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
20420b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
20430b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
20440b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP: {
20450b57cec5SDimitry Andric     if (TypeIdx == 0) {
20460b57cec5SDimitry Andric       Observer.changingInstr(MI);
20470b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
20480b57cec5SDimitry Andric       Observer.changedInstr(MI);
20490b57cec5SDimitry Andric       return Legalized;
20500b57cec5SDimitry Andric     }
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
20530b57cec5SDimitry Andric 
20540b57cec5SDimitry Andric     // First ZEXT the input.
20550b57cec5SDimitry Andric     auto MIBSrc = MIRBuilder.buildZExt(WideTy, SrcReg);
20560b57cec5SDimitry Andric     LLT CurTy = MRI.getType(SrcReg);
20570b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTTZ) {
20580b57cec5SDimitry Andric       // The count is the same in the larger type except if the original
20590b57cec5SDimitry Andric       // value was zero.  This can be handled by setting the bit just off
20600b57cec5SDimitry Andric       // the top of the original type.
20610b57cec5SDimitry Andric       auto TopBit =
20620b57cec5SDimitry Andric           APInt::getOneBitSet(WideTy.getSizeInBits(), CurTy.getSizeInBits());
20630b57cec5SDimitry Andric       MIBSrc = MIRBuilder.buildOr(
20640b57cec5SDimitry Andric         WideTy, MIBSrc, MIRBuilder.buildConstant(WideTy, TopBit));
20650b57cec5SDimitry Andric     }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric     // Perform the operation at the larger size.
20680b57cec5SDimitry Andric     auto MIBNewOp = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy}, {MIBSrc});
20690b57cec5SDimitry Andric     // This is already the correct result for CTPOP and CTTZs
20700b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTLZ ||
20710b57cec5SDimitry Andric         MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF) {
20720b57cec5SDimitry Andric       // The correct result is NewOp - (Difference in widety and current ty).
20730b57cec5SDimitry Andric       unsigned SizeDiff = WideTy.getSizeInBits() - CurTy.getSizeInBits();
20745ffd83dbSDimitry Andric       MIBNewOp = MIRBuilder.buildSub(
20755ffd83dbSDimitry Andric           WideTy, MIBNewOp, MIRBuilder.buildConstant(WideTy, SizeDiff));
20760b57cec5SDimitry Andric     }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric     MIRBuilder.buildZExtOrTrunc(MI.getOperand(0), MIBNewOp);
20790b57cec5SDimitry Andric     MI.eraseFromParent();
20800b57cec5SDimitry Andric     return Legalized;
20810b57cec5SDimitry Andric   }
20820b57cec5SDimitry Andric   case TargetOpcode::G_BSWAP: {
20830b57cec5SDimitry Andric     Observer.changingInstr(MI);
20840b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric     Register ShrReg = MRI.createGenericVirtualRegister(WideTy);
20870b57cec5SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
20880b57cec5SDimitry Andric     Register ShiftAmtReg = MRI.createGenericVirtualRegister(WideTy);
20890b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric     MI.getOperand(0).setReg(DstExt);
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     LLT Ty = MRI.getType(DstReg);
20960b57cec5SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
20970b57cec5SDimitry Andric     MIRBuilder.buildConstant(ShiftAmtReg, DiffBits);
20985ffd83dbSDimitry Andric     MIRBuilder.buildLShr(ShrReg, DstExt, ShiftAmtReg);
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, ShrReg);
21010b57cec5SDimitry Andric     Observer.changedInstr(MI);
21020b57cec5SDimitry Andric     return Legalized;
21030b57cec5SDimitry Andric   }
21048bcb0991SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
21058bcb0991SDimitry Andric     Observer.changingInstr(MI);
21068bcb0991SDimitry Andric 
21078bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
21088bcb0991SDimitry Andric     LLT Ty = MRI.getType(DstReg);
21098bcb0991SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
21108bcb0991SDimitry Andric 
21118bcb0991SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
21128bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21138bcb0991SDimitry Andric     MI.getOperand(0).setReg(DstExt);
21148bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
21158bcb0991SDimitry Andric 
21168bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, DiffBits);
21178bcb0991SDimitry Andric     auto Shift = MIRBuilder.buildLShr(WideTy, DstExt, ShiftAmt);
21188bcb0991SDimitry Andric     MIRBuilder.buildTrunc(DstReg, Shift);
21198bcb0991SDimitry Andric     Observer.changedInstr(MI);
21208bcb0991SDimitry Andric     return Legalized;
21218bcb0991SDimitry Andric   }
21225ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
21235ffd83dbSDimitry Andric     Observer.changingInstr(MI);
21245ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21255ffd83dbSDimitry Andric     widenScalarDst(MI, WideTy);
21265ffd83dbSDimitry Andric     Observer.changedInstr(MI);
21275ffd83dbSDimitry Andric     return Legalized;
21285ffd83dbSDimitry Andric 
2129*fe6060f1SDimitry Andric   case TargetOpcode::G_ABS:
2130*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2131*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
2132*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy);
2133*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2134*fe6060f1SDimitry Andric     return Legalized;
2135*fe6060f1SDimitry Andric 
21360b57cec5SDimitry Andric   case TargetOpcode::G_ADD:
21370b57cec5SDimitry Andric   case TargetOpcode::G_AND:
21380b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
21390b57cec5SDimitry Andric   case TargetOpcode::G_OR:
21400b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
21410b57cec5SDimitry Andric   case TargetOpcode::G_SUB:
21420b57cec5SDimitry Andric     // Perform operation at larger width (any extension is fines here, high bits
21430b57cec5SDimitry Andric     // don't affect the result) and then truncate the result back to the
21440b57cec5SDimitry Andric     // original type.
21450b57cec5SDimitry Andric     Observer.changingInstr(MI);
21460b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21470b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
21480b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21490b57cec5SDimitry Andric     Observer.changedInstr(MI);
21500b57cec5SDimitry Andric     return Legalized;
21510b57cec5SDimitry Andric 
2152*fe6060f1SDimitry Andric   case TargetOpcode::G_SBFX:
2153*fe6060f1SDimitry Andric   case TargetOpcode::G_UBFX:
2154*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2155*fe6060f1SDimitry Andric 
2156*fe6060f1SDimitry Andric     if (TypeIdx == 0) {
2157*fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
2158*fe6060f1SDimitry Andric       widenScalarDst(MI, WideTy);
2159*fe6060f1SDimitry Andric     } else {
2160*fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
2161*fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ZEXT);
2162*fe6060f1SDimitry Andric     }
2163*fe6060f1SDimitry Andric 
2164*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2165*fe6060f1SDimitry Andric     return Legalized;
2166*fe6060f1SDimitry Andric 
21670b57cec5SDimitry Andric   case TargetOpcode::G_SHL:
21680b57cec5SDimitry Andric     Observer.changingInstr(MI);
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric     if (TypeIdx == 0) {
21710b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21720b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
21730b57cec5SDimitry Andric     } else {
21740b57cec5SDimitry Andric       assert(TypeIdx == 1);
21750b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
21760b57cec5SDimitry Andric       // unsigned integer:
21770b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
21780b57cec5SDimitry Andric     }
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric     Observer.changedInstr(MI);
21810b57cec5SDimitry Andric     return Legalized;
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
21840b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
21850b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
21860b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
21870b57cec5SDimitry Andric     Observer.changingInstr(MI);
21880b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
21890b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
21900b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21910b57cec5SDimitry Andric     Observer.changedInstr(MI);
21920b57cec5SDimitry Andric     return Legalized;
21930b57cec5SDimitry Andric 
2194*fe6060f1SDimitry Andric   case TargetOpcode::G_SDIVREM:
2195*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2196*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
2197*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2198*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy);
2199*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 1);
2200*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2201*fe6060f1SDimitry Andric     return Legalized;
2202*fe6060f1SDimitry Andric 
22030b57cec5SDimitry Andric   case TargetOpcode::G_ASHR:
22040b57cec5SDimitry Andric   case TargetOpcode::G_LSHR:
22050b57cec5SDimitry Andric     Observer.changingInstr(MI);
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric     if (TypeIdx == 0) {
22080b57cec5SDimitry Andric       unsigned CvtOp = MI.getOpcode() == TargetOpcode::G_ASHR ?
22090b57cec5SDimitry Andric         TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, CvtOp);
22120b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
22130b57cec5SDimitry Andric     } else {
22140b57cec5SDimitry Andric       assert(TypeIdx == 1);
22150b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
22160b57cec5SDimitry Andric       // unsigned integer:
22170b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
22180b57cec5SDimitry Andric     }
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric     Observer.changedInstr(MI);
22210b57cec5SDimitry Andric     return Legalized;
22220b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
22230b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
22240b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
22250b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
22260b57cec5SDimitry Andric     Observer.changingInstr(MI);
22270b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
22280b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
22290b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
22300b57cec5SDimitry Andric     Observer.changedInstr(MI);
22310b57cec5SDimitry Andric     return Legalized;
22320b57cec5SDimitry Andric 
2233*fe6060f1SDimitry Andric   case TargetOpcode::G_UDIVREM:
2234*fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2235*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
2236*fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ZEXT);
2237*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy);
2238*fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 1);
2239*fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2240*fe6060f1SDimitry Andric     return Legalized;
2241*fe6060f1SDimitry Andric 
22420b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
22430b57cec5SDimitry Andric     Observer.changingInstr(MI);
22440b57cec5SDimitry Andric     if (TypeIdx == 0) {
22450b57cec5SDimitry Andric       // Perform operation at larger width (any extension is fine here, high
22460b57cec5SDimitry Andric       // bits don't affect the result) and then truncate the result back to the
22470b57cec5SDimitry Andric       // original type.
22480b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
22490b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
22500b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
22510b57cec5SDimitry Andric     } else {
22520b57cec5SDimitry Andric       bool IsVec = MRI.getType(MI.getOperand(1).getReg()).isVector();
22530b57cec5SDimitry Andric       // Explicit extension is required here since high bits affect the result.
22540b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, MIRBuilder.getBoolExtOp(IsVec, false));
22550b57cec5SDimitry Andric     }
22560b57cec5SDimitry Andric     Observer.changedInstr(MI);
22570b57cec5SDimitry Andric     return Legalized;
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
22600b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
22610b57cec5SDimitry Andric     Observer.changingInstr(MI);
22628bcb0991SDimitry Andric 
22638bcb0991SDimitry Andric     if (TypeIdx == 0)
22640b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
22658bcb0991SDimitry Andric     else
22668bcb0991SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
22678bcb0991SDimitry Andric 
22680b57cec5SDimitry Andric     Observer.changedInstr(MI);
22690b57cec5SDimitry Andric     return Legalized;
22700b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
22710b57cec5SDimitry Andric     Observer.changingInstr(MI);
2272e8d8bef9SDimitry Andric 
2273e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2274e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2275e8d8bef9SDimitry Andric     else
22760b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
2277e8d8bef9SDimitry Andric 
22780b57cec5SDimitry Andric     Observer.changedInstr(MI);
22790b57cec5SDimitry Andric     return Legalized;
22800b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
22810b57cec5SDimitry Andric     Observer.changingInstr(MI);
2282e8d8bef9SDimitry Andric 
2283e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2284e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2285e8d8bef9SDimitry Andric     else
22860b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
2287e8d8bef9SDimitry Andric 
22880b57cec5SDimitry Andric     Observer.changedInstr(MI);
22890b57cec5SDimitry Andric     return Legalized;
22900b57cec5SDimitry Andric   case TargetOpcode::G_LOAD:
22910b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
22920b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
22930b57cec5SDimitry Andric     Observer.changingInstr(MI);
22940b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
22950b57cec5SDimitry Andric     Observer.changedInstr(MI);
22960b57cec5SDimitry Andric     return Legalized;
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
22990b57cec5SDimitry Andric     if (TypeIdx != 0)
23000b57cec5SDimitry Andric       return UnableToLegalize;
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2303e8d8bef9SDimitry Andric     if (!Ty.isScalar())
23040b57cec5SDimitry Andric       return UnableToLegalize;
23050b57cec5SDimitry Andric 
23060b57cec5SDimitry Andric     Observer.changingInstr(MI);
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric     unsigned ExtType = Ty.getScalarSizeInBits() == 1 ?
23090b57cec5SDimitry Andric       TargetOpcode::G_ZEXT : TargetOpcode::G_ANYEXT;
23100b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, ExtType);
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric     Observer.changedInstr(MI);
23130b57cec5SDimitry Andric     return Legalized;
23140b57cec5SDimitry Andric   }
23150b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
23160b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
23170b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
2318480093f4SDimitry Andric     unsigned ExtOpc = LI.getExtOpcodeForWideningConstant(
2319480093f4SDimitry Andric         MRI.getType(MI.getOperand(0).getReg()));
2320480093f4SDimitry Andric     assert((ExtOpc == TargetOpcode::G_ZEXT || ExtOpc == TargetOpcode::G_SEXT ||
2321480093f4SDimitry Andric             ExtOpc == TargetOpcode::G_ANYEXT) &&
2322480093f4SDimitry Andric            "Illegal Extend");
2323480093f4SDimitry Andric     const APInt &SrcVal = SrcMO.getCImm()->getValue();
2324480093f4SDimitry Andric     const APInt &Val = (ExtOpc == TargetOpcode::G_SEXT)
2325480093f4SDimitry Andric                            ? SrcVal.sext(WideTy.getSizeInBits())
2326480093f4SDimitry Andric                            : SrcVal.zext(WideTy.getSizeInBits());
23270b57cec5SDimitry Andric     Observer.changingInstr(MI);
23280b57cec5SDimitry Andric     SrcMO.setCImm(ConstantInt::get(Ctx, Val));
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
23310b57cec5SDimitry Andric     Observer.changedInstr(MI);
23320b57cec5SDimitry Andric     return Legalized;
23330b57cec5SDimitry Andric   }
23340b57cec5SDimitry Andric   case TargetOpcode::G_FCONSTANT: {
23350b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
23360b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
23370b57cec5SDimitry Andric     APFloat Val = SrcMO.getFPImm()->getValueAPF();
23380b57cec5SDimitry Andric     bool LosesInfo;
23390b57cec5SDimitry Andric     switch (WideTy.getSizeInBits()) {
23400b57cec5SDimitry Andric     case 32:
23410b57cec5SDimitry Andric       Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
23420b57cec5SDimitry Andric                   &LosesInfo);
23430b57cec5SDimitry Andric       break;
23440b57cec5SDimitry Andric     case 64:
23450b57cec5SDimitry Andric       Val.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
23460b57cec5SDimitry Andric                   &LosesInfo);
23470b57cec5SDimitry Andric       break;
23480b57cec5SDimitry Andric     default:
23490b57cec5SDimitry Andric       return UnableToLegalize;
23500b57cec5SDimitry Andric     }
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric     assert(!LosesInfo && "extend should always be lossless");
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric     Observer.changingInstr(MI);
23550b57cec5SDimitry Andric     SrcMO.setFPImm(ConstantFP::get(Ctx, Val));
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
23580b57cec5SDimitry Andric     Observer.changedInstr(MI);
23590b57cec5SDimitry Andric     return Legalized;
23600b57cec5SDimitry Andric   }
23610b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
23620b57cec5SDimitry Andric     Observer.changingInstr(MI);
23630b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
23640b57cec5SDimitry Andric     Observer.changedInstr(MI);
23650b57cec5SDimitry Andric     return Legalized;
23660b57cec5SDimitry Andric   }
23670b57cec5SDimitry Andric   case TargetOpcode::G_BRCOND:
23680b57cec5SDimitry Andric     Observer.changingInstr(MI);
23690b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, MIRBuilder.getBoolExtOp(false, false));
23700b57cec5SDimitry Andric     Observer.changedInstr(MI);
23710b57cec5SDimitry Andric     return Legalized;
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric   case TargetOpcode::G_FCMP:
23740b57cec5SDimitry Andric     Observer.changingInstr(MI);
23750b57cec5SDimitry Andric     if (TypeIdx == 0)
23760b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
23770b57cec5SDimitry Andric     else {
23780b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
23790b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_FPEXT);
23800b57cec5SDimitry Andric     }
23810b57cec5SDimitry Andric     Observer.changedInstr(MI);
23820b57cec5SDimitry Andric     return Legalized;
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric   case TargetOpcode::G_ICMP:
23850b57cec5SDimitry Andric     Observer.changingInstr(MI);
23860b57cec5SDimitry Andric     if (TypeIdx == 0)
23870b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
23880b57cec5SDimitry Andric     else {
23890b57cec5SDimitry Andric       unsigned ExtOpcode = CmpInst::isSigned(static_cast<CmpInst::Predicate>(
23900b57cec5SDimitry Andric                                MI.getOperand(1).getPredicate()))
23910b57cec5SDimitry Andric                                ? TargetOpcode::G_SEXT
23920b57cec5SDimitry Andric                                : TargetOpcode::G_ZEXT;
23930b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, ExtOpcode);
23940b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, ExtOpcode);
23950b57cec5SDimitry Andric     }
23960b57cec5SDimitry Andric     Observer.changedInstr(MI);
23970b57cec5SDimitry Andric     return Legalized;
23980b57cec5SDimitry Andric 
2399480093f4SDimitry Andric   case TargetOpcode::G_PTR_ADD:
2400480093f4SDimitry Andric     assert(TypeIdx == 1 && "unable to legalize pointer of G_PTR_ADD");
24010b57cec5SDimitry Andric     Observer.changingInstr(MI);
24020b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
24030b57cec5SDimitry Andric     Observer.changedInstr(MI);
24040b57cec5SDimitry Andric     return Legalized;
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   case TargetOpcode::G_PHI: {
24070b57cec5SDimitry Andric     assert(TypeIdx == 0 && "Expecting only Idx 0");
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric     Observer.changingInstr(MI);
24100b57cec5SDimitry Andric     for (unsigned I = 1; I < MI.getNumOperands(); I += 2) {
24110b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
24120b57cec5SDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
24130b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_ANYEXT);
24140b57cec5SDimitry Andric     }
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
24170b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
24180b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
24190b57cec5SDimitry Andric     Observer.changedInstr(MI);
24200b57cec5SDimitry Andric     return Legalized;
24210b57cec5SDimitry Andric   }
24220b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
24230b57cec5SDimitry Andric     if (TypeIdx == 0) {
24240b57cec5SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
24250b57cec5SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
24260b57cec5SDimitry Andric       Observer.changingInstr(MI);
24270b57cec5SDimitry Andric 
2428*fe6060f1SDimitry Andric       widenScalarSrc(
2429*fe6060f1SDimitry Andric           MI, LLT::vector(VecTy.getElementCount(), WideTy.getSizeInBits()), 1,
2430*fe6060f1SDimitry Andric           TargetOpcode::G_SEXT);
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
24330b57cec5SDimitry Andric       Observer.changedInstr(MI);
24340b57cec5SDimitry Andric       return Legalized;
24350b57cec5SDimitry Andric     }
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric     if (TypeIdx != 2)
24380b57cec5SDimitry Andric       return UnableToLegalize;
24390b57cec5SDimitry Andric     Observer.changingInstr(MI);
2440480093f4SDimitry Andric     // TODO: Probably should be zext
24410b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
24420b57cec5SDimitry Andric     Observer.changedInstr(MI);
24430b57cec5SDimitry Andric     return Legalized;
24440b57cec5SDimitry Andric   }
2445480093f4SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
2446480093f4SDimitry Andric     if (TypeIdx == 1) {
2447480093f4SDimitry Andric       Observer.changingInstr(MI);
2448480093f4SDimitry Andric 
2449480093f4SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
2450480093f4SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
2451*fe6060f1SDimitry Andric       LLT WideVecTy = LLT::vector(VecTy.getElementCount(), WideTy);
2452480093f4SDimitry Andric 
2453480093f4SDimitry Andric       widenScalarSrc(MI, WideVecTy, 1, TargetOpcode::G_ANYEXT);
2454480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2455480093f4SDimitry Andric       widenScalarDst(MI, WideVecTy, 0);
2456480093f4SDimitry Andric       Observer.changedInstr(MI);
2457480093f4SDimitry Andric       return Legalized;
2458480093f4SDimitry Andric     }
2459480093f4SDimitry Andric 
2460480093f4SDimitry Andric     if (TypeIdx == 2) {
2461480093f4SDimitry Andric       Observer.changingInstr(MI);
2462480093f4SDimitry Andric       // TODO: Probably should be zext
2463480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2464480093f4SDimitry Andric       Observer.changedInstr(MI);
24655ffd83dbSDimitry Andric       return Legalized;
2466480093f4SDimitry Andric     }
2467480093f4SDimitry Andric 
24685ffd83dbSDimitry Andric     return UnableToLegalize;
2469480093f4SDimitry Andric   }
24700b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
24710b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
24720b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
24730b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
24748bcb0991SDimitry Andric   case TargetOpcode::G_FMAD:
24750b57cec5SDimitry Andric   case TargetOpcode::G_FNEG:
24760b57cec5SDimitry Andric   case TargetOpcode::G_FABS:
24770b57cec5SDimitry Andric   case TargetOpcode::G_FCANONICALIZE:
24780b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM:
24790b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM:
24800b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
24810b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
24820b57cec5SDimitry Andric   case TargetOpcode::G_FMINIMUM:
24830b57cec5SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
24840b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
24850b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
24860b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
24870b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
24880b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
24890b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
24900b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
24910b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
24920b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
24930b57cec5SDimitry Andric   case TargetOpcode::G_FRINT:
24940b57cec5SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
24950b57cec5SDimitry Andric   case TargetOpcode::G_FSQRT:
24960b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
24970b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
24980b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
24990b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_TRUNC:
25000b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
2501e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
25020b57cec5SDimitry Andric     assert(TypeIdx == 0);
25030b57cec5SDimitry Andric     Observer.changingInstr(MI);
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
25060b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_FPEXT);
25070b57cec5SDimitry Andric 
25080b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
25090b57cec5SDimitry Andric     Observer.changedInstr(MI);
25100b57cec5SDimitry Andric     return Legalized;
2511e8d8bef9SDimitry Andric   case TargetOpcode::G_FPOWI: {
2512e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2513e8d8bef9SDimitry Andric       return UnableToLegalize;
2514e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2515e8d8bef9SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
2516e8d8bef9SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2517e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2518e8d8bef9SDimitry Andric     return Legalized;
2519e8d8bef9SDimitry Andric   }
25200b57cec5SDimitry Andric   case TargetOpcode::G_INTTOPTR:
25210b57cec5SDimitry Andric     if (TypeIdx != 1)
25220b57cec5SDimitry Andric       return UnableToLegalize;
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric     Observer.changingInstr(MI);
25250b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
25260b57cec5SDimitry Andric     Observer.changedInstr(MI);
25270b57cec5SDimitry Andric     return Legalized;
25280b57cec5SDimitry Andric   case TargetOpcode::G_PTRTOINT:
25290b57cec5SDimitry Andric     if (TypeIdx != 0)
25300b57cec5SDimitry Andric       return UnableToLegalize;
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric     Observer.changingInstr(MI);
25330b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0);
25340b57cec5SDimitry Andric     Observer.changedInstr(MI);
25350b57cec5SDimitry Andric     return Legalized;
25360b57cec5SDimitry Andric   case TargetOpcode::G_BUILD_VECTOR: {
25370b57cec5SDimitry Andric     Observer.changingInstr(MI);
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric     const LLT WideEltTy = TypeIdx == 1 ? WideTy : WideTy.getElementType();
25400b57cec5SDimitry Andric     for (int I = 1, E = MI.getNumOperands(); I != E; ++I)
25410b57cec5SDimitry Andric       widenScalarSrc(MI, WideEltTy, I, TargetOpcode::G_ANYEXT);
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric     // Avoid changing the result vector type if the source element type was
25440b57cec5SDimitry Andric     // requested.
25450b57cec5SDimitry Andric     if (TypeIdx == 1) {
2546e8d8bef9SDimitry Andric       MI.setDesc(MIRBuilder.getTII().get(TargetOpcode::G_BUILD_VECTOR_TRUNC));
25470b57cec5SDimitry Andric     } else {
25480b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
25490b57cec5SDimitry Andric     }
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric     Observer.changedInstr(MI);
25520b57cec5SDimitry Andric     return Legalized;
25530b57cec5SDimitry Andric   }
25548bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG:
25558bcb0991SDimitry Andric     if (TypeIdx != 0)
25568bcb0991SDimitry Andric       return UnableToLegalize;
25578bcb0991SDimitry Andric 
25588bcb0991SDimitry Andric     Observer.changingInstr(MI);
25598bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
25608bcb0991SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_TRUNC);
25618bcb0991SDimitry Andric     Observer.changedInstr(MI);
25628bcb0991SDimitry Andric     return Legalized;
25635ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
25645ffd83dbSDimitry Andric     if (TypeIdx != 1)
25655ffd83dbSDimitry Andric       return UnableToLegalize;
25665ffd83dbSDimitry Andric     Observer.changingInstr(MI);
25675ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
25685ffd83dbSDimitry Andric     Observer.changedInstr(MI);
25695ffd83dbSDimitry Andric     return Legalized;
25705ffd83dbSDimitry Andric   }
25715ffd83dbSDimitry Andric   }
25725ffd83dbSDimitry Andric }
25735ffd83dbSDimitry Andric 
25745ffd83dbSDimitry Andric static void getUnmergePieces(SmallVectorImpl<Register> &Pieces,
25755ffd83dbSDimitry Andric                              MachineIRBuilder &B, Register Src, LLT Ty) {
25765ffd83dbSDimitry Andric   auto Unmerge = B.buildUnmerge(Ty, Src);
25775ffd83dbSDimitry Andric   for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
25785ffd83dbSDimitry Andric     Pieces.push_back(Unmerge.getReg(I));
25795ffd83dbSDimitry Andric }
25805ffd83dbSDimitry Andric 
25815ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
25825ffd83dbSDimitry Andric LegalizerHelper::lowerBitcast(MachineInstr &MI) {
25835ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
25845ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
25855ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
25865ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
25875ffd83dbSDimitry Andric 
25885ffd83dbSDimitry Andric   if (SrcTy.isVector()) {
25895ffd83dbSDimitry Andric     LLT SrcEltTy = SrcTy.getElementType();
25905ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
25915ffd83dbSDimitry Andric 
25925ffd83dbSDimitry Andric     if (DstTy.isVector()) {
25935ffd83dbSDimitry Andric       int NumDstElt = DstTy.getNumElements();
25945ffd83dbSDimitry Andric       int NumSrcElt = SrcTy.getNumElements();
25955ffd83dbSDimitry Andric 
25965ffd83dbSDimitry Andric       LLT DstEltTy = DstTy.getElementType();
25975ffd83dbSDimitry Andric       LLT DstCastTy = DstEltTy; // Intermediate bitcast result type
25985ffd83dbSDimitry Andric       LLT SrcPartTy = SrcEltTy; // Original unmerge result type.
25995ffd83dbSDimitry Andric 
26005ffd83dbSDimitry Andric       // If there's an element size mismatch, insert intermediate casts to match
26015ffd83dbSDimitry Andric       // the result element type.
26025ffd83dbSDimitry Andric       if (NumSrcElt < NumDstElt) { // Source element type is larger.
26035ffd83dbSDimitry Andric         // %1:_(<4 x s8>) = G_BITCAST %0:_(<2 x s16>)
26045ffd83dbSDimitry Andric         //
26055ffd83dbSDimitry Andric         // =>
26065ffd83dbSDimitry Andric         //
26075ffd83dbSDimitry Andric         // %2:_(s16), %3:_(s16) = G_UNMERGE_VALUES %0
26085ffd83dbSDimitry Andric         // %3:_(<2 x s8>) = G_BITCAST %2
26095ffd83dbSDimitry Andric         // %4:_(<2 x s8>) = G_BITCAST %3
26105ffd83dbSDimitry Andric         // %1:_(<4 x s16>) = G_CONCAT_VECTORS %3, %4
2611*fe6060f1SDimitry Andric         DstCastTy = LLT::fixed_vector(NumDstElt / NumSrcElt, DstEltTy);
26125ffd83dbSDimitry Andric         SrcPartTy = SrcEltTy;
26135ffd83dbSDimitry Andric       } else if (NumSrcElt > NumDstElt) { // Source element type is smaller.
26145ffd83dbSDimitry Andric         //
26155ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BITCAST %0:_(<4 x s8>)
26165ffd83dbSDimitry Andric         //
26175ffd83dbSDimitry Andric         // =>
26185ffd83dbSDimitry Andric         //
26195ffd83dbSDimitry Andric         // %2:_(<2 x s8>), %3:_(<2 x s8>) = G_UNMERGE_VALUES %0
26205ffd83dbSDimitry Andric         // %3:_(s16) = G_BITCAST %2
26215ffd83dbSDimitry Andric         // %4:_(s16) = G_BITCAST %3
26225ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BUILD_VECTOR %3, %4
2623*fe6060f1SDimitry Andric         SrcPartTy = LLT::fixed_vector(NumSrcElt / NumDstElt, SrcEltTy);
26245ffd83dbSDimitry Andric         DstCastTy = DstEltTy;
26255ffd83dbSDimitry Andric       }
26265ffd83dbSDimitry Andric 
26275ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcPartTy);
26285ffd83dbSDimitry Andric       for (Register &SrcReg : SrcRegs)
26295ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(DstCastTy, SrcReg).getReg(0);
26305ffd83dbSDimitry Andric     } else
26315ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcEltTy);
26325ffd83dbSDimitry Andric 
26335ffd83dbSDimitry Andric     MIRBuilder.buildMerge(Dst, SrcRegs);
26345ffd83dbSDimitry Andric     MI.eraseFromParent();
26355ffd83dbSDimitry Andric     return Legalized;
26365ffd83dbSDimitry Andric   }
26375ffd83dbSDimitry Andric 
26385ffd83dbSDimitry Andric   if (DstTy.isVector()) {
26395ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
26405ffd83dbSDimitry Andric     getUnmergePieces(SrcRegs, MIRBuilder, Src, DstTy.getElementType());
26415ffd83dbSDimitry Andric     MIRBuilder.buildMerge(Dst, SrcRegs);
26425ffd83dbSDimitry Andric     MI.eraseFromParent();
26435ffd83dbSDimitry Andric     return Legalized;
26445ffd83dbSDimitry Andric   }
26455ffd83dbSDimitry Andric 
26465ffd83dbSDimitry Andric   return UnableToLegalize;
26475ffd83dbSDimitry Andric }
26485ffd83dbSDimitry Andric 
2649e8d8bef9SDimitry Andric /// Figure out the bit offset into a register when coercing a vector index for
2650e8d8bef9SDimitry Andric /// the wide element type. This is only for the case when promoting vector to
2651e8d8bef9SDimitry Andric /// one with larger elements.
2652e8d8bef9SDimitry Andric //
2653e8d8bef9SDimitry Andric ///
2654e8d8bef9SDimitry Andric /// %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2655e8d8bef9SDimitry Andric /// %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2656e8d8bef9SDimitry Andric static Register getBitcastWiderVectorElementOffset(MachineIRBuilder &B,
2657e8d8bef9SDimitry Andric                                                    Register Idx,
2658e8d8bef9SDimitry Andric                                                    unsigned NewEltSize,
2659e8d8bef9SDimitry Andric                                                    unsigned OldEltSize) {
2660e8d8bef9SDimitry Andric   const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2661e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(Idx);
2662e8d8bef9SDimitry Andric 
2663e8d8bef9SDimitry Andric   // Now figure out the amount we need to shift to get the target bits.
2664e8d8bef9SDimitry Andric   auto OffsetMask = B.buildConstant(
2665e8d8bef9SDimitry Andric     IdxTy, ~(APInt::getAllOnesValue(IdxTy.getSizeInBits()) << Log2EltRatio));
2666e8d8bef9SDimitry Andric   auto OffsetIdx = B.buildAnd(IdxTy, Idx, OffsetMask);
2667e8d8bef9SDimitry Andric   return B.buildShl(IdxTy, OffsetIdx,
2668e8d8bef9SDimitry Andric                     B.buildConstant(IdxTy, Log2_32(OldEltSize))).getReg(0);
2669e8d8bef9SDimitry Andric }
2670e8d8bef9SDimitry Andric 
2671e8d8bef9SDimitry Andric /// Perform a G_EXTRACT_VECTOR_ELT in a different sized vector element. If this
2672e8d8bef9SDimitry Andric /// is casting to a vector with a smaller element size, perform multiple element
2673e8d8bef9SDimitry Andric /// extracts and merge the results. If this is coercing to a vector with larger
2674e8d8bef9SDimitry Andric /// elements, index the bitcasted vector and extract the target element with bit
2675e8d8bef9SDimitry Andric /// operations. This is intended to force the indexing in the native register
2676e8d8bef9SDimitry Andric /// size for architectures that can dynamically index the register file.
26775ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
2678e8d8bef9SDimitry Andric LegalizerHelper::bitcastExtractVectorElt(MachineInstr &MI, unsigned TypeIdx,
2679e8d8bef9SDimitry Andric                                          LLT CastTy) {
2680e8d8bef9SDimitry Andric   if (TypeIdx != 1)
2681e8d8bef9SDimitry Andric     return UnableToLegalize;
2682e8d8bef9SDimitry Andric 
2683e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2684e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
2685e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(2).getReg();
2686e8d8bef9SDimitry Andric   LLT SrcVecTy = MRI.getType(SrcVec);
2687e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Idx);
2688e8d8bef9SDimitry Andric 
2689e8d8bef9SDimitry Andric   LLT SrcEltTy = SrcVecTy.getElementType();
2690e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2691e8d8bef9SDimitry Andric   unsigned OldNumElts = SrcVecTy.getNumElements();
2692e8d8bef9SDimitry Andric 
2693e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2694e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2695e8d8bef9SDimitry Andric 
2696e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2697e8d8bef9SDimitry Andric   const unsigned OldEltSize = SrcEltTy.getSizeInBits();
2698e8d8bef9SDimitry Andric   if (NewNumElts > OldNumElts) {
2699e8d8bef9SDimitry Andric     // Decreasing the vector element size
2700e8d8bef9SDimitry Andric     //
2701e8d8bef9SDimitry Andric     // e.g. i64 = extract_vector_elt x:v2i64, y:i32
2702e8d8bef9SDimitry Andric     //  =>
2703e8d8bef9SDimitry Andric     //  v4i32:castx = bitcast x:v2i64
2704e8d8bef9SDimitry Andric     //
2705e8d8bef9SDimitry Andric     // i64 = bitcast
2706e8d8bef9SDimitry Andric     //   (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
2707e8d8bef9SDimitry Andric     //                       (i32 (extract_vector_elt castx, (2 * y + 1)))
2708e8d8bef9SDimitry Andric     //
2709e8d8bef9SDimitry Andric     if (NewNumElts % OldNumElts != 0)
2710e8d8bef9SDimitry Andric       return UnableToLegalize;
2711e8d8bef9SDimitry Andric 
2712e8d8bef9SDimitry Andric     // Type of the intermediate result vector.
2713e8d8bef9SDimitry Andric     const unsigned NewEltsPerOldElt = NewNumElts / OldNumElts;
2714*fe6060f1SDimitry Andric     LLT MidTy =
2715*fe6060f1SDimitry Andric         LLT::scalarOrVector(ElementCount::getFixed(NewEltsPerOldElt), NewEltTy);
2716e8d8bef9SDimitry Andric 
2717e8d8bef9SDimitry Andric     auto NewEltsPerOldEltK = MIRBuilder.buildConstant(IdxTy, NewEltsPerOldElt);
2718e8d8bef9SDimitry Andric 
2719e8d8bef9SDimitry Andric     SmallVector<Register, 8> NewOps(NewEltsPerOldElt);
2720e8d8bef9SDimitry Andric     auto NewBaseIdx = MIRBuilder.buildMul(IdxTy, Idx, NewEltsPerOldEltK);
2721e8d8bef9SDimitry Andric 
2722e8d8bef9SDimitry Andric     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
2723e8d8bef9SDimitry Andric       auto IdxOffset = MIRBuilder.buildConstant(IdxTy, I);
2724e8d8bef9SDimitry Andric       auto TmpIdx = MIRBuilder.buildAdd(IdxTy, NewBaseIdx, IdxOffset);
2725e8d8bef9SDimitry Andric       auto Elt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec, TmpIdx);
2726e8d8bef9SDimitry Andric       NewOps[I] = Elt.getReg(0);
2727e8d8bef9SDimitry Andric     }
2728e8d8bef9SDimitry Andric 
2729e8d8bef9SDimitry Andric     auto NewVec = MIRBuilder.buildBuildVector(MidTy, NewOps);
2730e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, NewVec);
2731e8d8bef9SDimitry Andric     MI.eraseFromParent();
2732e8d8bef9SDimitry Andric     return Legalized;
2733e8d8bef9SDimitry Andric   }
2734e8d8bef9SDimitry Andric 
2735e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2736e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
2737e8d8bef9SDimitry Andric       return UnableToLegalize;
2738e8d8bef9SDimitry Andric 
2739e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2740e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2741e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2742e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
2743e8d8bef9SDimitry Andric       return UnableToLegalize;
2744e8d8bef9SDimitry Andric 
2745e8d8bef9SDimitry Andric     // Increasing the vector element size.
2746e8d8bef9SDimitry Andric     // %elt:_(small_elt) = G_EXTRACT_VECTOR_ELT %vec:_(<N x small_elt>), %idx
2747e8d8bef9SDimitry Andric     //
2748e8d8bef9SDimitry Andric     //   =>
2749e8d8bef9SDimitry Andric     //
2750e8d8bef9SDimitry Andric     // %cast = G_BITCAST %vec
2751e8d8bef9SDimitry Andric     // %scaled_idx = G_LSHR %idx, Log2(DstEltSize / SrcEltSize)
2752e8d8bef9SDimitry Andric     // %wide_elt  = G_EXTRACT_VECTOR_ELT %cast, %scaled_idx
2753e8d8bef9SDimitry Andric     // %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2754e8d8bef9SDimitry Andric     // %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2755e8d8bef9SDimitry Andric     // %elt_bits = G_LSHR %wide_elt, %offset_bits
2756e8d8bef9SDimitry Andric     // %elt = G_TRUNC %elt_bits
2757e8d8bef9SDimitry Andric 
2758e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2759e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2760e8d8bef9SDimitry Andric 
2761e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2762e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2763e8d8bef9SDimitry Andric 
2764e8d8bef9SDimitry Andric     Register WideElt = CastVec;
2765e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2766e8d8bef9SDimitry Andric       WideElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2767e8d8bef9SDimitry Andric                                                      ScaledIdx).getReg(0);
2768e8d8bef9SDimitry Andric     }
2769e8d8bef9SDimitry Andric 
2770e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2771e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2772e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2773e8d8bef9SDimitry Andric 
2774e8d8bef9SDimitry Andric     // Shift the wide element to get the target element.
2775e8d8bef9SDimitry Andric     auto ExtractedBits = MIRBuilder.buildLShr(NewEltTy, WideElt, OffsetBits);
2776e8d8bef9SDimitry Andric     MIRBuilder.buildTrunc(Dst, ExtractedBits);
2777e8d8bef9SDimitry Andric     MI.eraseFromParent();
2778e8d8bef9SDimitry Andric     return Legalized;
2779e8d8bef9SDimitry Andric   }
2780e8d8bef9SDimitry Andric 
2781e8d8bef9SDimitry Andric   return UnableToLegalize;
2782e8d8bef9SDimitry Andric }
2783e8d8bef9SDimitry Andric 
2784e8d8bef9SDimitry Andric /// Emit code to insert \p InsertReg into \p TargetRet at \p OffsetBits in \p
2785e8d8bef9SDimitry Andric /// TargetReg, while preserving other bits in \p TargetReg.
2786e8d8bef9SDimitry Andric ///
2787e8d8bef9SDimitry Andric /// (InsertReg << Offset) | (TargetReg & ~(-1 >> InsertReg.size()) << Offset)
2788e8d8bef9SDimitry Andric static Register buildBitFieldInsert(MachineIRBuilder &B,
2789e8d8bef9SDimitry Andric                                     Register TargetReg, Register InsertReg,
2790e8d8bef9SDimitry Andric                                     Register OffsetBits) {
2791e8d8bef9SDimitry Andric   LLT TargetTy = B.getMRI()->getType(TargetReg);
2792e8d8bef9SDimitry Andric   LLT InsertTy = B.getMRI()->getType(InsertReg);
2793e8d8bef9SDimitry Andric   auto ZextVal = B.buildZExt(TargetTy, InsertReg);
2794e8d8bef9SDimitry Andric   auto ShiftedInsertVal = B.buildShl(TargetTy, ZextVal, OffsetBits);
2795e8d8bef9SDimitry Andric 
2796e8d8bef9SDimitry Andric   // Produce a bitmask of the value to insert
2797e8d8bef9SDimitry Andric   auto EltMask = B.buildConstant(
2798e8d8bef9SDimitry Andric     TargetTy, APInt::getLowBitsSet(TargetTy.getSizeInBits(),
2799e8d8bef9SDimitry Andric                                    InsertTy.getSizeInBits()));
2800e8d8bef9SDimitry Andric   // Shift it into position
2801e8d8bef9SDimitry Andric   auto ShiftedMask = B.buildShl(TargetTy, EltMask, OffsetBits);
2802e8d8bef9SDimitry Andric   auto InvShiftedMask = B.buildNot(TargetTy, ShiftedMask);
2803e8d8bef9SDimitry Andric 
2804e8d8bef9SDimitry Andric   // Clear out the bits in the wide element
2805e8d8bef9SDimitry Andric   auto MaskedOldElt = B.buildAnd(TargetTy, TargetReg, InvShiftedMask);
2806e8d8bef9SDimitry Andric 
2807e8d8bef9SDimitry Andric   // The value to insert has all zeros already, so stick it into the masked
2808e8d8bef9SDimitry Andric   // wide element.
2809e8d8bef9SDimitry Andric   return B.buildOr(TargetTy, MaskedOldElt, ShiftedInsertVal).getReg(0);
2810e8d8bef9SDimitry Andric }
2811e8d8bef9SDimitry Andric 
2812e8d8bef9SDimitry Andric /// Perform a G_INSERT_VECTOR_ELT in a different sized vector element. If this
2813e8d8bef9SDimitry Andric /// is increasing the element size, perform the indexing in the target element
2814e8d8bef9SDimitry Andric /// type, and use bit operations to insert at the element position. This is
2815e8d8bef9SDimitry Andric /// intended for architectures that can dynamically index the register file and
2816e8d8bef9SDimitry Andric /// want to force indexing in the native register size.
2817e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2818e8d8bef9SDimitry Andric LegalizerHelper::bitcastInsertVectorElt(MachineInstr &MI, unsigned TypeIdx,
2819e8d8bef9SDimitry Andric                                         LLT CastTy) {
28205ffd83dbSDimitry Andric   if (TypeIdx != 0)
28215ffd83dbSDimitry Andric     return UnableToLegalize;
28225ffd83dbSDimitry Andric 
2823e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2824e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
2825e8d8bef9SDimitry Andric   Register Val = MI.getOperand(2).getReg();
2826e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(3).getReg();
2827e8d8bef9SDimitry Andric 
2828e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(Dst);
2829e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Idx);
2830e8d8bef9SDimitry Andric 
2831e8d8bef9SDimitry Andric   LLT VecEltTy = VecTy.getElementType();
2832e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2833e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2834e8d8bef9SDimitry Andric   const unsigned OldEltSize = VecEltTy.getSizeInBits();
2835e8d8bef9SDimitry Andric 
2836e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2837e8d8bef9SDimitry Andric   unsigned OldNumElts = VecTy.getNumElements();
2838e8d8bef9SDimitry Andric 
2839e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2840e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2841e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
28425ffd83dbSDimitry Andric       return UnableToLegalize;
28435ffd83dbSDimitry Andric 
2844e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2845e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2846e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2847e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
28485ffd83dbSDimitry Andric       return UnableToLegalize;
28495ffd83dbSDimitry Andric 
2850e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2851e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2852e8d8bef9SDimitry Andric 
2853e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2854e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2855e8d8bef9SDimitry Andric 
2856e8d8bef9SDimitry Andric     Register ExtractedElt = CastVec;
2857e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2858e8d8bef9SDimitry Andric       ExtractedElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2859e8d8bef9SDimitry Andric                                                           ScaledIdx).getReg(0);
28605ffd83dbSDimitry Andric     }
28615ffd83dbSDimitry Andric 
2862e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2863e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2864e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2865e8d8bef9SDimitry Andric 
2866e8d8bef9SDimitry Andric     Register InsertedElt = buildBitFieldInsert(MIRBuilder, ExtractedElt,
2867e8d8bef9SDimitry Andric                                                Val, OffsetBits);
2868e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2869e8d8bef9SDimitry Andric       InsertedElt = MIRBuilder.buildInsertVectorElement(
2870e8d8bef9SDimitry Andric         CastTy, CastVec, InsertedElt, ScaledIdx).getReg(0);
2871e8d8bef9SDimitry Andric     }
2872e8d8bef9SDimitry Andric 
2873e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, InsertedElt);
2874e8d8bef9SDimitry Andric     MI.eraseFromParent();
28755ffd83dbSDimitry Andric     return Legalized;
28765ffd83dbSDimitry Andric   }
2877e8d8bef9SDimitry Andric 
28785ffd83dbSDimitry Andric   return UnableToLegalize;
28790b57cec5SDimitry Andric }
28800b57cec5SDimitry Andric 
2881*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerLoad(GAnyLoad &LoadMI) {
28820b57cec5SDimitry Andric   // Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
2883*fe6060f1SDimitry Andric   Register DstReg = LoadMI.getDstReg();
2884*fe6060f1SDimitry Andric   Register PtrReg = LoadMI.getPointerReg();
28850b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2886*fe6060f1SDimitry Andric   MachineMemOperand &MMO = LoadMI.getMMO();
2887*fe6060f1SDimitry Andric   LLT MemTy = MMO.getMemoryType();
2888*fe6060f1SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
2889*fe6060f1SDimitry Andric   if (MemTy.isVector())
2890*fe6060f1SDimitry Andric     return UnableToLegalize;
28910b57cec5SDimitry Andric 
2892*fe6060f1SDimitry Andric   unsigned MemSizeInBits = MemTy.getSizeInBits();
2893*fe6060f1SDimitry Andric   unsigned MemStoreSizeInBits = 8 * MemTy.getSizeInBytes();
2894*fe6060f1SDimitry Andric 
2895*fe6060f1SDimitry Andric   if (MemSizeInBits != MemStoreSizeInBits) {
2896*fe6060f1SDimitry Andric     // Promote to a byte-sized load if not loading an integral number of
2897*fe6060f1SDimitry Andric     // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
2898*fe6060f1SDimitry Andric     LLT WideMemTy = LLT::scalar(MemStoreSizeInBits);
2899*fe6060f1SDimitry Andric     MachineMemOperand *NewMMO =
2900*fe6060f1SDimitry Andric         MF.getMachineMemOperand(&MMO, MMO.getPointerInfo(), WideMemTy);
2901*fe6060f1SDimitry Andric 
2902*fe6060f1SDimitry Andric     Register LoadReg = DstReg;
2903*fe6060f1SDimitry Andric     LLT LoadTy = DstTy;
2904*fe6060f1SDimitry Andric 
2905*fe6060f1SDimitry Andric     // If this wasn't already an extending load, we need to widen the result
2906*fe6060f1SDimitry Andric     // register to avoid creating a load with a narrower result than the source.
2907*fe6060f1SDimitry Andric     if (MemStoreSizeInBits > DstTy.getSizeInBits()) {
2908*fe6060f1SDimitry Andric       LoadTy = WideMemTy;
2909*fe6060f1SDimitry Andric       LoadReg = MRI.createGenericVirtualRegister(WideMemTy);
2910*fe6060f1SDimitry Andric     }
2911*fe6060f1SDimitry Andric 
2912*fe6060f1SDimitry Andric     if (isa<GSExtLoad>(LoadMI)) {
2913*fe6060f1SDimitry Andric       auto NewLoad = MIRBuilder.buildLoad(LoadTy, PtrReg, *NewMMO);
2914*fe6060f1SDimitry Andric       MIRBuilder.buildSExtInReg(LoadReg, NewLoad, MemSizeInBits);
2915*fe6060f1SDimitry Andric     } else if (isa<GZExtLoad>(LoadMI) || WideMemTy == DstTy) {
2916*fe6060f1SDimitry Andric       auto NewLoad = MIRBuilder.buildLoad(LoadTy, PtrReg, *NewMMO);
2917*fe6060f1SDimitry Andric       // The extra bits are guaranteed to be zero, since we stored them that
2918*fe6060f1SDimitry Andric       // way.  A zext load from Wide thus automatically gives zext from MemVT.
2919*fe6060f1SDimitry Andric       MIRBuilder.buildAssertZExt(LoadReg, NewLoad, MemSizeInBits);
2920*fe6060f1SDimitry Andric     } else {
2921*fe6060f1SDimitry Andric       MIRBuilder.buildLoad(LoadReg, PtrReg, *NewMMO);
2922*fe6060f1SDimitry Andric     }
2923*fe6060f1SDimitry Andric 
2924*fe6060f1SDimitry Andric     if (DstTy != LoadTy)
2925*fe6060f1SDimitry Andric       MIRBuilder.buildTrunc(DstReg, LoadReg);
2926*fe6060f1SDimitry Andric 
2927*fe6060f1SDimitry Andric     LoadMI.eraseFromParent();
2928*fe6060f1SDimitry Andric     return Legalized;
2929*fe6060f1SDimitry Andric   }
2930*fe6060f1SDimitry Andric 
29318bcb0991SDimitry Andric   // This load needs splitting into power of 2 sized loads.
29328bcb0991SDimitry Andric   if (DstTy.isVector())
29330b57cec5SDimitry Andric     return UnableToLegalize;
2934*fe6060f1SDimitry Andric   if (isPowerOf2_32(MemSizeInBits))
29358bcb0991SDimitry Andric     return UnableToLegalize; // Don't know what we're being asked to do.
29368bcb0991SDimitry Andric 
2937*fe6060f1SDimitry Andric   // Big endian lowering not implemented.
2938*fe6060f1SDimitry Andric   if (MIRBuilder.getDataLayout().isBigEndian())
2939*fe6060f1SDimitry Andric     return UnableToLegalize;
2940*fe6060f1SDimitry Andric 
29418bcb0991SDimitry Andric   // Our strategy here is to generate anyextending loads for the smaller
29428bcb0991SDimitry Andric   // types up to next power-2 result type, and then combine the two larger
29438bcb0991SDimitry Andric   // result values together, before truncating back down to the non-pow-2
29448bcb0991SDimitry Andric   // type.
29458bcb0991SDimitry Andric   // E.g. v1 = i24 load =>
29465ffd83dbSDimitry Andric   // v2 = i32 zextload (2 byte)
29478bcb0991SDimitry Andric   // v3 = i32 load (1 byte)
29488bcb0991SDimitry Andric   // v4 = i32 shl v3, 16
29498bcb0991SDimitry Andric   // v5 = i32 or v4, v2
29508bcb0991SDimitry Andric   // v1 = i24 trunc v5
29518bcb0991SDimitry Andric   // By doing this we generate the correct truncate which should get
29528bcb0991SDimitry Andric   // combined away as an artifact with a matching extend.
2953*fe6060f1SDimitry Andric   uint64_t LargeSplitSize = PowerOf2Floor(MemSizeInBits);
2954*fe6060f1SDimitry Andric   uint64_t SmallSplitSize = MemSizeInBits - LargeSplitSize;
29558bcb0991SDimitry Andric 
29568bcb0991SDimitry Andric   MachineMemOperand *LargeMMO =
29578bcb0991SDimitry Andric       MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
2958*fe6060f1SDimitry Andric   MachineMemOperand *SmallMMO =
2959*fe6060f1SDimitry Andric       MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
29608bcb0991SDimitry Andric 
29618bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(PtrReg);
2962*fe6060f1SDimitry Andric   unsigned AnyExtSize = PowerOf2Ceil(DstTy.getSizeInBits());
29638bcb0991SDimitry Andric   LLT AnyExtTy = LLT::scalar(AnyExtSize);
2964*fe6060f1SDimitry Andric   auto LargeLoad = MIRBuilder.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, AnyExtTy,
2965*fe6060f1SDimitry Andric                                              PtrReg, *LargeMMO);
29668bcb0991SDimitry Andric 
2967*fe6060f1SDimitry Andric   auto OffsetCst = MIRBuilder.buildConstant(LLT::scalar(PtrTy.getSizeInBits()),
2968*fe6060f1SDimitry Andric                                             LargeSplitSize / 8);
2969480093f4SDimitry Andric   Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2970*fe6060f1SDimitry Andric   auto SmallPtr = MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst);
2971*fe6060f1SDimitry Andric   auto SmallLoad = MIRBuilder.buildLoadInstr(LoadMI.getOpcode(), AnyExtTy,
2972*fe6060f1SDimitry Andric                                              SmallPtr, *SmallMMO);
29738bcb0991SDimitry Andric 
29748bcb0991SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(AnyExtTy, LargeSplitSize);
29758bcb0991SDimitry Andric   auto Shift = MIRBuilder.buildShl(AnyExtTy, SmallLoad, ShiftAmt);
2976*fe6060f1SDimitry Andric 
2977*fe6060f1SDimitry Andric   if (AnyExtTy == DstTy)
2978*fe6060f1SDimitry Andric     MIRBuilder.buildOr(DstReg, Shift, LargeLoad);
2979*fe6060f1SDimitry Andric   else {
29808bcb0991SDimitry Andric     auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
2981*fe6060f1SDimitry Andric     MIRBuilder.buildTrunc(DstReg, {Or});
2982*fe6060f1SDimitry Andric   }
2983*fe6060f1SDimitry Andric 
2984*fe6060f1SDimitry Andric   LoadMI.eraseFromParent();
29858bcb0991SDimitry Andric   return Legalized;
29868bcb0991SDimitry Andric }
2987e8d8bef9SDimitry Andric 
2988*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerStore(GStore &StoreMI) {
29898bcb0991SDimitry Andric   // Lower a non-power of 2 store into multiple pow-2 stores.
29908bcb0991SDimitry Andric   // E.g. split an i24 store into an i16 store + i8 store.
29918bcb0991SDimitry Andric   // We do this by first extending the stored value to the next largest power
29928bcb0991SDimitry Andric   // of 2 type, and then using truncating stores to store the components.
29938bcb0991SDimitry Andric   // By doing this, likewise with G_LOAD, generate an extend that can be
29948bcb0991SDimitry Andric   // artifact-combined away instead of leaving behind extracts.
2995*fe6060f1SDimitry Andric   Register SrcReg = StoreMI.getValueReg();
2996*fe6060f1SDimitry Andric   Register PtrReg = StoreMI.getPointerReg();
29978bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2998*fe6060f1SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
2999*fe6060f1SDimitry Andric   MachineMemOperand &MMO = **StoreMI.memoperands_begin();
3000*fe6060f1SDimitry Andric   LLT MemTy = MMO.getMemoryType();
3001*fe6060f1SDimitry Andric 
30028bcb0991SDimitry Andric   if (SrcTy.isVector())
30038bcb0991SDimitry Andric     return UnableToLegalize;
3004*fe6060f1SDimitry Andric 
3005*fe6060f1SDimitry Andric   unsigned StoreWidth = MemTy.getSizeInBits();
3006*fe6060f1SDimitry Andric   unsigned StoreSizeInBits = 8 * MemTy.getSizeInBytes();
3007*fe6060f1SDimitry Andric 
3008*fe6060f1SDimitry Andric   if (StoreWidth != StoreSizeInBits) {
3009*fe6060f1SDimitry Andric     // Promote to a byte-sized store with upper bits zero if not
3010*fe6060f1SDimitry Andric     // storing an integral number of bytes.  For example, promote
3011*fe6060f1SDimitry Andric     // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
3012*fe6060f1SDimitry Andric     LLT WideTy = LLT::scalar(StoreSizeInBits);
3013*fe6060f1SDimitry Andric 
3014*fe6060f1SDimitry Andric     if (StoreSizeInBits > SrcTy.getSizeInBits()) {
3015*fe6060f1SDimitry Andric       // Avoid creating a store with a narrower source than result.
3016*fe6060f1SDimitry Andric       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
3017*fe6060f1SDimitry Andric       SrcTy = WideTy;
3018*fe6060f1SDimitry Andric     }
3019*fe6060f1SDimitry Andric 
3020*fe6060f1SDimitry Andric     auto ZextInReg = MIRBuilder.buildZExtInReg(SrcTy, SrcReg, StoreWidth);
3021*fe6060f1SDimitry Andric 
3022*fe6060f1SDimitry Andric     MachineMemOperand *NewMMO =
3023*fe6060f1SDimitry Andric         MF.getMachineMemOperand(&MMO, MMO.getPointerInfo(), WideTy);
3024*fe6060f1SDimitry Andric     MIRBuilder.buildStore(ZextInReg, PtrReg, *NewMMO);
3025*fe6060f1SDimitry Andric     StoreMI.eraseFromParent();
3026*fe6060f1SDimitry Andric     return Legalized;
3027*fe6060f1SDimitry Andric   }
3028*fe6060f1SDimitry Andric 
3029*fe6060f1SDimitry Andric   if (isPowerOf2_32(MemTy.getSizeInBits()))
30308bcb0991SDimitry Andric     return UnableToLegalize; // Don't know what we're being asked to do.
30318bcb0991SDimitry Andric 
3032*fe6060f1SDimitry Andric   // Extend to the next pow-2. If this store was itself the result of lowering,
3033*fe6060f1SDimitry Andric   // e.g. an s56 store being broken into s32 + s24, we might have a stored type
3034*fe6060f1SDimitry Andric   // that's wider the stored size.
3035*fe6060f1SDimitry Andric   const LLT NewSrcTy = LLT::scalar(NextPowerOf2(MemTy.getSizeInBits()));
3036*fe6060f1SDimitry Andric   auto ExtVal = MIRBuilder.buildAnyExtOrTrunc(NewSrcTy, SrcReg);
30378bcb0991SDimitry Andric 
30388bcb0991SDimitry Andric   // Obtain the smaller value by shifting away the larger value.
3039*fe6060f1SDimitry Andric   uint64_t LargeSplitSize = PowerOf2Floor(MemTy.getSizeInBits());
3040*fe6060f1SDimitry Andric   uint64_t SmallSplitSize = MemTy.getSizeInBits() - LargeSplitSize;
3041*fe6060f1SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(NewSrcTy, LargeSplitSize);
3042*fe6060f1SDimitry Andric   auto SmallVal = MIRBuilder.buildLShr(NewSrcTy, ExtVal, ShiftAmt);
30438bcb0991SDimitry Andric 
3044480093f4SDimitry Andric   // Generate the PtrAdd and truncating stores.
30458bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(PtrReg);
30465ffd83dbSDimitry Andric   auto OffsetCst = MIRBuilder.buildConstant(
30475ffd83dbSDimitry Andric     LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
3048480093f4SDimitry Andric   Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
3049480093f4SDimitry Andric   auto SmallPtr =
3050*fe6060f1SDimitry Andric     MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst);
30518bcb0991SDimitry Andric 
30528bcb0991SDimitry Andric   MachineMemOperand *LargeMMO =
30538bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
30548bcb0991SDimitry Andric   MachineMemOperand *SmallMMO =
30558bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
3056*fe6060f1SDimitry Andric   MIRBuilder.buildStore(ExtVal, PtrReg, *LargeMMO);
3057*fe6060f1SDimitry Andric   MIRBuilder.buildStore(SmallVal, SmallPtr, *SmallMMO);
3058*fe6060f1SDimitry Andric   StoreMI.eraseFromParent();
30598bcb0991SDimitry Andric   return Legalized;
30608bcb0991SDimitry Andric }
3061e8d8bef9SDimitry Andric 
3062e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3063e8d8bef9SDimitry Andric LegalizerHelper::bitcast(MachineInstr &MI, unsigned TypeIdx, LLT CastTy) {
3064e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
3065e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD: {
3066e8d8bef9SDimitry Andric     if (TypeIdx != 0)
3067e8d8bef9SDimitry Andric       return UnableToLegalize;
3068*fe6060f1SDimitry Andric     MachineMemOperand &MMO = **MI.memoperands_begin();
3069*fe6060f1SDimitry Andric 
3070*fe6060f1SDimitry Andric     // Not sure how to interpret a bitcast of an extending load.
3071*fe6060f1SDimitry Andric     if (MMO.getMemoryType().getSizeInBits() != CastTy.getSizeInBits())
3072*fe6060f1SDimitry Andric       return UnableToLegalize;
3073e8d8bef9SDimitry Andric 
3074e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3075e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
3076*fe6060f1SDimitry Andric     MMO.setType(CastTy);
3077e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3078e8d8bef9SDimitry Andric     return Legalized;
3079e8d8bef9SDimitry Andric   }
3080e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE: {
3081e8d8bef9SDimitry Andric     if (TypeIdx != 0)
3082e8d8bef9SDimitry Andric       return UnableToLegalize;
3083e8d8bef9SDimitry Andric 
3084*fe6060f1SDimitry Andric     MachineMemOperand &MMO = **MI.memoperands_begin();
3085*fe6060f1SDimitry Andric 
3086*fe6060f1SDimitry Andric     // Not sure how to interpret a bitcast of a truncating store.
3087*fe6060f1SDimitry Andric     if (MMO.getMemoryType().getSizeInBits() != CastTy.getSizeInBits())
3088*fe6060f1SDimitry Andric       return UnableToLegalize;
3089*fe6060f1SDimitry Andric 
3090e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3091e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 0);
3092*fe6060f1SDimitry Andric     MMO.setType(CastTy);
3093e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3094e8d8bef9SDimitry Andric     return Legalized;
3095e8d8bef9SDimitry Andric   }
3096e8d8bef9SDimitry Andric   case TargetOpcode::G_SELECT: {
3097e8d8bef9SDimitry Andric     if (TypeIdx != 0)
3098e8d8bef9SDimitry Andric       return UnableToLegalize;
3099e8d8bef9SDimitry Andric 
3100e8d8bef9SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector()) {
3101e8d8bef9SDimitry Andric       LLVM_DEBUG(
3102e8d8bef9SDimitry Andric           dbgs() << "bitcast action not implemented for vector select\n");
3103e8d8bef9SDimitry Andric       return UnableToLegalize;
3104e8d8bef9SDimitry Andric     }
3105e8d8bef9SDimitry Andric 
3106e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3107e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
3108e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 3);
3109e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
3110e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3111e8d8bef9SDimitry Andric     return Legalized;
3112e8d8bef9SDimitry Andric   }
3113e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
3114e8d8bef9SDimitry Andric   case TargetOpcode::G_OR:
3115e8d8bef9SDimitry Andric   case TargetOpcode::G_XOR: {
3116e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3117e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 1);
3118e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
3119e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
3120e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3121e8d8bef9SDimitry Andric     return Legalized;
3122e8d8bef9SDimitry Andric   }
3123e8d8bef9SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
3124e8d8bef9SDimitry Andric     return bitcastExtractVectorElt(MI, TypeIdx, CastTy);
3125e8d8bef9SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT:
3126e8d8bef9SDimitry Andric     return bitcastInsertVectorElt(MI, TypeIdx, CastTy);
3127e8d8bef9SDimitry Andric   default:
3128e8d8bef9SDimitry Andric     return UnableToLegalize;
3129e8d8bef9SDimitry Andric   }
3130e8d8bef9SDimitry Andric }
3131e8d8bef9SDimitry Andric 
3132e8d8bef9SDimitry Andric // Legalize an instruction by changing the opcode in place.
3133e8d8bef9SDimitry Andric void LegalizerHelper::changeOpcode(MachineInstr &MI, unsigned NewOpcode) {
3134e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3135e8d8bef9SDimitry Andric     MI.setDesc(MIRBuilder.getTII().get(NewOpcode));
3136e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3137e8d8bef9SDimitry Andric }
3138e8d8bef9SDimitry Andric 
3139e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3140e8d8bef9SDimitry Andric LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT LowerHintTy) {
3141e8d8bef9SDimitry Andric   using namespace TargetOpcode;
3142e8d8bef9SDimitry Andric 
3143e8d8bef9SDimitry Andric   switch(MI.getOpcode()) {
3144e8d8bef9SDimitry Andric   default:
3145e8d8bef9SDimitry Andric     return UnableToLegalize;
3146e8d8bef9SDimitry Andric   case TargetOpcode::G_BITCAST:
3147e8d8bef9SDimitry Andric     return lowerBitcast(MI);
3148e8d8bef9SDimitry Andric   case TargetOpcode::G_SREM:
3149e8d8bef9SDimitry Andric   case TargetOpcode::G_UREM: {
3150e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3151e8d8bef9SDimitry Andric     auto Quot =
3152e8d8bef9SDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV, {Ty},
3153e8d8bef9SDimitry Andric                               {MI.getOperand(1), MI.getOperand(2)});
3154e8d8bef9SDimitry Andric 
3155e8d8bef9SDimitry Andric     auto Prod = MIRBuilder.buildMul(Ty, Quot, MI.getOperand(2));
3156e8d8bef9SDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MI.getOperand(1), Prod);
3157e8d8bef9SDimitry Andric     MI.eraseFromParent();
3158e8d8bef9SDimitry Andric     return Legalized;
3159e8d8bef9SDimitry Andric   }
3160e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
3161e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
3162e8d8bef9SDimitry Andric     return lowerSADDO_SSUBO(MI);
3163e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULH:
3164e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULH:
3165e8d8bef9SDimitry Andric     return lowerSMULH_UMULH(MI);
3166e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULO:
3167e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULO: {
3168e8d8bef9SDimitry Andric     // Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
3169e8d8bef9SDimitry Andric     // result.
3170e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
3171e8d8bef9SDimitry Andric     Register Overflow = MI.getOperand(1).getReg();
3172e8d8bef9SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
3173e8d8bef9SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
3174e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
3175e8d8bef9SDimitry Andric 
3176e8d8bef9SDimitry Andric     unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
3177e8d8bef9SDimitry Andric                           ? TargetOpcode::G_SMULH
3178e8d8bef9SDimitry Andric                           : TargetOpcode::G_UMULH;
3179e8d8bef9SDimitry Andric 
3180e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3181e8d8bef9SDimitry Andric     const auto &TII = MIRBuilder.getTII();
3182e8d8bef9SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_MUL));
3183e8d8bef9SDimitry Andric     MI.RemoveOperand(1);
3184e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3185e8d8bef9SDimitry Andric 
3186e8d8bef9SDimitry Andric     auto HiPart = MIRBuilder.buildInstr(Opcode, {Ty}, {LHS, RHS});
3187e8d8bef9SDimitry Andric     auto Zero = MIRBuilder.buildConstant(Ty, 0);
3188e8d8bef9SDimitry Andric 
3189e8d8bef9SDimitry Andric     // Move insert point forward so we can use the Res register if needed.
3190e8d8bef9SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
3191e8d8bef9SDimitry Andric 
3192e8d8bef9SDimitry Andric     // For *signed* multiply, overflow is detected by checking:
3193e8d8bef9SDimitry Andric     // (hi != (lo >> bitwidth-1))
3194e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SMULH) {
3195e8d8bef9SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(Ty, Ty.getSizeInBits() - 1);
3196e8d8bef9SDimitry Andric       auto Shifted = MIRBuilder.buildAShr(Ty, Res, ShiftAmt);
3197e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
3198e8d8bef9SDimitry Andric     } else {
3199e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
3200e8d8bef9SDimitry Andric     }
3201e8d8bef9SDimitry Andric     return Legalized;
3202e8d8bef9SDimitry Andric   }
3203e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
3204e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
3205e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
3206e8d8bef9SDimitry Andric 
3207e8d8bef9SDimitry Andric     // TODO: Handle vector types once we are able to
3208e8d8bef9SDimitry Andric     // represent them.
3209e8d8bef9SDimitry Andric     if (Ty.isVector())
3210e8d8bef9SDimitry Andric       return UnableToLegalize;
3211e8d8bef9SDimitry Andric     auto SignMask =
3212e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignMask(Ty.getSizeInBits()));
3213e8d8bef9SDimitry Andric     Register SubByReg = MI.getOperand(1).getReg();
3214e8d8bef9SDimitry Andric     MIRBuilder.buildXor(Res, SubByReg, SignMask);
3215e8d8bef9SDimitry Andric     MI.eraseFromParent();
3216e8d8bef9SDimitry Andric     return Legalized;
3217e8d8bef9SDimitry Andric   }
3218e8d8bef9SDimitry Andric   case TargetOpcode::G_FSUB: {
3219e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
3220e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
3221e8d8bef9SDimitry Andric 
3222e8d8bef9SDimitry Andric     // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
3223e8d8bef9SDimitry Andric     // First, check if G_FNEG is marked as Lower. If so, we may
3224e8d8bef9SDimitry Andric     // end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
3225e8d8bef9SDimitry Andric     if (LI.getAction({G_FNEG, {Ty}}).Action == Lower)
3226e8d8bef9SDimitry Andric       return UnableToLegalize;
3227e8d8bef9SDimitry Andric     Register LHS = MI.getOperand(1).getReg();
3228e8d8bef9SDimitry Andric     Register RHS = MI.getOperand(2).getReg();
3229e8d8bef9SDimitry Andric     Register Neg = MRI.createGenericVirtualRegister(Ty);
3230e8d8bef9SDimitry Andric     MIRBuilder.buildFNeg(Neg, RHS);
3231e8d8bef9SDimitry Andric     MIRBuilder.buildFAdd(Res, LHS, Neg, MI.getFlags());
3232e8d8bef9SDimitry Andric     MI.eraseFromParent();
3233e8d8bef9SDimitry Andric     return Legalized;
3234e8d8bef9SDimitry Andric   }
3235e8d8bef9SDimitry Andric   case TargetOpcode::G_FMAD:
3236e8d8bef9SDimitry Andric     return lowerFMad(MI);
3237e8d8bef9SDimitry Andric   case TargetOpcode::G_FFLOOR:
3238e8d8bef9SDimitry Andric     return lowerFFloor(MI);
3239e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
3240e8d8bef9SDimitry Andric     return lowerIntrinsicRound(MI);
3241e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
3242e8d8bef9SDimitry Andric     // Since round even is the assumed rounding mode for unconstrained FP
3243e8d8bef9SDimitry Andric     // operations, rint and roundeven are the same operation.
3244e8d8bef9SDimitry Andric     changeOpcode(MI, TargetOpcode::G_FRINT);
3245e8d8bef9SDimitry Andric     return Legalized;
3246e8d8bef9SDimitry Andric   }
3247e8d8bef9SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
3248e8d8bef9SDimitry Andric     Register OldValRes = MI.getOperand(0).getReg();
3249e8d8bef9SDimitry Andric     Register SuccessRes = MI.getOperand(1).getReg();
3250e8d8bef9SDimitry Andric     Register Addr = MI.getOperand(2).getReg();
3251e8d8bef9SDimitry Andric     Register CmpVal = MI.getOperand(3).getReg();
3252e8d8bef9SDimitry Andric     Register NewVal = MI.getOperand(4).getReg();
3253e8d8bef9SDimitry Andric     MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
3254e8d8bef9SDimitry Andric                                   **MI.memoperands_begin());
3255e8d8bef9SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
3256e8d8bef9SDimitry Andric     MI.eraseFromParent();
3257e8d8bef9SDimitry Andric     return Legalized;
3258e8d8bef9SDimitry Andric   }
3259e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD:
3260e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
3261e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
3262*fe6060f1SDimitry Andric     return lowerLoad(cast<GAnyLoad>(MI));
3263e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE:
3264*fe6060f1SDimitry Andric     return lowerStore(cast<GStore>(MI));
32650b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
32660b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
32670b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
32680b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
32690b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP:
3270e8d8bef9SDimitry Andric     return lowerBitCount(MI);
32710b57cec5SDimitry Andric   case G_UADDO: {
32720b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
32730b57cec5SDimitry Andric     Register CarryOut = MI.getOperand(1).getReg();
32740b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
32750b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
32760b57cec5SDimitry Andric 
32770b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, LHS, RHS);
32780b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, RHS);
32790b57cec5SDimitry Andric 
32800b57cec5SDimitry Andric     MI.eraseFromParent();
32810b57cec5SDimitry Andric     return Legalized;
32820b57cec5SDimitry Andric   }
32830b57cec5SDimitry Andric   case G_UADDE: {
32840b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
32850b57cec5SDimitry Andric     Register CarryOut = MI.getOperand(1).getReg();
32860b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
32870b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
32880b57cec5SDimitry Andric     Register CarryIn = MI.getOperand(4).getReg();
32895ffd83dbSDimitry Andric     LLT Ty = MRI.getType(Res);
32900b57cec5SDimitry Andric 
32915ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildAdd(Ty, LHS, RHS);
32925ffd83dbSDimitry Andric     auto ZExtCarryIn = MIRBuilder.buildZExt(Ty, CarryIn);
32930b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
32940b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
32950b57cec5SDimitry Andric 
32960b57cec5SDimitry Andric     MI.eraseFromParent();
32970b57cec5SDimitry Andric     return Legalized;
32980b57cec5SDimitry Andric   }
32990b57cec5SDimitry Andric   case G_USUBO: {
33000b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
33010b57cec5SDimitry Andric     Register BorrowOut = MI.getOperand(1).getReg();
33020b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
33030b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, LHS, RHS);
33060b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric     MI.eraseFromParent();
33090b57cec5SDimitry Andric     return Legalized;
33100b57cec5SDimitry Andric   }
33110b57cec5SDimitry Andric   case G_USUBE: {
33120b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
33130b57cec5SDimitry Andric     Register BorrowOut = MI.getOperand(1).getReg();
33140b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
33150b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
33160b57cec5SDimitry Andric     Register BorrowIn = MI.getOperand(4).getReg();
33175ffd83dbSDimitry Andric     const LLT CondTy = MRI.getType(BorrowOut);
33185ffd83dbSDimitry Andric     const LLT Ty = MRI.getType(Res);
33190b57cec5SDimitry Andric 
33205ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildSub(Ty, LHS, RHS);
33215ffd83dbSDimitry Andric     auto ZExtBorrowIn = MIRBuilder.buildZExt(Ty, BorrowIn);
33220b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
33235ffd83dbSDimitry Andric 
33245ffd83dbSDimitry Andric     auto LHS_EQ_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, CondTy, LHS, RHS);
33255ffd83dbSDimitry Andric     auto LHS_ULT_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CondTy, LHS, RHS);
33260b57cec5SDimitry Andric     MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric     MI.eraseFromParent();
33290b57cec5SDimitry Andric     return Legalized;
33300b57cec5SDimitry Andric   }
33310b57cec5SDimitry Andric   case G_UITOFP:
3332e8d8bef9SDimitry Andric     return lowerUITOFP(MI);
33330b57cec5SDimitry Andric   case G_SITOFP:
3334e8d8bef9SDimitry Andric     return lowerSITOFP(MI);
33358bcb0991SDimitry Andric   case G_FPTOUI:
3336e8d8bef9SDimitry Andric     return lowerFPTOUI(MI);
33375ffd83dbSDimitry Andric   case G_FPTOSI:
33385ffd83dbSDimitry Andric     return lowerFPTOSI(MI);
33395ffd83dbSDimitry Andric   case G_FPTRUNC:
3340e8d8bef9SDimitry Andric     return lowerFPTRUNC(MI);
3341e8d8bef9SDimitry Andric   case G_FPOWI:
3342e8d8bef9SDimitry Andric     return lowerFPOWI(MI);
33430b57cec5SDimitry Andric   case G_SMIN:
33440b57cec5SDimitry Andric   case G_SMAX:
33450b57cec5SDimitry Andric   case G_UMIN:
33460b57cec5SDimitry Andric   case G_UMAX:
3347e8d8bef9SDimitry Andric     return lowerMinMax(MI);
33480b57cec5SDimitry Andric   case G_FCOPYSIGN:
3349e8d8bef9SDimitry Andric     return lowerFCopySign(MI);
33500b57cec5SDimitry Andric   case G_FMINNUM:
33510b57cec5SDimitry Andric   case G_FMAXNUM:
33520b57cec5SDimitry Andric     return lowerFMinNumMaxNum(MI);
33535ffd83dbSDimitry Andric   case G_MERGE_VALUES:
33545ffd83dbSDimitry Andric     return lowerMergeValues(MI);
33558bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
33568bcb0991SDimitry Andric     return lowerUnmergeValues(MI);
33578bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
33588bcb0991SDimitry Andric     assert(MI.getOperand(2).isImm() && "Expected immediate");
33598bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
33608bcb0991SDimitry Andric 
33618bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
33628bcb0991SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
33638bcb0991SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
33648bcb0991SDimitry Andric     Register TmpRes = MRI.createGenericVirtualRegister(DstTy);
33658bcb0991SDimitry Andric 
33668bcb0991SDimitry Andric     auto MIBSz = MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - SizeInBits);
33675ffd83dbSDimitry Andric     MIRBuilder.buildShl(TmpRes, SrcReg, MIBSz->getOperand(0));
33685ffd83dbSDimitry Andric     MIRBuilder.buildAShr(DstReg, TmpRes, MIBSz->getOperand(0));
33698bcb0991SDimitry Andric     MI.eraseFromParent();
33708bcb0991SDimitry Andric     return Legalized;
33718bcb0991SDimitry Andric   }
3372e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
3373e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
3374e8d8bef9SDimitry Andric     return lowerExtractInsertVectorElt(MI);
33758bcb0991SDimitry Andric   case G_SHUFFLE_VECTOR:
33768bcb0991SDimitry Andric     return lowerShuffleVector(MI);
33778bcb0991SDimitry Andric   case G_DYN_STACKALLOC:
33788bcb0991SDimitry Andric     return lowerDynStackAlloc(MI);
33798bcb0991SDimitry Andric   case G_EXTRACT:
33808bcb0991SDimitry Andric     return lowerExtract(MI);
33818bcb0991SDimitry Andric   case G_INSERT:
33828bcb0991SDimitry Andric     return lowerInsert(MI);
3383480093f4SDimitry Andric   case G_BSWAP:
3384480093f4SDimitry Andric     return lowerBswap(MI);
3385480093f4SDimitry Andric   case G_BITREVERSE:
3386480093f4SDimitry Andric     return lowerBitreverse(MI);
3387480093f4SDimitry Andric   case G_READ_REGISTER:
33885ffd83dbSDimitry Andric   case G_WRITE_REGISTER:
33895ffd83dbSDimitry Andric     return lowerReadWriteRegister(MI);
3390e8d8bef9SDimitry Andric   case G_UADDSAT:
3391e8d8bef9SDimitry Andric   case G_USUBSAT: {
3392e8d8bef9SDimitry Andric     // Try to make a reasonable guess about which lowering strategy to use. The
3393e8d8bef9SDimitry Andric     // target can override this with custom lowering and calling the
3394e8d8bef9SDimitry Andric     // implementation functions.
3395e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3396e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_UMIN, Ty}))
3397e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3398e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
33990b57cec5SDimitry Andric   }
3400e8d8bef9SDimitry Andric   case G_SADDSAT:
3401e8d8bef9SDimitry Andric   case G_SSUBSAT: {
3402e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3403e8d8bef9SDimitry Andric 
3404e8d8bef9SDimitry Andric     // FIXME: It would probably make more sense to see if G_SADDO is preferred,
3405e8d8bef9SDimitry Andric     // since it's a shorter expansion. However, we would need to figure out the
3406e8d8bef9SDimitry Andric     // preferred boolean type for the carry out for the query.
3407e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_SMIN, Ty}) && LI.isLegalOrCustom({G_SMAX, Ty}))
3408e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3409e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
3410e8d8bef9SDimitry Andric   }
3411e8d8bef9SDimitry Andric   case G_SSHLSAT:
3412e8d8bef9SDimitry Andric   case G_USHLSAT:
3413e8d8bef9SDimitry Andric     return lowerShlSat(MI);
3414*fe6060f1SDimitry Andric   case G_ABS:
3415*fe6060f1SDimitry Andric     return lowerAbsToAddXor(MI);
3416e8d8bef9SDimitry Andric   case G_SELECT:
3417e8d8bef9SDimitry Andric     return lowerSelect(MI);
3418*fe6060f1SDimitry Andric   case G_SDIVREM:
3419*fe6060f1SDimitry Andric   case G_UDIVREM:
3420*fe6060f1SDimitry Andric     return lowerDIVREM(MI);
3421*fe6060f1SDimitry Andric   case G_FSHL:
3422*fe6060f1SDimitry Andric   case G_FSHR:
3423*fe6060f1SDimitry Andric     return lowerFunnelShift(MI);
3424*fe6060f1SDimitry Andric   case G_ROTL:
3425*fe6060f1SDimitry Andric   case G_ROTR:
3426*fe6060f1SDimitry Andric     return lowerRotate(MI);
3427e8d8bef9SDimitry Andric   }
3428e8d8bef9SDimitry Andric }
3429e8d8bef9SDimitry Andric 
3430e8d8bef9SDimitry Andric Align LegalizerHelper::getStackTemporaryAlignment(LLT Ty,
3431e8d8bef9SDimitry Andric                                                   Align MinAlign) const {
3432e8d8bef9SDimitry Andric   // FIXME: We're missing a way to go back from LLT to llvm::Type to query the
3433e8d8bef9SDimitry Andric   // datalayout for the preferred alignment. Also there should be a target hook
3434e8d8bef9SDimitry Andric   // for this to allow targets to reduce the alignment and ignore the
3435e8d8bef9SDimitry Andric   // datalayout. e.g. AMDGPU should always use a 4-byte alignment, regardless of
3436e8d8bef9SDimitry Andric   // the type.
3437e8d8bef9SDimitry Andric   return std::max(Align(PowerOf2Ceil(Ty.getSizeInBytes())), MinAlign);
3438e8d8bef9SDimitry Andric }
3439e8d8bef9SDimitry Andric 
3440e8d8bef9SDimitry Andric MachineInstrBuilder
3441e8d8bef9SDimitry Andric LegalizerHelper::createStackTemporary(TypeSize Bytes, Align Alignment,
3442e8d8bef9SDimitry Andric                                       MachinePointerInfo &PtrInfo) {
3443e8d8bef9SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
3444e8d8bef9SDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
3445e8d8bef9SDimitry Andric   int FrameIdx = MF.getFrameInfo().CreateStackObject(Bytes, Alignment, false);
3446e8d8bef9SDimitry Andric 
3447e8d8bef9SDimitry Andric   unsigned AddrSpace = DL.getAllocaAddrSpace();
3448e8d8bef9SDimitry Andric   LLT FramePtrTy = LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace));
3449e8d8bef9SDimitry Andric 
3450e8d8bef9SDimitry Andric   PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIdx);
3451e8d8bef9SDimitry Andric   return MIRBuilder.buildFrameIndex(FramePtrTy, FrameIdx);
3452e8d8bef9SDimitry Andric }
3453e8d8bef9SDimitry Andric 
3454e8d8bef9SDimitry Andric static Register clampDynamicVectorIndex(MachineIRBuilder &B, Register IdxReg,
3455e8d8bef9SDimitry Andric                                         LLT VecTy) {
3456e8d8bef9SDimitry Andric   int64_t IdxVal;
3457e8d8bef9SDimitry Andric   if (mi_match(IdxReg, *B.getMRI(), m_ICst(IdxVal)))
3458e8d8bef9SDimitry Andric     return IdxReg;
3459e8d8bef9SDimitry Andric 
3460e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(IdxReg);
3461e8d8bef9SDimitry Andric   unsigned NElts = VecTy.getNumElements();
3462e8d8bef9SDimitry Andric   if (isPowerOf2_32(NElts)) {
3463e8d8bef9SDimitry Andric     APInt Imm = APInt::getLowBitsSet(IdxTy.getSizeInBits(), Log2_32(NElts));
3464e8d8bef9SDimitry Andric     return B.buildAnd(IdxTy, IdxReg, B.buildConstant(IdxTy, Imm)).getReg(0);
3465e8d8bef9SDimitry Andric   }
3466e8d8bef9SDimitry Andric 
3467e8d8bef9SDimitry Andric   return B.buildUMin(IdxTy, IdxReg, B.buildConstant(IdxTy, NElts - 1))
3468e8d8bef9SDimitry Andric       .getReg(0);
3469e8d8bef9SDimitry Andric }
3470e8d8bef9SDimitry Andric 
3471e8d8bef9SDimitry Andric Register LegalizerHelper::getVectorElementPointer(Register VecPtr, LLT VecTy,
3472e8d8bef9SDimitry Andric                                                   Register Index) {
3473e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
3474e8d8bef9SDimitry Andric 
3475e8d8bef9SDimitry Andric   // Calculate the element offset and add it to the pointer.
3476e8d8bef9SDimitry Andric   unsigned EltSize = EltTy.getSizeInBits() / 8; // FIXME: should be ABI size.
3477e8d8bef9SDimitry Andric   assert(EltSize * 8 == EltTy.getSizeInBits() &&
3478e8d8bef9SDimitry Andric          "Converting bits to bytes lost precision");
3479e8d8bef9SDimitry Andric 
3480e8d8bef9SDimitry Andric   Index = clampDynamicVectorIndex(MIRBuilder, Index, VecTy);
3481e8d8bef9SDimitry Andric 
3482e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Index);
3483e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(IdxTy, Index,
3484e8d8bef9SDimitry Andric                                  MIRBuilder.buildConstant(IdxTy, EltSize));
3485e8d8bef9SDimitry Andric 
3486e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(VecPtr);
3487e8d8bef9SDimitry Andric   return MIRBuilder.buildPtrAdd(PtrTy, VecPtr, Mul).getReg(0);
34880b57cec5SDimitry Andric }
34890b57cec5SDimitry Andric 
34900b57cec5SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorImplicitDef(
34910b57cec5SDimitry Andric     MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy) {
34920b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3493e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3494e8d8bef9SDimitry Andric   LLT LCMTy = getLCMType(DstTy, NarrowTy);
34950b57cec5SDimitry Andric 
3496e8d8bef9SDimitry Andric   unsigned NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
34970b57cec5SDimitry Andric 
3498e8d8bef9SDimitry Andric   auto NewUndef = MIRBuilder.buildUndef(NarrowTy);
3499e8d8bef9SDimitry Andric   SmallVector<Register, 8> Parts(NumParts, NewUndef.getReg(0));
35000b57cec5SDimitry Andric 
3501e8d8bef9SDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
35020b57cec5SDimitry Andric   MI.eraseFromParent();
35030b57cec5SDimitry Andric   return Legalized;
35040b57cec5SDimitry Andric }
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric // Handle splitting vector operations which need to have the same number of
35070b57cec5SDimitry Andric // elements in each type index, but each type index may have a different element
35080b57cec5SDimitry Andric // type.
35090b57cec5SDimitry Andric //
35100b57cec5SDimitry Andric // e.g.  <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
35110b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
35120b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
35130b57cec5SDimitry Andric //
35140b57cec5SDimitry Andric // Also handles some irregular breakdown cases, e.g.
35150b57cec5SDimitry Andric // e.g.  <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
35160b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
35170b57cec5SDimitry Andric //             s64 = G_SHL s64, s32
35180b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
35190b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorMultiEltType(
35200b57cec5SDimitry Andric   MachineInstr &MI, unsigned TypeIdx, LLT NarrowTyArg) {
35210b57cec5SDimitry Andric   if (TypeIdx != 0)
35220b57cec5SDimitry Andric     return UnableToLegalize;
35230b57cec5SDimitry Andric 
35240b57cec5SDimitry Andric   const LLT NarrowTy0 = NarrowTyArg;
35250b57cec5SDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
35260b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
35270b57cec5SDimitry Andric   LLT LeftoverTy0;
35280b57cec5SDimitry Andric 
35290b57cec5SDimitry Andric   // All of the operands need to have the same number of elements, so if we can
35300b57cec5SDimitry Andric   // determine a type breakdown for the result type, we can for all of the
35310b57cec5SDimitry Andric   // source types.
35320b57cec5SDimitry Andric   int NumParts = getNarrowTypeBreakDown(DstTy, NarrowTy0, LeftoverTy0).first;
35330b57cec5SDimitry Andric   if (NumParts < 0)
35340b57cec5SDimitry Andric     return UnableToLegalize;
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric   SmallVector<MachineInstrBuilder, 4> NewInsts;
35370b57cec5SDimitry Andric 
35380b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
35390b57cec5SDimitry Andric   SmallVector<Register, 4> PartRegs, LeftoverRegs;
35400b57cec5SDimitry Andric 
35410b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
35420b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
35430b57cec5SDimitry Andric     LLT SrcTyI = MRI.getType(SrcReg);
3544*fe6060f1SDimitry Andric     const auto NewEC = NarrowTy0.isVector() ? NarrowTy0.getElementCount()
3545*fe6060f1SDimitry Andric                                             : ElementCount::getFixed(1);
3546*fe6060f1SDimitry Andric     LLT NarrowTyI = LLT::scalarOrVector(NewEC, SrcTyI.getScalarType());
35470b57cec5SDimitry Andric     LLT LeftoverTyI;
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric     // Split this operand into the requested typed registers, and any leftover
35500b57cec5SDimitry Andric     // required to reproduce the original type.
35510b57cec5SDimitry Andric     if (!extractParts(SrcReg, SrcTyI, NarrowTyI, LeftoverTyI, PartRegs,
35520b57cec5SDimitry Andric                       LeftoverRegs))
35530b57cec5SDimitry Andric       return UnableToLegalize;
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric     if (I == 1) {
35560b57cec5SDimitry Andric       // For the first operand, create an instruction for each part and setup
35570b57cec5SDimitry Andric       // the result.
35580b57cec5SDimitry Andric       for (Register PartReg : PartRegs) {
35590b57cec5SDimitry Andric         Register PartDstReg = MRI.createGenericVirtualRegister(NarrowTy0);
35600b57cec5SDimitry Andric         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
35610b57cec5SDimitry Andric                                .addDef(PartDstReg)
35620b57cec5SDimitry Andric                                .addUse(PartReg));
35630b57cec5SDimitry Andric         DstRegs.push_back(PartDstReg);
35640b57cec5SDimitry Andric       }
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric       for (Register LeftoverReg : LeftoverRegs) {
35670b57cec5SDimitry Andric         Register PartDstReg = MRI.createGenericVirtualRegister(LeftoverTy0);
35680b57cec5SDimitry Andric         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
35690b57cec5SDimitry Andric                                .addDef(PartDstReg)
35700b57cec5SDimitry Andric                                .addUse(LeftoverReg));
35710b57cec5SDimitry Andric         LeftoverDstRegs.push_back(PartDstReg);
35720b57cec5SDimitry Andric       }
35730b57cec5SDimitry Andric     } else {
35740b57cec5SDimitry Andric       assert(NewInsts.size() == PartRegs.size() + LeftoverRegs.size());
35750b57cec5SDimitry Andric 
35760b57cec5SDimitry Andric       // Add the newly created operand splits to the existing instructions. The
35770b57cec5SDimitry Andric       // odd-sized pieces are ordered after the requested NarrowTyArg sized
35780b57cec5SDimitry Andric       // pieces.
35790b57cec5SDimitry Andric       unsigned InstCount = 0;
35800b57cec5SDimitry Andric       for (unsigned J = 0, JE = PartRegs.size(); J != JE; ++J)
35810b57cec5SDimitry Andric         NewInsts[InstCount++].addUse(PartRegs[J]);
35820b57cec5SDimitry Andric       for (unsigned J = 0, JE = LeftoverRegs.size(); J != JE; ++J)
35830b57cec5SDimitry Andric         NewInsts[InstCount++].addUse(LeftoverRegs[J]);
35840b57cec5SDimitry Andric     }
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric     PartRegs.clear();
35870b57cec5SDimitry Andric     LeftoverRegs.clear();
35880b57cec5SDimitry Andric   }
35890b57cec5SDimitry Andric 
35900b57cec5SDimitry Andric   // Insert the newly built operations and rebuild the result register.
35910b57cec5SDimitry Andric   for (auto &MIB : NewInsts)
35920b57cec5SDimitry Andric     MIRBuilder.insertInstr(MIB);
35930b57cec5SDimitry Andric 
35940b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy0, DstRegs, LeftoverTy0, LeftoverDstRegs);
35950b57cec5SDimitry Andric 
35960b57cec5SDimitry Andric   MI.eraseFromParent();
35970b57cec5SDimitry Andric   return Legalized;
35980b57cec5SDimitry Andric }
35990b57cec5SDimitry Andric 
36000b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
36010b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorCasts(MachineInstr &MI, unsigned TypeIdx,
36020b57cec5SDimitry Andric                                           LLT NarrowTy) {
36030b57cec5SDimitry Andric   if (TypeIdx != 0)
36040b57cec5SDimitry Andric     return UnableToLegalize;
36050b57cec5SDimitry Andric 
36060b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
36070b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
36080b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
36090b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
36100b57cec5SDimitry Andric 
36110b57cec5SDimitry Andric   LLT NarrowTy0 = NarrowTy;
36120b57cec5SDimitry Andric   LLT NarrowTy1;
36130b57cec5SDimitry Andric   unsigned NumParts;
36140b57cec5SDimitry Andric 
36150b57cec5SDimitry Andric   if (NarrowTy.isVector()) {
36160b57cec5SDimitry Andric     // Uneven breakdown not handled.
36170b57cec5SDimitry Andric     NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
36180b57cec5SDimitry Andric     if (NumParts * NarrowTy.getNumElements() != DstTy.getNumElements())
36190b57cec5SDimitry Andric       return UnableToLegalize;
36200b57cec5SDimitry Andric 
3621*fe6060f1SDimitry Andric     NarrowTy1 = LLT::vector(NarrowTy.getElementCount(), SrcTy.getElementType());
36220b57cec5SDimitry Andric   } else {
36230b57cec5SDimitry Andric     NumParts = DstTy.getNumElements();
36240b57cec5SDimitry Andric     NarrowTy1 = SrcTy.getElementType();
36250b57cec5SDimitry Andric   }
36260b57cec5SDimitry Andric 
36270b57cec5SDimitry Andric   SmallVector<Register, 4> SrcRegs, DstRegs;
36280b57cec5SDimitry Andric   extractParts(SrcReg, NarrowTy1, NumParts, SrcRegs);
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric   for (unsigned I = 0; I < NumParts; ++I) {
36310b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
36325ffd83dbSDimitry Andric     MachineInstr *NewInst =
36335ffd83dbSDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode(), {DstReg}, {SrcRegs[I]});
36340b57cec5SDimitry Andric 
36350b57cec5SDimitry Andric     NewInst->setFlags(MI.getFlags());
36360b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
36370b57cec5SDimitry Andric   }
36380b57cec5SDimitry Andric 
36390b57cec5SDimitry Andric   if (NarrowTy.isVector())
36400b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
36410b57cec5SDimitry Andric   else
36420b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
36430b57cec5SDimitry Andric 
36440b57cec5SDimitry Andric   MI.eraseFromParent();
36450b57cec5SDimitry Andric   return Legalized;
36460b57cec5SDimitry Andric }
36470b57cec5SDimitry Andric 
36480b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
36490b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorCmp(MachineInstr &MI, unsigned TypeIdx,
36500b57cec5SDimitry Andric                                         LLT NarrowTy) {
36510b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
36520b57cec5SDimitry Andric   Register Src0Reg = MI.getOperand(2).getReg();
36530b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
36540b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src0Reg);
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric   unsigned NumParts;
36570b57cec5SDimitry Andric   LLT NarrowTy0, NarrowTy1;
36580b57cec5SDimitry Andric 
36590b57cec5SDimitry Andric   if (TypeIdx == 0) {
36600b57cec5SDimitry Andric     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
36610b57cec5SDimitry Andric     unsigned OldElts = DstTy.getNumElements();
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric     NarrowTy0 = NarrowTy;
36640b57cec5SDimitry Andric     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) : DstTy.getNumElements();
3665*fe6060f1SDimitry Andric     NarrowTy1 = NarrowTy.isVector() ? LLT::vector(NarrowTy.getElementCount(),
3666*fe6060f1SDimitry Andric                                                   SrcTy.getScalarSizeInBits())
3667*fe6060f1SDimitry Andric                                     : SrcTy.getElementType();
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric   } else {
36700b57cec5SDimitry Andric     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
36710b57cec5SDimitry Andric     unsigned OldElts = SrcTy.getNumElements();
36720b57cec5SDimitry Andric 
36730b57cec5SDimitry Andric     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) :
36740b57cec5SDimitry Andric       NarrowTy.getNumElements();
3675*fe6060f1SDimitry Andric     NarrowTy0 =
3676*fe6060f1SDimitry Andric         LLT::vector(NarrowTy.getElementCount(), DstTy.getScalarSizeInBits());
36770b57cec5SDimitry Andric     NarrowTy1 = NarrowTy;
36780b57cec5SDimitry Andric   }
36790b57cec5SDimitry Andric 
36800b57cec5SDimitry Andric   // FIXME: Don't know how to handle the situation where the small vectors
36810b57cec5SDimitry Andric   // aren't all the same size yet.
36820b57cec5SDimitry Andric   if (NarrowTy1.isVector() &&
36830b57cec5SDimitry Andric       NarrowTy1.getNumElements() * NumParts != DstTy.getNumElements())
36840b57cec5SDimitry Andric     return UnableToLegalize;
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric   CmpInst::Predicate Pred
36870b57cec5SDimitry Andric     = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
36880b57cec5SDimitry Andric 
36890b57cec5SDimitry Andric   SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
36900b57cec5SDimitry Andric   extractParts(MI.getOperand(2).getReg(), NarrowTy1, NumParts, Src1Regs);
36910b57cec5SDimitry Andric   extractParts(MI.getOperand(3).getReg(), NarrowTy1, NumParts, Src2Regs);
36920b57cec5SDimitry Andric 
36930b57cec5SDimitry Andric   for (unsigned I = 0; I < NumParts; ++I) {
36940b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
36950b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
36960b57cec5SDimitry Andric 
36970b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_ICMP)
36980b57cec5SDimitry Andric       MIRBuilder.buildICmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
36990b57cec5SDimitry Andric     else {
37000b57cec5SDimitry Andric       MachineInstr *NewCmp
37010b57cec5SDimitry Andric         = MIRBuilder.buildFCmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
37020b57cec5SDimitry Andric       NewCmp->setFlags(MI.getFlags());
37030b57cec5SDimitry Andric     }
37040b57cec5SDimitry Andric   }
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric   if (NarrowTy1.isVector())
37070b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
37080b57cec5SDimitry Andric   else
37090b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
37100b57cec5SDimitry Andric 
37110b57cec5SDimitry Andric   MI.eraseFromParent();
37120b57cec5SDimitry Andric   return Legalized;
37130b57cec5SDimitry Andric }
37140b57cec5SDimitry Andric 
37150b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
37160b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorSelect(MachineInstr &MI, unsigned TypeIdx,
37170b57cec5SDimitry Andric                                            LLT NarrowTy) {
37180b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
37190b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
37200b57cec5SDimitry Andric 
37210b57cec5SDimitry Andric   unsigned NumParts = 0;
37220b57cec5SDimitry Andric   LLT NarrowTy0, NarrowTy1;
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
37250b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
37260b57cec5SDimitry Andric   unsigned Size = DstTy.getSizeInBits();
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric   assert(TypeIdx == 0 || CondTy.isVector());
37290b57cec5SDimitry Andric 
37300b57cec5SDimitry Andric   if (TypeIdx == 0) {
37310b57cec5SDimitry Andric     NarrowTy0 = NarrowTy;
37320b57cec5SDimitry Andric     NarrowTy1 = CondTy;
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric     unsigned NarrowSize = NarrowTy0.getSizeInBits();
37350b57cec5SDimitry Andric     // FIXME: Don't know how to handle the situation where the small vectors
37360b57cec5SDimitry Andric     // aren't all the same size yet.
37370b57cec5SDimitry Andric     if (Size % NarrowSize != 0)
37380b57cec5SDimitry Andric       return UnableToLegalize;
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric     NumParts = Size / NarrowSize;
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric     // Need to break down the condition type
37430b57cec5SDimitry Andric     if (CondTy.isVector()) {
37440b57cec5SDimitry Andric       if (CondTy.getNumElements() == NumParts)
37450b57cec5SDimitry Andric         NarrowTy1 = CondTy.getElementType();
37460b57cec5SDimitry Andric       else
3747*fe6060f1SDimitry Andric         NarrowTy1 =
3748*fe6060f1SDimitry Andric             LLT::vector(CondTy.getElementCount().divideCoefficientBy(NumParts),
37490b57cec5SDimitry Andric                         CondTy.getScalarSizeInBits());
37500b57cec5SDimitry Andric     }
37510b57cec5SDimitry Andric   } else {
37520b57cec5SDimitry Andric     NumParts = CondTy.getNumElements();
37530b57cec5SDimitry Andric     if (NarrowTy.isVector()) {
37540b57cec5SDimitry Andric       // TODO: Handle uneven breakdown.
37550b57cec5SDimitry Andric       if (NumParts * NarrowTy.getNumElements() != CondTy.getNumElements())
37560b57cec5SDimitry Andric         return UnableToLegalize;
37570b57cec5SDimitry Andric 
37580b57cec5SDimitry Andric       return UnableToLegalize;
37590b57cec5SDimitry Andric     } else {
37600b57cec5SDimitry Andric       NarrowTy0 = DstTy.getElementType();
37610b57cec5SDimitry Andric       NarrowTy1 = NarrowTy;
37620b57cec5SDimitry Andric     }
37630b57cec5SDimitry Andric   }
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   SmallVector<Register, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
37660b57cec5SDimitry Andric   if (CondTy.isVector())
37670b57cec5SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy1, NumParts, Src0Regs);
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric   extractParts(MI.getOperand(2).getReg(), NarrowTy0, NumParts, Src1Regs);
37700b57cec5SDimitry Andric   extractParts(MI.getOperand(3).getReg(), NarrowTy0, NumParts, Src2Regs);
37710b57cec5SDimitry Andric 
37720b57cec5SDimitry Andric   for (unsigned i = 0; i < NumParts; ++i) {
37730b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
37740b57cec5SDimitry Andric     MIRBuilder.buildSelect(DstReg, CondTy.isVector() ? Src0Regs[i] : CondReg,
37750b57cec5SDimitry Andric                            Src1Regs[i], Src2Regs[i]);
37760b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
37770b57cec5SDimitry Andric   }
37780b57cec5SDimitry Andric 
37790b57cec5SDimitry Andric   if (NarrowTy0.isVector())
37800b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
37810b57cec5SDimitry Andric   else
37820b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
37830b57cec5SDimitry Andric 
37840b57cec5SDimitry Andric   MI.eraseFromParent();
37850b57cec5SDimitry Andric   return Legalized;
37860b57cec5SDimitry Andric }
37870b57cec5SDimitry Andric 
37880b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
37890b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
37900b57cec5SDimitry Andric                                         LLT NarrowTy) {
37910b57cec5SDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
37920b57cec5SDimitry Andric   LLT PhiTy = MRI.getType(DstReg);
37930b57cec5SDimitry Andric   LLT LeftoverTy;
37940b57cec5SDimitry Andric 
37950b57cec5SDimitry Andric   // All of the operands need to have the same number of elements, so if we can
37960b57cec5SDimitry Andric   // determine a type breakdown for the result type, we can for all of the
37970b57cec5SDimitry Andric   // source types.
37980b57cec5SDimitry Andric   int NumParts, NumLeftover;
37990b57cec5SDimitry Andric   std::tie(NumParts, NumLeftover)
38000b57cec5SDimitry Andric     = getNarrowTypeBreakDown(PhiTy, NarrowTy, LeftoverTy);
38010b57cec5SDimitry Andric   if (NumParts < 0)
38020b57cec5SDimitry Andric     return UnableToLegalize;
38030b57cec5SDimitry Andric 
38040b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
38050b57cec5SDimitry Andric   SmallVector<MachineInstrBuilder, 4> NewInsts;
38060b57cec5SDimitry Andric 
38070b57cec5SDimitry Andric   const int TotalNumParts = NumParts + NumLeftover;
38080b57cec5SDimitry Andric 
38090b57cec5SDimitry Andric   // Insert the new phis in the result block first.
38100b57cec5SDimitry Andric   for (int I = 0; I != TotalNumParts; ++I) {
38110b57cec5SDimitry Andric     LLT Ty = I < NumParts ? NarrowTy : LeftoverTy;
38120b57cec5SDimitry Andric     Register PartDstReg = MRI.createGenericVirtualRegister(Ty);
38130b57cec5SDimitry Andric     NewInsts.push_back(MIRBuilder.buildInstr(TargetOpcode::G_PHI)
38140b57cec5SDimitry Andric                        .addDef(PartDstReg));
38150b57cec5SDimitry Andric     if (I < NumParts)
38160b57cec5SDimitry Andric       DstRegs.push_back(PartDstReg);
38170b57cec5SDimitry Andric     else
38180b57cec5SDimitry Andric       LeftoverDstRegs.push_back(PartDstReg);
38190b57cec5SDimitry Andric   }
38200b57cec5SDimitry Andric 
38210b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
38220b57cec5SDimitry Andric   MIRBuilder.setInsertPt(*MBB, MBB->getFirstNonPHI());
38230b57cec5SDimitry Andric   insertParts(DstReg, PhiTy, NarrowTy, DstRegs, LeftoverTy, LeftoverDstRegs);
38240b57cec5SDimitry Andric 
38250b57cec5SDimitry Andric   SmallVector<Register, 4> PartRegs, LeftoverRegs;
38260b57cec5SDimitry Andric 
38270b57cec5SDimitry Andric   // Insert code to extract the incoming values in each predecessor block.
38280b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
38290b57cec5SDimitry Andric     PartRegs.clear();
38300b57cec5SDimitry Andric     LeftoverRegs.clear();
38310b57cec5SDimitry Andric 
38320b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
38330b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
38340b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
38350b57cec5SDimitry Andric 
38360b57cec5SDimitry Andric     LLT Unused;
38370b57cec5SDimitry Andric     if (!extractParts(SrcReg, PhiTy, NarrowTy, Unused, PartRegs,
38380b57cec5SDimitry Andric                       LeftoverRegs))
38390b57cec5SDimitry Andric       return UnableToLegalize;
38400b57cec5SDimitry Andric 
38410b57cec5SDimitry Andric     // Add the newly created operand splits to the existing instructions. The
38420b57cec5SDimitry Andric     // odd-sized pieces are ordered after the requested NarrowTyArg sized
38430b57cec5SDimitry Andric     // pieces.
38440b57cec5SDimitry Andric     for (int J = 0; J != TotalNumParts; ++J) {
38450b57cec5SDimitry Andric       MachineInstrBuilder MIB = NewInsts[J];
38460b57cec5SDimitry Andric       MIB.addUse(J < NumParts ? PartRegs[J] : LeftoverRegs[J - NumParts]);
38470b57cec5SDimitry Andric       MIB.addMBB(&OpMBB);
38480b57cec5SDimitry Andric     }
38490b57cec5SDimitry Andric   }
38500b57cec5SDimitry Andric 
38510b57cec5SDimitry Andric   MI.eraseFromParent();
38520b57cec5SDimitry Andric   return Legalized;
38530b57cec5SDimitry Andric }
38540b57cec5SDimitry Andric 
38550b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
38568bcb0991SDimitry Andric LegalizerHelper::fewerElementsVectorUnmergeValues(MachineInstr &MI,
38578bcb0991SDimitry Andric                                                   unsigned TypeIdx,
38588bcb0991SDimitry Andric                                                   LLT NarrowTy) {
38598bcb0991SDimitry Andric   if (TypeIdx != 1)
38608bcb0991SDimitry Andric     return UnableToLegalize;
38618bcb0991SDimitry Andric 
38628bcb0991SDimitry Andric   const int NumDst = MI.getNumOperands() - 1;
38638bcb0991SDimitry Andric   const Register SrcReg = MI.getOperand(NumDst).getReg();
38648bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
38658bcb0991SDimitry Andric 
38668bcb0991SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
38678bcb0991SDimitry Andric 
38688bcb0991SDimitry Andric   // TODO: Create sequence of extracts.
38698bcb0991SDimitry Andric   if (DstTy == NarrowTy)
38708bcb0991SDimitry Andric     return UnableToLegalize;
38718bcb0991SDimitry Andric 
38728bcb0991SDimitry Andric   LLT GCDTy = getGCDType(SrcTy, NarrowTy);
38738bcb0991SDimitry Andric   if (DstTy == GCDTy) {
38748bcb0991SDimitry Andric     // This would just be a copy of the same unmerge.
38758bcb0991SDimitry Andric     // TODO: Create extracts, pad with undef and create intermediate merges.
38768bcb0991SDimitry Andric     return UnableToLegalize;
38778bcb0991SDimitry Andric   }
38788bcb0991SDimitry Andric 
38798bcb0991SDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
38808bcb0991SDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
38818bcb0991SDimitry Andric   const int PartsPerUnmerge = NumDst / NumUnmerge;
38828bcb0991SDimitry Andric 
38838bcb0991SDimitry Andric   for (int I = 0; I != NumUnmerge; ++I) {
38848bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
38858bcb0991SDimitry Andric 
38868bcb0991SDimitry Andric     for (int J = 0; J != PartsPerUnmerge; ++J)
38878bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I * PartsPerUnmerge + J).getReg());
38888bcb0991SDimitry Andric     MIB.addUse(Unmerge.getReg(I));
38898bcb0991SDimitry Andric   }
38908bcb0991SDimitry Andric 
38918bcb0991SDimitry Andric   MI.eraseFromParent();
38928bcb0991SDimitry Andric   return Legalized;
38938bcb0991SDimitry Andric }
38948bcb0991SDimitry Andric 
3895*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
3896*fe6060f1SDimitry Andric LegalizerHelper::fewerElementsVectorMulo(MachineInstr &MI, unsigned TypeIdx,
3897*fe6060f1SDimitry Andric                                          LLT NarrowTy) {
3898*fe6060f1SDimitry Andric   Register Result = MI.getOperand(0).getReg();
3899*fe6060f1SDimitry Andric   Register Overflow = MI.getOperand(1).getReg();
3900*fe6060f1SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
3901*fe6060f1SDimitry Andric   Register RHS = MI.getOperand(3).getReg();
3902*fe6060f1SDimitry Andric 
3903*fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(LHS);
3904*fe6060f1SDimitry Andric   if (!SrcTy.isVector())
3905*fe6060f1SDimitry Andric     return UnableToLegalize;
3906*fe6060f1SDimitry Andric 
3907*fe6060f1SDimitry Andric   LLT ElementType = SrcTy.getElementType();
3908*fe6060f1SDimitry Andric   LLT OverflowElementTy = MRI.getType(Overflow).getElementType();
3909*fe6060f1SDimitry Andric   const ElementCount NumResult = SrcTy.getElementCount();
3910*fe6060f1SDimitry Andric   LLT GCDTy = getGCDType(SrcTy, NarrowTy);
3911*fe6060f1SDimitry Andric 
3912*fe6060f1SDimitry Andric   // Unmerge the operands to smaller parts of GCD type.
3913*fe6060f1SDimitry Andric   auto UnmergeLHS = MIRBuilder.buildUnmerge(GCDTy, LHS);
3914*fe6060f1SDimitry Andric   auto UnmergeRHS = MIRBuilder.buildUnmerge(GCDTy, RHS);
3915*fe6060f1SDimitry Andric 
3916*fe6060f1SDimitry Andric   const int NumOps = UnmergeLHS->getNumOperands() - 1;
3917*fe6060f1SDimitry Andric   const ElementCount PartsPerUnmerge = NumResult.divideCoefficientBy(NumOps);
3918*fe6060f1SDimitry Andric   LLT OverflowTy = LLT::scalarOrVector(PartsPerUnmerge, OverflowElementTy);
3919*fe6060f1SDimitry Andric   LLT ResultTy = LLT::scalarOrVector(PartsPerUnmerge, ElementType);
3920*fe6060f1SDimitry Andric 
3921*fe6060f1SDimitry Andric   // Perform the operation over unmerged parts.
3922*fe6060f1SDimitry Andric   SmallVector<Register, 8> ResultParts;
3923*fe6060f1SDimitry Andric   SmallVector<Register, 8> OverflowParts;
3924*fe6060f1SDimitry Andric   for (int I = 0; I != NumOps; ++I) {
3925*fe6060f1SDimitry Andric     Register Operand1 = UnmergeLHS->getOperand(I).getReg();
3926*fe6060f1SDimitry Andric     Register Operand2 = UnmergeRHS->getOperand(I).getReg();
3927*fe6060f1SDimitry Andric     auto PartMul = MIRBuilder.buildInstr(MI.getOpcode(), {ResultTy, OverflowTy},
3928*fe6060f1SDimitry Andric                                          {Operand1, Operand2});
3929*fe6060f1SDimitry Andric     ResultParts.push_back(PartMul->getOperand(0).getReg());
3930*fe6060f1SDimitry Andric     OverflowParts.push_back(PartMul->getOperand(1).getReg());
3931*fe6060f1SDimitry Andric   }
3932*fe6060f1SDimitry Andric 
3933*fe6060f1SDimitry Andric   LLT ResultLCMTy = buildLCMMergePieces(SrcTy, NarrowTy, GCDTy, ResultParts);
3934*fe6060f1SDimitry Andric   LLT OverflowLCMTy =
3935*fe6060f1SDimitry Andric       LLT::scalarOrVector(ResultLCMTy.getElementCount(), OverflowElementTy);
3936*fe6060f1SDimitry Andric 
3937*fe6060f1SDimitry Andric   // Recombine the pieces to the original result and overflow registers.
3938*fe6060f1SDimitry Andric   buildWidenedRemergeToDst(Result, ResultLCMTy, ResultParts);
3939*fe6060f1SDimitry Andric   buildWidenedRemergeToDst(Overflow, OverflowLCMTy, OverflowParts);
3940*fe6060f1SDimitry Andric   MI.eraseFromParent();
3941*fe6060f1SDimitry Andric   return Legalized;
3942*fe6060f1SDimitry Andric }
3943*fe6060f1SDimitry Andric 
3944e8d8bef9SDimitry Andric // Handle FewerElementsVector a G_BUILD_VECTOR or G_CONCAT_VECTORS that produces
3945e8d8bef9SDimitry Andric // a vector
3946e8d8bef9SDimitry Andric //
3947e8d8bef9SDimitry Andric // Create a G_BUILD_VECTOR or G_CONCAT_VECTORS of NarrowTy pieces, padding with
3948e8d8bef9SDimitry Andric // undef as necessary.
39498bcb0991SDimitry Andric //
39508bcb0991SDimitry Andric // %3:_(<3 x s16>) = G_BUILD_VECTOR %0, %1, %2
39518bcb0991SDimitry Andric //   -> <2 x s16>
39528bcb0991SDimitry Andric //
39538bcb0991SDimitry Andric // %4:_(s16) = G_IMPLICIT_DEF
39548bcb0991SDimitry Andric // %5:_(<2 x s16>) = G_BUILD_VECTOR %0, %1
39558bcb0991SDimitry Andric // %6:_(<2 x s16>) = G_BUILD_VECTOR %2, %4
3956e8d8bef9SDimitry Andric // %7:_(<2 x s16>) = G_IMPLICIT_DEF
3957e8d8bef9SDimitry Andric // %8:_(<6 x s16>) = G_CONCAT_VECTORS %5, %6, %7
3958e8d8bef9SDimitry Andric // %3:_(<3 x s16>), %8:_(<3 x s16>) = G_UNMERGE_VALUES %8
3959e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3960e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorMerge(MachineInstr &MI, unsigned TypeIdx,
3961e8d8bef9SDimitry Andric                                           LLT NarrowTy) {
3962e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3963e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3964e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
3965e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
39668bcb0991SDimitry Andric 
3967e8d8bef9SDimitry Andric   // Break into a common type
3968e8d8bef9SDimitry Andric   SmallVector<Register, 16> Parts;
3969e8d8bef9SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3970e8d8bef9SDimitry Andric     extractGCDType(Parts, GCDTy, MI.getOperand(I).getReg());
3971e8d8bef9SDimitry Andric 
3972e8d8bef9SDimitry Andric   // Build the requested new merge, padding with undef.
3973e8d8bef9SDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts,
3974e8d8bef9SDimitry Andric                                   TargetOpcode::G_ANYEXT);
3975e8d8bef9SDimitry Andric 
3976e8d8bef9SDimitry Andric   // Pack into the original result register.
3977e8d8bef9SDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
3978e8d8bef9SDimitry Andric 
3979e8d8bef9SDimitry Andric   MI.eraseFromParent();
3980e8d8bef9SDimitry Andric   return Legalized;
39818bcb0991SDimitry Andric }
39828bcb0991SDimitry Andric 
3983e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3984e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorExtractInsertVectorElt(MachineInstr &MI,
3985e8d8bef9SDimitry Andric                                                            unsigned TypeIdx,
3986e8d8bef9SDimitry Andric                                                            LLT NarrowVecTy) {
3987e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3988e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
3989e8d8bef9SDimitry Andric   Register InsertVal;
3990e8d8bef9SDimitry Andric   bool IsInsert = MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT;
3991e8d8bef9SDimitry Andric 
3992e8d8bef9SDimitry Andric   assert((IsInsert ? TypeIdx == 0 : TypeIdx == 1) && "not a vector type index");
3993e8d8bef9SDimitry Andric   if (IsInsert)
3994e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
3995e8d8bef9SDimitry Andric 
3996e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
3997e8d8bef9SDimitry Andric 
3998e8d8bef9SDimitry Andric   // TODO: Handle total scalarization case.
3999e8d8bef9SDimitry Andric   if (!NarrowVecTy.isVector())
4000e8d8bef9SDimitry Andric     return UnableToLegalize;
4001e8d8bef9SDimitry Andric 
4002e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
4003e8d8bef9SDimitry Andric 
4004e8d8bef9SDimitry Andric   // If the index is a constant, we can really break this down as you would
4005e8d8bef9SDimitry Andric   // expect, and index into the target size pieces.
4006e8d8bef9SDimitry Andric   int64_t IdxVal;
4007*fe6060f1SDimitry Andric   auto MaybeCst =
4008*fe6060f1SDimitry Andric       getConstantVRegValWithLookThrough(Idx, MRI, /*LookThroughInstrs*/ true,
4009*fe6060f1SDimitry Andric                                         /*HandleFConstants*/ false);
4010*fe6060f1SDimitry Andric   if (MaybeCst) {
4011*fe6060f1SDimitry Andric     IdxVal = MaybeCst->Value.getSExtValue();
4012e8d8bef9SDimitry Andric     // Avoid out of bounds indexing the pieces.
4013e8d8bef9SDimitry Andric     if (IdxVal >= VecTy.getNumElements()) {
4014e8d8bef9SDimitry Andric       MIRBuilder.buildUndef(DstReg);
4015e8d8bef9SDimitry Andric       MI.eraseFromParent();
4016e8d8bef9SDimitry Andric       return Legalized;
40178bcb0991SDimitry Andric     }
40188bcb0991SDimitry Andric 
4019e8d8bef9SDimitry Andric     SmallVector<Register, 8> VecParts;
4020e8d8bef9SDimitry Andric     LLT GCDTy = extractGCDType(VecParts, VecTy, NarrowVecTy, SrcVec);
4021e8d8bef9SDimitry Andric 
4022e8d8bef9SDimitry Andric     // Build a sequence of NarrowTy pieces in VecParts for this operand.
4023e8d8bef9SDimitry Andric     LLT LCMTy = buildLCMMergePieces(VecTy, NarrowVecTy, GCDTy, VecParts,
4024e8d8bef9SDimitry Andric                                     TargetOpcode::G_ANYEXT);
4025e8d8bef9SDimitry Andric 
4026e8d8bef9SDimitry Andric     unsigned NewNumElts = NarrowVecTy.getNumElements();
4027e8d8bef9SDimitry Andric 
4028e8d8bef9SDimitry Andric     LLT IdxTy = MRI.getType(Idx);
4029e8d8bef9SDimitry Andric     int64_t PartIdx = IdxVal / NewNumElts;
4030e8d8bef9SDimitry Andric     auto NewIdx =
4031e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(IdxTy, IdxVal - NewNumElts * PartIdx);
4032e8d8bef9SDimitry Andric 
4033e8d8bef9SDimitry Andric     if (IsInsert) {
4034e8d8bef9SDimitry Andric       LLT PartTy = MRI.getType(VecParts[PartIdx]);
4035e8d8bef9SDimitry Andric 
4036e8d8bef9SDimitry Andric       // Use the adjusted index to insert into one of the subvectors.
4037e8d8bef9SDimitry Andric       auto InsertPart = MIRBuilder.buildInsertVectorElement(
4038e8d8bef9SDimitry Andric           PartTy, VecParts[PartIdx], InsertVal, NewIdx);
4039e8d8bef9SDimitry Andric       VecParts[PartIdx] = InsertPart.getReg(0);
4040e8d8bef9SDimitry Andric 
4041e8d8bef9SDimitry Andric       // Recombine the inserted subvector with the others to reform the result
4042e8d8bef9SDimitry Andric       // vector.
4043e8d8bef9SDimitry Andric       buildWidenedRemergeToDst(DstReg, LCMTy, VecParts);
4044e8d8bef9SDimitry Andric     } else {
4045e8d8bef9SDimitry Andric       MIRBuilder.buildExtractVectorElement(DstReg, VecParts[PartIdx], NewIdx);
40468bcb0991SDimitry Andric     }
40478bcb0991SDimitry Andric 
40488bcb0991SDimitry Andric     MI.eraseFromParent();
40498bcb0991SDimitry Andric     return Legalized;
40508bcb0991SDimitry Andric   }
40518bcb0991SDimitry Andric 
4052e8d8bef9SDimitry Andric   // With a variable index, we can't perform the operation in a smaller type, so
4053e8d8bef9SDimitry Andric   // we're forced to expand this.
4054e8d8bef9SDimitry Andric   //
4055e8d8bef9SDimitry Andric   // TODO: We could emit a chain of compare/select to figure out which piece to
4056e8d8bef9SDimitry Andric   // index.
4057e8d8bef9SDimitry Andric   return lowerExtractInsertVectorElt(MI);
4058e8d8bef9SDimitry Andric }
4059e8d8bef9SDimitry Andric 
40608bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
4061*fe6060f1SDimitry Andric LegalizerHelper::reduceLoadStoreWidth(GLoadStore &LdStMI, unsigned TypeIdx,
40620b57cec5SDimitry Andric                                       LLT NarrowTy) {
40630b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
40640b57cec5SDimitry Andric   if (TypeIdx != 0)
40650b57cec5SDimitry Andric     return UnableToLegalize;
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   // This implementation doesn't work for atomics. Give up instead of doing
40680b57cec5SDimitry Andric   // something invalid.
4069*fe6060f1SDimitry Andric   if (LdStMI.isAtomic())
40700b57cec5SDimitry Andric     return UnableToLegalize;
40710b57cec5SDimitry Andric 
4072*fe6060f1SDimitry Andric   bool IsLoad = isa<GLoad>(LdStMI);
4073*fe6060f1SDimitry Andric   Register ValReg = LdStMI.getReg(0);
4074*fe6060f1SDimitry Andric   Register AddrReg = LdStMI.getPointerReg();
40750b57cec5SDimitry Andric   LLT ValTy = MRI.getType(ValReg);
40760b57cec5SDimitry Andric 
40775ffd83dbSDimitry Andric   // FIXME: Do we need a distinct NarrowMemory legalize action?
4078*fe6060f1SDimitry Andric   if (ValTy.getSizeInBits() != 8 * LdStMI.getMemSize()) {
40795ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Can't narrow extload/truncstore\n");
40805ffd83dbSDimitry Andric     return UnableToLegalize;
40815ffd83dbSDimitry Andric   }
40825ffd83dbSDimitry Andric 
40830b57cec5SDimitry Andric   int NumParts = -1;
40840b57cec5SDimitry Andric   int NumLeftover = -1;
40850b57cec5SDimitry Andric   LLT LeftoverTy;
40860b57cec5SDimitry Andric   SmallVector<Register, 8> NarrowRegs, NarrowLeftoverRegs;
40870b57cec5SDimitry Andric   if (IsLoad) {
40880b57cec5SDimitry Andric     std::tie(NumParts, NumLeftover) = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
40890b57cec5SDimitry Andric   } else {
40900b57cec5SDimitry Andric     if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
40910b57cec5SDimitry Andric                      NarrowLeftoverRegs)) {
40920b57cec5SDimitry Andric       NumParts = NarrowRegs.size();
40930b57cec5SDimitry Andric       NumLeftover = NarrowLeftoverRegs.size();
40940b57cec5SDimitry Andric     }
40950b57cec5SDimitry Andric   }
40960b57cec5SDimitry Andric 
40970b57cec5SDimitry Andric   if (NumParts == -1)
40980b57cec5SDimitry Andric     return UnableToLegalize;
40990b57cec5SDimitry Andric 
4100e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(AddrReg);
4101e8d8bef9SDimitry Andric   const LLT OffsetTy = LLT::scalar(PtrTy.getSizeInBits());
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   unsigned TotalSize = ValTy.getSizeInBits();
41040b57cec5SDimitry Andric 
41050b57cec5SDimitry Andric   // Split the load/store into PartTy sized pieces starting at Offset. If this
41060b57cec5SDimitry Andric   // is a load, return the new registers in ValRegs. For a store, each elements
41070b57cec5SDimitry Andric   // of ValRegs should be PartTy. Returns the next offset that needs to be
41080b57cec5SDimitry Andric   // handled.
4109*fe6060f1SDimitry Andric   auto MMO = LdStMI.getMMO();
41100b57cec5SDimitry Andric   auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<Register> &ValRegs,
41110b57cec5SDimitry Andric                              unsigned Offset) -> unsigned {
41120b57cec5SDimitry Andric     MachineFunction &MF = MIRBuilder.getMF();
41130b57cec5SDimitry Andric     unsigned PartSize = PartTy.getSizeInBits();
41140b57cec5SDimitry Andric     for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
41150b57cec5SDimitry Andric          Offset += PartSize, ++Idx) {
41160b57cec5SDimitry Andric       unsigned ByteOffset = Offset / 8;
41170b57cec5SDimitry Andric       Register NewAddrReg;
41180b57cec5SDimitry Andric 
4119480093f4SDimitry Andric       MIRBuilder.materializePtrAdd(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric       MachineMemOperand *NewMMO =
4122*fe6060f1SDimitry Andric           MF.getMachineMemOperand(&MMO, ByteOffset, PartTy);
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric       if (IsLoad) {
41250b57cec5SDimitry Andric         Register Dst = MRI.createGenericVirtualRegister(PartTy);
41260b57cec5SDimitry Andric         ValRegs.push_back(Dst);
41270b57cec5SDimitry Andric         MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
41280b57cec5SDimitry Andric       } else {
41290b57cec5SDimitry Andric         MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
41300b57cec5SDimitry Andric       }
41310b57cec5SDimitry Andric     }
41320b57cec5SDimitry Andric 
41330b57cec5SDimitry Andric     return Offset;
41340b57cec5SDimitry Andric   };
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric   unsigned HandledOffset = splitTypePieces(NarrowTy, NarrowRegs, 0);
41370b57cec5SDimitry Andric 
41380b57cec5SDimitry Andric   // Handle the rest of the register if this isn't an even type breakdown.
41390b57cec5SDimitry Andric   if (LeftoverTy.isValid())
41400b57cec5SDimitry Andric     splitTypePieces(LeftoverTy, NarrowLeftoverRegs, HandledOffset);
41410b57cec5SDimitry Andric 
41420b57cec5SDimitry Andric   if (IsLoad) {
41430b57cec5SDimitry Andric     insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
41440b57cec5SDimitry Andric                 LeftoverTy, NarrowLeftoverRegs);
41450b57cec5SDimitry Andric   }
41460b57cec5SDimitry Andric 
4147*fe6060f1SDimitry Andric   LdStMI.eraseFromParent();
41480b57cec5SDimitry Andric   return Legalized;
41490b57cec5SDimitry Andric }
41500b57cec5SDimitry Andric 
41510b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
41525ffd83dbSDimitry Andric LegalizerHelper::reduceOperationWidth(MachineInstr &MI, unsigned int TypeIdx,
41535ffd83dbSDimitry Andric                                       LLT NarrowTy) {
41545ffd83dbSDimitry Andric   assert(TypeIdx == 0 && "only one type index expected");
41555ffd83dbSDimitry Andric 
41565ffd83dbSDimitry Andric   const unsigned Opc = MI.getOpcode();
4157*fe6060f1SDimitry Andric   const int NumDefOps = MI.getNumExplicitDefs();
4158*fe6060f1SDimitry Andric   const int NumSrcOps = MI.getNumOperands() - NumDefOps;
41595ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
41605ffd83dbSDimitry Andric   const unsigned NarrowSize = NarrowTy.getSizeInBits();
41615ffd83dbSDimitry Andric   const LLT NarrowScalarTy = LLT::scalar(NarrowSize);
41625ffd83dbSDimitry Andric 
4163*fe6060f1SDimitry Andric   assert(MI.getNumOperands() <= 4 && "expected instruction with either 1 "
4164*fe6060f1SDimitry Andric                                      "result and 1-3 sources or 2 results and "
4165*fe6060f1SDimitry Andric                                      "1-2 sources");
4166*fe6060f1SDimitry Andric 
4167*fe6060f1SDimitry Andric   SmallVector<Register, 2> DstRegs;
4168*fe6060f1SDimitry Andric   for (int I = 0; I < NumDefOps; ++I)
4169*fe6060f1SDimitry Andric     DstRegs.push_back(MI.getOperand(I).getReg());
41705ffd83dbSDimitry Andric 
41715ffd83dbSDimitry Andric   // First of all check whether we are narrowing (changing the element type)
41725ffd83dbSDimitry Andric   // or reducing the vector elements
4173*fe6060f1SDimitry Andric   const LLT DstTy = MRI.getType(DstRegs[0]);
41745ffd83dbSDimitry Andric   const bool IsNarrow = NarrowTy.getScalarType() != DstTy.getScalarType();
41755ffd83dbSDimitry Andric 
41765ffd83dbSDimitry Andric   SmallVector<Register, 8> ExtractedRegs[3];
41775ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
41785ffd83dbSDimitry Andric 
41795ffd83dbSDimitry Andric   // Break down all the sources into NarrowTy pieces we can operate on. This may
41805ffd83dbSDimitry Andric   // involve creating merges to a wider type, padded with undef.
4181*fe6060f1SDimitry Andric   for (int I = 0; I != NumSrcOps; ++I) {
4182*fe6060f1SDimitry Andric     Register SrcReg = MI.getOperand(I + NumDefOps).getReg();
41835ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
41845ffd83dbSDimitry Andric 
41855ffd83dbSDimitry Andric     // The type to narrow SrcReg to. For narrowing, this is a smaller scalar.
41865ffd83dbSDimitry Andric     // For fewerElements, this is a smaller vector with the same element type.
41875ffd83dbSDimitry Andric     LLT OpNarrowTy;
41885ffd83dbSDimitry Andric     if (IsNarrow) {
41895ffd83dbSDimitry Andric       OpNarrowTy = NarrowScalarTy;
41905ffd83dbSDimitry Andric 
41915ffd83dbSDimitry Andric       // In case of narrowing, we need to cast vectors to scalars for this to
41925ffd83dbSDimitry Andric       // work properly
41935ffd83dbSDimitry Andric       // FIXME: Can we do without the bitcast here if we're narrowing?
41945ffd83dbSDimitry Andric       if (SrcTy.isVector()) {
41955ffd83dbSDimitry Andric         SrcTy = LLT::scalar(SrcTy.getSizeInBits());
41965ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(SrcTy, SrcReg).getReg(0);
41975ffd83dbSDimitry Andric       }
41985ffd83dbSDimitry Andric     } else {
4199*fe6060f1SDimitry Andric       auto NarrowEC = NarrowTy.isVector() ? NarrowTy.getElementCount()
4200*fe6060f1SDimitry Andric                                           : ElementCount::getFixed(1);
4201*fe6060f1SDimitry Andric       OpNarrowTy = LLT::scalarOrVector(NarrowEC, SrcTy.getScalarType());
42025ffd83dbSDimitry Andric     }
42035ffd83dbSDimitry Andric 
42045ffd83dbSDimitry Andric     LLT GCDTy = extractGCDType(ExtractedRegs[I], SrcTy, OpNarrowTy, SrcReg);
42055ffd83dbSDimitry Andric 
42065ffd83dbSDimitry Andric     // Build a sequence of NarrowTy pieces in ExtractedRegs for this operand.
42075ffd83dbSDimitry Andric     buildLCMMergePieces(SrcTy, OpNarrowTy, GCDTy, ExtractedRegs[I],
42085ffd83dbSDimitry Andric                         TargetOpcode::G_ANYEXT);
42095ffd83dbSDimitry Andric   }
42105ffd83dbSDimitry Andric 
4211*fe6060f1SDimitry Andric   SmallVector<Register, 8> ResultRegs[2];
42125ffd83dbSDimitry Andric 
42135ffd83dbSDimitry Andric   // Input operands for each sub-instruction.
4214*fe6060f1SDimitry Andric   SmallVector<SrcOp, 4> InputRegs(NumSrcOps, Register());
42155ffd83dbSDimitry Andric 
42165ffd83dbSDimitry Andric   int NumParts = ExtractedRegs[0].size();
42175ffd83dbSDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
42185ffd83dbSDimitry Andric   const LLT DstScalarTy = LLT::scalar(DstSize);
42195ffd83dbSDimitry Andric 
42205ffd83dbSDimitry Andric   // Narrowing needs to use scalar types
42215ffd83dbSDimitry Andric   LLT DstLCMTy, NarrowDstTy;
42225ffd83dbSDimitry Andric   if (IsNarrow) {
42235ffd83dbSDimitry Andric     DstLCMTy = getLCMType(DstScalarTy, NarrowScalarTy);
42245ffd83dbSDimitry Andric     NarrowDstTy = NarrowScalarTy;
42255ffd83dbSDimitry Andric   } else {
42265ffd83dbSDimitry Andric     DstLCMTy = getLCMType(DstTy, NarrowTy);
42275ffd83dbSDimitry Andric     NarrowDstTy = NarrowTy;
42285ffd83dbSDimitry Andric   }
42295ffd83dbSDimitry Andric 
42305ffd83dbSDimitry Andric   // We widened the source registers to satisfy merge/unmerge size
42315ffd83dbSDimitry Andric   // constraints. We'll have some extra fully undef parts.
42325ffd83dbSDimitry Andric   const int NumRealParts = (DstSize + NarrowSize - 1) / NarrowSize;
42335ffd83dbSDimitry Andric 
42345ffd83dbSDimitry Andric   for (int I = 0; I != NumRealParts; ++I) {
42355ffd83dbSDimitry Andric     // Emit this instruction on each of the split pieces.
4236*fe6060f1SDimitry Andric     for (int J = 0; J != NumSrcOps; ++J)
42375ffd83dbSDimitry Andric       InputRegs[J] = ExtractedRegs[J][I];
42385ffd83dbSDimitry Andric 
4239*fe6060f1SDimitry Andric     MachineInstrBuilder Inst;
4240*fe6060f1SDimitry Andric     if (NumDefOps == 1)
4241*fe6060f1SDimitry Andric       Inst = MIRBuilder.buildInstr(Opc, {NarrowDstTy}, InputRegs, Flags);
4242*fe6060f1SDimitry Andric     else
4243*fe6060f1SDimitry Andric       Inst = MIRBuilder.buildInstr(Opc, {NarrowDstTy, NarrowDstTy}, InputRegs,
4244*fe6060f1SDimitry Andric                                    Flags);
4245*fe6060f1SDimitry Andric 
4246*fe6060f1SDimitry Andric     for (int J = 0; J != NumDefOps; ++J)
4247*fe6060f1SDimitry Andric       ResultRegs[J].push_back(Inst.getReg(J));
42485ffd83dbSDimitry Andric   }
42495ffd83dbSDimitry Andric 
42505ffd83dbSDimitry Andric   // Fill out the widened result with undef instead of creating instructions
42515ffd83dbSDimitry Andric   // with undef inputs.
42525ffd83dbSDimitry Andric   int NumUndefParts = NumParts - NumRealParts;
4253*fe6060f1SDimitry Andric   if (NumUndefParts != 0) {
4254*fe6060f1SDimitry Andric     Register Undef = MIRBuilder.buildUndef(NarrowDstTy).getReg(0);
4255*fe6060f1SDimitry Andric     for (int I = 0; I != NumDefOps; ++I)
4256*fe6060f1SDimitry Andric       ResultRegs[I].append(NumUndefParts, Undef);
4257*fe6060f1SDimitry Andric   }
42585ffd83dbSDimitry Andric 
42595ffd83dbSDimitry Andric   // Extract the possibly padded result. Use a scratch register if we need to do
42605ffd83dbSDimitry Andric   // a final bitcast, otherwise use the original result register.
42615ffd83dbSDimitry Andric   Register MergeDstReg;
4262*fe6060f1SDimitry Andric   for (int I = 0; I != NumDefOps; ++I) {
42635ffd83dbSDimitry Andric     if (IsNarrow && DstTy.isVector())
42645ffd83dbSDimitry Andric       MergeDstReg = MRI.createGenericVirtualRegister(DstScalarTy);
42655ffd83dbSDimitry Andric     else
4266*fe6060f1SDimitry Andric       MergeDstReg = DstRegs[I];
42675ffd83dbSDimitry Andric 
4268*fe6060f1SDimitry Andric     buildWidenedRemergeToDst(MergeDstReg, DstLCMTy, ResultRegs[I]);
42695ffd83dbSDimitry Andric 
42705ffd83dbSDimitry Andric     // Recast to vector if we narrowed a vector
42715ffd83dbSDimitry Andric     if (IsNarrow && DstTy.isVector())
4272*fe6060f1SDimitry Andric       MIRBuilder.buildBitcast(DstRegs[I], MergeDstReg);
4273*fe6060f1SDimitry Andric   }
42745ffd83dbSDimitry Andric 
42755ffd83dbSDimitry Andric   MI.eraseFromParent();
42765ffd83dbSDimitry Andric   return Legalized;
42775ffd83dbSDimitry Andric }
42785ffd83dbSDimitry Andric 
42795ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
42805ffd83dbSDimitry Andric LegalizerHelper::fewerElementsVectorSextInReg(MachineInstr &MI, unsigned TypeIdx,
42815ffd83dbSDimitry Andric                                               LLT NarrowTy) {
42825ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
42835ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
42845ffd83dbSDimitry Andric   int64_t Imm = MI.getOperand(2).getImm();
42855ffd83dbSDimitry Andric 
42865ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
42875ffd83dbSDimitry Andric 
42885ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
42895ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
42905ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts);
42915ffd83dbSDimitry Andric 
42925ffd83dbSDimitry Andric   for (Register &R : Parts)
42935ffd83dbSDimitry Andric     R = MIRBuilder.buildSExtInReg(NarrowTy, R, Imm).getReg(0);
42945ffd83dbSDimitry Andric 
42955ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
42965ffd83dbSDimitry Andric 
42975ffd83dbSDimitry Andric   MI.eraseFromParent();
42985ffd83dbSDimitry Andric   return Legalized;
42995ffd83dbSDimitry Andric }
43005ffd83dbSDimitry Andric 
43015ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
43020b57cec5SDimitry Andric LegalizerHelper::fewerElementsVector(MachineInstr &MI, unsigned TypeIdx,
43030b57cec5SDimitry Andric                                      LLT NarrowTy) {
43040b57cec5SDimitry Andric   using namespace TargetOpcode;
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric   switch (MI.getOpcode()) {
43070b57cec5SDimitry Andric   case G_IMPLICIT_DEF:
43080b57cec5SDimitry Andric     return fewerElementsVectorImplicitDef(MI, TypeIdx, NarrowTy);
43095ffd83dbSDimitry Andric   case G_TRUNC:
43100b57cec5SDimitry Andric   case G_AND:
43110b57cec5SDimitry Andric   case G_OR:
43120b57cec5SDimitry Andric   case G_XOR:
43130b57cec5SDimitry Andric   case G_ADD:
43140b57cec5SDimitry Andric   case G_SUB:
43150b57cec5SDimitry Andric   case G_MUL:
4316e8d8bef9SDimitry Andric   case G_PTR_ADD:
43170b57cec5SDimitry Andric   case G_SMULH:
43180b57cec5SDimitry Andric   case G_UMULH:
43190b57cec5SDimitry Andric   case G_FADD:
43200b57cec5SDimitry Andric   case G_FMUL:
43210b57cec5SDimitry Andric   case G_FSUB:
43220b57cec5SDimitry Andric   case G_FNEG:
43230b57cec5SDimitry Andric   case G_FABS:
43240b57cec5SDimitry Andric   case G_FCANONICALIZE:
43250b57cec5SDimitry Andric   case G_FDIV:
43260b57cec5SDimitry Andric   case G_FREM:
43270b57cec5SDimitry Andric   case G_FMA:
43288bcb0991SDimitry Andric   case G_FMAD:
43290b57cec5SDimitry Andric   case G_FPOW:
43300b57cec5SDimitry Andric   case G_FEXP:
43310b57cec5SDimitry Andric   case G_FEXP2:
43320b57cec5SDimitry Andric   case G_FLOG:
43330b57cec5SDimitry Andric   case G_FLOG2:
43340b57cec5SDimitry Andric   case G_FLOG10:
43350b57cec5SDimitry Andric   case G_FNEARBYINT:
43360b57cec5SDimitry Andric   case G_FCEIL:
43370b57cec5SDimitry Andric   case G_FFLOOR:
43380b57cec5SDimitry Andric   case G_FRINT:
43390b57cec5SDimitry Andric   case G_INTRINSIC_ROUND:
4340e8d8bef9SDimitry Andric   case G_INTRINSIC_ROUNDEVEN:
43410b57cec5SDimitry Andric   case G_INTRINSIC_TRUNC:
43420b57cec5SDimitry Andric   case G_FCOS:
43430b57cec5SDimitry Andric   case G_FSIN:
43440b57cec5SDimitry Andric   case G_FSQRT:
43450b57cec5SDimitry Andric   case G_BSWAP:
43468bcb0991SDimitry Andric   case G_BITREVERSE:
43470b57cec5SDimitry Andric   case G_SDIV:
4348480093f4SDimitry Andric   case G_UDIV:
4349480093f4SDimitry Andric   case G_SREM:
4350480093f4SDimitry Andric   case G_UREM:
4351*fe6060f1SDimitry Andric   case G_SDIVREM:
4352*fe6060f1SDimitry Andric   case G_UDIVREM:
43530b57cec5SDimitry Andric   case G_SMIN:
43540b57cec5SDimitry Andric   case G_SMAX:
43550b57cec5SDimitry Andric   case G_UMIN:
43560b57cec5SDimitry Andric   case G_UMAX:
4357*fe6060f1SDimitry Andric   case G_ABS:
43580b57cec5SDimitry Andric   case G_FMINNUM:
43590b57cec5SDimitry Andric   case G_FMAXNUM:
43600b57cec5SDimitry Andric   case G_FMINNUM_IEEE:
43610b57cec5SDimitry Andric   case G_FMAXNUM_IEEE:
43620b57cec5SDimitry Andric   case G_FMINIMUM:
43630b57cec5SDimitry Andric   case G_FMAXIMUM:
43645ffd83dbSDimitry Andric   case G_FSHL:
43655ffd83dbSDimitry Andric   case G_FSHR:
43665ffd83dbSDimitry Andric   case G_FREEZE:
43675ffd83dbSDimitry Andric   case G_SADDSAT:
43685ffd83dbSDimitry Andric   case G_SSUBSAT:
43695ffd83dbSDimitry Andric   case G_UADDSAT:
43705ffd83dbSDimitry Andric   case G_USUBSAT:
43715ffd83dbSDimitry Andric     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
4372*fe6060f1SDimitry Andric   case G_UMULO:
4373*fe6060f1SDimitry Andric   case G_SMULO:
4374*fe6060f1SDimitry Andric     return fewerElementsVectorMulo(MI, TypeIdx, NarrowTy);
43750b57cec5SDimitry Andric   case G_SHL:
43760b57cec5SDimitry Andric   case G_LSHR:
43770b57cec5SDimitry Andric   case G_ASHR:
4378e8d8bef9SDimitry Andric   case G_SSHLSAT:
4379e8d8bef9SDimitry Andric   case G_USHLSAT:
43800b57cec5SDimitry Andric   case G_CTLZ:
43810b57cec5SDimitry Andric   case G_CTLZ_ZERO_UNDEF:
43820b57cec5SDimitry Andric   case G_CTTZ:
43830b57cec5SDimitry Andric   case G_CTTZ_ZERO_UNDEF:
43840b57cec5SDimitry Andric   case G_CTPOP:
43850b57cec5SDimitry Andric   case G_FCOPYSIGN:
43860b57cec5SDimitry Andric     return fewerElementsVectorMultiEltType(MI, TypeIdx, NarrowTy);
43870b57cec5SDimitry Andric   case G_ZEXT:
43880b57cec5SDimitry Andric   case G_SEXT:
43890b57cec5SDimitry Andric   case G_ANYEXT:
43900b57cec5SDimitry Andric   case G_FPEXT:
43910b57cec5SDimitry Andric   case G_FPTRUNC:
43920b57cec5SDimitry Andric   case G_SITOFP:
43930b57cec5SDimitry Andric   case G_UITOFP:
43940b57cec5SDimitry Andric   case G_FPTOSI:
43950b57cec5SDimitry Andric   case G_FPTOUI:
43960b57cec5SDimitry Andric   case G_INTTOPTR:
43970b57cec5SDimitry Andric   case G_PTRTOINT:
43980b57cec5SDimitry Andric   case G_ADDRSPACE_CAST:
43990b57cec5SDimitry Andric     return fewerElementsVectorCasts(MI, TypeIdx, NarrowTy);
44000b57cec5SDimitry Andric   case G_ICMP:
44010b57cec5SDimitry Andric   case G_FCMP:
44020b57cec5SDimitry Andric     return fewerElementsVectorCmp(MI, TypeIdx, NarrowTy);
44030b57cec5SDimitry Andric   case G_SELECT:
44040b57cec5SDimitry Andric     return fewerElementsVectorSelect(MI, TypeIdx, NarrowTy);
44050b57cec5SDimitry Andric   case G_PHI:
44060b57cec5SDimitry Andric     return fewerElementsVectorPhi(MI, TypeIdx, NarrowTy);
44078bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
44088bcb0991SDimitry Andric     return fewerElementsVectorUnmergeValues(MI, TypeIdx, NarrowTy);
44098bcb0991SDimitry Andric   case G_BUILD_VECTOR:
4410e8d8bef9SDimitry Andric     assert(TypeIdx == 0 && "not a vector type index");
4411e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4412e8d8bef9SDimitry Andric   case G_CONCAT_VECTORS:
4413e8d8bef9SDimitry Andric     if (TypeIdx != 1) // TODO: This probably does work as expected already.
4414e8d8bef9SDimitry Andric       return UnableToLegalize;
4415e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4416e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
4417e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
4418e8d8bef9SDimitry Andric     return fewerElementsVectorExtractInsertVectorElt(MI, TypeIdx, NarrowTy);
44190b57cec5SDimitry Andric   case G_LOAD:
44200b57cec5SDimitry Andric   case G_STORE:
4421*fe6060f1SDimitry Andric     return reduceLoadStoreWidth(cast<GLoadStore>(MI), TypeIdx, NarrowTy);
44225ffd83dbSDimitry Andric   case G_SEXT_INREG:
44235ffd83dbSDimitry Andric     return fewerElementsVectorSextInReg(MI, TypeIdx, NarrowTy);
4424*fe6060f1SDimitry Andric   GISEL_VECREDUCE_CASES_NONSEQ
4425*fe6060f1SDimitry Andric     return fewerElementsVectorReductions(MI, TypeIdx, NarrowTy);
4426*fe6060f1SDimitry Andric   case G_SHUFFLE_VECTOR:
4427*fe6060f1SDimitry Andric     return fewerElementsVectorShuffle(MI, TypeIdx, NarrowTy);
44280b57cec5SDimitry Andric   default:
44290b57cec5SDimitry Andric     return UnableToLegalize;
44300b57cec5SDimitry Andric   }
44310b57cec5SDimitry Andric }
44320b57cec5SDimitry Andric 
4433*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorShuffle(
4434*fe6060f1SDimitry Andric     MachineInstr &MI, unsigned int TypeIdx, LLT NarrowTy) {
4435*fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
4436*fe6060f1SDimitry Andric   if (TypeIdx != 0)
4437*fe6060f1SDimitry Andric     return UnableToLegalize;
4438*fe6060f1SDimitry Andric 
4439*fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
4440*fe6060f1SDimitry Andric   Register Src1Reg = MI.getOperand(1).getReg();
4441*fe6060f1SDimitry Andric   Register Src2Reg = MI.getOperand(2).getReg();
4442*fe6060f1SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
4443*fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
4444*fe6060f1SDimitry Andric   LLT Src1Ty = MRI.getType(Src1Reg);
4445*fe6060f1SDimitry Andric   LLT Src2Ty = MRI.getType(Src2Reg);
4446*fe6060f1SDimitry Andric   // The shuffle should be canonicalized by now.
4447*fe6060f1SDimitry Andric   if (DstTy != Src1Ty)
4448*fe6060f1SDimitry Andric     return UnableToLegalize;
4449*fe6060f1SDimitry Andric   if (DstTy != Src2Ty)
4450*fe6060f1SDimitry Andric     return UnableToLegalize;
4451*fe6060f1SDimitry Andric 
4452*fe6060f1SDimitry Andric   if (!isPowerOf2_32(DstTy.getNumElements()))
4453*fe6060f1SDimitry Andric     return UnableToLegalize;
4454*fe6060f1SDimitry Andric 
4455*fe6060f1SDimitry Andric   // We only support splitting a shuffle into 2, so adjust NarrowTy accordingly.
4456*fe6060f1SDimitry Andric   // Further legalization attempts will be needed to do split further.
4457*fe6060f1SDimitry Andric   NarrowTy =
4458*fe6060f1SDimitry Andric       DstTy.changeElementCount(DstTy.getElementCount().divideCoefficientBy(2));
4459*fe6060f1SDimitry Andric   unsigned NewElts = NarrowTy.getNumElements();
4460*fe6060f1SDimitry Andric 
4461*fe6060f1SDimitry Andric   SmallVector<Register> SplitSrc1Regs, SplitSrc2Regs;
4462*fe6060f1SDimitry Andric   extractParts(Src1Reg, NarrowTy, 2, SplitSrc1Regs);
4463*fe6060f1SDimitry Andric   extractParts(Src2Reg, NarrowTy, 2, SplitSrc2Regs);
4464*fe6060f1SDimitry Andric   Register Inputs[4] = {SplitSrc1Regs[0], SplitSrc1Regs[1], SplitSrc2Regs[0],
4465*fe6060f1SDimitry Andric                         SplitSrc2Regs[1]};
4466*fe6060f1SDimitry Andric 
4467*fe6060f1SDimitry Andric   Register Hi, Lo;
4468*fe6060f1SDimitry Andric 
4469*fe6060f1SDimitry Andric   // If Lo or Hi uses elements from at most two of the four input vectors, then
4470*fe6060f1SDimitry Andric   // express it as a vector shuffle of those two inputs.  Otherwise extract the
4471*fe6060f1SDimitry Andric   // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
4472*fe6060f1SDimitry Andric   SmallVector<int, 16> Ops;
4473*fe6060f1SDimitry Andric   for (unsigned High = 0; High < 2; ++High) {
4474*fe6060f1SDimitry Andric     Register &Output = High ? Hi : Lo;
4475*fe6060f1SDimitry Andric 
4476*fe6060f1SDimitry Andric     // Build a shuffle mask for the output, discovering on the fly which
4477*fe6060f1SDimitry Andric     // input vectors to use as shuffle operands (recorded in InputUsed).
4478*fe6060f1SDimitry Andric     // If building a suitable shuffle vector proves too hard, then bail
4479*fe6060f1SDimitry Andric     // out with useBuildVector set.
4480*fe6060f1SDimitry Andric     unsigned InputUsed[2] = {-1U, -1U}; // Not yet discovered.
4481*fe6060f1SDimitry Andric     unsigned FirstMaskIdx = High * NewElts;
4482*fe6060f1SDimitry Andric     bool UseBuildVector = false;
4483*fe6060f1SDimitry Andric     for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
4484*fe6060f1SDimitry Andric       // The mask element.  This indexes into the input.
4485*fe6060f1SDimitry Andric       int Idx = Mask[FirstMaskIdx + MaskOffset];
4486*fe6060f1SDimitry Andric 
4487*fe6060f1SDimitry Andric       // The input vector this mask element indexes into.
4488*fe6060f1SDimitry Andric       unsigned Input = (unsigned)Idx / NewElts;
4489*fe6060f1SDimitry Andric 
4490*fe6060f1SDimitry Andric       if (Input >= array_lengthof(Inputs)) {
4491*fe6060f1SDimitry Andric         // The mask element does not index into any input vector.
4492*fe6060f1SDimitry Andric         Ops.push_back(-1);
4493*fe6060f1SDimitry Andric         continue;
4494*fe6060f1SDimitry Andric       }
4495*fe6060f1SDimitry Andric 
4496*fe6060f1SDimitry Andric       // Turn the index into an offset from the start of the input vector.
4497*fe6060f1SDimitry Andric       Idx -= Input * NewElts;
4498*fe6060f1SDimitry Andric 
4499*fe6060f1SDimitry Andric       // Find or create a shuffle vector operand to hold this input.
4500*fe6060f1SDimitry Andric       unsigned OpNo;
4501*fe6060f1SDimitry Andric       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
4502*fe6060f1SDimitry Andric         if (InputUsed[OpNo] == Input) {
4503*fe6060f1SDimitry Andric           // This input vector is already an operand.
4504*fe6060f1SDimitry Andric           break;
4505*fe6060f1SDimitry Andric         } else if (InputUsed[OpNo] == -1U) {
4506*fe6060f1SDimitry Andric           // Create a new operand for this input vector.
4507*fe6060f1SDimitry Andric           InputUsed[OpNo] = Input;
4508*fe6060f1SDimitry Andric           break;
4509*fe6060f1SDimitry Andric         }
4510*fe6060f1SDimitry Andric       }
4511*fe6060f1SDimitry Andric 
4512*fe6060f1SDimitry Andric       if (OpNo >= array_lengthof(InputUsed)) {
4513*fe6060f1SDimitry Andric         // More than two input vectors used!  Give up on trying to create a
4514*fe6060f1SDimitry Andric         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
4515*fe6060f1SDimitry Andric         UseBuildVector = true;
4516*fe6060f1SDimitry Andric         break;
4517*fe6060f1SDimitry Andric       }
4518*fe6060f1SDimitry Andric 
4519*fe6060f1SDimitry Andric       // Add the mask index for the new shuffle vector.
4520*fe6060f1SDimitry Andric       Ops.push_back(Idx + OpNo * NewElts);
4521*fe6060f1SDimitry Andric     }
4522*fe6060f1SDimitry Andric 
4523*fe6060f1SDimitry Andric     if (UseBuildVector) {
4524*fe6060f1SDimitry Andric       LLT EltTy = NarrowTy.getElementType();
4525*fe6060f1SDimitry Andric       SmallVector<Register, 16> SVOps;
4526*fe6060f1SDimitry Andric 
4527*fe6060f1SDimitry Andric       // Extract the input elements by hand.
4528*fe6060f1SDimitry Andric       for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
4529*fe6060f1SDimitry Andric         // The mask element.  This indexes into the input.
4530*fe6060f1SDimitry Andric         int Idx = Mask[FirstMaskIdx + MaskOffset];
4531*fe6060f1SDimitry Andric 
4532*fe6060f1SDimitry Andric         // The input vector this mask element indexes into.
4533*fe6060f1SDimitry Andric         unsigned Input = (unsigned)Idx / NewElts;
4534*fe6060f1SDimitry Andric 
4535*fe6060f1SDimitry Andric         if (Input >= array_lengthof(Inputs)) {
4536*fe6060f1SDimitry Andric           // The mask element is "undef" or indexes off the end of the input.
4537*fe6060f1SDimitry Andric           SVOps.push_back(MIRBuilder.buildUndef(EltTy).getReg(0));
4538*fe6060f1SDimitry Andric           continue;
4539*fe6060f1SDimitry Andric         }
4540*fe6060f1SDimitry Andric 
4541*fe6060f1SDimitry Andric         // Turn the index into an offset from the start of the input vector.
4542*fe6060f1SDimitry Andric         Idx -= Input * NewElts;
4543*fe6060f1SDimitry Andric 
4544*fe6060f1SDimitry Andric         // Extract the vector element by hand.
4545*fe6060f1SDimitry Andric         SVOps.push_back(MIRBuilder
4546*fe6060f1SDimitry Andric                             .buildExtractVectorElement(
4547*fe6060f1SDimitry Andric                                 EltTy, Inputs[Input],
4548*fe6060f1SDimitry Andric                                 MIRBuilder.buildConstant(LLT::scalar(32), Idx))
4549*fe6060f1SDimitry Andric                             .getReg(0));
4550*fe6060f1SDimitry Andric       }
4551*fe6060f1SDimitry Andric 
4552*fe6060f1SDimitry Andric       // Construct the Lo/Hi output using a G_BUILD_VECTOR.
4553*fe6060f1SDimitry Andric       Output = MIRBuilder.buildBuildVector(NarrowTy, SVOps).getReg(0);
4554*fe6060f1SDimitry Andric     } else if (InputUsed[0] == -1U) {
4555*fe6060f1SDimitry Andric       // No input vectors were used! The result is undefined.
4556*fe6060f1SDimitry Andric       Output = MIRBuilder.buildUndef(NarrowTy).getReg(0);
4557*fe6060f1SDimitry Andric     } else {
4558*fe6060f1SDimitry Andric       Register Op0 = Inputs[InputUsed[0]];
4559*fe6060f1SDimitry Andric       // If only one input was used, use an undefined vector for the other.
4560*fe6060f1SDimitry Andric       Register Op1 = InputUsed[1] == -1U
4561*fe6060f1SDimitry Andric                          ? MIRBuilder.buildUndef(NarrowTy).getReg(0)
4562*fe6060f1SDimitry Andric                          : Inputs[InputUsed[1]];
4563*fe6060f1SDimitry Andric       // At least one input vector was used. Create a new shuffle vector.
4564*fe6060f1SDimitry Andric       Output = MIRBuilder.buildShuffleVector(NarrowTy, Op0, Op1, Ops).getReg(0);
4565*fe6060f1SDimitry Andric     }
4566*fe6060f1SDimitry Andric 
4567*fe6060f1SDimitry Andric     Ops.clear();
4568*fe6060f1SDimitry Andric   }
4569*fe6060f1SDimitry Andric 
4570*fe6060f1SDimitry Andric   MIRBuilder.buildConcatVectors(DstReg, {Lo, Hi});
4571*fe6060f1SDimitry Andric   MI.eraseFromParent();
4572*fe6060f1SDimitry Andric   return Legalized;
4573*fe6060f1SDimitry Andric }
4574*fe6060f1SDimitry Andric 
4575*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorReductions(
4576*fe6060f1SDimitry Andric     MachineInstr &MI, unsigned int TypeIdx, LLT NarrowTy) {
4577*fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
4578*fe6060f1SDimitry Andric   assert(Opc != TargetOpcode::G_VECREDUCE_SEQ_FADD &&
4579*fe6060f1SDimitry Andric          Opc != TargetOpcode::G_VECREDUCE_SEQ_FMUL &&
4580*fe6060f1SDimitry Andric          "Sequential reductions not expected");
4581*fe6060f1SDimitry Andric 
4582*fe6060f1SDimitry Andric   if (TypeIdx != 1)
4583*fe6060f1SDimitry Andric     return UnableToLegalize;
4584*fe6060f1SDimitry Andric 
4585*fe6060f1SDimitry Andric   // The semantics of the normal non-sequential reductions allow us to freely
4586*fe6060f1SDimitry Andric   // re-associate the operation.
4587*fe6060f1SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
4588*fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
4589*fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
4590*fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
4591*fe6060f1SDimitry Andric 
4592*fe6060f1SDimitry Andric   if (SrcTy.getNumElements() % NarrowTy.getNumElements() != 0)
4593*fe6060f1SDimitry Andric     return UnableToLegalize;
4594*fe6060f1SDimitry Andric 
4595*fe6060f1SDimitry Andric   SmallVector<Register> SplitSrcs;
4596*fe6060f1SDimitry Andric   const unsigned NumParts = SrcTy.getNumElements() / NarrowTy.getNumElements();
4597*fe6060f1SDimitry Andric   extractParts(SrcReg, NarrowTy, NumParts, SplitSrcs);
4598*fe6060f1SDimitry Andric   SmallVector<Register> PartialReductions;
4599*fe6060f1SDimitry Andric   for (unsigned Part = 0; Part < NumParts; ++Part) {
4600*fe6060f1SDimitry Andric     PartialReductions.push_back(
4601*fe6060f1SDimitry Andric         MIRBuilder.buildInstr(Opc, {DstTy}, {SplitSrcs[Part]}).getReg(0));
4602*fe6060f1SDimitry Andric   }
4603*fe6060f1SDimitry Andric 
4604*fe6060f1SDimitry Andric   unsigned ScalarOpc;
4605*fe6060f1SDimitry Andric   switch (Opc) {
4606*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FADD:
4607*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FADD;
4608*fe6060f1SDimitry Andric     break;
4609*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FMUL:
4610*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FMUL;
4611*fe6060f1SDimitry Andric     break;
4612*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FMAX:
4613*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FMAXNUM;
4614*fe6060f1SDimitry Andric     break;
4615*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FMIN:
4616*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FMINNUM;
4617*fe6060f1SDimitry Andric     break;
4618*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_ADD:
4619*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_ADD;
4620*fe6060f1SDimitry Andric     break;
4621*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_MUL:
4622*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_MUL;
4623*fe6060f1SDimitry Andric     break;
4624*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_AND:
4625*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_AND;
4626*fe6060f1SDimitry Andric     break;
4627*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_OR:
4628*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_OR;
4629*fe6060f1SDimitry Andric     break;
4630*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_XOR:
4631*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_XOR;
4632*fe6060f1SDimitry Andric     break;
4633*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_SMAX:
4634*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_SMAX;
4635*fe6060f1SDimitry Andric     break;
4636*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_SMIN:
4637*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_SMIN;
4638*fe6060f1SDimitry Andric     break;
4639*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_UMAX:
4640*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_UMAX;
4641*fe6060f1SDimitry Andric     break;
4642*fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_UMIN:
4643*fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_UMIN;
4644*fe6060f1SDimitry Andric     break;
4645*fe6060f1SDimitry Andric   default:
4646*fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't legalize: unknown reduction kind.\n");
4647*fe6060f1SDimitry Andric     return UnableToLegalize;
4648*fe6060f1SDimitry Andric   }
4649*fe6060f1SDimitry Andric 
4650*fe6060f1SDimitry Andric   // If the types involved are powers of 2, we can generate intermediate vector
4651*fe6060f1SDimitry Andric   // ops, before generating a final reduction operation.
4652*fe6060f1SDimitry Andric   if (isPowerOf2_32(SrcTy.getNumElements()) &&
4653*fe6060f1SDimitry Andric       isPowerOf2_32(NarrowTy.getNumElements())) {
4654*fe6060f1SDimitry Andric     return tryNarrowPow2Reduction(MI, SrcReg, SrcTy, NarrowTy, ScalarOpc);
4655*fe6060f1SDimitry Andric   }
4656*fe6060f1SDimitry Andric 
4657*fe6060f1SDimitry Andric   Register Acc = PartialReductions[0];
4658*fe6060f1SDimitry Andric   for (unsigned Part = 1; Part < NumParts; ++Part) {
4659*fe6060f1SDimitry Andric     if (Part == NumParts - 1) {
4660*fe6060f1SDimitry Andric       MIRBuilder.buildInstr(ScalarOpc, {DstReg},
4661*fe6060f1SDimitry Andric                             {Acc, PartialReductions[Part]});
4662*fe6060f1SDimitry Andric     } else {
4663*fe6060f1SDimitry Andric       Acc = MIRBuilder
4664*fe6060f1SDimitry Andric                 .buildInstr(ScalarOpc, {DstTy}, {Acc, PartialReductions[Part]})
4665*fe6060f1SDimitry Andric                 .getReg(0);
4666*fe6060f1SDimitry Andric     }
4667*fe6060f1SDimitry Andric   }
4668*fe6060f1SDimitry Andric   MI.eraseFromParent();
4669*fe6060f1SDimitry Andric   return Legalized;
4670*fe6060f1SDimitry Andric }
4671*fe6060f1SDimitry Andric 
4672*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
4673*fe6060f1SDimitry Andric LegalizerHelper::tryNarrowPow2Reduction(MachineInstr &MI, Register SrcReg,
4674*fe6060f1SDimitry Andric                                         LLT SrcTy, LLT NarrowTy,
4675*fe6060f1SDimitry Andric                                         unsigned ScalarOpc) {
4676*fe6060f1SDimitry Andric   SmallVector<Register> SplitSrcs;
4677*fe6060f1SDimitry Andric   // Split the sources into NarrowTy size pieces.
4678*fe6060f1SDimitry Andric   extractParts(SrcReg, NarrowTy,
4679*fe6060f1SDimitry Andric                SrcTy.getNumElements() / NarrowTy.getNumElements(), SplitSrcs);
4680*fe6060f1SDimitry Andric   // We're going to do a tree reduction using vector operations until we have
4681*fe6060f1SDimitry Andric   // one NarrowTy size value left.
4682*fe6060f1SDimitry Andric   while (SplitSrcs.size() > 1) {
4683*fe6060f1SDimitry Andric     SmallVector<Register> PartialRdxs;
4684*fe6060f1SDimitry Andric     for (unsigned Idx = 0; Idx < SplitSrcs.size()-1; Idx += 2) {
4685*fe6060f1SDimitry Andric       Register LHS = SplitSrcs[Idx];
4686*fe6060f1SDimitry Andric       Register RHS = SplitSrcs[Idx + 1];
4687*fe6060f1SDimitry Andric       // Create the intermediate vector op.
4688*fe6060f1SDimitry Andric       Register Res =
4689*fe6060f1SDimitry Andric           MIRBuilder.buildInstr(ScalarOpc, {NarrowTy}, {LHS, RHS}).getReg(0);
4690*fe6060f1SDimitry Andric       PartialRdxs.push_back(Res);
4691*fe6060f1SDimitry Andric     }
4692*fe6060f1SDimitry Andric     SplitSrcs = std::move(PartialRdxs);
4693*fe6060f1SDimitry Andric   }
4694*fe6060f1SDimitry Andric   // Finally generate the requested NarrowTy based reduction.
4695*fe6060f1SDimitry Andric   Observer.changingInstr(MI);
4696*fe6060f1SDimitry Andric   MI.getOperand(1).setReg(SplitSrcs[0]);
4697*fe6060f1SDimitry Andric   Observer.changedInstr(MI);
4698*fe6060f1SDimitry Andric   return Legalized;
4699*fe6060f1SDimitry Andric }
4700*fe6060f1SDimitry Andric 
47010b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
47020b57cec5SDimitry Andric LegalizerHelper::narrowScalarShiftByConstant(MachineInstr &MI, const APInt &Amt,
47030b57cec5SDimitry Andric                                              const LLT HalfTy, const LLT AmtTy) {
47040b57cec5SDimitry Andric 
47050b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
47060b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
47075ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
47080b57cec5SDimitry Andric 
47090b57cec5SDimitry Andric   if (Amt.isNullValue()) {
47105ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), {InL, InH});
47110b57cec5SDimitry Andric     MI.eraseFromParent();
47120b57cec5SDimitry Andric     return Legalized;
47130b57cec5SDimitry Andric   }
47140b57cec5SDimitry Andric 
47150b57cec5SDimitry Andric   LLT NVT = HalfTy;
47160b57cec5SDimitry Andric   unsigned NVTBits = HalfTy.getSizeInBits();
47170b57cec5SDimitry Andric   unsigned VTBits = 2 * NVTBits;
47180b57cec5SDimitry Andric 
47190b57cec5SDimitry Andric   SrcOp Lo(Register(0)), Hi(Register(0));
47200b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_SHL) {
47210b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
47220b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
47230b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
47240b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
47250b57cec5SDimitry Andric       Hi = MIRBuilder.buildShl(NVT, InL,
47260b57cec5SDimitry Andric                                MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
47270b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
47280b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
47290b57cec5SDimitry Andric       Hi = InL;
47300b57cec5SDimitry Andric     } else {
47310b57cec5SDimitry Andric       Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
47320b57cec5SDimitry Andric       auto OrLHS =
47330b57cec5SDimitry Andric           MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
47340b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildLShr(
47350b57cec5SDimitry Andric           NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
47360b57cec5SDimitry Andric       Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
47370b57cec5SDimitry Andric     }
47380b57cec5SDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
47390b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
47400b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
47410b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
47420b57cec5SDimitry Andric       Lo = MIRBuilder.buildLShr(NVT, InH,
47430b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
47440b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
47450b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
47460b57cec5SDimitry Andric       Lo = InH;
47470b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
47480b57cec5SDimitry Andric     } else {
47490b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
47500b57cec5SDimitry Andric 
47510b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
47520b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
47530b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
47560b57cec5SDimitry Andric       Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
47570b57cec5SDimitry Andric     }
47580b57cec5SDimitry Andric   } else {
47590b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
47600b57cec5SDimitry Andric       Hi = Lo = MIRBuilder.buildAShr(
47610b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
47620b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
47630b57cec5SDimitry Andric       Lo = MIRBuilder.buildAShr(NVT, InH,
47640b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
47650b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
47660b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
47670b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
47680b57cec5SDimitry Andric       Lo = InH;
47690b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
47700b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
47710b57cec5SDimitry Andric     } else {
47720b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
47730b57cec5SDimitry Andric 
47740b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
47750b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
47760b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
47770b57cec5SDimitry Andric 
47780b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
47790b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
47800b57cec5SDimitry Andric     }
47810b57cec5SDimitry Andric   }
47820b57cec5SDimitry Andric 
47835ffd83dbSDimitry Andric   MIRBuilder.buildMerge(MI.getOperand(0), {Lo, Hi});
47840b57cec5SDimitry Andric   MI.eraseFromParent();
47850b57cec5SDimitry Andric 
47860b57cec5SDimitry Andric   return Legalized;
47870b57cec5SDimitry Andric }
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric // TODO: Optimize if constant shift amount.
47900b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
47910b57cec5SDimitry Andric LegalizerHelper::narrowScalarShift(MachineInstr &MI, unsigned TypeIdx,
47920b57cec5SDimitry Andric                                    LLT RequestedTy) {
47930b57cec5SDimitry Andric   if (TypeIdx == 1) {
47940b57cec5SDimitry Andric     Observer.changingInstr(MI);
47950b57cec5SDimitry Andric     narrowScalarSrc(MI, RequestedTy, 2);
47960b57cec5SDimitry Andric     Observer.changedInstr(MI);
47970b57cec5SDimitry Andric     return Legalized;
47980b57cec5SDimitry Andric   }
47990b57cec5SDimitry Andric 
48000b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
48010b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
48020b57cec5SDimitry Andric   if (DstTy.isVector())
48030b57cec5SDimitry Andric     return UnableToLegalize;
48040b57cec5SDimitry Andric 
48050b57cec5SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
48060b57cec5SDimitry Andric   LLT ShiftAmtTy = MRI.getType(Amt);
48070b57cec5SDimitry Andric   const unsigned DstEltSize = DstTy.getScalarSizeInBits();
48080b57cec5SDimitry Andric   if (DstEltSize % 2 != 0)
48090b57cec5SDimitry Andric     return UnableToLegalize;
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric   // Ignore the input type. We can only go to exactly half the size of the
48120b57cec5SDimitry Andric   // input. If that isn't small enough, the resulting pieces will be further
48130b57cec5SDimitry Andric   // legalized.
48140b57cec5SDimitry Andric   const unsigned NewBitSize = DstEltSize / 2;
48150b57cec5SDimitry Andric   const LLT HalfTy = LLT::scalar(NewBitSize);
48160b57cec5SDimitry Andric   const LLT CondTy = LLT::scalar(1);
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric   if (const MachineInstr *KShiftAmt =
48190b57cec5SDimitry Andric           getOpcodeDef(TargetOpcode::G_CONSTANT, Amt, MRI)) {
48200b57cec5SDimitry Andric     return narrowScalarShiftByConstant(
48210b57cec5SDimitry Andric         MI, KShiftAmt->getOperand(1).getCImm()->getValue(), HalfTy, ShiftAmtTy);
48220b57cec5SDimitry Andric   }
48230b57cec5SDimitry Andric 
48240b57cec5SDimitry Andric   // TODO: Expand with known bits.
48250b57cec5SDimitry Andric 
48260b57cec5SDimitry Andric   // Handle the fully general expansion by an unknown amount.
48270b57cec5SDimitry Andric   auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
48280b57cec5SDimitry Andric 
48290b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
48300b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
48315ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
48320b57cec5SDimitry Andric 
48330b57cec5SDimitry Andric   auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
48340b57cec5SDimitry Andric   auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric   auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
48370b57cec5SDimitry Andric   auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
48380b57cec5SDimitry Andric   auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
48390b57cec5SDimitry Andric 
48400b57cec5SDimitry Andric   Register ResultRegs[2];
48410b57cec5SDimitry Andric   switch (MI.getOpcode()) {
48420b57cec5SDimitry Andric   case TargetOpcode::G_SHL: {
48430b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
48448bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildShl(HalfTy, InL, Amt);
48450b57cec5SDimitry Andric 
48468bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
48478bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, Amt);
48488bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
48490b57cec5SDimitry Andric 
48500b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
48510b57cec5SDimitry Andric     auto LoL = MIRBuilder.buildConstant(HalfTy, 0);         // Lo part is zero.
48520b57cec5SDimitry Andric     auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
48550b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(
48560b57cec5SDimitry Andric         HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
48570b57cec5SDimitry Andric 
48580b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
48590b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
48600b57cec5SDimitry Andric     break;
48610b57cec5SDimitry Andric   }
48628bcb0991SDimitry Andric   case TargetOpcode::G_LSHR:
48630b57cec5SDimitry Andric   case TargetOpcode::G_ASHR: {
48640b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
48658bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy}, {InH, Amt});
48660b57cec5SDimitry Andric 
48678bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, Amt);
48688bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
48698bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
48700b57cec5SDimitry Andric 
48710b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
48728bcb0991SDimitry Andric     MachineInstrBuilder HiL;
48738bcb0991SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_LSHR) {
48748bcb0991SDimitry Andric       HiL = MIRBuilder.buildConstant(HalfTy, 0);            // Hi part is zero.
48758bcb0991SDimitry Andric     } else {
48768bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1);
48778bcb0991SDimitry Andric       HiL = MIRBuilder.buildAShr(HalfTy, InH, ShiftAmt);    // Sign of Hi part.
48788bcb0991SDimitry Andric     }
48798bcb0991SDimitry Andric     auto LoL = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy},
48808bcb0991SDimitry Andric                                      {InH, AmtExcess});     // Lo from Hi part.
48810b57cec5SDimitry Andric 
48820b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(
48830b57cec5SDimitry Andric         HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
48840b57cec5SDimitry Andric 
48850b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
48860b57cec5SDimitry Andric 
48870b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
48880b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
48890b57cec5SDimitry Andric     break;
48900b57cec5SDimitry Andric   }
48910b57cec5SDimitry Andric   default:
48920b57cec5SDimitry Andric     llvm_unreachable("not a shift");
48930b57cec5SDimitry Andric   }
48940b57cec5SDimitry Andric 
48950b57cec5SDimitry Andric   MIRBuilder.buildMerge(DstReg, ResultRegs);
48960b57cec5SDimitry Andric   MI.eraseFromParent();
48970b57cec5SDimitry Andric   return Legalized;
48980b57cec5SDimitry Andric }
48990b57cec5SDimitry Andric 
49000b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
49010b57cec5SDimitry Andric LegalizerHelper::moreElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
49020b57cec5SDimitry Andric                                        LLT MoreTy) {
49030b57cec5SDimitry Andric   assert(TypeIdx == 0 && "Expecting only Idx 0");
49040b57cec5SDimitry Andric 
49050b57cec5SDimitry Andric   Observer.changingInstr(MI);
49060b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
49070b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
49080b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
49090b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, I);
49100b57cec5SDimitry Andric   }
49110b57cec5SDimitry Andric 
49120b57cec5SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
49130b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
49140b57cec5SDimitry Andric   moreElementsVectorDst(MI, MoreTy, 0);
49150b57cec5SDimitry Andric   Observer.changedInstr(MI);
49160b57cec5SDimitry Andric   return Legalized;
49170b57cec5SDimitry Andric }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
49200b57cec5SDimitry Andric LegalizerHelper::moreElementsVector(MachineInstr &MI, unsigned TypeIdx,
49210b57cec5SDimitry Andric                                     LLT MoreTy) {
49220b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
49230b57cec5SDimitry Andric   switch (Opc) {
49248bcb0991SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF:
49258bcb0991SDimitry Andric   case TargetOpcode::G_LOAD: {
49268bcb0991SDimitry Andric     if (TypeIdx != 0)
49278bcb0991SDimitry Andric       return UnableToLegalize;
49280b57cec5SDimitry Andric     Observer.changingInstr(MI);
49290b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
49300b57cec5SDimitry Andric     Observer.changedInstr(MI);
49310b57cec5SDimitry Andric     return Legalized;
49320b57cec5SDimitry Andric   }
49338bcb0991SDimitry Andric   case TargetOpcode::G_STORE:
49348bcb0991SDimitry Andric     if (TypeIdx != 0)
49358bcb0991SDimitry Andric       return UnableToLegalize;
49368bcb0991SDimitry Andric     Observer.changingInstr(MI);
49378bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 0);
49388bcb0991SDimitry Andric     Observer.changedInstr(MI);
49398bcb0991SDimitry Andric     return Legalized;
49400b57cec5SDimitry Andric   case TargetOpcode::G_AND:
49410b57cec5SDimitry Andric   case TargetOpcode::G_OR:
49420b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
49430b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
49440b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
49450b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
4946480093f4SDimitry Andric   case TargetOpcode::G_UMAX:
4947480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM:
4948480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM:
4949480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
4950480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
4951480093f4SDimitry Andric   case TargetOpcode::G_FMINIMUM:
4952480093f4SDimitry Andric   case TargetOpcode::G_FMAXIMUM: {
49530b57cec5SDimitry Andric     Observer.changingInstr(MI);
49540b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
49550b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
49560b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
49570b57cec5SDimitry Andric     Observer.changedInstr(MI);
49580b57cec5SDimitry Andric     return Legalized;
49590b57cec5SDimitry Andric   }
49600b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
49610b57cec5SDimitry Andric     if (TypeIdx != 1)
49620b57cec5SDimitry Andric       return UnableToLegalize;
49630b57cec5SDimitry Andric     Observer.changingInstr(MI);
49640b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
49650b57cec5SDimitry Andric     Observer.changedInstr(MI);
49660b57cec5SDimitry Andric     return Legalized;
49670b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
49685ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
49690b57cec5SDimitry Andric     if (TypeIdx != 0)
49700b57cec5SDimitry Andric       return UnableToLegalize;
49710b57cec5SDimitry Andric     Observer.changingInstr(MI);
49720b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
49730b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
49740b57cec5SDimitry Andric     Observer.changedInstr(MI);
49750b57cec5SDimitry Andric     return Legalized;
49760b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
49770b57cec5SDimitry Andric     if (TypeIdx != 0)
49780b57cec5SDimitry Andric       return UnableToLegalize;
49790b57cec5SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector())
49800b57cec5SDimitry Andric       return UnableToLegalize;
49810b57cec5SDimitry Andric 
49820b57cec5SDimitry Andric     Observer.changingInstr(MI);
49830b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
49840b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 3);
49850b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
49860b57cec5SDimitry Andric     Observer.changedInstr(MI);
49870b57cec5SDimitry Andric     return Legalized;
49888bcb0991SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES: {
49898bcb0991SDimitry Andric     if (TypeIdx != 1)
49908bcb0991SDimitry Andric       return UnableToLegalize;
49918bcb0991SDimitry Andric 
49928bcb0991SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
49938bcb0991SDimitry Andric     int NumDst = MI.getNumOperands() - 1;
49948bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, NumDst);
49958bcb0991SDimitry Andric 
49968bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
49978bcb0991SDimitry Andric     for (int I = 0; I != NumDst; ++I)
49988bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I).getReg());
49998bcb0991SDimitry Andric 
50008bcb0991SDimitry Andric     int NewNumDst = MoreTy.getSizeInBits() / DstTy.getSizeInBits();
50018bcb0991SDimitry Andric     for (int I = NumDst; I != NewNumDst; ++I)
50028bcb0991SDimitry Andric       MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
50038bcb0991SDimitry Andric 
50048bcb0991SDimitry Andric     MIB.addUse(MI.getOperand(NumDst).getReg());
50058bcb0991SDimitry Andric     MI.eraseFromParent();
50068bcb0991SDimitry Andric     return Legalized;
50078bcb0991SDimitry Andric   }
50080b57cec5SDimitry Andric   case TargetOpcode::G_PHI:
50090b57cec5SDimitry Andric     return moreElementsVectorPhi(MI, TypeIdx, MoreTy);
5010*fe6060f1SDimitry Andric   case TargetOpcode::G_SHUFFLE_VECTOR:
5011*fe6060f1SDimitry Andric     return moreElementsVectorShuffle(MI, TypeIdx, MoreTy);
50120b57cec5SDimitry Andric   default:
50130b57cec5SDimitry Andric     return UnableToLegalize;
50140b57cec5SDimitry Andric   }
50150b57cec5SDimitry Andric }
50160b57cec5SDimitry Andric 
5017*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5018*fe6060f1SDimitry Andric LegalizerHelper::moreElementsVectorShuffle(MachineInstr &MI,
5019*fe6060f1SDimitry Andric                                            unsigned int TypeIdx, LLT MoreTy) {
5020*fe6060f1SDimitry Andric   if (TypeIdx != 0)
5021*fe6060f1SDimitry Andric     return UnableToLegalize;
5022*fe6060f1SDimitry Andric 
5023*fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5024*fe6060f1SDimitry Andric   Register Src1Reg = MI.getOperand(1).getReg();
5025*fe6060f1SDimitry Andric   Register Src2Reg = MI.getOperand(2).getReg();
5026*fe6060f1SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
5027*fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
5028*fe6060f1SDimitry Andric   LLT Src1Ty = MRI.getType(Src1Reg);
5029*fe6060f1SDimitry Andric   LLT Src2Ty = MRI.getType(Src2Reg);
5030*fe6060f1SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
5031*fe6060f1SDimitry Andric   unsigned WidenNumElts = MoreTy.getNumElements();
5032*fe6060f1SDimitry Andric 
5033*fe6060f1SDimitry Andric   // Expect a canonicalized shuffle.
5034*fe6060f1SDimitry Andric   if (DstTy != Src1Ty || DstTy != Src2Ty)
5035*fe6060f1SDimitry Andric     return UnableToLegalize;
5036*fe6060f1SDimitry Andric 
5037*fe6060f1SDimitry Andric   moreElementsVectorSrc(MI, MoreTy, 1);
5038*fe6060f1SDimitry Andric   moreElementsVectorSrc(MI, MoreTy, 2);
5039*fe6060f1SDimitry Andric 
5040*fe6060f1SDimitry Andric   // Adjust mask based on new input vector length.
5041*fe6060f1SDimitry Andric   SmallVector<int, 16> NewMask;
5042*fe6060f1SDimitry Andric   for (unsigned I = 0; I != NumElts; ++I) {
5043*fe6060f1SDimitry Andric     int Idx = Mask[I];
5044*fe6060f1SDimitry Andric     if (Idx < static_cast<int>(NumElts))
5045*fe6060f1SDimitry Andric       NewMask.push_back(Idx);
5046*fe6060f1SDimitry Andric     else
5047*fe6060f1SDimitry Andric       NewMask.push_back(Idx - NumElts + WidenNumElts);
5048*fe6060f1SDimitry Andric   }
5049*fe6060f1SDimitry Andric   for (unsigned I = NumElts; I != WidenNumElts; ++I)
5050*fe6060f1SDimitry Andric     NewMask.push_back(-1);
5051*fe6060f1SDimitry Andric   moreElementsVectorDst(MI, MoreTy, 0);
5052*fe6060f1SDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
5053*fe6060f1SDimitry Andric   MIRBuilder.buildShuffleVector(MI.getOperand(0).getReg(),
5054*fe6060f1SDimitry Andric                                 MI.getOperand(1).getReg(),
5055*fe6060f1SDimitry Andric                                 MI.getOperand(2).getReg(), NewMask);
5056*fe6060f1SDimitry Andric   MI.eraseFromParent();
5057*fe6060f1SDimitry Andric   return Legalized;
5058*fe6060f1SDimitry Andric }
5059*fe6060f1SDimitry Andric 
50600b57cec5SDimitry Andric void LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
50610b57cec5SDimitry Andric                                         ArrayRef<Register> Src1Regs,
50620b57cec5SDimitry Andric                                         ArrayRef<Register> Src2Regs,
50630b57cec5SDimitry Andric                                         LLT NarrowTy) {
50640b57cec5SDimitry Andric   MachineIRBuilder &B = MIRBuilder;
50650b57cec5SDimitry Andric   unsigned SrcParts = Src1Regs.size();
50660b57cec5SDimitry Andric   unsigned DstParts = DstRegs.size();
50670b57cec5SDimitry Andric 
50680b57cec5SDimitry Andric   unsigned DstIdx = 0; // Low bits of the result.
50690b57cec5SDimitry Andric   Register FactorSum =
50700b57cec5SDimitry Andric       B.buildMul(NarrowTy, Src1Regs[DstIdx], Src2Regs[DstIdx]).getReg(0);
50710b57cec5SDimitry Andric   DstRegs[DstIdx] = FactorSum;
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   unsigned CarrySumPrevDstIdx;
50740b57cec5SDimitry Andric   SmallVector<Register, 4> Factors;
50750b57cec5SDimitry Andric 
50760b57cec5SDimitry Andric   for (DstIdx = 1; DstIdx < DstParts; DstIdx++) {
50770b57cec5SDimitry Andric     // Collect low parts of muls for DstIdx.
50780b57cec5SDimitry Andric     for (unsigned i = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
50790b57cec5SDimitry Andric          i <= std::min(DstIdx, SrcParts - 1); ++i) {
50800b57cec5SDimitry Andric       MachineInstrBuilder Mul =
50810b57cec5SDimitry Andric           B.buildMul(NarrowTy, Src1Regs[DstIdx - i], Src2Regs[i]);
50820b57cec5SDimitry Andric       Factors.push_back(Mul.getReg(0));
50830b57cec5SDimitry Andric     }
50840b57cec5SDimitry Andric     // Collect high parts of muls from previous DstIdx.
50850b57cec5SDimitry Andric     for (unsigned i = DstIdx < SrcParts ? 0 : DstIdx - SrcParts;
50860b57cec5SDimitry Andric          i <= std::min(DstIdx - 1, SrcParts - 1); ++i) {
50870b57cec5SDimitry Andric       MachineInstrBuilder Umulh =
50880b57cec5SDimitry Andric           B.buildUMulH(NarrowTy, Src1Regs[DstIdx - 1 - i], Src2Regs[i]);
50890b57cec5SDimitry Andric       Factors.push_back(Umulh.getReg(0));
50900b57cec5SDimitry Andric     }
5091480093f4SDimitry Andric     // Add CarrySum from additions calculated for previous DstIdx.
50920b57cec5SDimitry Andric     if (DstIdx != 1) {
50930b57cec5SDimitry Andric       Factors.push_back(CarrySumPrevDstIdx);
50940b57cec5SDimitry Andric     }
50950b57cec5SDimitry Andric 
50960b57cec5SDimitry Andric     Register CarrySum;
50970b57cec5SDimitry Andric     // Add all factors and accumulate all carries into CarrySum.
50980b57cec5SDimitry Andric     if (DstIdx != DstParts - 1) {
50990b57cec5SDimitry Andric       MachineInstrBuilder Uaddo =
51000b57cec5SDimitry Andric           B.buildUAddo(NarrowTy, LLT::scalar(1), Factors[0], Factors[1]);
51010b57cec5SDimitry Andric       FactorSum = Uaddo.getReg(0);
51020b57cec5SDimitry Andric       CarrySum = B.buildZExt(NarrowTy, Uaddo.getReg(1)).getReg(0);
51030b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i) {
51040b57cec5SDimitry Andric         MachineInstrBuilder Uaddo =
51050b57cec5SDimitry Andric             B.buildUAddo(NarrowTy, LLT::scalar(1), FactorSum, Factors[i]);
51060b57cec5SDimitry Andric         FactorSum = Uaddo.getReg(0);
51070b57cec5SDimitry Andric         MachineInstrBuilder Carry = B.buildZExt(NarrowTy, Uaddo.getReg(1));
51080b57cec5SDimitry Andric         CarrySum = B.buildAdd(NarrowTy, CarrySum, Carry).getReg(0);
51090b57cec5SDimitry Andric       }
51100b57cec5SDimitry Andric     } else {
51110b57cec5SDimitry Andric       // Since value for the next index is not calculated, neither is CarrySum.
51120b57cec5SDimitry Andric       FactorSum = B.buildAdd(NarrowTy, Factors[0], Factors[1]).getReg(0);
51130b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i)
51140b57cec5SDimitry Andric         FactorSum = B.buildAdd(NarrowTy, FactorSum, Factors[i]).getReg(0);
51150b57cec5SDimitry Andric     }
51160b57cec5SDimitry Andric 
51170b57cec5SDimitry Andric     CarrySumPrevDstIdx = CarrySum;
51180b57cec5SDimitry Andric     DstRegs[DstIdx] = FactorSum;
51190b57cec5SDimitry Andric     Factors.clear();
51200b57cec5SDimitry Andric   }
51210b57cec5SDimitry Andric }
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
5124*fe6060f1SDimitry Andric LegalizerHelper::narrowScalarAddSub(MachineInstr &MI, unsigned TypeIdx,
5125*fe6060f1SDimitry Andric                                     LLT NarrowTy) {
5126*fe6060f1SDimitry Andric   if (TypeIdx != 0)
5127*fe6060f1SDimitry Andric     return UnableToLegalize;
5128*fe6060f1SDimitry Andric 
5129*fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5130*fe6060f1SDimitry Andric   LLT DstType = MRI.getType(DstReg);
5131*fe6060f1SDimitry Andric   // FIXME: add support for vector types
5132*fe6060f1SDimitry Andric   if (DstType.isVector())
5133*fe6060f1SDimitry Andric     return UnableToLegalize;
5134*fe6060f1SDimitry Andric 
5135*fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
5136*fe6060f1SDimitry Andric   unsigned OpO, OpE, OpF;
5137*fe6060f1SDimitry Andric   switch (Opcode) {
5138*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDO:
5139*fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
5140*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDO:
5141*fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
5142*fe6060f1SDimitry Andric   case TargetOpcode::G_ADD:
5143*fe6060f1SDimitry Andric     OpO = TargetOpcode::G_UADDO;
5144*fe6060f1SDimitry Andric     OpE = TargetOpcode::G_UADDE;
5145*fe6060f1SDimitry Andric     OpF = TargetOpcode::G_UADDE;
5146*fe6060f1SDimitry Andric     if (Opcode == TargetOpcode::G_SADDO || Opcode == TargetOpcode::G_SADDE)
5147*fe6060f1SDimitry Andric       OpF = TargetOpcode::G_SADDE;
5148*fe6060f1SDimitry Andric     break;
5149*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBO:
5150*fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
5151*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBO:
5152*fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
5153*fe6060f1SDimitry Andric   case TargetOpcode::G_SUB:
5154*fe6060f1SDimitry Andric     OpO = TargetOpcode::G_USUBO;
5155*fe6060f1SDimitry Andric     OpE = TargetOpcode::G_USUBE;
5156*fe6060f1SDimitry Andric     OpF = TargetOpcode::G_USUBE;
5157*fe6060f1SDimitry Andric     if (Opcode == TargetOpcode::G_SSUBO || Opcode == TargetOpcode::G_SSUBE)
5158*fe6060f1SDimitry Andric       OpF = TargetOpcode::G_SSUBE;
5159*fe6060f1SDimitry Andric     break;
5160*fe6060f1SDimitry Andric   default:
5161*fe6060f1SDimitry Andric     llvm_unreachable("Unexpected add/sub opcode!");
5162*fe6060f1SDimitry Andric   }
5163*fe6060f1SDimitry Andric 
5164*fe6060f1SDimitry Andric   // 1 for a plain add/sub, 2 if this is an operation with a carry-out.
5165*fe6060f1SDimitry Andric   unsigned NumDefs = MI.getNumExplicitDefs();
5166*fe6060f1SDimitry Andric   Register Src1 = MI.getOperand(NumDefs).getReg();
5167*fe6060f1SDimitry Andric   Register Src2 = MI.getOperand(NumDefs + 1).getReg();
5168*fe6060f1SDimitry Andric   Register CarryDst, CarryIn;
5169*fe6060f1SDimitry Andric   if (NumDefs == 2)
5170*fe6060f1SDimitry Andric     CarryDst = MI.getOperand(1).getReg();
5171*fe6060f1SDimitry Andric   if (MI.getNumOperands() == NumDefs + 3)
5172*fe6060f1SDimitry Andric     CarryIn = MI.getOperand(NumDefs + 2).getReg();
5173*fe6060f1SDimitry Andric 
5174*fe6060f1SDimitry Andric   LLT RegTy = MRI.getType(MI.getOperand(0).getReg());
5175*fe6060f1SDimitry Andric   LLT LeftoverTy, DummyTy;
5176*fe6060f1SDimitry Andric   SmallVector<Register, 2> Src1Regs, Src2Regs, Src1Left, Src2Left, DstRegs;
5177*fe6060f1SDimitry Andric   extractParts(Src1, RegTy, NarrowTy, LeftoverTy, Src1Regs, Src1Left);
5178*fe6060f1SDimitry Andric   extractParts(Src2, RegTy, NarrowTy, DummyTy, Src2Regs, Src2Left);
5179*fe6060f1SDimitry Andric 
5180*fe6060f1SDimitry Andric   int NarrowParts = Src1Regs.size();
5181*fe6060f1SDimitry Andric   for (int I = 0, E = Src1Left.size(); I != E; ++I) {
5182*fe6060f1SDimitry Andric     Src1Regs.push_back(Src1Left[I]);
5183*fe6060f1SDimitry Andric     Src2Regs.push_back(Src2Left[I]);
5184*fe6060f1SDimitry Andric   }
5185*fe6060f1SDimitry Andric   DstRegs.reserve(Src1Regs.size());
5186*fe6060f1SDimitry Andric 
5187*fe6060f1SDimitry Andric   for (int i = 0, e = Src1Regs.size(); i != e; ++i) {
5188*fe6060f1SDimitry Andric     Register DstReg =
5189*fe6060f1SDimitry Andric         MRI.createGenericVirtualRegister(MRI.getType(Src1Regs[i]));
5190*fe6060f1SDimitry Andric     Register CarryOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
5191*fe6060f1SDimitry Andric     // Forward the final carry-out to the destination register
5192*fe6060f1SDimitry Andric     if (i == e - 1 && CarryDst)
5193*fe6060f1SDimitry Andric       CarryOut = CarryDst;
5194*fe6060f1SDimitry Andric 
5195*fe6060f1SDimitry Andric     if (!CarryIn) {
5196*fe6060f1SDimitry Andric       MIRBuilder.buildInstr(OpO, {DstReg, CarryOut},
5197*fe6060f1SDimitry Andric                             {Src1Regs[i], Src2Regs[i]});
5198*fe6060f1SDimitry Andric     } else if (i == e - 1) {
5199*fe6060f1SDimitry Andric       MIRBuilder.buildInstr(OpF, {DstReg, CarryOut},
5200*fe6060f1SDimitry Andric                             {Src1Regs[i], Src2Regs[i], CarryIn});
5201*fe6060f1SDimitry Andric     } else {
5202*fe6060f1SDimitry Andric       MIRBuilder.buildInstr(OpE, {DstReg, CarryOut},
5203*fe6060f1SDimitry Andric                             {Src1Regs[i], Src2Regs[i], CarryIn});
5204*fe6060f1SDimitry Andric     }
5205*fe6060f1SDimitry Andric 
5206*fe6060f1SDimitry Andric     DstRegs.push_back(DstReg);
5207*fe6060f1SDimitry Andric     CarryIn = CarryOut;
5208*fe6060f1SDimitry Andric   }
5209*fe6060f1SDimitry Andric   insertParts(MI.getOperand(0).getReg(), RegTy, NarrowTy,
5210*fe6060f1SDimitry Andric               makeArrayRef(DstRegs).take_front(NarrowParts), LeftoverTy,
5211*fe6060f1SDimitry Andric               makeArrayRef(DstRegs).drop_front(NarrowParts));
5212*fe6060f1SDimitry Andric 
5213*fe6060f1SDimitry Andric   MI.eraseFromParent();
5214*fe6060f1SDimitry Andric   return Legalized;
5215*fe6060f1SDimitry Andric }
5216*fe6060f1SDimitry Andric 
5217*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
52180b57cec5SDimitry Andric LegalizerHelper::narrowScalarMul(MachineInstr &MI, LLT NarrowTy) {
52190b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
52200b57cec5SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
52210b57cec5SDimitry Andric   Register Src2 = MI.getOperand(2).getReg();
52220b57cec5SDimitry Andric 
52230b57cec5SDimitry Andric   LLT Ty = MRI.getType(DstReg);
52240b57cec5SDimitry Andric   if (Ty.isVector())
52250b57cec5SDimitry Andric     return UnableToLegalize;
52260b57cec5SDimitry Andric 
52270b57cec5SDimitry Andric   unsigned SrcSize = MRI.getType(Src1).getSizeInBits();
52280b57cec5SDimitry Andric   unsigned DstSize = Ty.getSizeInBits();
52290b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
52300b57cec5SDimitry Andric   if (DstSize % NarrowSize != 0 || SrcSize % NarrowSize != 0)
52310b57cec5SDimitry Andric     return UnableToLegalize;
52320b57cec5SDimitry Andric 
52330b57cec5SDimitry Andric   unsigned NumDstParts = DstSize / NarrowSize;
52340b57cec5SDimitry Andric   unsigned NumSrcParts = SrcSize / NarrowSize;
52350b57cec5SDimitry Andric   bool IsMulHigh = MI.getOpcode() == TargetOpcode::G_UMULH;
52360b57cec5SDimitry Andric   unsigned DstTmpParts = NumDstParts * (IsMulHigh ? 2 : 1);
52370b57cec5SDimitry Andric 
52385ffd83dbSDimitry Andric   SmallVector<Register, 2> Src1Parts, Src2Parts;
52395ffd83dbSDimitry Andric   SmallVector<Register, 2> DstTmpRegs(DstTmpParts);
52400b57cec5SDimitry Andric   extractParts(Src1, NarrowTy, NumSrcParts, Src1Parts);
52410b57cec5SDimitry Andric   extractParts(Src2, NarrowTy, NumSrcParts, Src2Parts);
52420b57cec5SDimitry Andric   multiplyRegisters(DstTmpRegs, Src1Parts, Src2Parts, NarrowTy);
52430b57cec5SDimitry Andric 
52440b57cec5SDimitry Andric   // Take only high half of registers if this is high mul.
52450b57cec5SDimitry Andric   ArrayRef<Register> DstRegs(
52460b57cec5SDimitry Andric       IsMulHigh ? &DstTmpRegs[DstTmpParts / 2] : &DstTmpRegs[0], NumDstParts);
52470b57cec5SDimitry Andric   MIRBuilder.buildMerge(DstReg, DstRegs);
52480b57cec5SDimitry Andric   MI.eraseFromParent();
52490b57cec5SDimitry Andric   return Legalized;
52500b57cec5SDimitry Andric }
52510b57cec5SDimitry Andric 
52520b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
525323408297SDimitry Andric LegalizerHelper::narrowScalarFPTOI(MachineInstr &MI, unsigned TypeIdx,
525423408297SDimitry Andric                                    LLT NarrowTy) {
525523408297SDimitry Andric   if (TypeIdx != 0)
525623408297SDimitry Andric     return UnableToLegalize;
525723408297SDimitry Andric 
525823408297SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_FPTOSI;
525923408297SDimitry Andric 
526023408297SDimitry Andric   Register Src = MI.getOperand(1).getReg();
526123408297SDimitry Andric   LLT SrcTy = MRI.getType(Src);
526223408297SDimitry Andric 
526323408297SDimitry Andric   // If all finite floats fit into the narrowed integer type, we can just swap
526423408297SDimitry Andric   // out the result type. This is practically only useful for conversions from
526523408297SDimitry Andric   // half to at least 16-bits, so just handle the one case.
526623408297SDimitry Andric   if (SrcTy.getScalarType() != LLT::scalar(16) ||
5267*fe6060f1SDimitry Andric       NarrowTy.getScalarSizeInBits() < (IsSigned ? 17u : 16u))
526823408297SDimitry Andric     return UnableToLegalize;
526923408297SDimitry Andric 
527023408297SDimitry Andric   Observer.changingInstr(MI);
527123408297SDimitry Andric   narrowScalarDst(MI, NarrowTy, 0,
527223408297SDimitry Andric                   IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT);
527323408297SDimitry Andric   Observer.changedInstr(MI);
527423408297SDimitry Andric   return Legalized;
527523408297SDimitry Andric }
527623408297SDimitry Andric 
527723408297SDimitry Andric LegalizerHelper::LegalizeResult
52780b57cec5SDimitry Andric LegalizerHelper::narrowScalarExtract(MachineInstr &MI, unsigned TypeIdx,
52790b57cec5SDimitry Andric                                      LLT NarrowTy) {
52800b57cec5SDimitry Andric   if (TypeIdx != 1)
52810b57cec5SDimitry Andric     return UnableToLegalize;
52820b57cec5SDimitry Andric 
52830b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric   int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
52860b57cec5SDimitry Andric   // FIXME: add support for when SizeOp1 isn't an exact multiple of
52870b57cec5SDimitry Andric   // NarrowSize.
52880b57cec5SDimitry Andric   if (SizeOp1 % NarrowSize != 0)
52890b57cec5SDimitry Andric     return UnableToLegalize;
52900b57cec5SDimitry Andric   int NumParts = SizeOp1 / NarrowSize;
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric   SmallVector<Register, 2> SrcRegs, DstRegs;
52930b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
52940b57cec5SDimitry Andric   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
52950b57cec5SDimitry Andric 
52960b57cec5SDimitry Andric   Register OpReg = MI.getOperand(0).getReg();
52970b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(2).getImm();
52980b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
52990b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i) {
53000b57cec5SDimitry Andric     unsigned SrcStart = i * NarrowSize;
53010b57cec5SDimitry Andric 
53020b57cec5SDimitry Andric     if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
53030b57cec5SDimitry Andric       // No part of the extract uses this subregister, ignore it.
53040b57cec5SDimitry Andric       continue;
53050b57cec5SDimitry Andric     } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
53060b57cec5SDimitry Andric       // The entire subregister is extracted, forward the value.
53070b57cec5SDimitry Andric       DstRegs.push_back(SrcRegs[i]);
53080b57cec5SDimitry Andric       continue;
53090b57cec5SDimitry Andric     }
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
53120b57cec5SDimitry Andric     // extended infinitely in both directions.
53130b57cec5SDimitry Andric     int64_t ExtractOffset;
53140b57cec5SDimitry Andric     uint64_t SegSize;
53150b57cec5SDimitry Andric     if (OpStart < SrcStart) {
53160b57cec5SDimitry Andric       ExtractOffset = 0;
53170b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
53180b57cec5SDimitry Andric     } else {
53190b57cec5SDimitry Andric       ExtractOffset = OpStart - SrcStart;
53200b57cec5SDimitry Andric       SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
53210b57cec5SDimitry Andric     }
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric     Register SegReg = SrcRegs[i];
53240b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != NarrowSize) {
53250b57cec5SDimitry Andric       // A genuine extract is needed.
53260b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
53270b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
53280b57cec5SDimitry Andric     }
53290b57cec5SDimitry Andric 
53300b57cec5SDimitry Andric     DstRegs.push_back(SegReg);
53310b57cec5SDimitry Andric   }
53320b57cec5SDimitry Andric 
53330b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
53340b57cec5SDimitry Andric   if (MRI.getType(DstReg).isVector())
53350b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
53365ffd83dbSDimitry Andric   else if (DstRegs.size() > 1)
53370b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
53385ffd83dbSDimitry Andric   else
53395ffd83dbSDimitry Andric     MIRBuilder.buildCopy(DstReg, DstRegs[0]);
53400b57cec5SDimitry Andric   MI.eraseFromParent();
53410b57cec5SDimitry Andric   return Legalized;
53420b57cec5SDimitry Andric }
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
53450b57cec5SDimitry Andric LegalizerHelper::narrowScalarInsert(MachineInstr &MI, unsigned TypeIdx,
53460b57cec5SDimitry Andric                                     LLT NarrowTy) {
53470b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
53480b57cec5SDimitry Andric   if (TypeIdx != 0)
53490b57cec5SDimitry Andric     return UnableToLegalize;
53500b57cec5SDimitry Andric 
5351*fe6060f1SDimitry Andric   SmallVector<Register, 2> SrcRegs, LeftoverRegs, DstRegs;
53520b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
5353*fe6060f1SDimitry Andric   LLT RegTy = MRI.getType(MI.getOperand(0).getReg());
5354*fe6060f1SDimitry Andric   LLT LeftoverTy;
5355*fe6060f1SDimitry Andric   extractParts(MI.getOperand(1).getReg(), RegTy, NarrowTy, LeftoverTy, SrcRegs,
5356*fe6060f1SDimitry Andric                LeftoverRegs);
53570b57cec5SDimitry Andric 
5358*fe6060f1SDimitry Andric   for (Register Reg : LeftoverRegs)
5359*fe6060f1SDimitry Andric     SrcRegs.push_back(Reg);
5360*fe6060f1SDimitry Andric 
5361*fe6060f1SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
53620b57cec5SDimitry Andric   Register OpReg = MI.getOperand(2).getReg();
53630b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(3).getImm();
53640b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
5365*fe6060f1SDimitry Andric   for (int I = 0, E = SrcRegs.size(); I != E; ++I) {
5366*fe6060f1SDimitry Andric     unsigned DstStart = I * NarrowSize;
53670b57cec5SDimitry Andric 
5368*fe6060f1SDimitry Andric     if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
53690b57cec5SDimitry Andric       // The entire subregister is defined by this insert, forward the new
53700b57cec5SDimitry Andric       // value.
53710b57cec5SDimitry Andric       DstRegs.push_back(OpReg);
53720b57cec5SDimitry Andric       continue;
53730b57cec5SDimitry Andric     }
53740b57cec5SDimitry Andric 
5375*fe6060f1SDimitry Andric     Register SrcReg = SrcRegs[I];
5376*fe6060f1SDimitry Andric     if (MRI.getType(SrcRegs[I]) == LeftoverTy) {
5377*fe6060f1SDimitry Andric       // The leftover reg is smaller than NarrowTy, so we need to extend it.
5378*fe6060f1SDimitry Andric       SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
5379*fe6060f1SDimitry Andric       MIRBuilder.buildAnyExt(SrcReg, SrcRegs[I]);
5380*fe6060f1SDimitry Andric     }
5381*fe6060f1SDimitry Andric 
5382*fe6060f1SDimitry Andric     if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
5383*fe6060f1SDimitry Andric       // No part of the insert affects this subregister, forward the original.
5384*fe6060f1SDimitry Andric       DstRegs.push_back(SrcReg);
5385*fe6060f1SDimitry Andric       continue;
5386*fe6060f1SDimitry Andric     }
5387*fe6060f1SDimitry Andric 
53880b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
53890b57cec5SDimitry Andric     // extended infinitely in both directions.
53900b57cec5SDimitry Andric     int64_t ExtractOffset, InsertOffset;
53910b57cec5SDimitry Andric     uint64_t SegSize;
53920b57cec5SDimitry Andric     if (OpStart < DstStart) {
53930b57cec5SDimitry Andric       InsertOffset = 0;
53940b57cec5SDimitry Andric       ExtractOffset = DstStart - OpStart;
53950b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
53960b57cec5SDimitry Andric     } else {
53970b57cec5SDimitry Andric       InsertOffset = OpStart - DstStart;
53980b57cec5SDimitry Andric       ExtractOffset = 0;
53990b57cec5SDimitry Andric       SegSize =
54000b57cec5SDimitry Andric         std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
54010b57cec5SDimitry Andric     }
54020b57cec5SDimitry Andric 
54030b57cec5SDimitry Andric     Register SegReg = OpReg;
54040b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != OpSize) {
54050b57cec5SDimitry Andric       // A genuine extract is needed.
54060b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
54070b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
54080b57cec5SDimitry Andric     }
54090b57cec5SDimitry Andric 
54100b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
5411*fe6060f1SDimitry Andric     MIRBuilder.buildInsert(DstReg, SrcReg, SegReg, InsertOffset);
54120b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
54130b57cec5SDimitry Andric   }
54140b57cec5SDimitry Andric 
5415*fe6060f1SDimitry Andric   uint64_t WideSize = DstRegs.size() * NarrowSize;
54160b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5417*fe6060f1SDimitry Andric   if (WideSize > RegTy.getSizeInBits()) {
5418*fe6060f1SDimitry Andric     Register MergeReg = MRI.createGenericVirtualRegister(LLT::scalar(WideSize));
5419*fe6060f1SDimitry Andric     MIRBuilder.buildMerge(MergeReg, DstRegs);
5420*fe6060f1SDimitry Andric     MIRBuilder.buildTrunc(DstReg, MergeReg);
5421*fe6060f1SDimitry Andric   } else
54220b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
5423*fe6060f1SDimitry Andric 
54240b57cec5SDimitry Andric   MI.eraseFromParent();
54250b57cec5SDimitry Andric   return Legalized;
54260b57cec5SDimitry Andric }
54270b57cec5SDimitry Andric 
54280b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
54290b57cec5SDimitry Andric LegalizerHelper::narrowScalarBasic(MachineInstr &MI, unsigned TypeIdx,
54300b57cec5SDimitry Andric                                    LLT NarrowTy) {
54310b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
54320b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
54330b57cec5SDimitry Andric 
54340b57cec5SDimitry Andric   assert(MI.getNumOperands() == 3 && TypeIdx == 0);
54350b57cec5SDimitry Andric 
54360b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
54370b57cec5SDimitry Andric   SmallVector<Register, 4> Src0Regs, Src0LeftoverRegs;
54380b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
54390b57cec5SDimitry Andric   LLT LeftoverTy;
54400b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(1).getReg(), DstTy, NarrowTy, LeftoverTy,
54410b57cec5SDimitry Andric                     Src0Regs, Src0LeftoverRegs))
54420b57cec5SDimitry Andric     return UnableToLegalize;
54430b57cec5SDimitry Andric 
54440b57cec5SDimitry Andric   LLT Unused;
54450b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, Unused,
54460b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
54470b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
54480b57cec5SDimitry Andric 
54490b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
54500b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
54510b57cec5SDimitry Andric                                         {Src0Regs[I], Src1Regs[I]});
54525ffd83dbSDimitry Andric     DstRegs.push_back(Inst.getReg(0));
54530b57cec5SDimitry Andric   }
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
54560b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(
54570b57cec5SDimitry Andric       MI.getOpcode(),
54580b57cec5SDimitry Andric       {LeftoverTy}, {Src0LeftoverRegs[I], Src1LeftoverRegs[I]});
54595ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Inst.getReg(0));
54600b57cec5SDimitry Andric   }
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
54630b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
54640b57cec5SDimitry Andric 
54650b57cec5SDimitry Andric   MI.eraseFromParent();
54660b57cec5SDimitry Andric   return Legalized;
54670b57cec5SDimitry Andric }
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
54705ffd83dbSDimitry Andric LegalizerHelper::narrowScalarExt(MachineInstr &MI, unsigned TypeIdx,
54715ffd83dbSDimitry Andric                                  LLT NarrowTy) {
54725ffd83dbSDimitry Andric   if (TypeIdx != 0)
54735ffd83dbSDimitry Andric     return UnableToLegalize;
54745ffd83dbSDimitry Andric 
54755ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
54765ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
54775ffd83dbSDimitry Andric 
54785ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
54795ffd83dbSDimitry Andric   if (DstTy.isVector())
54805ffd83dbSDimitry Andric     return UnableToLegalize;
54815ffd83dbSDimitry Andric 
54825ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
54835ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
54845ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts, MI.getOpcode());
54855ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
54865ffd83dbSDimitry Andric 
54875ffd83dbSDimitry Andric   MI.eraseFromParent();
54885ffd83dbSDimitry Andric   return Legalized;
54895ffd83dbSDimitry Andric }
54905ffd83dbSDimitry Andric 
54915ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
54920b57cec5SDimitry Andric LegalizerHelper::narrowScalarSelect(MachineInstr &MI, unsigned TypeIdx,
54930b57cec5SDimitry Andric                                     LLT NarrowTy) {
54940b57cec5SDimitry Andric   if (TypeIdx != 0)
54950b57cec5SDimitry Andric     return UnableToLegalize;
54960b57cec5SDimitry Andric 
54970b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
54980b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
54990b57cec5SDimitry Andric   if (CondTy.isVector()) // TODO: Handle vselect
55000b57cec5SDimitry Andric     return UnableToLegalize;
55010b57cec5SDimitry Andric 
55020b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55030b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
55040b57cec5SDimitry Andric 
55050b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
55060b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
55070b57cec5SDimitry Andric   SmallVector<Register, 4> Src2Regs, Src2LeftoverRegs;
55080b57cec5SDimitry Andric   LLT LeftoverTy;
55090b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
55100b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
55110b57cec5SDimitry Andric     return UnableToLegalize;
55120b57cec5SDimitry Andric 
55130b57cec5SDimitry Andric   LLT Unused;
55140b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
55150b57cec5SDimitry Andric                     Src2Regs, Src2LeftoverRegs))
55160b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
55170b57cec5SDimitry Andric 
55180b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
55190b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(NarrowTy,
55200b57cec5SDimitry Andric                                          CondReg, Src1Regs[I], Src2Regs[I]);
55215ffd83dbSDimitry Andric     DstRegs.push_back(Select.getReg(0));
55220b57cec5SDimitry Andric   }
55230b57cec5SDimitry Andric 
55240b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
55250b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(
55260b57cec5SDimitry Andric       LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
55275ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Select.getReg(0));
55280b57cec5SDimitry Andric   }
55290b57cec5SDimitry Andric 
55300b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
55310b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
55320b57cec5SDimitry Andric 
55330b57cec5SDimitry Andric   MI.eraseFromParent();
55340b57cec5SDimitry Andric   return Legalized;
55350b57cec5SDimitry Andric }
55360b57cec5SDimitry Andric 
55370b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
55385ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTLZ(MachineInstr &MI, unsigned TypeIdx,
55395ffd83dbSDimitry Andric                                   LLT NarrowTy) {
55405ffd83dbSDimitry Andric   if (TypeIdx != 1)
55415ffd83dbSDimitry Andric     return UnableToLegalize;
55425ffd83dbSDimitry Andric 
55435ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55445ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
55455ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
55465ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
55475ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
55485ffd83dbSDimitry Andric 
55495ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
55505ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF;
55515ffd83dbSDimitry Andric 
55525ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
55535ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
55545ffd83dbSDimitry Andric     // ctlz(Hi:Lo) -> Hi == 0 ? (NarrowSize + ctlz(Lo)) : ctlz(Hi)
55555ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
55565ffd83dbSDimitry Andric     auto HiIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
55575ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(1), C_0);
55585ffd83dbSDimitry Andric     auto LoCTLZ = IsUndef ?
55595ffd83dbSDimitry Andric       B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0)) :
55605ffd83dbSDimitry Andric       B.buildCTLZ(DstTy, UnmergeSrc.getReg(0));
55615ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
55625ffd83dbSDimitry Andric     auto HiIsZeroCTLZ = B.buildAdd(DstTy, LoCTLZ, C_NarrowSize);
55635ffd83dbSDimitry Andric     auto HiCTLZ = B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1));
55645ffd83dbSDimitry Andric     B.buildSelect(DstReg, HiIsZero, HiIsZeroCTLZ, HiCTLZ);
55655ffd83dbSDimitry Andric 
55665ffd83dbSDimitry Andric     MI.eraseFromParent();
55675ffd83dbSDimitry Andric     return Legalized;
55685ffd83dbSDimitry Andric   }
55695ffd83dbSDimitry Andric 
55705ffd83dbSDimitry Andric   return UnableToLegalize;
55715ffd83dbSDimitry Andric }
55725ffd83dbSDimitry Andric 
55735ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55745ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTTZ(MachineInstr &MI, unsigned TypeIdx,
55755ffd83dbSDimitry Andric                                   LLT NarrowTy) {
55765ffd83dbSDimitry Andric   if (TypeIdx != 1)
55775ffd83dbSDimitry Andric     return UnableToLegalize;
55785ffd83dbSDimitry Andric 
55795ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55805ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
55815ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
55825ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
55835ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
55845ffd83dbSDimitry Andric 
55855ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
55865ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF;
55875ffd83dbSDimitry Andric 
55885ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
55895ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
55905ffd83dbSDimitry Andric     // cttz(Hi:Lo) -> Lo == 0 ? (cttz(Hi) + NarrowSize) : cttz(Lo)
55915ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
55925ffd83dbSDimitry Andric     auto LoIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
55935ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(0), C_0);
55945ffd83dbSDimitry Andric     auto HiCTTZ = IsUndef ?
55955ffd83dbSDimitry Andric       B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1)) :
55965ffd83dbSDimitry Andric       B.buildCTTZ(DstTy, UnmergeSrc.getReg(1));
55975ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
55985ffd83dbSDimitry Andric     auto LoIsZeroCTTZ = B.buildAdd(DstTy, HiCTTZ, C_NarrowSize);
55995ffd83dbSDimitry Andric     auto LoCTTZ = B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0));
56005ffd83dbSDimitry Andric     B.buildSelect(DstReg, LoIsZero, LoIsZeroCTTZ, LoCTTZ);
56015ffd83dbSDimitry Andric 
56025ffd83dbSDimitry Andric     MI.eraseFromParent();
56035ffd83dbSDimitry Andric     return Legalized;
56045ffd83dbSDimitry Andric   }
56055ffd83dbSDimitry Andric 
56065ffd83dbSDimitry Andric   return UnableToLegalize;
56075ffd83dbSDimitry Andric }
56085ffd83dbSDimitry Andric 
56095ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
56105ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTPOP(MachineInstr &MI, unsigned TypeIdx,
56115ffd83dbSDimitry Andric                                    LLT NarrowTy) {
56125ffd83dbSDimitry Andric   if (TypeIdx != 1)
56135ffd83dbSDimitry Andric     return UnableToLegalize;
56145ffd83dbSDimitry Andric 
56155ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
56165ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
56175ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
56185ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
56195ffd83dbSDimitry Andric 
56205ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
56215ffd83dbSDimitry Andric     auto UnmergeSrc = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
56225ffd83dbSDimitry Andric 
56235ffd83dbSDimitry Andric     auto LoCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(0));
56245ffd83dbSDimitry Andric     auto HiCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(1));
56255ffd83dbSDimitry Andric     MIRBuilder.buildAdd(DstReg, HiCTPOP, LoCTPOP);
56265ffd83dbSDimitry Andric 
56275ffd83dbSDimitry Andric     MI.eraseFromParent();
56285ffd83dbSDimitry Andric     return Legalized;
56295ffd83dbSDimitry Andric   }
56305ffd83dbSDimitry Andric 
56315ffd83dbSDimitry Andric   return UnableToLegalize;
56325ffd83dbSDimitry Andric }
56335ffd83dbSDimitry Andric 
56345ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
5635e8d8bef9SDimitry Andric LegalizerHelper::lowerBitCount(MachineInstr &MI) {
56360b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
5637e8d8bef9SDimitry Andric   const auto &TII = MIRBuilder.getTII();
56380b57cec5SDimitry Andric   auto isSupported = [this](const LegalityQuery &Q) {
56390b57cec5SDimitry Andric     auto QAction = LI.getAction(Q).Action;
56400b57cec5SDimitry Andric     return QAction == Legal || QAction == Libcall || QAction == Custom;
56410b57cec5SDimitry Andric   };
56420b57cec5SDimitry Andric   switch (Opc) {
56430b57cec5SDimitry Andric   default:
56440b57cec5SDimitry Andric     return UnableToLegalize;
56450b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
56460b57cec5SDimitry Andric     // This trivially expands to CTLZ.
56470b57cec5SDimitry Andric     Observer.changingInstr(MI);
56480b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
56490b57cec5SDimitry Andric     Observer.changedInstr(MI);
56500b57cec5SDimitry Andric     return Legalized;
56510b57cec5SDimitry Andric   }
56520b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ: {
56535ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
56540b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
56555ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
56565ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
56575ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
56585ffd83dbSDimitry Andric 
56595ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
56600b57cec5SDimitry Andric       // If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
56615ffd83dbSDimitry Andric       auto CtlzZU = MIRBuilder.buildCTLZ_ZERO_UNDEF(DstTy, SrcReg);
56625ffd83dbSDimitry Andric       auto ZeroSrc = MIRBuilder.buildConstant(SrcTy, 0);
56635ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
56645ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, SrcTy.changeElementSize(1), SrcReg, ZeroSrc);
56655ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
56665ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CtlzZU);
56670b57cec5SDimitry Andric       MI.eraseFromParent();
56680b57cec5SDimitry Andric       return Legalized;
56690b57cec5SDimitry Andric     }
56700b57cec5SDimitry Andric     // for now, we do this:
56710b57cec5SDimitry Andric     // NewLen = NextPowerOf2(Len);
56720b57cec5SDimitry Andric     // x = x | (x >> 1);
56730b57cec5SDimitry Andric     // x = x | (x >> 2);
56740b57cec5SDimitry Andric     // ...
56750b57cec5SDimitry Andric     // x = x | (x >>16);
56760b57cec5SDimitry Andric     // x = x | (x >>32); // for 64-bit input
56770b57cec5SDimitry Andric     // Upto NewLen/2
56780b57cec5SDimitry Andric     // return Len - popcount(x);
56790b57cec5SDimitry Andric     //
56800b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
56810b57cec5SDimitry Andric     Register Op = SrcReg;
56820b57cec5SDimitry Andric     unsigned NewLen = PowerOf2Ceil(Len);
56830b57cec5SDimitry Andric     for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
56845ffd83dbSDimitry Andric       auto MIBShiftAmt = MIRBuilder.buildConstant(SrcTy, 1ULL << i);
56855ffd83dbSDimitry Andric       auto MIBOp = MIRBuilder.buildOr(
56865ffd83dbSDimitry Andric           SrcTy, Op, MIRBuilder.buildLShr(SrcTy, Op, MIBShiftAmt));
56875ffd83dbSDimitry Andric       Op = MIBOp.getReg(0);
56880b57cec5SDimitry Andric     }
56895ffd83dbSDimitry Andric     auto MIBPop = MIRBuilder.buildCTPOP(DstTy, Op);
56905ffd83dbSDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MIRBuilder.buildConstant(DstTy, Len),
56915ffd83dbSDimitry Andric                         MIBPop);
56920b57cec5SDimitry Andric     MI.eraseFromParent();
56930b57cec5SDimitry Andric     return Legalized;
56940b57cec5SDimitry Andric   }
56950b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
56960b57cec5SDimitry Andric     // This trivially expands to CTTZ.
56970b57cec5SDimitry Andric     Observer.changingInstr(MI);
56980b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
56990b57cec5SDimitry Andric     Observer.changedInstr(MI);
57000b57cec5SDimitry Andric     return Legalized;
57010b57cec5SDimitry Andric   }
57020b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ: {
57035ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
57040b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
57055ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
57065ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
57075ffd83dbSDimitry Andric 
57085ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
57095ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
57100b57cec5SDimitry Andric       // If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
57110b57cec5SDimitry Andric       // zero.
57125ffd83dbSDimitry Andric       auto CttzZU = MIRBuilder.buildCTTZ_ZERO_UNDEF(DstTy, SrcReg);
57135ffd83dbSDimitry Andric       auto Zero = MIRBuilder.buildConstant(SrcTy, 0);
57145ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
57155ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, DstTy.changeElementSize(1), SrcReg, Zero);
57165ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
57175ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CttzZU);
57180b57cec5SDimitry Andric       MI.eraseFromParent();
57190b57cec5SDimitry Andric       return Legalized;
57200b57cec5SDimitry Andric     }
57210b57cec5SDimitry Andric     // for now, we use: { return popcount(~x & (x - 1)); }
57220b57cec5SDimitry Andric     // unless the target has ctlz but not ctpop, in which case we use:
57230b57cec5SDimitry Andric     // { return 32 - nlz(~x & (x-1)); }
57240b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
5725e8d8bef9SDimitry Andric     auto MIBCstNeg1 = MIRBuilder.buildConstant(SrcTy, -1);
5726e8d8bef9SDimitry Andric     auto MIBNot = MIRBuilder.buildXor(SrcTy, SrcReg, MIBCstNeg1);
57275ffd83dbSDimitry Andric     auto MIBTmp = MIRBuilder.buildAnd(
5728e8d8bef9SDimitry Andric         SrcTy, MIBNot, MIRBuilder.buildAdd(SrcTy, SrcReg, MIBCstNeg1));
5729e8d8bef9SDimitry Andric     if (!isSupported({TargetOpcode::G_CTPOP, {SrcTy, SrcTy}}) &&
5730e8d8bef9SDimitry Andric         isSupported({TargetOpcode::G_CTLZ, {SrcTy, SrcTy}})) {
5731e8d8bef9SDimitry Andric       auto MIBCstLen = MIRBuilder.buildConstant(SrcTy, Len);
57325ffd83dbSDimitry Andric       MIRBuilder.buildSub(MI.getOperand(0), MIBCstLen,
5733e8d8bef9SDimitry Andric                           MIRBuilder.buildCTLZ(SrcTy, MIBTmp));
57340b57cec5SDimitry Andric       MI.eraseFromParent();
57350b57cec5SDimitry Andric       return Legalized;
57360b57cec5SDimitry Andric     }
57370b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
57385ffd83dbSDimitry Andric     MI.getOperand(1).setReg(MIBTmp.getReg(0));
57395ffd83dbSDimitry Andric     return Legalized;
57405ffd83dbSDimitry Andric   }
57415ffd83dbSDimitry Andric   case TargetOpcode::G_CTPOP: {
5742e8d8bef9SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
5743e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(SrcReg);
57445ffd83dbSDimitry Andric     unsigned Size = Ty.getSizeInBits();
57455ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
57465ffd83dbSDimitry Andric 
57475ffd83dbSDimitry Andric     // Count set bits in blocks of 2 bits. Default approach would be
57485ffd83dbSDimitry Andric     // B2Count = { val & 0x55555555 } + { (val >> 1) & 0x55555555 }
57495ffd83dbSDimitry Andric     // We use following formula instead:
57505ffd83dbSDimitry Andric     // B2Count = val - { (val >> 1) & 0x55555555 }
57515ffd83dbSDimitry Andric     // since it gives same result in blocks of 2 with one instruction less.
57525ffd83dbSDimitry Andric     auto C_1 = B.buildConstant(Ty, 1);
5753e8d8bef9SDimitry Andric     auto B2Set1LoTo1Hi = B.buildLShr(Ty, SrcReg, C_1);
57545ffd83dbSDimitry Andric     APInt B2Mask1HiTo0 = APInt::getSplat(Size, APInt(8, 0x55));
57555ffd83dbSDimitry Andric     auto C_B2Mask1HiTo0 = B.buildConstant(Ty, B2Mask1HiTo0);
57565ffd83dbSDimitry Andric     auto B2Count1Hi = B.buildAnd(Ty, B2Set1LoTo1Hi, C_B2Mask1HiTo0);
5757e8d8bef9SDimitry Andric     auto B2Count = B.buildSub(Ty, SrcReg, B2Count1Hi);
57585ffd83dbSDimitry Andric 
57595ffd83dbSDimitry Andric     // In order to get count in blocks of 4 add values from adjacent block of 2.
57605ffd83dbSDimitry Andric     // B4Count = { B2Count & 0x33333333 } + { (B2Count >> 2) & 0x33333333 }
57615ffd83dbSDimitry Andric     auto C_2 = B.buildConstant(Ty, 2);
57625ffd83dbSDimitry Andric     auto B4Set2LoTo2Hi = B.buildLShr(Ty, B2Count, C_2);
57635ffd83dbSDimitry Andric     APInt B4Mask2HiTo0 = APInt::getSplat(Size, APInt(8, 0x33));
57645ffd83dbSDimitry Andric     auto C_B4Mask2HiTo0 = B.buildConstant(Ty, B4Mask2HiTo0);
57655ffd83dbSDimitry Andric     auto B4HiB2Count = B.buildAnd(Ty, B4Set2LoTo2Hi, C_B4Mask2HiTo0);
57665ffd83dbSDimitry Andric     auto B4LoB2Count = B.buildAnd(Ty, B2Count, C_B4Mask2HiTo0);
57675ffd83dbSDimitry Andric     auto B4Count = B.buildAdd(Ty, B4HiB2Count, B4LoB2Count);
57685ffd83dbSDimitry Andric 
57695ffd83dbSDimitry Andric     // For count in blocks of 8 bits we don't have to mask high 4 bits before
57705ffd83dbSDimitry Andric     // addition since count value sits in range {0,...,8} and 4 bits are enough
57715ffd83dbSDimitry Andric     // to hold such binary values. After addition high 4 bits still hold count
57725ffd83dbSDimitry Andric     // of set bits in high 4 bit block, set them to zero and get 8 bit result.
57735ffd83dbSDimitry Andric     // B8Count = { B4Count + (B4Count >> 4) } & 0x0F0F0F0F
57745ffd83dbSDimitry Andric     auto C_4 = B.buildConstant(Ty, 4);
57755ffd83dbSDimitry Andric     auto B8HiB4Count = B.buildLShr(Ty, B4Count, C_4);
57765ffd83dbSDimitry Andric     auto B8CountDirty4Hi = B.buildAdd(Ty, B8HiB4Count, B4Count);
57775ffd83dbSDimitry Andric     APInt B8Mask4HiTo0 = APInt::getSplat(Size, APInt(8, 0x0F));
57785ffd83dbSDimitry Andric     auto C_B8Mask4HiTo0 = B.buildConstant(Ty, B8Mask4HiTo0);
57795ffd83dbSDimitry Andric     auto B8Count = B.buildAnd(Ty, B8CountDirty4Hi, C_B8Mask4HiTo0);
57805ffd83dbSDimitry Andric 
57815ffd83dbSDimitry Andric     assert(Size<=128 && "Scalar size is too large for CTPOP lower algorithm");
57825ffd83dbSDimitry Andric     // 8 bits can hold CTPOP result of 128 bit int or smaller. Mul with this
57835ffd83dbSDimitry Andric     // bitmask will set 8 msb in ResTmp to sum of all B8Counts in 8 bit blocks.
57845ffd83dbSDimitry Andric     auto MulMask = B.buildConstant(Ty, APInt::getSplat(Size, APInt(8, 0x01)));
57855ffd83dbSDimitry Andric     auto ResTmp = B.buildMul(Ty, B8Count, MulMask);
57865ffd83dbSDimitry Andric 
57875ffd83dbSDimitry Andric     // Shift count result from 8 high bits to low bits.
57885ffd83dbSDimitry Andric     auto C_SizeM8 = B.buildConstant(Ty, Size - 8);
57895ffd83dbSDimitry Andric     B.buildLShr(MI.getOperand(0).getReg(), ResTmp, C_SizeM8);
57905ffd83dbSDimitry Andric 
57915ffd83dbSDimitry Andric     MI.eraseFromParent();
57920b57cec5SDimitry Andric     return Legalized;
57930b57cec5SDimitry Andric   }
57940b57cec5SDimitry Andric   }
57950b57cec5SDimitry Andric }
57960b57cec5SDimitry Andric 
5797*fe6060f1SDimitry Andric // Check that (every element of) Reg is undef or not an exact multiple of BW.
5798*fe6060f1SDimitry Andric static bool isNonZeroModBitWidthOrUndef(const MachineRegisterInfo &MRI,
5799*fe6060f1SDimitry Andric                                         Register Reg, unsigned BW) {
5800*fe6060f1SDimitry Andric   return matchUnaryPredicate(
5801*fe6060f1SDimitry Andric       MRI, Reg,
5802*fe6060f1SDimitry Andric       [=](const Constant *C) {
5803*fe6060f1SDimitry Andric         // Null constant here means an undef.
5804*fe6060f1SDimitry Andric         const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C);
5805*fe6060f1SDimitry Andric         return !CI || CI->getValue().urem(BW) != 0;
5806*fe6060f1SDimitry Andric       },
5807*fe6060f1SDimitry Andric       /*AllowUndefs*/ true);
5808*fe6060f1SDimitry Andric }
5809*fe6060f1SDimitry Andric 
5810*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5811*fe6060f1SDimitry Andric LegalizerHelper::lowerFunnelShiftWithInverse(MachineInstr &MI) {
5812*fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5813*fe6060f1SDimitry Andric   Register X = MI.getOperand(1).getReg();
5814*fe6060f1SDimitry Andric   Register Y = MI.getOperand(2).getReg();
5815*fe6060f1SDimitry Andric   Register Z = MI.getOperand(3).getReg();
5816*fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
5817*fe6060f1SDimitry Andric   LLT ShTy = MRI.getType(Z);
5818*fe6060f1SDimitry Andric 
5819*fe6060f1SDimitry Andric   unsigned BW = Ty.getScalarSizeInBits();
5820*fe6060f1SDimitry Andric 
5821*fe6060f1SDimitry Andric   if (!isPowerOf2_32(BW))
5822*fe6060f1SDimitry Andric     return UnableToLegalize;
5823*fe6060f1SDimitry Andric 
5824*fe6060f1SDimitry Andric   const bool IsFSHL = MI.getOpcode() == TargetOpcode::G_FSHL;
5825*fe6060f1SDimitry Andric   unsigned RevOpcode = IsFSHL ? TargetOpcode::G_FSHR : TargetOpcode::G_FSHL;
5826*fe6060f1SDimitry Andric 
5827*fe6060f1SDimitry Andric   if (isNonZeroModBitWidthOrUndef(MRI, Z, BW)) {
5828*fe6060f1SDimitry Andric     // fshl X, Y, Z -> fshr X, Y, -Z
5829*fe6060f1SDimitry Andric     // fshr X, Y, Z -> fshl X, Y, -Z
5830*fe6060f1SDimitry Andric     auto Zero = MIRBuilder.buildConstant(ShTy, 0);
5831*fe6060f1SDimitry Andric     Z = MIRBuilder.buildSub(Ty, Zero, Z).getReg(0);
5832*fe6060f1SDimitry Andric   } else {
5833*fe6060f1SDimitry Andric     // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
5834*fe6060f1SDimitry Andric     // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
5835*fe6060f1SDimitry Andric     auto One = MIRBuilder.buildConstant(ShTy, 1);
5836*fe6060f1SDimitry Andric     if (IsFSHL) {
5837*fe6060f1SDimitry Andric       Y = MIRBuilder.buildInstr(RevOpcode, {Ty}, {X, Y, One}).getReg(0);
5838*fe6060f1SDimitry Andric       X = MIRBuilder.buildLShr(Ty, X, One).getReg(0);
5839*fe6060f1SDimitry Andric     } else {
5840*fe6060f1SDimitry Andric       X = MIRBuilder.buildInstr(RevOpcode, {Ty}, {X, Y, One}).getReg(0);
5841*fe6060f1SDimitry Andric       Y = MIRBuilder.buildShl(Ty, Y, One).getReg(0);
5842*fe6060f1SDimitry Andric     }
5843*fe6060f1SDimitry Andric 
5844*fe6060f1SDimitry Andric     Z = MIRBuilder.buildNot(ShTy, Z).getReg(0);
5845*fe6060f1SDimitry Andric   }
5846*fe6060f1SDimitry Andric 
5847*fe6060f1SDimitry Andric   MIRBuilder.buildInstr(RevOpcode, {Dst}, {X, Y, Z});
5848*fe6060f1SDimitry Andric   MI.eraseFromParent();
5849*fe6060f1SDimitry Andric   return Legalized;
5850*fe6060f1SDimitry Andric }
5851*fe6060f1SDimitry Andric 
5852*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5853*fe6060f1SDimitry Andric LegalizerHelper::lowerFunnelShiftAsShifts(MachineInstr &MI) {
5854*fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5855*fe6060f1SDimitry Andric   Register X = MI.getOperand(1).getReg();
5856*fe6060f1SDimitry Andric   Register Y = MI.getOperand(2).getReg();
5857*fe6060f1SDimitry Andric   Register Z = MI.getOperand(3).getReg();
5858*fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
5859*fe6060f1SDimitry Andric   LLT ShTy = MRI.getType(Z);
5860*fe6060f1SDimitry Andric 
5861*fe6060f1SDimitry Andric   const unsigned BW = Ty.getScalarSizeInBits();
5862*fe6060f1SDimitry Andric   const bool IsFSHL = MI.getOpcode() == TargetOpcode::G_FSHL;
5863*fe6060f1SDimitry Andric 
5864*fe6060f1SDimitry Andric   Register ShX, ShY;
5865*fe6060f1SDimitry Andric   Register ShAmt, InvShAmt;
5866*fe6060f1SDimitry Andric 
5867*fe6060f1SDimitry Andric   // FIXME: Emit optimized urem by constant instead of letting it expand later.
5868*fe6060f1SDimitry Andric   if (isNonZeroModBitWidthOrUndef(MRI, Z, BW)) {
5869*fe6060f1SDimitry Andric     // fshl: X << C | Y >> (BW - C)
5870*fe6060f1SDimitry Andric     // fshr: X << (BW - C) | Y >> C
5871*fe6060f1SDimitry Andric     // where C = Z % BW is not zero
5872*fe6060f1SDimitry Andric     auto BitWidthC = MIRBuilder.buildConstant(ShTy, BW);
5873*fe6060f1SDimitry Andric     ShAmt = MIRBuilder.buildURem(ShTy, Z, BitWidthC).getReg(0);
5874*fe6060f1SDimitry Andric     InvShAmt = MIRBuilder.buildSub(ShTy, BitWidthC, ShAmt).getReg(0);
5875*fe6060f1SDimitry Andric     ShX = MIRBuilder.buildShl(Ty, X, IsFSHL ? ShAmt : InvShAmt).getReg(0);
5876*fe6060f1SDimitry Andric     ShY = MIRBuilder.buildLShr(Ty, Y, IsFSHL ? InvShAmt : ShAmt).getReg(0);
5877*fe6060f1SDimitry Andric   } else {
5878*fe6060f1SDimitry Andric     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
5879*fe6060f1SDimitry Andric     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
5880*fe6060f1SDimitry Andric     auto Mask = MIRBuilder.buildConstant(ShTy, BW - 1);
5881*fe6060f1SDimitry Andric     if (isPowerOf2_32(BW)) {
5882*fe6060f1SDimitry Andric       // Z % BW -> Z & (BW - 1)
5883*fe6060f1SDimitry Andric       ShAmt = MIRBuilder.buildAnd(ShTy, Z, Mask).getReg(0);
5884*fe6060f1SDimitry Andric       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
5885*fe6060f1SDimitry Andric       auto NotZ = MIRBuilder.buildNot(ShTy, Z);
5886*fe6060f1SDimitry Andric       InvShAmt = MIRBuilder.buildAnd(ShTy, NotZ, Mask).getReg(0);
5887*fe6060f1SDimitry Andric     } else {
5888*fe6060f1SDimitry Andric       auto BitWidthC = MIRBuilder.buildConstant(ShTy, BW);
5889*fe6060f1SDimitry Andric       ShAmt = MIRBuilder.buildURem(ShTy, Z, BitWidthC).getReg(0);
5890*fe6060f1SDimitry Andric       InvShAmt = MIRBuilder.buildSub(ShTy, Mask, ShAmt).getReg(0);
5891*fe6060f1SDimitry Andric     }
5892*fe6060f1SDimitry Andric 
5893*fe6060f1SDimitry Andric     auto One = MIRBuilder.buildConstant(ShTy, 1);
5894*fe6060f1SDimitry Andric     if (IsFSHL) {
5895*fe6060f1SDimitry Andric       ShX = MIRBuilder.buildShl(Ty, X, ShAmt).getReg(0);
5896*fe6060f1SDimitry Andric       auto ShY1 = MIRBuilder.buildLShr(Ty, Y, One);
5897*fe6060f1SDimitry Andric       ShY = MIRBuilder.buildLShr(Ty, ShY1, InvShAmt).getReg(0);
5898*fe6060f1SDimitry Andric     } else {
5899*fe6060f1SDimitry Andric       auto ShX1 = MIRBuilder.buildShl(Ty, X, One);
5900*fe6060f1SDimitry Andric       ShX = MIRBuilder.buildShl(Ty, ShX1, InvShAmt).getReg(0);
5901*fe6060f1SDimitry Andric       ShY = MIRBuilder.buildLShr(Ty, Y, ShAmt).getReg(0);
5902*fe6060f1SDimitry Andric     }
5903*fe6060f1SDimitry Andric   }
5904*fe6060f1SDimitry Andric 
5905*fe6060f1SDimitry Andric   MIRBuilder.buildOr(Dst, ShX, ShY);
5906*fe6060f1SDimitry Andric   MI.eraseFromParent();
5907*fe6060f1SDimitry Andric   return Legalized;
5908*fe6060f1SDimitry Andric }
5909*fe6060f1SDimitry Andric 
5910*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5911*fe6060f1SDimitry Andric LegalizerHelper::lowerFunnelShift(MachineInstr &MI) {
5912*fe6060f1SDimitry Andric   // These operations approximately do the following (while avoiding undefined
5913*fe6060f1SDimitry Andric   // shifts by BW):
5914*fe6060f1SDimitry Andric   // G_FSHL: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5915*fe6060f1SDimitry Andric   // G_FSHR: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5916*fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5917*fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
5918*fe6060f1SDimitry Andric   LLT ShTy = MRI.getType(MI.getOperand(3).getReg());
5919*fe6060f1SDimitry Andric 
5920*fe6060f1SDimitry Andric   bool IsFSHL = MI.getOpcode() == TargetOpcode::G_FSHL;
5921*fe6060f1SDimitry Andric   unsigned RevOpcode = IsFSHL ? TargetOpcode::G_FSHR : TargetOpcode::G_FSHL;
5922*fe6060f1SDimitry Andric 
5923*fe6060f1SDimitry Andric   // TODO: Use smarter heuristic that accounts for vector legalization.
5924*fe6060f1SDimitry Andric   if (LI.getAction({RevOpcode, {Ty, ShTy}}).Action == Lower)
5925*fe6060f1SDimitry Andric     return lowerFunnelShiftAsShifts(MI);
5926*fe6060f1SDimitry Andric 
5927*fe6060f1SDimitry Andric   // This only works for powers of 2, fallback to shifts if it fails.
5928*fe6060f1SDimitry Andric   LegalizerHelper::LegalizeResult Result = lowerFunnelShiftWithInverse(MI);
5929*fe6060f1SDimitry Andric   if (Result == UnableToLegalize)
5930*fe6060f1SDimitry Andric     return lowerFunnelShiftAsShifts(MI);
5931*fe6060f1SDimitry Andric   return Result;
5932*fe6060f1SDimitry Andric }
5933*fe6060f1SDimitry Andric 
5934*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5935*fe6060f1SDimitry Andric LegalizerHelper::lowerRotateWithReverseRotate(MachineInstr &MI) {
5936*fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5937*fe6060f1SDimitry Andric   Register Src = MI.getOperand(1).getReg();
5938*fe6060f1SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
5939*fe6060f1SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
5940*fe6060f1SDimitry Andric   auto Zero = MIRBuilder.buildConstant(AmtTy, 0);
5941*fe6060f1SDimitry Andric   bool IsLeft = MI.getOpcode() == TargetOpcode::G_ROTL;
5942*fe6060f1SDimitry Andric   unsigned RevRot = IsLeft ? TargetOpcode::G_ROTR : TargetOpcode::G_ROTL;
5943*fe6060f1SDimitry Andric   auto Neg = MIRBuilder.buildSub(AmtTy, Zero, Amt);
5944*fe6060f1SDimitry Andric   MIRBuilder.buildInstr(RevRot, {Dst}, {Src, Neg});
5945*fe6060f1SDimitry Andric   MI.eraseFromParent();
5946*fe6060f1SDimitry Andric   return Legalized;
5947*fe6060f1SDimitry Andric }
5948*fe6060f1SDimitry Andric 
5949*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerRotate(MachineInstr &MI) {
5950*fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5951*fe6060f1SDimitry Andric   Register Src = MI.getOperand(1).getReg();
5952*fe6060f1SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
5953*fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(Dst);
5954*fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(Dst);
5955*fe6060f1SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
5956*fe6060f1SDimitry Andric 
5957*fe6060f1SDimitry Andric   unsigned EltSizeInBits = DstTy.getScalarSizeInBits();
5958*fe6060f1SDimitry Andric   bool IsLeft = MI.getOpcode() == TargetOpcode::G_ROTL;
5959*fe6060f1SDimitry Andric 
5960*fe6060f1SDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
5961*fe6060f1SDimitry Andric 
5962*fe6060f1SDimitry Andric   // If a rotate in the other direction is supported, use it.
5963*fe6060f1SDimitry Andric   unsigned RevRot = IsLeft ? TargetOpcode::G_ROTR : TargetOpcode::G_ROTL;
5964*fe6060f1SDimitry Andric   if (LI.isLegalOrCustom({RevRot, {DstTy, SrcTy}}) &&
5965*fe6060f1SDimitry Andric       isPowerOf2_32(EltSizeInBits))
5966*fe6060f1SDimitry Andric     return lowerRotateWithReverseRotate(MI);
5967*fe6060f1SDimitry Andric 
5968*fe6060f1SDimitry Andric   auto Zero = MIRBuilder.buildConstant(AmtTy, 0);
5969*fe6060f1SDimitry Andric   unsigned ShOpc = IsLeft ? TargetOpcode::G_SHL : TargetOpcode::G_LSHR;
5970*fe6060f1SDimitry Andric   unsigned RevShiftOpc = IsLeft ? TargetOpcode::G_LSHR : TargetOpcode::G_SHL;
5971*fe6060f1SDimitry Andric   auto BitWidthMinusOneC = MIRBuilder.buildConstant(AmtTy, EltSizeInBits - 1);
5972*fe6060f1SDimitry Andric   Register ShVal;
5973*fe6060f1SDimitry Andric   Register RevShiftVal;
5974*fe6060f1SDimitry Andric   if (isPowerOf2_32(EltSizeInBits)) {
5975*fe6060f1SDimitry Andric     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
5976*fe6060f1SDimitry Andric     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
5977*fe6060f1SDimitry Andric     auto NegAmt = MIRBuilder.buildSub(AmtTy, Zero, Amt);
5978*fe6060f1SDimitry Andric     auto ShAmt = MIRBuilder.buildAnd(AmtTy, Amt, BitWidthMinusOneC);
5979*fe6060f1SDimitry Andric     ShVal = MIRBuilder.buildInstr(ShOpc, {DstTy}, {Src, ShAmt}).getReg(0);
5980*fe6060f1SDimitry Andric     auto RevAmt = MIRBuilder.buildAnd(AmtTy, NegAmt, BitWidthMinusOneC);
5981*fe6060f1SDimitry Andric     RevShiftVal =
5982*fe6060f1SDimitry Andric         MIRBuilder.buildInstr(RevShiftOpc, {DstTy}, {Src, RevAmt}).getReg(0);
5983*fe6060f1SDimitry Andric   } else {
5984*fe6060f1SDimitry Andric     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
5985*fe6060f1SDimitry Andric     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
5986*fe6060f1SDimitry Andric     auto BitWidthC = MIRBuilder.buildConstant(AmtTy, EltSizeInBits);
5987*fe6060f1SDimitry Andric     auto ShAmt = MIRBuilder.buildURem(AmtTy, Amt, BitWidthC);
5988*fe6060f1SDimitry Andric     ShVal = MIRBuilder.buildInstr(ShOpc, {DstTy}, {Src, ShAmt}).getReg(0);
5989*fe6060f1SDimitry Andric     auto RevAmt = MIRBuilder.buildSub(AmtTy, BitWidthMinusOneC, ShAmt);
5990*fe6060f1SDimitry Andric     auto One = MIRBuilder.buildConstant(AmtTy, 1);
5991*fe6060f1SDimitry Andric     auto Inner = MIRBuilder.buildInstr(RevShiftOpc, {DstTy}, {Src, One});
5992*fe6060f1SDimitry Andric     RevShiftVal =
5993*fe6060f1SDimitry Andric         MIRBuilder.buildInstr(RevShiftOpc, {DstTy}, {Inner, RevAmt}).getReg(0);
5994*fe6060f1SDimitry Andric   }
5995*fe6060f1SDimitry Andric   MIRBuilder.buildOr(Dst, ShVal, RevShiftVal);
5996*fe6060f1SDimitry Andric   MI.eraseFromParent();
5997*fe6060f1SDimitry Andric   return Legalized;
5998*fe6060f1SDimitry Andric }
5999*fe6060f1SDimitry Andric 
60000b57cec5SDimitry Andric // Expand s32 = G_UITOFP s64 using bit operations to an IEEE float
60010b57cec5SDimitry Andric // representation.
60020b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
60030b57cec5SDimitry Andric LegalizerHelper::lowerU64ToF32BitOps(MachineInstr &MI) {
60040b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
60050b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
60060b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
60070b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
60080b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
60090b57cec5SDimitry Andric 
60100b57cec5SDimitry Andric   assert(MRI.getType(Src) == S64 && MRI.getType(Dst) == S32);
60110b57cec5SDimitry Andric 
60120b57cec5SDimitry Andric   // unsigned cul2f(ulong u) {
60130b57cec5SDimitry Andric   //   uint lz = clz(u);
60140b57cec5SDimitry Andric   //   uint e = (u != 0) ? 127U + 63U - lz : 0;
60150b57cec5SDimitry Andric   //   u = (u << lz) & 0x7fffffffffffffffUL;
60160b57cec5SDimitry Andric   //   ulong t = u & 0xffffffffffUL;
60170b57cec5SDimitry Andric   //   uint v = (e << 23) | (uint)(u >> 40);
60180b57cec5SDimitry Andric   //   uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
60190b57cec5SDimitry Andric   //   return as_float(v + r);
60200b57cec5SDimitry Andric   // }
60210b57cec5SDimitry Andric 
60220b57cec5SDimitry Andric   auto Zero32 = MIRBuilder.buildConstant(S32, 0);
60230b57cec5SDimitry Andric   auto Zero64 = MIRBuilder.buildConstant(S64, 0);
60240b57cec5SDimitry Andric 
60250b57cec5SDimitry Andric   auto LZ = MIRBuilder.buildCTLZ_ZERO_UNDEF(S32, Src);
60260b57cec5SDimitry Andric 
60270b57cec5SDimitry Andric   auto K = MIRBuilder.buildConstant(S32, 127U + 63U);
60280b57cec5SDimitry Andric   auto Sub = MIRBuilder.buildSub(S32, K, LZ);
60290b57cec5SDimitry Andric 
60300b57cec5SDimitry Andric   auto NotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, Src, Zero64);
60310b57cec5SDimitry Andric   auto E = MIRBuilder.buildSelect(S32, NotZero, Sub, Zero32);
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric   auto Mask0 = MIRBuilder.buildConstant(S64, (-1ULL) >> 1);
60340b57cec5SDimitry Andric   auto ShlLZ = MIRBuilder.buildShl(S64, Src, LZ);
60350b57cec5SDimitry Andric 
60360b57cec5SDimitry Andric   auto U = MIRBuilder.buildAnd(S64, ShlLZ, Mask0);
60370b57cec5SDimitry Andric 
60380b57cec5SDimitry Andric   auto Mask1 = MIRBuilder.buildConstant(S64, 0xffffffffffULL);
60390b57cec5SDimitry Andric   auto T = MIRBuilder.buildAnd(S64, U, Mask1);
60400b57cec5SDimitry Andric 
60410b57cec5SDimitry Andric   auto UShl = MIRBuilder.buildLShr(S64, U, MIRBuilder.buildConstant(S64, 40));
60420b57cec5SDimitry Andric   auto ShlE = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 23));
60430b57cec5SDimitry Andric   auto V = MIRBuilder.buildOr(S32, ShlE, MIRBuilder.buildTrunc(S32, UShl));
60440b57cec5SDimitry Andric 
60450b57cec5SDimitry Andric   auto C = MIRBuilder.buildConstant(S64, 0x8000000000ULL);
60460b57cec5SDimitry Andric   auto RCmp = MIRBuilder.buildICmp(CmpInst::ICMP_UGT, S1, T, C);
60470b57cec5SDimitry Andric   auto TCmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, T, C);
60480b57cec5SDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
60490b57cec5SDimitry Andric 
60500b57cec5SDimitry Andric   auto VTrunc1 = MIRBuilder.buildAnd(S32, V, One);
60510b57cec5SDimitry Andric   auto Select0 = MIRBuilder.buildSelect(S32, TCmp, VTrunc1, Zero32);
60520b57cec5SDimitry Andric   auto R = MIRBuilder.buildSelect(S32, RCmp, One, Select0);
60530b57cec5SDimitry Andric   MIRBuilder.buildAdd(Dst, V, R);
60540b57cec5SDimitry Andric 
60555ffd83dbSDimitry Andric   MI.eraseFromParent();
60560b57cec5SDimitry Andric   return Legalized;
60570b57cec5SDimitry Andric }
60580b57cec5SDimitry Andric 
6059e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerUITOFP(MachineInstr &MI) {
60600b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
60610b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
60620b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst);
60630b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src);
60640b57cec5SDimitry Andric 
6065480093f4SDimitry Andric   if (SrcTy == LLT::scalar(1)) {
6066480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, 1.0);
6067480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
6068480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
6069480093f4SDimitry Andric     MI.eraseFromParent();
6070480093f4SDimitry Andric     return Legalized;
6071480093f4SDimitry Andric   }
6072480093f4SDimitry Andric 
60730b57cec5SDimitry Andric   if (SrcTy != LLT::scalar(64))
60740b57cec5SDimitry Andric     return UnableToLegalize;
60750b57cec5SDimitry Andric 
60760b57cec5SDimitry Andric   if (DstTy == LLT::scalar(32)) {
60770b57cec5SDimitry Andric     // TODO: SelectionDAG has several alternative expansions to port which may
60780b57cec5SDimitry Andric     // be more reasonble depending on the available instructions. If a target
60790b57cec5SDimitry Andric     // has sitofp, does not have CTLZ, or can efficiently use f64 as an
60800b57cec5SDimitry Andric     // intermediate type, this is probably worse.
60810b57cec5SDimitry Andric     return lowerU64ToF32BitOps(MI);
60820b57cec5SDimitry Andric   }
60830b57cec5SDimitry Andric 
60840b57cec5SDimitry Andric   return UnableToLegalize;
60850b57cec5SDimitry Andric }
60860b57cec5SDimitry Andric 
6087e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSITOFP(MachineInstr &MI) {
60880b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
60890b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
60900b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst);
60910b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src);
60920b57cec5SDimitry Andric 
60930b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
60940b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
60950b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
60960b57cec5SDimitry Andric 
6097480093f4SDimitry Andric   if (SrcTy == S1) {
6098480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, -1.0);
6099480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
6100480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
6101480093f4SDimitry Andric     MI.eraseFromParent();
6102480093f4SDimitry Andric     return Legalized;
6103480093f4SDimitry Andric   }
6104480093f4SDimitry Andric 
61050b57cec5SDimitry Andric   if (SrcTy != S64)
61060b57cec5SDimitry Andric     return UnableToLegalize;
61070b57cec5SDimitry Andric 
61080b57cec5SDimitry Andric   if (DstTy == S32) {
61090b57cec5SDimitry Andric     // signed cl2f(long l) {
61100b57cec5SDimitry Andric     //   long s = l >> 63;
61110b57cec5SDimitry Andric     //   float r = cul2f((l + s) ^ s);
61120b57cec5SDimitry Andric     //   return s ? -r : r;
61130b57cec5SDimitry Andric     // }
61140b57cec5SDimitry Andric     Register L = Src;
61150b57cec5SDimitry Andric     auto SignBit = MIRBuilder.buildConstant(S64, 63);
61160b57cec5SDimitry Andric     auto S = MIRBuilder.buildAShr(S64, L, SignBit);
61170b57cec5SDimitry Andric 
61180b57cec5SDimitry Andric     auto LPlusS = MIRBuilder.buildAdd(S64, L, S);
61190b57cec5SDimitry Andric     auto Xor = MIRBuilder.buildXor(S64, LPlusS, S);
61200b57cec5SDimitry Andric     auto R = MIRBuilder.buildUITOFP(S32, Xor);
61210b57cec5SDimitry Andric 
61220b57cec5SDimitry Andric     auto RNeg = MIRBuilder.buildFNeg(S32, R);
61230b57cec5SDimitry Andric     auto SignNotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, S,
61240b57cec5SDimitry Andric                                             MIRBuilder.buildConstant(S64, 0));
61250b57cec5SDimitry Andric     MIRBuilder.buildSelect(Dst, SignNotZero, RNeg, R);
61265ffd83dbSDimitry Andric     MI.eraseFromParent();
61270b57cec5SDimitry Andric     return Legalized;
61280b57cec5SDimitry Andric   }
61290b57cec5SDimitry Andric 
61300b57cec5SDimitry Andric   return UnableToLegalize;
61310b57cec5SDimitry Andric }
61320b57cec5SDimitry Andric 
6133e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOUI(MachineInstr &MI) {
61348bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
61358bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
61368bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst);
61378bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(Src);
61388bcb0991SDimitry Andric   const LLT S64 = LLT::scalar(64);
61398bcb0991SDimitry Andric   const LLT S32 = LLT::scalar(32);
61408bcb0991SDimitry Andric 
61418bcb0991SDimitry Andric   if (SrcTy != S64 && SrcTy != S32)
61428bcb0991SDimitry Andric     return UnableToLegalize;
61438bcb0991SDimitry Andric   if (DstTy != S32 && DstTy != S64)
61448bcb0991SDimitry Andric     return UnableToLegalize;
61458bcb0991SDimitry Andric 
61468bcb0991SDimitry Andric   // FPTOSI gives same result as FPTOUI for positive signed integers.
61478bcb0991SDimitry Andric   // FPTOUI needs to deal with fp values that convert to unsigned integers
61488bcb0991SDimitry Andric   // greater or equal to 2^31 for float or 2^63 for double. For brevity 2^Exp.
61498bcb0991SDimitry Andric 
61508bcb0991SDimitry Andric   APInt TwoPExpInt = APInt::getSignMask(DstTy.getSizeInBits());
61518bcb0991SDimitry Andric   APFloat TwoPExpFP(SrcTy.getSizeInBits() == 32 ? APFloat::IEEEsingle()
61528bcb0991SDimitry Andric                                                 : APFloat::IEEEdouble(),
61538bcb0991SDimitry Andric                     APInt::getNullValue(SrcTy.getSizeInBits()));
61548bcb0991SDimitry Andric   TwoPExpFP.convertFromAPInt(TwoPExpInt, false, APFloat::rmNearestTiesToEven);
61558bcb0991SDimitry Andric 
61568bcb0991SDimitry Andric   MachineInstrBuilder FPTOSI = MIRBuilder.buildFPTOSI(DstTy, Src);
61578bcb0991SDimitry Andric 
61588bcb0991SDimitry Andric   MachineInstrBuilder Threshold = MIRBuilder.buildFConstant(SrcTy, TwoPExpFP);
61598bcb0991SDimitry Andric   // For fp Value greater or equal to Threshold(2^Exp), we use FPTOSI on
61608bcb0991SDimitry Andric   // (Value - 2^Exp) and add 2^Exp by setting highest bit in result to 1.
61618bcb0991SDimitry Andric   MachineInstrBuilder FSub = MIRBuilder.buildFSub(SrcTy, Src, Threshold);
61628bcb0991SDimitry Andric   MachineInstrBuilder ResLowBits = MIRBuilder.buildFPTOSI(DstTy, FSub);
61638bcb0991SDimitry Andric   MachineInstrBuilder ResHighBit = MIRBuilder.buildConstant(DstTy, TwoPExpInt);
61648bcb0991SDimitry Andric   MachineInstrBuilder Res = MIRBuilder.buildXor(DstTy, ResLowBits, ResHighBit);
61658bcb0991SDimitry Andric 
6166480093f4SDimitry Andric   const LLT S1 = LLT::scalar(1);
6167480093f4SDimitry Andric 
61688bcb0991SDimitry Andric   MachineInstrBuilder FCMP =
6169480093f4SDimitry Andric       MIRBuilder.buildFCmp(CmpInst::FCMP_ULT, S1, Src, Threshold);
61708bcb0991SDimitry Andric   MIRBuilder.buildSelect(Dst, FCMP, FPTOSI, Res);
61718bcb0991SDimitry Andric 
61728bcb0991SDimitry Andric   MI.eraseFromParent();
61738bcb0991SDimitry Andric   return Legalized;
61748bcb0991SDimitry Andric }
61758bcb0991SDimitry Andric 
61765ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOSI(MachineInstr &MI) {
61775ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
61785ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
61795ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
61805ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
61815ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
61825ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
61835ffd83dbSDimitry Andric 
61845ffd83dbSDimitry Andric   // FIXME: Only f32 to i64 conversions are supported.
61855ffd83dbSDimitry Andric   if (SrcTy.getScalarType() != S32 || DstTy.getScalarType() != S64)
61865ffd83dbSDimitry Andric     return UnableToLegalize;
61875ffd83dbSDimitry Andric 
61885ffd83dbSDimitry Andric   // Expand f32 -> i64 conversion
61895ffd83dbSDimitry Andric   // This algorithm comes from compiler-rt's implementation of fixsfdi:
6190*fe6060f1SDimitry Andric   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
61915ffd83dbSDimitry Andric 
61925ffd83dbSDimitry Andric   unsigned SrcEltBits = SrcTy.getScalarSizeInBits();
61935ffd83dbSDimitry Andric 
61945ffd83dbSDimitry Andric   auto ExponentMask = MIRBuilder.buildConstant(SrcTy, 0x7F800000);
61955ffd83dbSDimitry Andric   auto ExponentLoBit = MIRBuilder.buildConstant(SrcTy, 23);
61965ffd83dbSDimitry Andric 
61975ffd83dbSDimitry Andric   auto AndExpMask = MIRBuilder.buildAnd(SrcTy, Src, ExponentMask);
61985ffd83dbSDimitry Andric   auto ExponentBits = MIRBuilder.buildLShr(SrcTy, AndExpMask, ExponentLoBit);
61995ffd83dbSDimitry Andric 
62005ffd83dbSDimitry Andric   auto SignMask = MIRBuilder.buildConstant(SrcTy,
62015ffd83dbSDimitry Andric                                            APInt::getSignMask(SrcEltBits));
62025ffd83dbSDimitry Andric   auto AndSignMask = MIRBuilder.buildAnd(SrcTy, Src, SignMask);
62035ffd83dbSDimitry Andric   auto SignLowBit = MIRBuilder.buildConstant(SrcTy, SrcEltBits - 1);
62045ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildAShr(SrcTy, AndSignMask, SignLowBit);
62055ffd83dbSDimitry Andric   Sign = MIRBuilder.buildSExt(DstTy, Sign);
62065ffd83dbSDimitry Andric 
62075ffd83dbSDimitry Andric   auto MantissaMask = MIRBuilder.buildConstant(SrcTy, 0x007FFFFF);
62085ffd83dbSDimitry Andric   auto AndMantissaMask = MIRBuilder.buildAnd(SrcTy, Src, MantissaMask);
62095ffd83dbSDimitry Andric   auto K = MIRBuilder.buildConstant(SrcTy, 0x00800000);
62105ffd83dbSDimitry Andric 
62115ffd83dbSDimitry Andric   auto R = MIRBuilder.buildOr(SrcTy, AndMantissaMask, K);
62125ffd83dbSDimitry Andric   R = MIRBuilder.buildZExt(DstTy, R);
62135ffd83dbSDimitry Andric 
62145ffd83dbSDimitry Andric   auto Bias = MIRBuilder.buildConstant(SrcTy, 127);
62155ffd83dbSDimitry Andric   auto Exponent = MIRBuilder.buildSub(SrcTy, ExponentBits, Bias);
62165ffd83dbSDimitry Andric   auto SubExponent = MIRBuilder.buildSub(SrcTy, Exponent, ExponentLoBit);
62175ffd83dbSDimitry Andric   auto ExponentSub = MIRBuilder.buildSub(SrcTy, ExponentLoBit, Exponent);
62185ffd83dbSDimitry Andric 
62195ffd83dbSDimitry Andric   auto Shl = MIRBuilder.buildShl(DstTy, R, SubExponent);
62205ffd83dbSDimitry Andric   auto Srl = MIRBuilder.buildLShr(DstTy, R, ExponentSub);
62215ffd83dbSDimitry Andric 
62225ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
62235ffd83dbSDimitry Andric   auto CmpGt = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,
62245ffd83dbSDimitry Andric                                     S1, Exponent, ExponentLoBit);
62255ffd83dbSDimitry Andric 
62265ffd83dbSDimitry Andric   R = MIRBuilder.buildSelect(DstTy, CmpGt, Shl, Srl);
62275ffd83dbSDimitry Andric 
62285ffd83dbSDimitry Andric   auto XorSign = MIRBuilder.buildXor(DstTy, R, Sign);
62295ffd83dbSDimitry Andric   auto Ret = MIRBuilder.buildSub(DstTy, XorSign, Sign);
62305ffd83dbSDimitry Andric 
62315ffd83dbSDimitry Andric   auto ZeroSrcTy = MIRBuilder.buildConstant(SrcTy, 0);
62325ffd83dbSDimitry Andric 
62335ffd83dbSDimitry Andric   auto ExponentLt0 = MIRBuilder.buildICmp(CmpInst::ICMP_SLT,
62345ffd83dbSDimitry Andric                                           S1, Exponent, ZeroSrcTy);
62355ffd83dbSDimitry Andric 
62365ffd83dbSDimitry Andric   auto ZeroDstTy = MIRBuilder.buildConstant(DstTy, 0);
62375ffd83dbSDimitry Andric   MIRBuilder.buildSelect(Dst, ExponentLt0, ZeroDstTy, Ret);
62385ffd83dbSDimitry Andric 
62395ffd83dbSDimitry Andric   MI.eraseFromParent();
62405ffd83dbSDimitry Andric   return Legalized;
62415ffd83dbSDimitry Andric }
62425ffd83dbSDimitry Andric 
62435ffd83dbSDimitry Andric // f64 -> f16 conversion using round-to-nearest-even rounding mode.
62445ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
62455ffd83dbSDimitry Andric LegalizerHelper::lowerFPTRUNC_F64_TO_F16(MachineInstr &MI) {
62465ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
62475ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
62485ffd83dbSDimitry Andric 
62495ffd83dbSDimitry Andric   if (MRI.getType(Src).isVector()) // TODO: Handle vectors directly.
62505ffd83dbSDimitry Andric     return UnableToLegalize;
62515ffd83dbSDimitry Andric 
62525ffd83dbSDimitry Andric   const unsigned ExpMask = 0x7ff;
62535ffd83dbSDimitry Andric   const unsigned ExpBiasf64 = 1023;
62545ffd83dbSDimitry Andric   const unsigned ExpBiasf16 = 15;
62555ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
62565ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
62575ffd83dbSDimitry Andric 
62585ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(S32, Src);
62595ffd83dbSDimitry Andric   Register U = Unmerge.getReg(0);
62605ffd83dbSDimitry Andric   Register UH = Unmerge.getReg(1);
62615ffd83dbSDimitry Andric 
62625ffd83dbSDimitry Andric   auto E = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 20));
62635ffd83dbSDimitry Andric   E = MIRBuilder.buildAnd(S32, E, MIRBuilder.buildConstant(S32, ExpMask));
62645ffd83dbSDimitry Andric 
62655ffd83dbSDimitry Andric   // Subtract the fp64 exponent bias (1023) to get the real exponent and
62665ffd83dbSDimitry Andric   // add the f16 bias (15) to get the biased exponent for the f16 format.
62675ffd83dbSDimitry Andric   E = MIRBuilder.buildAdd(
62685ffd83dbSDimitry Andric     S32, E, MIRBuilder.buildConstant(S32, -ExpBiasf64 + ExpBiasf16));
62695ffd83dbSDimitry Andric 
62705ffd83dbSDimitry Andric   auto M = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 8));
62715ffd83dbSDimitry Andric   M = MIRBuilder.buildAnd(S32, M, MIRBuilder.buildConstant(S32, 0xffe));
62725ffd83dbSDimitry Andric 
62735ffd83dbSDimitry Andric   auto MaskedSig = MIRBuilder.buildAnd(S32, UH,
62745ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1ff));
62755ffd83dbSDimitry Andric   MaskedSig = MIRBuilder.buildOr(S32, MaskedSig, U);
62765ffd83dbSDimitry Andric 
62775ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildConstant(S32, 0);
62785ffd83dbSDimitry Andric   auto SigCmpNE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, MaskedSig, Zero);
62795ffd83dbSDimitry Andric   auto Lo40Set = MIRBuilder.buildZExt(S32, SigCmpNE0);
62805ffd83dbSDimitry Andric   M = MIRBuilder.buildOr(S32, M, Lo40Set);
62815ffd83dbSDimitry Andric 
62825ffd83dbSDimitry Andric   // (M != 0 ? 0x0200 : 0) | 0x7c00;
62835ffd83dbSDimitry Andric   auto Bits0x200 = MIRBuilder.buildConstant(S32, 0x0200);
62845ffd83dbSDimitry Andric   auto CmpM_NE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, M, Zero);
62855ffd83dbSDimitry Andric   auto SelectCC = MIRBuilder.buildSelect(S32, CmpM_NE0, Bits0x200, Zero);
62865ffd83dbSDimitry Andric 
62875ffd83dbSDimitry Andric   auto Bits0x7c00 = MIRBuilder.buildConstant(S32, 0x7c00);
62885ffd83dbSDimitry Andric   auto I = MIRBuilder.buildOr(S32, SelectCC, Bits0x7c00);
62895ffd83dbSDimitry Andric 
62905ffd83dbSDimitry Andric   // N = M | (E << 12);
62915ffd83dbSDimitry Andric   auto EShl12 = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 12));
62925ffd83dbSDimitry Andric   auto N = MIRBuilder.buildOr(S32, M, EShl12);
62935ffd83dbSDimitry Andric 
62945ffd83dbSDimitry Andric   // B = clamp(1-E, 0, 13);
62955ffd83dbSDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
62965ffd83dbSDimitry Andric   auto OneSubExp = MIRBuilder.buildSub(S32, One, E);
62975ffd83dbSDimitry Andric   auto B = MIRBuilder.buildSMax(S32, OneSubExp, Zero);
62985ffd83dbSDimitry Andric   B = MIRBuilder.buildSMin(S32, B, MIRBuilder.buildConstant(S32, 13));
62995ffd83dbSDimitry Andric 
63005ffd83dbSDimitry Andric   auto SigSetHigh = MIRBuilder.buildOr(S32, M,
63015ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1000));
63025ffd83dbSDimitry Andric 
63035ffd83dbSDimitry Andric   auto D = MIRBuilder.buildLShr(S32, SigSetHigh, B);
63045ffd83dbSDimitry Andric   auto D0 = MIRBuilder.buildShl(S32, D, B);
63055ffd83dbSDimitry Andric 
63065ffd83dbSDimitry Andric   auto D0_NE_SigSetHigh = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1,
63075ffd83dbSDimitry Andric                                              D0, SigSetHigh);
63085ffd83dbSDimitry Andric   auto D1 = MIRBuilder.buildZExt(S32, D0_NE_SigSetHigh);
63095ffd83dbSDimitry Andric   D = MIRBuilder.buildOr(S32, D, D1);
63105ffd83dbSDimitry Andric 
63115ffd83dbSDimitry Andric   auto CmpELtOne = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, S1, E, One);
63125ffd83dbSDimitry Andric   auto V = MIRBuilder.buildSelect(S32, CmpELtOne, D, N);
63135ffd83dbSDimitry Andric 
63145ffd83dbSDimitry Andric   auto VLow3 = MIRBuilder.buildAnd(S32, V, MIRBuilder.buildConstant(S32, 7));
63155ffd83dbSDimitry Andric   V = MIRBuilder.buildLShr(S32, V, MIRBuilder.buildConstant(S32, 2));
63165ffd83dbSDimitry Andric 
63175ffd83dbSDimitry Andric   auto VLow3Eq3 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, VLow3,
63185ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 3));
63195ffd83dbSDimitry Andric   auto V0 = MIRBuilder.buildZExt(S32, VLow3Eq3);
63205ffd83dbSDimitry Andric 
63215ffd83dbSDimitry Andric   auto VLow3Gt5 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT, S1, VLow3,
63225ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 5));
63235ffd83dbSDimitry Andric   auto V1 = MIRBuilder.buildZExt(S32, VLow3Gt5);
63245ffd83dbSDimitry Andric 
63255ffd83dbSDimitry Andric   V1 = MIRBuilder.buildOr(S32, V0, V1);
63265ffd83dbSDimitry Andric   V = MIRBuilder.buildAdd(S32, V, V1);
63275ffd83dbSDimitry Andric 
63285ffd83dbSDimitry Andric   auto CmpEGt30 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,  S1,
63295ffd83dbSDimitry Andric                                        E, MIRBuilder.buildConstant(S32, 30));
63305ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt30,
63315ffd83dbSDimitry Andric                              MIRBuilder.buildConstant(S32, 0x7c00), V);
63325ffd83dbSDimitry Andric 
63335ffd83dbSDimitry Andric   auto CmpEGt1039 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1,
63345ffd83dbSDimitry Andric                                          E, MIRBuilder.buildConstant(S32, 1039));
63355ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt1039, I, V);
63365ffd83dbSDimitry Andric 
63375ffd83dbSDimitry Andric   // Extract the sign bit.
63385ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 16));
63395ffd83dbSDimitry Andric   Sign = MIRBuilder.buildAnd(S32, Sign, MIRBuilder.buildConstant(S32, 0x8000));
63405ffd83dbSDimitry Andric 
63415ffd83dbSDimitry Andric   // Insert the sign bit
63425ffd83dbSDimitry Andric   V = MIRBuilder.buildOr(S32, Sign, V);
63435ffd83dbSDimitry Andric 
63445ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst, V);
63455ffd83dbSDimitry Andric   MI.eraseFromParent();
63465ffd83dbSDimitry Andric   return Legalized;
63475ffd83dbSDimitry Andric }
63485ffd83dbSDimitry Andric 
63495ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
6350e8d8bef9SDimitry Andric LegalizerHelper::lowerFPTRUNC(MachineInstr &MI) {
63515ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
63525ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
63535ffd83dbSDimitry Andric 
63545ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
63555ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
63565ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
63575ffd83dbSDimitry Andric   const LLT S16 = LLT::scalar(16);
63585ffd83dbSDimitry Andric 
63595ffd83dbSDimitry Andric   if (DstTy.getScalarType() == S16 && SrcTy.getScalarType() == S64)
63605ffd83dbSDimitry Andric     return lowerFPTRUNC_F64_TO_F16(MI);
63615ffd83dbSDimitry Andric 
63625ffd83dbSDimitry Andric   return UnableToLegalize;
63635ffd83dbSDimitry Andric }
63645ffd83dbSDimitry Andric 
6365e8d8bef9SDimitry Andric // TODO: If RHS is a constant SelectionDAGBuilder expands this into a
6366e8d8bef9SDimitry Andric // multiplication tree.
6367e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPOWI(MachineInstr &MI) {
6368e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6369e8d8bef9SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
6370e8d8bef9SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
6371e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
6372e8d8bef9SDimitry Andric 
6373e8d8bef9SDimitry Andric   auto CvtSrc1 = MIRBuilder.buildSITOFP(Ty, Src1);
6374e8d8bef9SDimitry Andric   MIRBuilder.buildFPow(Dst, Src0, CvtSrc1, MI.getFlags());
6375e8d8bef9SDimitry Andric   MI.eraseFromParent();
6376e8d8bef9SDimitry Andric   return Legalized;
6377e8d8bef9SDimitry Andric }
6378e8d8bef9SDimitry Andric 
63790b57cec5SDimitry Andric static CmpInst::Predicate minMaxToCompare(unsigned Opc) {
63800b57cec5SDimitry Andric   switch (Opc) {
63810b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
63820b57cec5SDimitry Andric     return CmpInst::ICMP_SLT;
63830b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
63840b57cec5SDimitry Andric     return CmpInst::ICMP_SGT;
63850b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
63860b57cec5SDimitry Andric     return CmpInst::ICMP_ULT;
63870b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
63880b57cec5SDimitry Andric     return CmpInst::ICMP_UGT;
63890b57cec5SDimitry Andric   default:
63900b57cec5SDimitry Andric     llvm_unreachable("not in integer min/max");
63910b57cec5SDimitry Andric   }
63920b57cec5SDimitry Andric }
63930b57cec5SDimitry Andric 
6394e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerMinMax(MachineInstr &MI) {
63950b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
63960b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
63970b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
63980b57cec5SDimitry Andric 
63990b57cec5SDimitry Andric   const CmpInst::Predicate Pred = minMaxToCompare(MI.getOpcode());
64000b57cec5SDimitry Andric   LLT CmpType = MRI.getType(Dst).changeElementSize(1);
64010b57cec5SDimitry Andric 
64020b57cec5SDimitry Andric   auto Cmp = MIRBuilder.buildICmp(Pred, CmpType, Src0, Src1);
64030b57cec5SDimitry Andric   MIRBuilder.buildSelect(Dst, Cmp, Src0, Src1);
64040b57cec5SDimitry Andric 
64050b57cec5SDimitry Andric   MI.eraseFromParent();
64060b57cec5SDimitry Andric   return Legalized;
64070b57cec5SDimitry Andric }
64080b57cec5SDimitry Andric 
64090b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
6410e8d8bef9SDimitry Andric LegalizerHelper::lowerFCopySign(MachineInstr &MI) {
64110b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
64120b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
64130b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
64140b57cec5SDimitry Andric 
64150b57cec5SDimitry Andric   const LLT Src0Ty = MRI.getType(Src0);
64160b57cec5SDimitry Andric   const LLT Src1Ty = MRI.getType(Src1);
64170b57cec5SDimitry Andric 
64180b57cec5SDimitry Andric   const int Src0Size = Src0Ty.getScalarSizeInBits();
64190b57cec5SDimitry Andric   const int Src1Size = Src1Ty.getScalarSizeInBits();
64200b57cec5SDimitry Andric 
64210b57cec5SDimitry Andric   auto SignBitMask = MIRBuilder.buildConstant(
64220b57cec5SDimitry Andric     Src0Ty, APInt::getSignMask(Src0Size));
64230b57cec5SDimitry Andric 
64240b57cec5SDimitry Andric   auto NotSignBitMask = MIRBuilder.buildConstant(
64250b57cec5SDimitry Andric     Src0Ty, APInt::getLowBitsSet(Src0Size, Src0Size - 1));
64260b57cec5SDimitry Andric 
6427*fe6060f1SDimitry Andric   Register And0 = MIRBuilder.buildAnd(Src0Ty, Src0, NotSignBitMask).getReg(0);
6428*fe6060f1SDimitry Andric   Register And1;
64290b57cec5SDimitry Andric   if (Src0Ty == Src1Ty) {
6430*fe6060f1SDimitry Andric     And1 = MIRBuilder.buildAnd(Src1Ty, Src1, SignBitMask).getReg(0);
64310b57cec5SDimitry Andric   } else if (Src0Size > Src1Size) {
64320b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src0Ty, Src0Size - Src1Size);
64330b57cec5SDimitry Andric     auto Zext = MIRBuilder.buildZExt(Src0Ty, Src1);
64340b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildShl(Src0Ty, Zext, ShiftAmt);
6435*fe6060f1SDimitry Andric     And1 = MIRBuilder.buildAnd(Src0Ty, Shift, SignBitMask).getReg(0);
64360b57cec5SDimitry Andric   } else {
64370b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src1Ty, Src1Size - Src0Size);
64380b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildLShr(Src1Ty, Src1, ShiftAmt);
64390b57cec5SDimitry Andric     auto Trunc = MIRBuilder.buildTrunc(Src0Ty, Shift);
6440*fe6060f1SDimitry Andric     And1 = MIRBuilder.buildAnd(Src0Ty, Trunc, SignBitMask).getReg(0);
64410b57cec5SDimitry Andric   }
64420b57cec5SDimitry Andric 
64430b57cec5SDimitry Andric   // Be careful about setting nsz/nnan/ninf on every instruction, since the
64440b57cec5SDimitry Andric   // constants are a nan and -0.0, but the final result should preserve
64450b57cec5SDimitry Andric   // everything.
6446*fe6060f1SDimitry Andric   unsigned Flags = MI.getFlags();
6447*fe6060f1SDimitry Andric   MIRBuilder.buildOr(Dst, And0, And1, Flags);
64480b57cec5SDimitry Andric 
64490b57cec5SDimitry Andric   MI.eraseFromParent();
64500b57cec5SDimitry Andric   return Legalized;
64510b57cec5SDimitry Andric }
64520b57cec5SDimitry Andric 
64530b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
64540b57cec5SDimitry Andric LegalizerHelper::lowerFMinNumMaxNum(MachineInstr &MI) {
64550b57cec5SDimitry Andric   unsigned NewOp = MI.getOpcode() == TargetOpcode::G_FMINNUM ?
64560b57cec5SDimitry Andric     TargetOpcode::G_FMINNUM_IEEE : TargetOpcode::G_FMAXNUM_IEEE;
64570b57cec5SDimitry Andric 
64580b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
64590b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
64600b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
64610b57cec5SDimitry Andric   LLT Ty = MRI.getType(Dst);
64620b57cec5SDimitry Andric 
64630b57cec5SDimitry Andric   if (!MI.getFlag(MachineInstr::FmNoNans)) {
64640b57cec5SDimitry Andric     // Insert canonicalizes if it's possible we need to quiet to get correct
64650b57cec5SDimitry Andric     // sNaN behavior.
64660b57cec5SDimitry Andric 
64670b57cec5SDimitry Andric     // Note this must be done here, and not as an optimization combine in the
64680b57cec5SDimitry Andric     // absence of a dedicate quiet-snan instruction as we're using an
64690b57cec5SDimitry Andric     // omni-purpose G_FCANONICALIZE.
64700b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src0, MRI))
64710b57cec5SDimitry Andric       Src0 = MIRBuilder.buildFCanonicalize(Ty, Src0, MI.getFlags()).getReg(0);
64720b57cec5SDimitry Andric 
64730b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src1, MRI))
64740b57cec5SDimitry Andric       Src1 = MIRBuilder.buildFCanonicalize(Ty, Src1, MI.getFlags()).getReg(0);
64750b57cec5SDimitry Andric   }
64760b57cec5SDimitry Andric 
64770b57cec5SDimitry Andric   // If there are no nans, it's safe to simply replace this with the non-IEEE
64780b57cec5SDimitry Andric   // version.
64790b57cec5SDimitry Andric   MIRBuilder.buildInstr(NewOp, {Dst}, {Src0, Src1}, MI.getFlags());
64800b57cec5SDimitry Andric   MI.eraseFromParent();
64810b57cec5SDimitry Andric   return Legalized;
64820b57cec5SDimitry Andric }
64838bcb0991SDimitry Andric 
64848bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFMad(MachineInstr &MI) {
64858bcb0991SDimitry Andric   // Expand G_FMAD a, b, c -> G_FADD (G_FMUL a, b), c
64868bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
64878bcb0991SDimitry Andric   LLT Ty = MRI.getType(DstReg);
64888bcb0991SDimitry Andric   unsigned Flags = MI.getFlags();
64898bcb0991SDimitry Andric 
64908bcb0991SDimitry Andric   auto Mul = MIRBuilder.buildFMul(Ty, MI.getOperand(1), MI.getOperand(2),
64918bcb0991SDimitry Andric                                   Flags);
64928bcb0991SDimitry Andric   MIRBuilder.buildFAdd(DstReg, Mul, MI.getOperand(3), Flags);
64938bcb0991SDimitry Andric   MI.eraseFromParent();
64948bcb0991SDimitry Andric   return Legalized;
64958bcb0991SDimitry Andric }
64968bcb0991SDimitry Andric 
64978bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
6498480093f4SDimitry Andric LegalizerHelper::lowerIntrinsicRound(MachineInstr &MI) {
6499480093f4SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
65005ffd83dbSDimitry Andric   Register X = MI.getOperand(1).getReg();
65015ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
65025ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(DstReg);
65035ffd83dbSDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
65045ffd83dbSDimitry Andric 
65055ffd83dbSDimitry Andric   // round(x) =>
65065ffd83dbSDimitry Andric   //  t = trunc(x);
65075ffd83dbSDimitry Andric   //  d = fabs(x - t);
65085ffd83dbSDimitry Andric   //  o = copysign(1.0f, x);
65095ffd83dbSDimitry Andric   //  return t + (d >= 0.5 ? o : 0.0);
65105ffd83dbSDimitry Andric 
65115ffd83dbSDimitry Andric   auto T = MIRBuilder.buildIntrinsicTrunc(Ty, X, Flags);
65125ffd83dbSDimitry Andric 
65135ffd83dbSDimitry Andric   auto Diff = MIRBuilder.buildFSub(Ty, X, T, Flags);
65145ffd83dbSDimitry Andric   auto AbsDiff = MIRBuilder.buildFAbs(Ty, Diff, Flags);
65155ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
65165ffd83dbSDimitry Andric   auto One = MIRBuilder.buildFConstant(Ty, 1.0);
65175ffd83dbSDimitry Andric   auto Half = MIRBuilder.buildFConstant(Ty, 0.5);
65185ffd83dbSDimitry Andric   auto SignOne = MIRBuilder.buildFCopysign(Ty, One, X);
65195ffd83dbSDimitry Andric 
65205ffd83dbSDimitry Andric   auto Cmp = MIRBuilder.buildFCmp(CmpInst::FCMP_OGE, CondTy, AbsDiff, Half,
65215ffd83dbSDimitry Andric                                   Flags);
65225ffd83dbSDimitry Andric   auto Sel = MIRBuilder.buildSelect(Ty, Cmp, SignOne, Zero, Flags);
65235ffd83dbSDimitry Andric 
65245ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, T, Sel, Flags);
65255ffd83dbSDimitry Andric 
65265ffd83dbSDimitry Andric   MI.eraseFromParent();
65275ffd83dbSDimitry Andric   return Legalized;
65285ffd83dbSDimitry Andric }
65295ffd83dbSDimitry Andric 
65305ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
65315ffd83dbSDimitry Andric LegalizerHelper::lowerFFloor(MachineInstr &MI) {
65325ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
6533480093f4SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
6534480093f4SDimitry Andric   unsigned Flags = MI.getFlags();
6535480093f4SDimitry Andric   LLT Ty = MRI.getType(DstReg);
6536480093f4SDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
6537480093f4SDimitry Andric 
6538480093f4SDimitry Andric   // result = trunc(src);
6539480093f4SDimitry Andric   // if (src < 0.0 && src != result)
6540480093f4SDimitry Andric   //   result += -1.0.
6541480093f4SDimitry Andric 
6542480093f4SDimitry Andric   auto Trunc = MIRBuilder.buildIntrinsicTrunc(Ty, SrcReg, Flags);
65435ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
6544480093f4SDimitry Andric 
6545480093f4SDimitry Andric   auto Lt0 = MIRBuilder.buildFCmp(CmpInst::FCMP_OLT, CondTy,
6546480093f4SDimitry Andric                                   SrcReg, Zero, Flags);
6547480093f4SDimitry Andric   auto NeTrunc = MIRBuilder.buildFCmp(CmpInst::FCMP_ONE, CondTy,
6548480093f4SDimitry Andric                                       SrcReg, Trunc, Flags);
6549480093f4SDimitry Andric   auto And = MIRBuilder.buildAnd(CondTy, Lt0, NeTrunc);
6550480093f4SDimitry Andric   auto AddVal = MIRBuilder.buildSITOFP(Ty, And);
6551480093f4SDimitry Andric 
65525ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, Trunc, AddVal, Flags);
65535ffd83dbSDimitry Andric   MI.eraseFromParent();
65545ffd83dbSDimitry Andric   return Legalized;
65555ffd83dbSDimitry Andric }
65565ffd83dbSDimitry Andric 
65575ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
65585ffd83dbSDimitry Andric LegalizerHelper::lowerMergeValues(MachineInstr &MI) {
65595ffd83dbSDimitry Andric   const unsigned NumOps = MI.getNumOperands();
65605ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
65615ffd83dbSDimitry Andric   Register Src0Reg = MI.getOperand(1).getReg();
65625ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
65635ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src0Reg);
65645ffd83dbSDimitry Andric   unsigned PartSize = SrcTy.getSizeInBits();
65655ffd83dbSDimitry Andric 
65665ffd83dbSDimitry Andric   LLT WideTy = LLT::scalar(DstTy.getSizeInBits());
65675ffd83dbSDimitry Andric   Register ResultReg = MIRBuilder.buildZExt(WideTy, Src0Reg).getReg(0);
65685ffd83dbSDimitry Andric 
65695ffd83dbSDimitry Andric   for (unsigned I = 2; I != NumOps; ++I) {
65705ffd83dbSDimitry Andric     const unsigned Offset = (I - 1) * PartSize;
65715ffd83dbSDimitry Andric 
65725ffd83dbSDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
65735ffd83dbSDimitry Andric     auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
65745ffd83dbSDimitry Andric 
65755ffd83dbSDimitry Andric     Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
65765ffd83dbSDimitry Andric       MRI.createGenericVirtualRegister(WideTy);
65775ffd83dbSDimitry Andric 
65785ffd83dbSDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
65795ffd83dbSDimitry Andric     auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
65805ffd83dbSDimitry Andric     MIRBuilder.buildOr(NextResult, ResultReg, Shl);
65815ffd83dbSDimitry Andric     ResultReg = NextResult;
65825ffd83dbSDimitry Andric   }
65835ffd83dbSDimitry Andric 
65845ffd83dbSDimitry Andric   if (DstTy.isPointer()) {
65855ffd83dbSDimitry Andric     if (MIRBuilder.getDataLayout().isNonIntegralAddressSpace(
65865ffd83dbSDimitry Andric           DstTy.getAddressSpace())) {
65875ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Not casting nonintegral address space\n");
65885ffd83dbSDimitry Andric       return UnableToLegalize;
65895ffd83dbSDimitry Andric     }
65905ffd83dbSDimitry Andric 
65915ffd83dbSDimitry Andric     MIRBuilder.buildIntToPtr(DstReg, ResultReg);
65925ffd83dbSDimitry Andric   }
65935ffd83dbSDimitry Andric 
6594480093f4SDimitry Andric   MI.eraseFromParent();
6595480093f4SDimitry Andric   return Legalized;
6596480093f4SDimitry Andric }
6597480093f4SDimitry Andric 
6598480093f4SDimitry Andric LegalizerHelper::LegalizeResult
65998bcb0991SDimitry Andric LegalizerHelper::lowerUnmergeValues(MachineInstr &MI) {
66008bcb0991SDimitry Andric   const unsigned NumDst = MI.getNumOperands() - 1;
66015ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
66028bcb0991SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
66038bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
66045ffd83dbSDimitry Andric   if (DstTy.isPointer())
66055ffd83dbSDimitry Andric     return UnableToLegalize; // TODO
66068bcb0991SDimitry Andric 
66075ffd83dbSDimitry Andric   SrcReg = coerceToScalar(SrcReg);
66085ffd83dbSDimitry Andric   if (!SrcReg)
66095ffd83dbSDimitry Andric     return UnableToLegalize;
66108bcb0991SDimitry Andric 
66118bcb0991SDimitry Andric   // Expand scalarizing unmerge as bitcast to integer and shift.
66125ffd83dbSDimitry Andric   LLT IntTy = MRI.getType(SrcReg);
66138bcb0991SDimitry Andric 
66145ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
66158bcb0991SDimitry Andric 
66168bcb0991SDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
66178bcb0991SDimitry Andric   unsigned Offset = DstSize;
66188bcb0991SDimitry Andric   for (unsigned I = 1; I != NumDst; ++I, Offset += DstSize) {
66198bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntTy, Offset);
66205ffd83dbSDimitry Andric     auto Shift = MIRBuilder.buildLShr(IntTy, SrcReg, ShiftAmt);
66218bcb0991SDimitry Andric     MIRBuilder.buildTrunc(MI.getOperand(I), Shift);
66228bcb0991SDimitry Andric   }
66238bcb0991SDimitry Andric 
66248bcb0991SDimitry Andric   MI.eraseFromParent();
66258bcb0991SDimitry Andric   return Legalized;
66268bcb0991SDimitry Andric }
66278bcb0991SDimitry Andric 
6628e8d8bef9SDimitry Andric /// Lower a vector extract or insert by writing the vector to a stack temporary
6629e8d8bef9SDimitry Andric /// and reloading the element or vector.
6630e8d8bef9SDimitry Andric ///
6631e8d8bef9SDimitry Andric /// %dst = G_EXTRACT_VECTOR_ELT %vec, %idx
6632e8d8bef9SDimitry Andric ///  =>
6633e8d8bef9SDimitry Andric ///  %stack_temp = G_FRAME_INDEX
6634e8d8bef9SDimitry Andric ///  G_STORE %vec, %stack_temp
6635e8d8bef9SDimitry Andric ///  %idx = clamp(%idx, %vec.getNumElements())
6636e8d8bef9SDimitry Andric ///  %element_ptr = G_PTR_ADD %stack_temp, %idx
6637e8d8bef9SDimitry Andric ///  %dst = G_LOAD %element_ptr
6638e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6639e8d8bef9SDimitry Andric LegalizerHelper::lowerExtractInsertVectorElt(MachineInstr &MI) {
6640e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
6641e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
6642e8d8bef9SDimitry Andric   Register InsertVal;
6643e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
6644e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
6645e8d8bef9SDimitry Andric 
6646e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
6647e8d8bef9SDimitry Andric 
6648e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
6649e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
6650e8d8bef9SDimitry Andric   if (!EltTy.isByteSized()) { // Not implemented.
6651e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-byte element vectors yet\n");
6652e8d8bef9SDimitry Andric     return UnableToLegalize;
6653e8d8bef9SDimitry Andric   }
6654e8d8bef9SDimitry Andric 
6655e8d8bef9SDimitry Andric   unsigned EltBytes = EltTy.getSizeInBytes();
6656e8d8bef9SDimitry Andric   Align VecAlign = getStackTemporaryAlignment(VecTy);
6657e8d8bef9SDimitry Andric   Align EltAlign;
6658e8d8bef9SDimitry Andric 
6659e8d8bef9SDimitry Andric   MachinePointerInfo PtrInfo;
6660e8d8bef9SDimitry Andric   auto StackTemp = createStackTemporary(TypeSize::Fixed(VecTy.getSizeInBytes()),
6661e8d8bef9SDimitry Andric                                         VecAlign, PtrInfo);
6662e8d8bef9SDimitry Andric   MIRBuilder.buildStore(SrcVec, StackTemp, PtrInfo, VecAlign);
6663e8d8bef9SDimitry Andric 
6664e8d8bef9SDimitry Andric   // Get the pointer to the element, and be sure not to hit undefined behavior
6665e8d8bef9SDimitry Andric   // if the index is out of bounds.
6666e8d8bef9SDimitry Andric   Register EltPtr = getVectorElementPointer(StackTemp.getReg(0), VecTy, Idx);
6667e8d8bef9SDimitry Andric 
6668e8d8bef9SDimitry Andric   int64_t IdxVal;
6669e8d8bef9SDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal))) {
6670e8d8bef9SDimitry Andric     int64_t Offset = IdxVal * EltBytes;
6671e8d8bef9SDimitry Andric     PtrInfo = PtrInfo.getWithOffset(Offset);
6672e8d8bef9SDimitry Andric     EltAlign = commonAlignment(VecAlign, Offset);
6673e8d8bef9SDimitry Andric   } else {
6674e8d8bef9SDimitry Andric     // We lose information with a variable offset.
6675e8d8bef9SDimitry Andric     EltAlign = getStackTemporaryAlignment(EltTy);
6676e8d8bef9SDimitry Andric     PtrInfo = MachinePointerInfo(MRI.getType(EltPtr).getAddressSpace());
6677e8d8bef9SDimitry Andric   }
6678e8d8bef9SDimitry Andric 
6679e8d8bef9SDimitry Andric   if (InsertVal) {
6680e8d8bef9SDimitry Andric     // Write the inserted element
6681e8d8bef9SDimitry Andric     MIRBuilder.buildStore(InsertVal, EltPtr, PtrInfo, EltAlign);
6682e8d8bef9SDimitry Andric 
6683e8d8bef9SDimitry Andric     // Reload the whole vector.
6684e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, StackTemp, PtrInfo, VecAlign);
6685e8d8bef9SDimitry Andric   } else {
6686e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, EltPtr, PtrInfo, EltAlign);
6687e8d8bef9SDimitry Andric   }
6688e8d8bef9SDimitry Andric 
6689e8d8bef9SDimitry Andric   MI.eraseFromParent();
6690e8d8bef9SDimitry Andric   return Legalized;
6691e8d8bef9SDimitry Andric }
6692e8d8bef9SDimitry Andric 
66938bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
66948bcb0991SDimitry Andric LegalizerHelper::lowerShuffleVector(MachineInstr &MI) {
66958bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
66968bcb0991SDimitry Andric   Register Src0Reg = MI.getOperand(1).getReg();
66978bcb0991SDimitry Andric   Register Src1Reg = MI.getOperand(2).getReg();
66988bcb0991SDimitry Andric   LLT Src0Ty = MRI.getType(Src0Reg);
66998bcb0991SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
67008bcb0991SDimitry Andric   LLT IdxTy = LLT::scalar(32);
67018bcb0991SDimitry Andric 
6702480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
67038bcb0991SDimitry Andric 
67048bcb0991SDimitry Andric   if (DstTy.isScalar()) {
67058bcb0991SDimitry Andric     if (Src0Ty.isVector())
67068bcb0991SDimitry Andric       return UnableToLegalize;
67078bcb0991SDimitry Andric 
67088bcb0991SDimitry Andric     // This is just a SELECT.
67098bcb0991SDimitry Andric     assert(Mask.size() == 1 && "Expected a single mask element");
67108bcb0991SDimitry Andric     Register Val;
67118bcb0991SDimitry Andric     if (Mask[0] < 0 || Mask[0] > 1)
67128bcb0991SDimitry Andric       Val = MIRBuilder.buildUndef(DstTy).getReg(0);
67138bcb0991SDimitry Andric     else
67148bcb0991SDimitry Andric       Val = Mask[0] == 0 ? Src0Reg : Src1Reg;
67158bcb0991SDimitry Andric     MIRBuilder.buildCopy(DstReg, Val);
67168bcb0991SDimitry Andric     MI.eraseFromParent();
67178bcb0991SDimitry Andric     return Legalized;
67188bcb0991SDimitry Andric   }
67198bcb0991SDimitry Andric 
67208bcb0991SDimitry Andric   Register Undef;
67218bcb0991SDimitry Andric   SmallVector<Register, 32> BuildVec;
67228bcb0991SDimitry Andric   LLT EltTy = DstTy.getElementType();
67238bcb0991SDimitry Andric 
67248bcb0991SDimitry Andric   for (int Idx : Mask) {
67258bcb0991SDimitry Andric     if (Idx < 0) {
67268bcb0991SDimitry Andric       if (!Undef.isValid())
67278bcb0991SDimitry Andric         Undef = MIRBuilder.buildUndef(EltTy).getReg(0);
67288bcb0991SDimitry Andric       BuildVec.push_back(Undef);
67298bcb0991SDimitry Andric       continue;
67308bcb0991SDimitry Andric     }
67318bcb0991SDimitry Andric 
67328bcb0991SDimitry Andric     if (Src0Ty.isScalar()) {
67338bcb0991SDimitry Andric       BuildVec.push_back(Idx == 0 ? Src0Reg : Src1Reg);
67348bcb0991SDimitry Andric     } else {
67358bcb0991SDimitry Andric       int NumElts = Src0Ty.getNumElements();
67368bcb0991SDimitry Andric       Register SrcVec = Idx < NumElts ? Src0Reg : Src1Reg;
67378bcb0991SDimitry Andric       int ExtractIdx = Idx < NumElts ? Idx : Idx - NumElts;
67388bcb0991SDimitry Andric       auto IdxK = MIRBuilder.buildConstant(IdxTy, ExtractIdx);
67398bcb0991SDimitry Andric       auto Extract = MIRBuilder.buildExtractVectorElement(EltTy, SrcVec, IdxK);
67408bcb0991SDimitry Andric       BuildVec.push_back(Extract.getReg(0));
67418bcb0991SDimitry Andric     }
67428bcb0991SDimitry Andric   }
67438bcb0991SDimitry Andric 
67448bcb0991SDimitry Andric   MIRBuilder.buildBuildVector(DstReg, BuildVec);
67458bcb0991SDimitry Andric   MI.eraseFromParent();
67468bcb0991SDimitry Andric   return Legalized;
67478bcb0991SDimitry Andric }
67488bcb0991SDimitry Andric 
67498bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
67508bcb0991SDimitry Andric LegalizerHelper::lowerDynStackAlloc(MachineInstr &MI) {
67515ffd83dbSDimitry Andric   const auto &MF = *MI.getMF();
67525ffd83dbSDimitry Andric   const auto &TFI = *MF.getSubtarget().getFrameLowering();
67535ffd83dbSDimitry Andric   if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
67545ffd83dbSDimitry Andric     return UnableToLegalize;
67555ffd83dbSDimitry Andric 
67568bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
67578bcb0991SDimitry Andric   Register AllocSize = MI.getOperand(1).getReg();
67585ffd83dbSDimitry Andric   Align Alignment = assumeAligned(MI.getOperand(2).getImm());
67598bcb0991SDimitry Andric 
67608bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(Dst);
67618bcb0991SDimitry Andric   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
67628bcb0991SDimitry Andric 
67638bcb0991SDimitry Andric   Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
67648bcb0991SDimitry Andric   auto SPTmp = MIRBuilder.buildCopy(PtrTy, SPReg);
67658bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(IntPtrTy, SPTmp);
67668bcb0991SDimitry Andric 
67678bcb0991SDimitry Andric   // Subtract the final alloc from the SP. We use G_PTRTOINT here so we don't
67688bcb0991SDimitry Andric   // have to generate an extra instruction to negate the alloc and then use
6769480093f4SDimitry Andric   // G_PTR_ADD to add the negative offset.
67708bcb0991SDimitry Andric   auto Alloc = MIRBuilder.buildSub(IntPtrTy, SPTmp, AllocSize);
67715ffd83dbSDimitry Andric   if (Alignment > Align(1)) {
67725ffd83dbSDimitry Andric     APInt AlignMask(IntPtrTy.getSizeInBits(), Alignment.value(), true);
67738bcb0991SDimitry Andric     AlignMask.negate();
67748bcb0991SDimitry Andric     auto AlignCst = MIRBuilder.buildConstant(IntPtrTy, AlignMask);
67758bcb0991SDimitry Andric     Alloc = MIRBuilder.buildAnd(IntPtrTy, Alloc, AlignCst);
67768bcb0991SDimitry Andric   }
67778bcb0991SDimitry Andric 
67788bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(PtrTy, Alloc);
67798bcb0991SDimitry Andric   MIRBuilder.buildCopy(SPReg, SPTmp);
67808bcb0991SDimitry Andric   MIRBuilder.buildCopy(Dst, SPTmp);
67818bcb0991SDimitry Andric 
67828bcb0991SDimitry Andric   MI.eraseFromParent();
67838bcb0991SDimitry Andric   return Legalized;
67848bcb0991SDimitry Andric }
67858bcb0991SDimitry Andric 
67868bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
67878bcb0991SDimitry Andric LegalizerHelper::lowerExtract(MachineInstr &MI) {
67888bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
67898bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
67908bcb0991SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
67918bcb0991SDimitry Andric 
67928bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst);
67938bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(Src);
67948bcb0991SDimitry Andric 
67958bcb0991SDimitry Andric   if (DstTy.isScalar() &&
67968bcb0991SDimitry Andric       (SrcTy.isScalar() ||
67978bcb0991SDimitry Andric        (SrcTy.isVector() && DstTy == SrcTy.getElementType()))) {
67988bcb0991SDimitry Andric     LLT SrcIntTy = SrcTy;
67998bcb0991SDimitry Andric     if (!SrcTy.isScalar()) {
68008bcb0991SDimitry Andric       SrcIntTy = LLT::scalar(SrcTy.getSizeInBits());
68018bcb0991SDimitry Andric       Src = MIRBuilder.buildBitcast(SrcIntTy, Src).getReg(0);
68028bcb0991SDimitry Andric     }
68038bcb0991SDimitry Andric 
68048bcb0991SDimitry Andric     if (Offset == 0)
68058bcb0991SDimitry Andric       MIRBuilder.buildTrunc(Dst, Src);
68068bcb0991SDimitry Andric     else {
68078bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcIntTy, Offset);
68088bcb0991SDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcIntTy, Src, ShiftAmt);
68098bcb0991SDimitry Andric       MIRBuilder.buildTrunc(Dst, Shr);
68108bcb0991SDimitry Andric     }
68118bcb0991SDimitry Andric 
68128bcb0991SDimitry Andric     MI.eraseFromParent();
68138bcb0991SDimitry Andric     return Legalized;
68148bcb0991SDimitry Andric   }
68158bcb0991SDimitry Andric 
68168bcb0991SDimitry Andric   return UnableToLegalize;
68178bcb0991SDimitry Andric }
68188bcb0991SDimitry Andric 
68198bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerInsert(MachineInstr &MI) {
68208bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
68218bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
68228bcb0991SDimitry Andric   Register InsertSrc = MI.getOperand(2).getReg();
68238bcb0991SDimitry Andric   uint64_t Offset = MI.getOperand(3).getImm();
68248bcb0991SDimitry Andric 
68258bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Src);
68268bcb0991SDimitry Andric   LLT InsertTy = MRI.getType(InsertSrc);
68278bcb0991SDimitry Andric 
68285ffd83dbSDimitry Andric   if (InsertTy.isVector() ||
68295ffd83dbSDimitry Andric       (DstTy.isVector() && DstTy.getElementType() != InsertTy))
68305ffd83dbSDimitry Andric     return UnableToLegalize;
68315ffd83dbSDimitry Andric 
68325ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
68335ffd83dbSDimitry Andric   if ((DstTy.isPointer() &&
68345ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(DstTy.getAddressSpace())) ||
68355ffd83dbSDimitry Andric       (InsertTy.isPointer() &&
68365ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(InsertTy.getAddressSpace()))) {
68375ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Not casting non-integral address space integer\n");
68385ffd83dbSDimitry Andric     return UnableToLegalize;
68395ffd83dbSDimitry Andric   }
68405ffd83dbSDimitry Andric 
68418bcb0991SDimitry Andric   LLT IntDstTy = DstTy;
68425ffd83dbSDimitry Andric 
68438bcb0991SDimitry Andric   if (!DstTy.isScalar()) {
68448bcb0991SDimitry Andric     IntDstTy = LLT::scalar(DstTy.getSizeInBits());
68455ffd83dbSDimitry Andric     Src = MIRBuilder.buildCast(IntDstTy, Src).getReg(0);
68465ffd83dbSDimitry Andric   }
68475ffd83dbSDimitry Andric 
68485ffd83dbSDimitry Andric   if (!InsertTy.isScalar()) {
68495ffd83dbSDimitry Andric     const LLT IntInsertTy = LLT::scalar(InsertTy.getSizeInBits());
68505ffd83dbSDimitry Andric     InsertSrc = MIRBuilder.buildPtrToInt(IntInsertTy, InsertSrc).getReg(0);
68518bcb0991SDimitry Andric   }
68528bcb0991SDimitry Andric 
68538bcb0991SDimitry Andric   Register ExtInsSrc = MIRBuilder.buildZExt(IntDstTy, InsertSrc).getReg(0);
68548bcb0991SDimitry Andric   if (Offset != 0) {
68558bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntDstTy, Offset);
68568bcb0991SDimitry Andric     ExtInsSrc = MIRBuilder.buildShl(IntDstTy, ExtInsSrc, ShiftAmt).getReg(0);
68578bcb0991SDimitry Andric   }
68588bcb0991SDimitry Andric 
68595ffd83dbSDimitry Andric   APInt MaskVal = APInt::getBitsSetWithWrap(
68605ffd83dbSDimitry Andric       DstTy.getSizeInBits(), Offset + InsertTy.getSizeInBits(), Offset);
68618bcb0991SDimitry Andric 
68628bcb0991SDimitry Andric   auto Mask = MIRBuilder.buildConstant(IntDstTy, MaskVal);
68638bcb0991SDimitry Andric   auto MaskedSrc = MIRBuilder.buildAnd(IntDstTy, Src, Mask);
68648bcb0991SDimitry Andric   auto Or = MIRBuilder.buildOr(IntDstTy, MaskedSrc, ExtInsSrc);
68658bcb0991SDimitry Andric 
68665ffd83dbSDimitry Andric   MIRBuilder.buildCast(Dst, Or);
68678bcb0991SDimitry Andric   MI.eraseFromParent();
68688bcb0991SDimitry Andric   return Legalized;
68698bcb0991SDimitry Andric }
68708bcb0991SDimitry Andric 
68718bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
68728bcb0991SDimitry Andric LegalizerHelper::lowerSADDO_SSUBO(MachineInstr &MI) {
68738bcb0991SDimitry Andric   Register Dst0 = MI.getOperand(0).getReg();
68748bcb0991SDimitry Andric   Register Dst1 = MI.getOperand(1).getReg();
68758bcb0991SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
68768bcb0991SDimitry Andric   Register RHS = MI.getOperand(3).getReg();
68778bcb0991SDimitry Andric   const bool IsAdd = MI.getOpcode() == TargetOpcode::G_SADDO;
68788bcb0991SDimitry Andric 
68798bcb0991SDimitry Andric   LLT Ty = MRI.getType(Dst0);
68808bcb0991SDimitry Andric   LLT BoolTy = MRI.getType(Dst1);
68818bcb0991SDimitry Andric 
68828bcb0991SDimitry Andric   if (IsAdd)
68838bcb0991SDimitry Andric     MIRBuilder.buildAdd(Dst0, LHS, RHS);
68848bcb0991SDimitry Andric   else
68858bcb0991SDimitry Andric     MIRBuilder.buildSub(Dst0, LHS, RHS);
68868bcb0991SDimitry Andric 
68878bcb0991SDimitry Andric   // TODO: If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
68888bcb0991SDimitry Andric 
68898bcb0991SDimitry Andric   auto Zero = MIRBuilder.buildConstant(Ty, 0);
68908bcb0991SDimitry Andric 
68918bcb0991SDimitry Andric   // For an addition, the result should be less than one of the operands (LHS)
68928bcb0991SDimitry Andric   // if and only if the other operand (RHS) is negative, otherwise there will
68938bcb0991SDimitry Andric   // be overflow.
68948bcb0991SDimitry Andric   // For a subtraction, the result should be less than one of the operands
68958bcb0991SDimitry Andric   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
68968bcb0991SDimitry Andric   // otherwise there will be overflow.
68978bcb0991SDimitry Andric   auto ResultLowerThanLHS =
68988bcb0991SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, Dst0, LHS);
68998bcb0991SDimitry Andric   auto ConditionRHS = MIRBuilder.buildICmp(
69008bcb0991SDimitry Andric       IsAdd ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGT, BoolTy, RHS, Zero);
69018bcb0991SDimitry Andric 
69028bcb0991SDimitry Andric   MIRBuilder.buildXor(Dst1, ConditionRHS, ResultLowerThanLHS);
69038bcb0991SDimitry Andric   MI.eraseFromParent();
69048bcb0991SDimitry Andric   return Legalized;
69058bcb0991SDimitry Andric }
6906480093f4SDimitry Andric 
6907480093f4SDimitry Andric LegalizerHelper::LegalizeResult
6908e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToMinMax(MachineInstr &MI) {
6909e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
6910e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
6911e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
6912e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
6913e8d8bef9SDimitry Andric   bool IsSigned;
6914e8d8bef9SDimitry Andric   bool IsAdd;
6915e8d8bef9SDimitry Andric   unsigned BaseOp;
6916e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
6917e8d8bef9SDimitry Andric   default:
6918e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
6919e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
6920e8d8bef9SDimitry Andric     IsSigned = false;
6921e8d8bef9SDimitry Andric     IsAdd = true;
6922e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
6923e8d8bef9SDimitry Andric     break;
6924e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
6925e8d8bef9SDimitry Andric     IsSigned = true;
6926e8d8bef9SDimitry Andric     IsAdd = true;
6927e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
6928e8d8bef9SDimitry Andric     break;
6929e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
6930e8d8bef9SDimitry Andric     IsSigned = false;
6931e8d8bef9SDimitry Andric     IsAdd = false;
6932e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
6933e8d8bef9SDimitry Andric     break;
6934e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
6935e8d8bef9SDimitry Andric     IsSigned = true;
6936e8d8bef9SDimitry Andric     IsAdd = false;
6937e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
6938e8d8bef9SDimitry Andric     break;
6939e8d8bef9SDimitry Andric   }
6940e8d8bef9SDimitry Andric 
6941e8d8bef9SDimitry Andric   if (IsSigned) {
6942e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
6943e8d8bef9SDimitry Andric     //   hi = 0x7fffffff - smax(a, 0)
6944e8d8bef9SDimitry Andric     //   lo = 0x80000000 - smin(a, 0)
6945e8d8bef9SDimitry Andric     //   a + smin(smax(lo, b), hi)
6946e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
6947e8d8bef9SDimitry Andric     //   lo = smax(a, -1) - 0x7fffffff
6948e8d8bef9SDimitry Andric     //   hi = smin(a, -1) - 0x80000000
6949e8d8bef9SDimitry Andric     //   a - smin(smax(lo, b), hi)
6950e8d8bef9SDimitry Andric     // TODO: AMDGPU can use a "median of 3" instruction here:
6951e8d8bef9SDimitry Andric     //   a +/- med3(lo, b, hi)
6952e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
6953e8d8bef9SDimitry Andric     auto MaxVal =
6954e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(NumBits));
6955e8d8bef9SDimitry Andric     auto MinVal =
6956e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
6957e8d8bef9SDimitry Andric     MachineInstrBuilder Hi, Lo;
6958e8d8bef9SDimitry Andric     if (IsAdd) {
6959e8d8bef9SDimitry Andric       auto Zero = MIRBuilder.buildConstant(Ty, 0);
6960e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MaxVal, MIRBuilder.buildSMax(Ty, LHS, Zero));
6961e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MinVal, MIRBuilder.buildSMin(Ty, LHS, Zero));
6962e8d8bef9SDimitry Andric     } else {
6963e8d8bef9SDimitry Andric       auto NegOne = MIRBuilder.buildConstant(Ty, -1);
6964e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMax(Ty, LHS, NegOne),
6965e8d8bef9SDimitry Andric                                MaxVal);
6966e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMin(Ty, LHS, NegOne),
6967e8d8bef9SDimitry Andric                                MinVal);
6968e8d8bef9SDimitry Andric     }
6969e8d8bef9SDimitry Andric     auto RHSClamped =
6970e8d8bef9SDimitry Andric         MIRBuilder.buildSMin(Ty, MIRBuilder.buildSMax(Ty, Lo, RHS), Hi);
6971e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, RHSClamped});
6972e8d8bef9SDimitry Andric   } else {
6973e8d8bef9SDimitry Andric     // uadd.sat(a, b) -> a + umin(~a, b)
6974e8d8bef9SDimitry Andric     // usub.sat(a, b) -> a - umin(a, b)
6975e8d8bef9SDimitry Andric     Register Not = IsAdd ? MIRBuilder.buildNot(Ty, LHS).getReg(0) : LHS;
6976e8d8bef9SDimitry Andric     auto Min = MIRBuilder.buildUMin(Ty, Not, RHS);
6977e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, Min});
6978e8d8bef9SDimitry Andric   }
6979e8d8bef9SDimitry Andric 
6980e8d8bef9SDimitry Andric   MI.eraseFromParent();
6981e8d8bef9SDimitry Andric   return Legalized;
6982e8d8bef9SDimitry Andric }
6983e8d8bef9SDimitry Andric 
6984e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6985e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToAddoSubo(MachineInstr &MI) {
6986e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
6987e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
6988e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
6989e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
6990e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
6991e8d8bef9SDimitry Andric   bool IsSigned;
6992e8d8bef9SDimitry Andric   bool IsAdd;
6993e8d8bef9SDimitry Andric   unsigned OverflowOp;
6994e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
6995e8d8bef9SDimitry Andric   default:
6996e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
6997e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
6998e8d8bef9SDimitry Andric     IsSigned = false;
6999e8d8bef9SDimitry Andric     IsAdd = true;
7000e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_UADDO;
7001e8d8bef9SDimitry Andric     break;
7002e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
7003e8d8bef9SDimitry Andric     IsSigned = true;
7004e8d8bef9SDimitry Andric     IsAdd = true;
7005e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SADDO;
7006e8d8bef9SDimitry Andric     break;
7007e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
7008e8d8bef9SDimitry Andric     IsSigned = false;
7009e8d8bef9SDimitry Andric     IsAdd = false;
7010e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_USUBO;
7011e8d8bef9SDimitry Andric     break;
7012e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
7013e8d8bef9SDimitry Andric     IsSigned = true;
7014e8d8bef9SDimitry Andric     IsAdd = false;
7015e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SSUBO;
7016e8d8bef9SDimitry Andric     break;
7017e8d8bef9SDimitry Andric   }
7018e8d8bef9SDimitry Andric 
7019e8d8bef9SDimitry Andric   auto OverflowRes =
7020e8d8bef9SDimitry Andric       MIRBuilder.buildInstr(OverflowOp, {Ty, BoolTy}, {LHS, RHS});
7021e8d8bef9SDimitry Andric   Register Tmp = OverflowRes.getReg(0);
7022e8d8bef9SDimitry Andric   Register Ov = OverflowRes.getReg(1);
7023e8d8bef9SDimitry Andric   MachineInstrBuilder Clamp;
7024e8d8bef9SDimitry Andric   if (IsSigned) {
7025e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
7026e8d8bef9SDimitry Andric     //   {tmp, ov} = saddo(a, b)
7027e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
7028e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
7029e8d8bef9SDimitry Andric     //   {tmp, ov} = ssubo(a, b)
7030e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
7031e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
7032e8d8bef9SDimitry Andric     auto ShiftAmount = MIRBuilder.buildConstant(Ty, NumBits - 1);
7033e8d8bef9SDimitry Andric     auto Sign = MIRBuilder.buildAShr(Ty, Tmp, ShiftAmount);
7034e8d8bef9SDimitry Andric     auto MinVal =
7035e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
7036e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildAdd(Ty, Sign, MinVal);
7037e8d8bef9SDimitry Andric   } else {
7038e8d8bef9SDimitry Andric     // uadd.sat(a, b) ->
7039e8d8bef9SDimitry Andric     //   {tmp, ov} = uaddo(a, b)
7040e8d8bef9SDimitry Andric     //   ov ? 0xffffffff : tmp
7041e8d8bef9SDimitry Andric     // usub.sat(a, b) ->
7042e8d8bef9SDimitry Andric     //   {tmp, ov} = usubo(a, b)
7043e8d8bef9SDimitry Andric     //   ov ? 0 : tmp
7044e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildConstant(Ty, IsAdd ? -1 : 0);
7045e8d8bef9SDimitry Andric   }
7046e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, Clamp, Tmp);
7047e8d8bef9SDimitry Andric 
7048e8d8bef9SDimitry Andric   MI.eraseFromParent();
7049e8d8bef9SDimitry Andric   return Legalized;
7050e8d8bef9SDimitry Andric }
7051e8d8bef9SDimitry Andric 
7052e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
7053e8d8bef9SDimitry Andric LegalizerHelper::lowerShlSat(MachineInstr &MI) {
7054e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
7055e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_USHLSAT) &&
7056e8d8bef9SDimitry Andric          "Expected shlsat opcode!");
7057e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SSHLSAT;
7058e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
7059e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
7060e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
7061e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
7062e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
7063e8d8bef9SDimitry Andric 
7064e8d8bef9SDimitry Andric   unsigned BW = Ty.getScalarSizeInBits();
7065e8d8bef9SDimitry Andric   auto Result = MIRBuilder.buildShl(Ty, LHS, RHS);
7066e8d8bef9SDimitry Andric   auto Orig = IsSigned ? MIRBuilder.buildAShr(Ty, Result, RHS)
7067e8d8bef9SDimitry Andric                        : MIRBuilder.buildLShr(Ty, Result, RHS);
7068e8d8bef9SDimitry Andric 
7069e8d8bef9SDimitry Andric   MachineInstrBuilder SatVal;
7070e8d8bef9SDimitry Andric   if (IsSigned) {
7071e8d8bef9SDimitry Andric     auto SatMin = MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(BW));
7072e8d8bef9SDimitry Andric     auto SatMax = MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(BW));
7073e8d8bef9SDimitry Andric     auto Cmp = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, LHS,
7074e8d8bef9SDimitry Andric                                     MIRBuilder.buildConstant(Ty, 0));
7075e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildSelect(Ty, Cmp, SatMin, SatMax);
7076e8d8bef9SDimitry Andric   } else {
7077e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildConstant(Ty, APInt::getMaxValue(BW));
7078e8d8bef9SDimitry Andric   }
7079e8d8bef9SDimitry Andric   auto Ov = MIRBuilder.buildICmp(CmpInst::ICMP_NE, BoolTy, LHS, Orig);
7080e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, SatVal, Result);
7081e8d8bef9SDimitry Andric 
7082e8d8bef9SDimitry Andric   MI.eraseFromParent();
7083e8d8bef9SDimitry Andric   return Legalized;
7084e8d8bef9SDimitry Andric }
7085e8d8bef9SDimitry Andric 
7086e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
7087480093f4SDimitry Andric LegalizerHelper::lowerBswap(MachineInstr &MI) {
7088480093f4SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
7089480093f4SDimitry Andric   Register Src = MI.getOperand(1).getReg();
7090480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
70915ffd83dbSDimitry Andric   unsigned SizeInBytes = (Ty.getScalarSizeInBits() + 7) / 8;
7092480093f4SDimitry Andric   unsigned BaseShiftAmt = (SizeInBytes - 1) * 8;
7093480093f4SDimitry Andric 
7094480093f4SDimitry Andric   // Swap most and least significant byte, set remaining bytes in Res to zero.
7095480093f4SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt);
7096480093f4SDimitry Andric   auto LSByteShiftedLeft = MIRBuilder.buildShl(Ty, Src, ShiftAmt);
7097480093f4SDimitry Andric   auto MSByteShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
7098480093f4SDimitry Andric   auto Res = MIRBuilder.buildOr(Ty, MSByteShiftedRight, LSByteShiftedLeft);
7099480093f4SDimitry Andric 
7100480093f4SDimitry Andric   // Set i-th high/low byte in Res to i-th low/high byte from Src.
7101480093f4SDimitry Andric   for (unsigned i = 1; i < SizeInBytes / 2; ++i) {
7102480093f4SDimitry Andric     // AND with Mask leaves byte i unchanged and sets remaining bytes to 0.
7103480093f4SDimitry Andric     APInt APMask(SizeInBytes * 8, 0xFF << (i * 8));
7104480093f4SDimitry Andric     auto Mask = MIRBuilder.buildConstant(Ty, APMask);
7105480093f4SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt - 16 * i);
7106480093f4SDimitry Andric     // Low byte shifted left to place of high byte: (Src & Mask) << ShiftAmt.
7107480093f4SDimitry Andric     auto LoByte = MIRBuilder.buildAnd(Ty, Src, Mask);
7108480093f4SDimitry Andric     auto LoShiftedLeft = MIRBuilder.buildShl(Ty, LoByte, ShiftAmt);
7109480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, LoShiftedLeft);
7110480093f4SDimitry Andric     // High byte shifted right to place of low byte: (Src >> ShiftAmt) & Mask.
7111480093f4SDimitry Andric     auto SrcShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
7112480093f4SDimitry Andric     auto HiShiftedRight = MIRBuilder.buildAnd(Ty, SrcShiftedRight, Mask);
7113480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, HiShiftedRight);
7114480093f4SDimitry Andric   }
7115480093f4SDimitry Andric   Res.getInstr()->getOperand(0).setReg(Dst);
7116480093f4SDimitry Andric 
7117480093f4SDimitry Andric   MI.eraseFromParent();
7118480093f4SDimitry Andric   return Legalized;
7119480093f4SDimitry Andric }
7120480093f4SDimitry Andric 
7121480093f4SDimitry Andric //{ (Src & Mask) >> N } | { (Src << N) & Mask }
7122480093f4SDimitry Andric static MachineInstrBuilder SwapN(unsigned N, DstOp Dst, MachineIRBuilder &B,
7123480093f4SDimitry Andric                                  MachineInstrBuilder Src, APInt Mask) {
7124480093f4SDimitry Andric   const LLT Ty = Dst.getLLTTy(*B.getMRI());
7125480093f4SDimitry Andric   MachineInstrBuilder C_N = B.buildConstant(Ty, N);
7126480093f4SDimitry Andric   MachineInstrBuilder MaskLoNTo0 = B.buildConstant(Ty, Mask);
7127480093f4SDimitry Andric   auto LHS = B.buildLShr(Ty, B.buildAnd(Ty, Src, MaskLoNTo0), C_N);
7128480093f4SDimitry Andric   auto RHS = B.buildAnd(Ty, B.buildShl(Ty, Src, C_N), MaskLoNTo0);
7129480093f4SDimitry Andric   return B.buildOr(Dst, LHS, RHS);
7130480093f4SDimitry Andric }
7131480093f4SDimitry Andric 
7132480093f4SDimitry Andric LegalizerHelper::LegalizeResult
7133480093f4SDimitry Andric LegalizerHelper::lowerBitreverse(MachineInstr &MI) {
7134480093f4SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
7135480093f4SDimitry Andric   Register Src = MI.getOperand(1).getReg();
7136480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
7137480093f4SDimitry Andric   unsigned Size = Ty.getSizeInBits();
7138480093f4SDimitry Andric 
7139480093f4SDimitry Andric   MachineInstrBuilder BSWAP =
7140480093f4SDimitry Andric       MIRBuilder.buildInstr(TargetOpcode::G_BSWAP, {Ty}, {Src});
7141480093f4SDimitry Andric 
7142480093f4SDimitry Andric   // swap high and low 4 bits in 8 bit blocks 7654|3210 -> 3210|7654
7143480093f4SDimitry Andric   //    [(val & 0xF0F0F0F0) >> 4] | [(val & 0x0F0F0F0F) << 4]
7144480093f4SDimitry Andric   // -> [(val & 0xF0F0F0F0) >> 4] | [(val << 4) & 0xF0F0F0F0]
7145480093f4SDimitry Andric   MachineInstrBuilder Swap4 =
7146480093f4SDimitry Andric       SwapN(4, Ty, MIRBuilder, BSWAP, APInt::getSplat(Size, APInt(8, 0xF0)));
7147480093f4SDimitry Andric 
7148480093f4SDimitry Andric   // swap high and low 2 bits in 4 bit blocks 32|10 76|54 -> 10|32 54|76
7149480093f4SDimitry Andric   //    [(val & 0xCCCCCCCC) >> 2] & [(val & 0x33333333) << 2]
7150480093f4SDimitry Andric   // -> [(val & 0xCCCCCCCC) >> 2] & [(val << 2) & 0xCCCCCCCC]
7151480093f4SDimitry Andric   MachineInstrBuilder Swap2 =
7152480093f4SDimitry Andric       SwapN(2, Ty, MIRBuilder, Swap4, APInt::getSplat(Size, APInt(8, 0xCC)));
7153480093f4SDimitry Andric 
7154480093f4SDimitry Andric   // swap high and low 1 bit in 2 bit blocks 1|0 3|2 5|4 7|6 -> 0|1 2|3 4|5 6|7
7155480093f4SDimitry Andric   //    [(val & 0xAAAAAAAA) >> 1] & [(val & 0x55555555) << 1]
7156480093f4SDimitry Andric   // -> [(val & 0xAAAAAAAA) >> 1] & [(val << 1) & 0xAAAAAAAA]
7157480093f4SDimitry Andric   SwapN(1, Dst, MIRBuilder, Swap2, APInt::getSplat(Size, APInt(8, 0xAA)));
7158480093f4SDimitry Andric 
7159480093f4SDimitry Andric   MI.eraseFromParent();
7160480093f4SDimitry Andric   return Legalized;
7161480093f4SDimitry Andric }
7162480093f4SDimitry Andric 
7163480093f4SDimitry Andric LegalizerHelper::LegalizeResult
71645ffd83dbSDimitry Andric LegalizerHelper::lowerReadWriteRegister(MachineInstr &MI) {
7165480093f4SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
71665ffd83dbSDimitry Andric 
71675ffd83dbSDimitry Andric   bool IsRead = MI.getOpcode() == TargetOpcode::G_READ_REGISTER;
71685ffd83dbSDimitry Andric   int NameOpIdx = IsRead ? 1 : 0;
71695ffd83dbSDimitry Andric   int ValRegIndex = IsRead ? 0 : 1;
71705ffd83dbSDimitry Andric 
71715ffd83dbSDimitry Andric   Register ValReg = MI.getOperand(ValRegIndex).getReg();
71725ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(ValReg);
71735ffd83dbSDimitry Andric   const MDString *RegStr = cast<MDString>(
71745ffd83dbSDimitry Andric     cast<MDNode>(MI.getOperand(NameOpIdx).getMetadata())->getOperand(0));
71755ffd83dbSDimitry Andric 
7176e8d8bef9SDimitry Andric   Register PhysReg = TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
71775ffd83dbSDimitry Andric   if (!PhysReg.isValid())
7178480093f4SDimitry Andric     return UnableToLegalize;
7179480093f4SDimitry Andric 
71805ffd83dbSDimitry Andric   if (IsRead)
71815ffd83dbSDimitry Andric     MIRBuilder.buildCopy(ValReg, PhysReg);
71825ffd83dbSDimitry Andric   else
71835ffd83dbSDimitry Andric     MIRBuilder.buildCopy(PhysReg, ValReg);
71845ffd83dbSDimitry Andric 
7185480093f4SDimitry Andric   MI.eraseFromParent();
7186480093f4SDimitry Andric   return Legalized;
7187480093f4SDimitry Andric }
7188e8d8bef9SDimitry Andric 
7189e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
7190e8d8bef9SDimitry Andric LegalizerHelper::lowerSMULH_UMULH(MachineInstr &MI) {
7191e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SMULH;
7192e8d8bef9SDimitry Andric   unsigned ExtOp = IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
7193e8d8bef9SDimitry Andric   Register Result = MI.getOperand(0).getReg();
7194e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(Result);
7195e8d8bef9SDimitry Andric   auto SizeInBits = OrigTy.getScalarSizeInBits();
7196e8d8bef9SDimitry Andric   LLT WideTy = OrigTy.changeElementSize(SizeInBits * 2);
7197e8d8bef9SDimitry Andric 
7198e8d8bef9SDimitry Andric   auto LHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(1)});
7199e8d8bef9SDimitry Andric   auto RHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(2)});
7200e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(WideTy, LHS, RHS);
7201e8d8bef9SDimitry Andric   unsigned ShiftOp = IsSigned ? TargetOpcode::G_ASHR : TargetOpcode::G_LSHR;
7202e8d8bef9SDimitry Andric 
7203e8d8bef9SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(WideTy, SizeInBits);
7204e8d8bef9SDimitry Andric   auto Shifted = MIRBuilder.buildInstr(ShiftOp, {WideTy}, {Mul, ShiftAmt});
7205e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(Result, Shifted);
7206e8d8bef9SDimitry Andric 
7207e8d8bef9SDimitry Andric   MI.eraseFromParent();
7208e8d8bef9SDimitry Andric   return Legalized;
7209e8d8bef9SDimitry Andric }
7210e8d8bef9SDimitry Andric 
7211e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSelect(MachineInstr &MI) {
7212e8d8bef9SDimitry Andric   // Implement vector G_SELECT in terms of XOR, AND, OR.
7213e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
7214e8d8bef9SDimitry Andric   Register MaskReg = MI.getOperand(1).getReg();
7215e8d8bef9SDimitry Andric   Register Op1Reg = MI.getOperand(2).getReg();
7216e8d8bef9SDimitry Andric   Register Op2Reg = MI.getOperand(3).getReg();
7217e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
7218e8d8bef9SDimitry Andric   LLT MaskTy = MRI.getType(MaskReg);
7219e8d8bef9SDimitry Andric   LLT Op1Ty = MRI.getType(Op1Reg);
7220e8d8bef9SDimitry Andric   if (!DstTy.isVector())
7221e8d8bef9SDimitry Andric     return UnableToLegalize;
7222e8d8bef9SDimitry Andric 
7223e8d8bef9SDimitry Andric   // Vector selects can have a scalar predicate. If so, splat into a vector and
7224e8d8bef9SDimitry Andric   // finish for later legalization attempts to try again.
7225e8d8bef9SDimitry Andric   if (MaskTy.isScalar()) {
7226e8d8bef9SDimitry Andric     Register MaskElt = MaskReg;
7227e8d8bef9SDimitry Andric     if (MaskTy.getSizeInBits() < DstTy.getScalarSizeInBits())
7228e8d8bef9SDimitry Andric       MaskElt = MIRBuilder.buildSExt(DstTy.getElementType(), MaskElt).getReg(0);
7229e8d8bef9SDimitry Andric     // Generate a vector splat idiom to be pattern matched later.
7230e8d8bef9SDimitry Andric     auto ShufSplat = MIRBuilder.buildShuffleSplat(DstTy, MaskElt);
7231e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
7232e8d8bef9SDimitry Andric     MI.getOperand(1).setReg(ShufSplat.getReg(0));
7233e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
7234e8d8bef9SDimitry Andric     return Legalized;
7235e8d8bef9SDimitry Andric   }
7236e8d8bef9SDimitry Andric 
7237e8d8bef9SDimitry Andric   if (MaskTy.getSizeInBits() != Op1Ty.getSizeInBits()) {
7238e8d8bef9SDimitry Andric     return UnableToLegalize;
7239e8d8bef9SDimitry Andric   }
7240e8d8bef9SDimitry Andric 
7241e8d8bef9SDimitry Andric   auto NotMask = MIRBuilder.buildNot(MaskTy, MaskReg);
7242e8d8bef9SDimitry Andric   auto NewOp1 = MIRBuilder.buildAnd(MaskTy, Op1Reg, MaskReg);
7243e8d8bef9SDimitry Andric   auto NewOp2 = MIRBuilder.buildAnd(MaskTy, Op2Reg, NotMask);
7244e8d8bef9SDimitry Andric   MIRBuilder.buildOr(DstReg, NewOp1, NewOp2);
7245e8d8bef9SDimitry Andric   MI.eraseFromParent();
7246e8d8bef9SDimitry Andric   return Legalized;
7247e8d8bef9SDimitry Andric }
7248*fe6060f1SDimitry Andric 
7249*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerDIVREM(MachineInstr &MI) {
7250*fe6060f1SDimitry Andric   // Split DIVREM into individual instructions.
7251*fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
7252*fe6060f1SDimitry Andric 
7253*fe6060f1SDimitry Andric   MIRBuilder.buildInstr(
7254*fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIVREM ? TargetOpcode::G_SDIV
7255*fe6060f1SDimitry Andric                                         : TargetOpcode::G_UDIV,
7256*fe6060f1SDimitry Andric       {MI.getOperand(0).getReg()}, {MI.getOperand(2), MI.getOperand(3)});
7257*fe6060f1SDimitry Andric   MIRBuilder.buildInstr(
7258*fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIVREM ? TargetOpcode::G_SREM
7259*fe6060f1SDimitry Andric                                         : TargetOpcode::G_UREM,
7260*fe6060f1SDimitry Andric       {MI.getOperand(1).getReg()}, {MI.getOperand(2), MI.getOperand(3)});
7261*fe6060f1SDimitry Andric   MI.eraseFromParent();
7262*fe6060f1SDimitry Andric   return Legalized;
7263*fe6060f1SDimitry Andric }
7264*fe6060f1SDimitry Andric 
7265*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
7266*fe6060f1SDimitry Andric LegalizerHelper::lowerAbsToAddXor(MachineInstr &MI) {
7267*fe6060f1SDimitry Andric   // Expand %res = G_ABS %a into:
7268*fe6060f1SDimitry Andric   // %v1 = G_ASHR %a, scalar_size-1
7269*fe6060f1SDimitry Andric   // %v2 = G_ADD %a, %v1
7270*fe6060f1SDimitry Andric   // %res = G_XOR %v2, %v1
7271*fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
7272*fe6060f1SDimitry Andric   Register OpReg = MI.getOperand(1).getReg();
7273*fe6060f1SDimitry Andric   auto ShiftAmt =
7274*fe6060f1SDimitry Andric       MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - 1);
7275*fe6060f1SDimitry Andric   auto Shift = MIRBuilder.buildAShr(DstTy, OpReg, ShiftAmt);
7276*fe6060f1SDimitry Andric   auto Add = MIRBuilder.buildAdd(DstTy, OpReg, Shift);
7277*fe6060f1SDimitry Andric   MIRBuilder.buildXor(MI.getOperand(0).getReg(), Add, Shift);
7278*fe6060f1SDimitry Andric   MI.eraseFromParent();
7279*fe6060f1SDimitry Andric   return Legalized;
7280*fe6060f1SDimitry Andric }
7281*fe6060f1SDimitry Andric 
7282*fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
7283*fe6060f1SDimitry Andric LegalizerHelper::lowerAbsToMaxNeg(MachineInstr &MI) {
7284*fe6060f1SDimitry Andric   // Expand %res = G_ABS %a into:
7285*fe6060f1SDimitry Andric   // %v1 = G_CONSTANT 0
7286*fe6060f1SDimitry Andric   // %v2 = G_SUB %v1, %a
7287*fe6060f1SDimitry Andric   // %res = G_SMAX %a, %v2
7288*fe6060f1SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
7289*fe6060f1SDimitry Andric   LLT Ty = MRI.getType(SrcReg);
7290*fe6060f1SDimitry Andric   auto Zero = MIRBuilder.buildConstant(Ty, 0).getReg(0);
7291*fe6060f1SDimitry Andric   auto Sub = MIRBuilder.buildSub(Ty, Zero, SrcReg).getReg(0);
7292*fe6060f1SDimitry Andric   MIRBuilder.buildSMax(MI.getOperand(0), SrcReg, Sub);
7293*fe6060f1SDimitry Andric   MI.eraseFromParent();
7294*fe6060f1SDimitry Andric   return Legalized;
7295*fe6060f1SDimitry Andric }
7296