xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp (revision 23408297fbf3089f0388a8873b02fa75ab3f5bb9)
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"
19e8d8bef9SDimitry Andric #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
218bcb0991SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
250b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
260b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
270b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric #define DEBUG_TYPE "legalizer"
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric using namespace llvm;
320b57cec5SDimitry Andric using namespace LegalizeActions;
33e8d8bef9SDimitry Andric using namespace MIPatternMatch;
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric /// Try to break down \p OrigTy into \p NarrowTy sized pieces.
360b57cec5SDimitry Andric ///
370b57cec5SDimitry Andric /// Returns the number of \p NarrowTy elements needed to reconstruct \p OrigTy,
380b57cec5SDimitry Andric /// with any leftover piece as type \p LeftoverTy
390b57cec5SDimitry Andric ///
400b57cec5SDimitry Andric /// Returns -1 in the first element of the pair if the breakdown is not
410b57cec5SDimitry Andric /// satisfiable.
420b57cec5SDimitry Andric static std::pair<int, int>
430b57cec5SDimitry Andric getNarrowTypeBreakDown(LLT OrigTy, LLT NarrowTy, LLT &LeftoverTy) {
440b57cec5SDimitry Andric   assert(!LeftoverTy.isValid() && "this is an out argument");
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric   unsigned Size = OrigTy.getSizeInBits();
470b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
480b57cec5SDimitry Andric   unsigned NumParts = Size / NarrowSize;
490b57cec5SDimitry Andric   unsigned LeftoverSize = Size - NumParts * NarrowSize;
500b57cec5SDimitry Andric   assert(Size > NarrowSize);
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   if (LeftoverSize == 0)
530b57cec5SDimitry Andric     return {NumParts, 0};
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   if (NarrowTy.isVector()) {
560b57cec5SDimitry Andric     unsigned EltSize = OrigTy.getScalarSizeInBits();
570b57cec5SDimitry Andric     if (LeftoverSize % EltSize != 0)
580b57cec5SDimitry Andric       return {-1, -1};
590b57cec5SDimitry Andric     LeftoverTy = LLT::scalarOrVector(LeftoverSize / EltSize, EltSize);
600b57cec5SDimitry Andric   } else {
610b57cec5SDimitry Andric     LeftoverTy = LLT::scalar(LeftoverSize);
620b57cec5SDimitry Andric   }
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric   int NumLeftover = LeftoverSize / LeftoverTy.getSizeInBits();
650b57cec5SDimitry Andric   return std::make_pair(NumParts, NumLeftover);
660b57cec5SDimitry Andric }
670b57cec5SDimitry Andric 
685ffd83dbSDimitry Andric static Type *getFloatTypeForLLT(LLVMContext &Ctx, LLT Ty) {
695ffd83dbSDimitry Andric 
705ffd83dbSDimitry Andric   if (!Ty.isScalar())
715ffd83dbSDimitry Andric     return nullptr;
725ffd83dbSDimitry Andric 
735ffd83dbSDimitry Andric   switch (Ty.getSizeInBits()) {
745ffd83dbSDimitry Andric   case 16:
755ffd83dbSDimitry Andric     return Type::getHalfTy(Ctx);
765ffd83dbSDimitry Andric   case 32:
775ffd83dbSDimitry Andric     return Type::getFloatTy(Ctx);
785ffd83dbSDimitry Andric   case 64:
795ffd83dbSDimitry Andric     return Type::getDoubleTy(Ctx);
80e8d8bef9SDimitry Andric   case 80:
81e8d8bef9SDimitry Andric     return Type::getX86_FP80Ty(Ctx);
825ffd83dbSDimitry Andric   case 128:
835ffd83dbSDimitry Andric     return Type::getFP128Ty(Ctx);
845ffd83dbSDimitry Andric   default:
855ffd83dbSDimitry Andric     return nullptr;
865ffd83dbSDimitry Andric   }
875ffd83dbSDimitry Andric }
885ffd83dbSDimitry Andric 
890b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF,
900b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
910b57cec5SDimitry Andric                                  MachineIRBuilder &Builder)
925ffd83dbSDimitry Andric     : MIRBuilder(Builder), Observer(Observer), MRI(MF.getRegInfo()),
93e8d8bef9SDimitry Andric       LI(*MF.getSubtarget().getLegalizerInfo()),
94e8d8bef9SDimitry Andric       TLI(*MF.getSubtarget().getTargetLowering()) { }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF, const LegalizerInfo &LI,
970b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
980b57cec5SDimitry Andric                                  MachineIRBuilder &B)
99e8d8bef9SDimitry Andric   : MIRBuilder(B), Observer(Observer), MRI(MF.getRegInfo()), LI(LI),
100e8d8bef9SDimitry Andric     TLI(*MF.getSubtarget().getTargetLowering()) { }
101e8d8bef9SDimitry Andric 
1020b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
1030b57cec5SDimitry Andric LegalizerHelper::legalizeInstrStep(MachineInstr &MI) {
1045ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "Legalizing: " << MI);
1055ffd83dbSDimitry Andric 
1065ffd83dbSDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INTRINSIC ||
1090b57cec5SDimitry Andric       MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS)
1105ffd83dbSDimitry Andric     return LI.legalizeIntrinsic(*this, MI) ? Legalized : UnableToLegalize;
1110b57cec5SDimitry Andric   auto Step = LI.getAction(MI, MRI);
1120b57cec5SDimitry Andric   switch (Step.Action) {
1130b57cec5SDimitry Andric   case Legal:
1140b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Already legal\n");
1150b57cec5SDimitry Andric     return AlreadyLegal;
1160b57cec5SDimitry Andric   case Libcall:
1170b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Convert to libcall\n");
1180b57cec5SDimitry Andric     return libcall(MI);
1190b57cec5SDimitry Andric   case NarrowScalar:
1200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Narrow scalar\n");
1210b57cec5SDimitry Andric     return narrowScalar(MI, Step.TypeIdx, Step.NewType);
1220b57cec5SDimitry Andric   case WidenScalar:
1230b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Widen scalar\n");
1240b57cec5SDimitry Andric     return widenScalar(MI, Step.TypeIdx, Step.NewType);
1255ffd83dbSDimitry Andric   case Bitcast:
1265ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << ".. Bitcast type\n");
1275ffd83dbSDimitry Andric     return bitcast(MI, Step.TypeIdx, Step.NewType);
1280b57cec5SDimitry Andric   case Lower:
1290b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Lower\n");
1300b57cec5SDimitry Andric     return lower(MI, Step.TypeIdx, Step.NewType);
1310b57cec5SDimitry Andric   case FewerElements:
1320b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Reduce number of elements\n");
1330b57cec5SDimitry Andric     return fewerElementsVector(MI, Step.TypeIdx, Step.NewType);
1340b57cec5SDimitry Andric   case MoreElements:
1350b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Increase number of elements\n");
1360b57cec5SDimitry Andric     return moreElementsVector(MI, Step.TypeIdx, Step.NewType);
1370b57cec5SDimitry Andric   case Custom:
1380b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Custom legalization\n");
1395ffd83dbSDimitry Andric     return LI.legalizeCustom(*this, MI) ? Legalized : UnableToLegalize;
1400b57cec5SDimitry Andric   default:
1410b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Unable to legalize\n");
1420b57cec5SDimitry Andric     return UnableToLegalize;
1430b57cec5SDimitry Andric   }
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric void LegalizerHelper::extractParts(Register Reg, LLT Ty, int NumParts,
1470b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &VRegs) {
1480b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i)
1490b57cec5SDimitry Andric     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
1500b57cec5SDimitry Andric   MIRBuilder.buildUnmerge(VRegs, Reg);
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric bool LegalizerHelper::extractParts(Register Reg, LLT RegTy,
1540b57cec5SDimitry Andric                                    LLT MainTy, LLT &LeftoverTy,
1550b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &VRegs,
1560b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &LeftoverRegs) {
1570b57cec5SDimitry Andric   assert(!LeftoverTy.isValid() && "this is an out argument");
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   unsigned RegSize = RegTy.getSizeInBits();
1600b57cec5SDimitry Andric   unsigned MainSize = MainTy.getSizeInBits();
1610b57cec5SDimitry Andric   unsigned NumParts = RegSize / MainSize;
1620b57cec5SDimitry Andric   unsigned LeftoverSize = RegSize - NumParts * MainSize;
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   // Use an unmerge when possible.
1650b57cec5SDimitry Andric   if (LeftoverSize == 0) {
1660b57cec5SDimitry Andric     for (unsigned I = 0; I < NumParts; ++I)
1670b57cec5SDimitry Andric       VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
1680b57cec5SDimitry Andric     MIRBuilder.buildUnmerge(VRegs, Reg);
1690b57cec5SDimitry Andric     return true;
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   if (MainTy.isVector()) {
1730b57cec5SDimitry Andric     unsigned EltSize = MainTy.getScalarSizeInBits();
1740b57cec5SDimitry Andric     if (LeftoverSize % EltSize != 0)
1750b57cec5SDimitry Andric       return false;
1760b57cec5SDimitry Andric     LeftoverTy = LLT::scalarOrVector(LeftoverSize / EltSize, EltSize);
1770b57cec5SDimitry Andric   } else {
1780b57cec5SDimitry Andric     LeftoverTy = LLT::scalar(LeftoverSize);
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   // For irregular sizes, extract the individual parts.
1820b57cec5SDimitry Andric   for (unsigned I = 0; I != NumParts; ++I) {
1830b57cec5SDimitry Andric     Register NewReg = MRI.createGenericVirtualRegister(MainTy);
1840b57cec5SDimitry Andric     VRegs.push_back(NewReg);
1850b57cec5SDimitry Andric     MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
1890b57cec5SDimitry Andric        Offset += LeftoverSize) {
1900b57cec5SDimitry Andric     Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
1910b57cec5SDimitry Andric     LeftoverRegs.push_back(NewReg);
1920b57cec5SDimitry Andric     MIRBuilder.buildExtract(NewReg, Reg, Offset);
1930b57cec5SDimitry Andric   }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   return true;
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric void LegalizerHelper::insertParts(Register DstReg,
1990b57cec5SDimitry Andric                                   LLT ResultTy, LLT PartTy,
2000b57cec5SDimitry Andric                                   ArrayRef<Register> PartRegs,
2010b57cec5SDimitry Andric                                   LLT LeftoverTy,
2020b57cec5SDimitry Andric                                   ArrayRef<Register> LeftoverRegs) {
2030b57cec5SDimitry Andric   if (!LeftoverTy.isValid()) {
2040b57cec5SDimitry Andric     assert(LeftoverRegs.empty());
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric     if (!ResultTy.isVector()) {
2070b57cec5SDimitry Andric       MIRBuilder.buildMerge(DstReg, PartRegs);
2080b57cec5SDimitry Andric       return;
2090b57cec5SDimitry Andric     }
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric     if (PartTy.isVector())
2120b57cec5SDimitry Andric       MIRBuilder.buildConcatVectors(DstReg, PartRegs);
2130b57cec5SDimitry Andric     else
2140b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, PartRegs);
2150b57cec5SDimitry Andric     return;
2160b57cec5SDimitry Andric   }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   unsigned PartSize = PartTy.getSizeInBits();
2190b57cec5SDimitry Andric   unsigned LeftoverPartSize = LeftoverTy.getSizeInBits();
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   Register CurResultReg = MRI.createGenericVirtualRegister(ResultTy);
2220b57cec5SDimitry Andric   MIRBuilder.buildUndef(CurResultReg);
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   unsigned Offset = 0;
2250b57cec5SDimitry Andric   for (Register PartReg : PartRegs) {
2260b57cec5SDimitry Andric     Register NewResultReg = MRI.createGenericVirtualRegister(ResultTy);
2270b57cec5SDimitry Andric     MIRBuilder.buildInsert(NewResultReg, CurResultReg, PartReg, Offset);
2280b57cec5SDimitry Andric     CurResultReg = NewResultReg;
2290b57cec5SDimitry Andric     Offset += PartSize;
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   for (unsigned I = 0, E = LeftoverRegs.size(); I != E; ++I) {
2330b57cec5SDimitry Andric     // Use the original output register for the final insert to avoid a copy.
2340b57cec5SDimitry Andric     Register NewResultReg = (I + 1 == E) ?
2350b57cec5SDimitry Andric       DstReg : MRI.createGenericVirtualRegister(ResultTy);
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     MIRBuilder.buildInsert(NewResultReg, CurResultReg, LeftoverRegs[I], Offset);
2380b57cec5SDimitry Andric     CurResultReg = NewResultReg;
2390b57cec5SDimitry Andric     Offset += LeftoverPartSize;
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric 
243e8d8bef9SDimitry Andric /// Append the result registers of G_UNMERGE_VALUES \p MI to \p Regs.
2445ffd83dbSDimitry Andric static void getUnmergeResults(SmallVectorImpl<Register> &Regs,
2455ffd83dbSDimitry Andric                               const MachineInstr &MI) {
2465ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES);
2475ffd83dbSDimitry Andric 
248e8d8bef9SDimitry Andric   const int StartIdx = Regs.size();
2495ffd83dbSDimitry Andric   const int NumResults = MI.getNumOperands() - 1;
250e8d8bef9SDimitry Andric   Regs.resize(Regs.size() + NumResults);
2515ffd83dbSDimitry Andric   for (int I = 0; I != NumResults; ++I)
252e8d8bef9SDimitry Andric     Regs[StartIdx + I] = MI.getOperand(I).getReg();
2535ffd83dbSDimitry Andric }
2545ffd83dbSDimitry Andric 
255e8d8bef9SDimitry Andric void LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts,
256e8d8bef9SDimitry Andric                                      LLT GCDTy, Register SrcReg) {
2575ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2585ffd83dbSDimitry Andric   if (SrcTy == GCDTy) {
2595ffd83dbSDimitry Andric     // If the source already evenly divides the result type, we don't need to do
2605ffd83dbSDimitry Andric     // anything.
2615ffd83dbSDimitry Andric     Parts.push_back(SrcReg);
2625ffd83dbSDimitry Andric   } else {
2635ffd83dbSDimitry Andric     // Need to split into common type sized pieces.
2645ffd83dbSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
2655ffd83dbSDimitry Andric     getUnmergeResults(Parts, *Unmerge);
2665ffd83dbSDimitry Andric   }
267e8d8bef9SDimitry Andric }
2685ffd83dbSDimitry Andric 
269e8d8bef9SDimitry Andric LLT LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts, LLT DstTy,
270e8d8bef9SDimitry Andric                                     LLT NarrowTy, Register SrcReg) {
271e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
272e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
273e8d8bef9SDimitry Andric   extractGCDType(Parts, GCDTy, SrcReg);
2745ffd83dbSDimitry Andric   return GCDTy;
2755ffd83dbSDimitry Andric }
2765ffd83dbSDimitry Andric 
2775ffd83dbSDimitry Andric LLT LegalizerHelper::buildLCMMergePieces(LLT DstTy, LLT NarrowTy, LLT GCDTy,
2785ffd83dbSDimitry Andric                                          SmallVectorImpl<Register> &VRegs,
2795ffd83dbSDimitry Andric                                          unsigned PadStrategy) {
2805ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(DstTy, NarrowTy);
2815ffd83dbSDimitry Andric 
2825ffd83dbSDimitry Andric   int NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
2835ffd83dbSDimitry Andric   int NumSubParts = NarrowTy.getSizeInBits() / GCDTy.getSizeInBits();
2845ffd83dbSDimitry Andric   int NumOrigSrc = VRegs.size();
2855ffd83dbSDimitry Andric 
2865ffd83dbSDimitry Andric   Register PadReg;
2875ffd83dbSDimitry Andric 
2885ffd83dbSDimitry Andric   // Get a value we can use to pad the source value if the sources won't evenly
2895ffd83dbSDimitry Andric   // cover the result type.
2905ffd83dbSDimitry Andric   if (NumOrigSrc < NumParts * NumSubParts) {
2915ffd83dbSDimitry Andric     if (PadStrategy == TargetOpcode::G_ZEXT)
2925ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildConstant(GCDTy, 0).getReg(0);
2935ffd83dbSDimitry Andric     else if (PadStrategy == TargetOpcode::G_ANYEXT)
2945ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
2955ffd83dbSDimitry Andric     else {
2965ffd83dbSDimitry Andric       assert(PadStrategy == TargetOpcode::G_SEXT);
2975ffd83dbSDimitry Andric 
2985ffd83dbSDimitry Andric       // Shift the sign bit of the low register through the high register.
2995ffd83dbSDimitry Andric       auto ShiftAmt =
3005ffd83dbSDimitry Andric         MIRBuilder.buildConstant(LLT::scalar(64), GCDTy.getSizeInBits() - 1);
3015ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildAShr(GCDTy, VRegs.back(), ShiftAmt).getReg(0);
3025ffd83dbSDimitry Andric     }
3035ffd83dbSDimitry Andric   }
3045ffd83dbSDimitry Andric 
3055ffd83dbSDimitry Andric   // Registers for the final merge to be produced.
3065ffd83dbSDimitry Andric   SmallVector<Register, 4> Remerge(NumParts);
3075ffd83dbSDimitry Andric 
3085ffd83dbSDimitry Andric   // Registers needed for intermediate merges, which will be merged into a
3095ffd83dbSDimitry Andric   // source for Remerge.
3105ffd83dbSDimitry Andric   SmallVector<Register, 4> SubMerge(NumSubParts);
3115ffd83dbSDimitry Andric 
3125ffd83dbSDimitry Andric   // Once we've fully read off the end of the original source bits, we can reuse
3135ffd83dbSDimitry Andric   // the same high bits for remaining padding elements.
3145ffd83dbSDimitry Andric   Register AllPadReg;
3155ffd83dbSDimitry Andric 
3165ffd83dbSDimitry Andric   // Build merges to the LCM type to cover the original result type.
3175ffd83dbSDimitry Andric   for (int I = 0; I != NumParts; ++I) {
3185ffd83dbSDimitry Andric     bool AllMergePartsArePadding = true;
3195ffd83dbSDimitry Andric 
3205ffd83dbSDimitry Andric     // Build the requested merges to the requested type.
3215ffd83dbSDimitry Andric     for (int J = 0; J != NumSubParts; ++J) {
3225ffd83dbSDimitry Andric       int Idx = I * NumSubParts + J;
3235ffd83dbSDimitry Andric       if (Idx >= NumOrigSrc) {
3245ffd83dbSDimitry Andric         SubMerge[J] = PadReg;
3255ffd83dbSDimitry Andric         continue;
3265ffd83dbSDimitry Andric       }
3275ffd83dbSDimitry Andric 
3285ffd83dbSDimitry Andric       SubMerge[J] = VRegs[Idx];
3295ffd83dbSDimitry Andric 
3305ffd83dbSDimitry Andric       // There are meaningful bits here we can't reuse later.
3315ffd83dbSDimitry Andric       AllMergePartsArePadding = false;
3325ffd83dbSDimitry Andric     }
3335ffd83dbSDimitry Andric 
3345ffd83dbSDimitry Andric     // If we've filled up a complete piece with padding bits, we can directly
3355ffd83dbSDimitry Andric     // emit the natural sized constant if applicable, rather than a merge of
3365ffd83dbSDimitry Andric     // smaller constants.
3375ffd83dbSDimitry Andric     if (AllMergePartsArePadding && !AllPadReg) {
3385ffd83dbSDimitry Andric       if (PadStrategy == TargetOpcode::G_ANYEXT)
3395ffd83dbSDimitry Andric         AllPadReg = MIRBuilder.buildUndef(NarrowTy).getReg(0);
3405ffd83dbSDimitry Andric       else if (PadStrategy == TargetOpcode::G_ZEXT)
3415ffd83dbSDimitry Andric         AllPadReg = MIRBuilder.buildConstant(NarrowTy, 0).getReg(0);
3425ffd83dbSDimitry Andric 
3435ffd83dbSDimitry Andric       // If this is a sign extension, we can't materialize a trivial constant
3445ffd83dbSDimitry Andric       // with the right type and have to produce a merge.
3455ffd83dbSDimitry Andric     }
3465ffd83dbSDimitry Andric 
3475ffd83dbSDimitry Andric     if (AllPadReg) {
3485ffd83dbSDimitry Andric       // Avoid creating additional instructions if we're just adding additional
3495ffd83dbSDimitry Andric       // copies of padding bits.
3505ffd83dbSDimitry Andric       Remerge[I] = AllPadReg;
3515ffd83dbSDimitry Andric       continue;
3525ffd83dbSDimitry Andric     }
3535ffd83dbSDimitry Andric 
3545ffd83dbSDimitry Andric     if (NumSubParts == 1)
3555ffd83dbSDimitry Andric       Remerge[I] = SubMerge[0];
3565ffd83dbSDimitry Andric     else
3575ffd83dbSDimitry Andric       Remerge[I] = MIRBuilder.buildMerge(NarrowTy, SubMerge).getReg(0);
3585ffd83dbSDimitry Andric 
3595ffd83dbSDimitry Andric     // In the sign extend padding case, re-use the first all-signbit merge.
3605ffd83dbSDimitry Andric     if (AllMergePartsArePadding && !AllPadReg)
3615ffd83dbSDimitry Andric       AllPadReg = Remerge[I];
3625ffd83dbSDimitry Andric   }
3635ffd83dbSDimitry Andric 
3645ffd83dbSDimitry Andric   VRegs = std::move(Remerge);
3655ffd83dbSDimitry Andric   return LCMTy;
3665ffd83dbSDimitry Andric }
3675ffd83dbSDimitry Andric 
3685ffd83dbSDimitry Andric void LegalizerHelper::buildWidenedRemergeToDst(Register DstReg, LLT LCMTy,
3695ffd83dbSDimitry Andric                                                ArrayRef<Register> RemergeRegs) {
3705ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3715ffd83dbSDimitry Andric 
3725ffd83dbSDimitry Andric   // Create the merge to the widened source, and extract the relevant bits into
3735ffd83dbSDimitry Andric   // the result.
3745ffd83dbSDimitry Andric 
3755ffd83dbSDimitry Andric   if (DstTy == LCMTy) {
3765ffd83dbSDimitry Andric     MIRBuilder.buildMerge(DstReg, RemergeRegs);
3775ffd83dbSDimitry Andric     return;
3785ffd83dbSDimitry Andric   }
3795ffd83dbSDimitry Andric 
3805ffd83dbSDimitry Andric   auto Remerge = MIRBuilder.buildMerge(LCMTy, RemergeRegs);
3815ffd83dbSDimitry Andric   if (DstTy.isScalar() && LCMTy.isScalar()) {
3825ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(DstReg, Remerge);
3835ffd83dbSDimitry Andric     return;
3845ffd83dbSDimitry Andric   }
3855ffd83dbSDimitry Andric 
3865ffd83dbSDimitry Andric   if (LCMTy.isVector()) {
387e8d8bef9SDimitry Andric     unsigned NumDefs = LCMTy.getSizeInBits() / DstTy.getSizeInBits();
388e8d8bef9SDimitry Andric     SmallVector<Register, 8> UnmergeDefs(NumDefs);
389e8d8bef9SDimitry Andric     UnmergeDefs[0] = DstReg;
390e8d8bef9SDimitry Andric     for (unsigned I = 1; I != NumDefs; ++I)
391e8d8bef9SDimitry Andric       UnmergeDefs[I] = MRI.createGenericVirtualRegister(DstTy);
392e8d8bef9SDimitry Andric 
393e8d8bef9SDimitry Andric     MIRBuilder.buildUnmerge(UnmergeDefs,
394e8d8bef9SDimitry Andric                             MIRBuilder.buildMerge(LCMTy, RemergeRegs));
3955ffd83dbSDimitry Andric     return;
3965ffd83dbSDimitry Andric   }
3975ffd83dbSDimitry Andric 
3985ffd83dbSDimitry Andric   llvm_unreachable("unhandled case");
3995ffd83dbSDimitry Andric }
4005ffd83dbSDimitry Andric 
4010b57cec5SDimitry Andric static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size) {
402e8d8bef9SDimitry Andric #define RTLIBCASE_INT(LibcallPrefix)                                           \
4035ffd83dbSDimitry Andric   do {                                                                         \
4045ffd83dbSDimitry Andric     switch (Size) {                                                            \
4055ffd83dbSDimitry Andric     case 32:                                                                   \
4065ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
4075ffd83dbSDimitry Andric     case 64:                                                                   \
4085ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
4095ffd83dbSDimitry Andric     case 128:                                                                  \
4105ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
4115ffd83dbSDimitry Andric     default:                                                                   \
4125ffd83dbSDimitry Andric       llvm_unreachable("unexpected size");                                     \
4135ffd83dbSDimitry Andric     }                                                                          \
4145ffd83dbSDimitry Andric   } while (0)
4155ffd83dbSDimitry Andric 
416e8d8bef9SDimitry Andric #define RTLIBCASE(LibcallPrefix)                                               \
417e8d8bef9SDimitry Andric   do {                                                                         \
418e8d8bef9SDimitry Andric     switch (Size) {                                                            \
419e8d8bef9SDimitry Andric     case 32:                                                                   \
420e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
421e8d8bef9SDimitry Andric     case 64:                                                                   \
422e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
423e8d8bef9SDimitry Andric     case 80:                                                                   \
424e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##80;                                         \
425e8d8bef9SDimitry Andric     case 128:                                                                  \
426e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
427e8d8bef9SDimitry Andric     default:                                                                   \
428e8d8bef9SDimitry Andric       llvm_unreachable("unexpected size");                                     \
429e8d8bef9SDimitry Andric     }                                                                          \
430e8d8bef9SDimitry Andric   } while (0)
4315ffd83dbSDimitry Andric 
4320b57cec5SDimitry Andric   switch (Opcode) {
4330b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
434e8d8bef9SDimitry Andric     RTLIBCASE_INT(SDIV_I);
4350b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
436e8d8bef9SDimitry Andric     RTLIBCASE_INT(UDIV_I);
4370b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
438e8d8bef9SDimitry Andric     RTLIBCASE_INT(SREM_I);
4390b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
440e8d8bef9SDimitry Andric     RTLIBCASE_INT(UREM_I);
4410b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
442e8d8bef9SDimitry Andric     RTLIBCASE_INT(CTLZ_I);
4430b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
4445ffd83dbSDimitry Andric     RTLIBCASE(ADD_F);
4450b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
4465ffd83dbSDimitry Andric     RTLIBCASE(SUB_F);
4470b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
4485ffd83dbSDimitry Andric     RTLIBCASE(MUL_F);
4490b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
4505ffd83dbSDimitry Andric     RTLIBCASE(DIV_F);
4510b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
4525ffd83dbSDimitry Andric     RTLIBCASE(EXP_F);
4530b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
4545ffd83dbSDimitry Andric     RTLIBCASE(EXP2_F);
4550b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
4565ffd83dbSDimitry Andric     RTLIBCASE(REM_F);
4570b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
4585ffd83dbSDimitry Andric     RTLIBCASE(POW_F);
4590b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
4605ffd83dbSDimitry Andric     RTLIBCASE(FMA_F);
4610b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
4625ffd83dbSDimitry Andric     RTLIBCASE(SIN_F);
4630b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
4645ffd83dbSDimitry Andric     RTLIBCASE(COS_F);
4650b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
4665ffd83dbSDimitry Andric     RTLIBCASE(LOG10_F);
4670b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
4685ffd83dbSDimitry Andric     RTLIBCASE(LOG_F);
4690b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
4705ffd83dbSDimitry Andric     RTLIBCASE(LOG2_F);
4710b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
4725ffd83dbSDimitry Andric     RTLIBCASE(CEIL_F);
4730b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
4745ffd83dbSDimitry Andric     RTLIBCASE(FLOOR_F);
4755ffd83dbSDimitry Andric   case TargetOpcode::G_FMINNUM:
4765ffd83dbSDimitry Andric     RTLIBCASE(FMIN_F);
4775ffd83dbSDimitry Andric   case TargetOpcode::G_FMAXNUM:
4785ffd83dbSDimitry Andric     RTLIBCASE(FMAX_F);
4795ffd83dbSDimitry Andric   case TargetOpcode::G_FSQRT:
4805ffd83dbSDimitry Andric     RTLIBCASE(SQRT_F);
4815ffd83dbSDimitry Andric   case TargetOpcode::G_FRINT:
4825ffd83dbSDimitry Andric     RTLIBCASE(RINT_F);
4835ffd83dbSDimitry Andric   case TargetOpcode::G_FNEARBYINT:
4845ffd83dbSDimitry Andric     RTLIBCASE(NEARBYINT_F);
485e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
486e8d8bef9SDimitry Andric     RTLIBCASE(ROUNDEVEN_F);
4870b57cec5SDimitry Andric   }
4880b57cec5SDimitry Andric   llvm_unreachable("Unknown libcall function");
4890b57cec5SDimitry Andric }
4900b57cec5SDimitry Andric 
4918bcb0991SDimitry Andric /// True if an instruction is in tail position in its caller. Intended for
4928bcb0991SDimitry Andric /// legalizing libcalls as tail calls when possible.
493e8d8bef9SDimitry Andric static bool isLibCallInTailPosition(const TargetInstrInfo &TII,
494e8d8bef9SDimitry Andric                                     MachineInstr &MI) {
4955ffd83dbSDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
4965ffd83dbSDimitry Andric   const Function &F = MBB.getParent()->getFunction();
4978bcb0991SDimitry Andric 
4988bcb0991SDimitry Andric   // Conservatively require the attributes of the call to match those of
4998bcb0991SDimitry Andric   // the return. Ignore NoAlias and NonNull because they don't affect the
5008bcb0991SDimitry Andric   // call sequence.
5018bcb0991SDimitry Andric   AttributeList CallerAttrs = F.getAttributes();
5028bcb0991SDimitry Andric   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
5038bcb0991SDimitry Andric           .removeAttribute(Attribute::NoAlias)
5048bcb0991SDimitry Andric           .removeAttribute(Attribute::NonNull)
5058bcb0991SDimitry Andric           .hasAttributes())
5068bcb0991SDimitry Andric     return false;
5078bcb0991SDimitry Andric 
5088bcb0991SDimitry Andric   // It's not safe to eliminate the sign / zero extension of the return value.
5098bcb0991SDimitry Andric   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
5108bcb0991SDimitry Andric       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
5118bcb0991SDimitry Andric     return false;
5128bcb0991SDimitry Andric 
5138bcb0991SDimitry Andric   // Only tail call if the following instruction is a standard return.
5145ffd83dbSDimitry Andric   auto Next = next_nodbg(MI.getIterator(), MBB.instr_end());
5155ffd83dbSDimitry Andric   if (Next == MBB.instr_end() || TII.isTailCall(*Next) || !Next->isReturn())
5168bcb0991SDimitry Andric     return false;
5178bcb0991SDimitry Andric 
5188bcb0991SDimitry Andric   return true;
5198bcb0991SDimitry Andric }
5208bcb0991SDimitry Andric 
5210b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
5225ffd83dbSDimitry Andric llvm::createLibcall(MachineIRBuilder &MIRBuilder, const char *Name,
5230b57cec5SDimitry Andric                     const CallLowering::ArgInfo &Result,
5245ffd83dbSDimitry Andric                     ArrayRef<CallLowering::ArgInfo> Args,
5255ffd83dbSDimitry Andric                     const CallingConv::ID CC) {
5260b57cec5SDimitry Andric   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
5270b57cec5SDimitry Andric 
5288bcb0991SDimitry Andric   CallLowering::CallLoweringInfo Info;
5295ffd83dbSDimitry Andric   Info.CallConv = CC;
5308bcb0991SDimitry Andric   Info.Callee = MachineOperand::CreateES(Name);
5318bcb0991SDimitry Andric   Info.OrigRet = Result;
5328bcb0991SDimitry Andric   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
5338bcb0991SDimitry Andric   if (!CLI.lowerCall(MIRBuilder, Info))
5340b57cec5SDimitry Andric     return LegalizerHelper::UnableToLegalize;
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric   return LegalizerHelper::Legalized;
5370b57cec5SDimitry Andric }
5380b57cec5SDimitry Andric 
5395ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
5405ffd83dbSDimitry Andric llvm::createLibcall(MachineIRBuilder &MIRBuilder, RTLIB::Libcall Libcall,
5415ffd83dbSDimitry Andric                     const CallLowering::ArgInfo &Result,
5425ffd83dbSDimitry Andric                     ArrayRef<CallLowering::ArgInfo> Args) {
5435ffd83dbSDimitry Andric   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
5445ffd83dbSDimitry Andric   const char *Name = TLI.getLibcallName(Libcall);
5455ffd83dbSDimitry Andric   const CallingConv::ID CC = TLI.getLibcallCallingConv(Libcall);
5465ffd83dbSDimitry Andric   return createLibcall(MIRBuilder, Name, Result, Args, CC);
5475ffd83dbSDimitry Andric }
5485ffd83dbSDimitry Andric 
5490b57cec5SDimitry Andric // Useful for libcalls where all operands have the same type.
5500b57cec5SDimitry Andric static LegalizerHelper::LegalizeResult
5510b57cec5SDimitry Andric simpleLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, unsigned Size,
5520b57cec5SDimitry Andric               Type *OpType) {
5530b57cec5SDimitry Andric   auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric   SmallVector<CallLowering::ArgInfo, 3> Args;
5560b57cec5SDimitry Andric   for (unsigned i = 1; i < MI.getNumOperands(); i++)
5570b57cec5SDimitry Andric     Args.push_back({MI.getOperand(i).getReg(), OpType});
5580b57cec5SDimitry Andric   return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), OpType},
5590b57cec5SDimitry Andric                        Args);
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric 
5628bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
5638bcb0991SDimitry Andric llvm::createMemLibcall(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
5648bcb0991SDimitry Andric                        MachineInstr &MI) {
5658bcb0991SDimitry Andric   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
5668bcb0991SDimitry Andric 
5678bcb0991SDimitry Andric   SmallVector<CallLowering::ArgInfo, 3> Args;
5688bcb0991SDimitry Andric   // Add all the args, except for the last which is an imm denoting 'tail'.
569e8d8bef9SDimitry Andric   for (unsigned i = 0; i < MI.getNumOperands() - 1; ++i) {
5708bcb0991SDimitry Andric     Register Reg = MI.getOperand(i).getReg();
5718bcb0991SDimitry Andric 
5728bcb0991SDimitry Andric     // Need derive an IR type for call lowering.
5738bcb0991SDimitry Andric     LLT OpLLT = MRI.getType(Reg);
5748bcb0991SDimitry Andric     Type *OpTy = nullptr;
5758bcb0991SDimitry Andric     if (OpLLT.isPointer())
5768bcb0991SDimitry Andric       OpTy = Type::getInt8PtrTy(Ctx, OpLLT.getAddressSpace());
5778bcb0991SDimitry Andric     else
5788bcb0991SDimitry Andric       OpTy = IntegerType::get(Ctx, OpLLT.getSizeInBits());
5798bcb0991SDimitry Andric     Args.push_back({Reg, OpTy});
5808bcb0991SDimitry Andric   }
5818bcb0991SDimitry Andric 
5828bcb0991SDimitry Andric   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
5838bcb0991SDimitry Andric   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
5848bcb0991SDimitry Andric   RTLIB::Libcall RTLibcall;
585e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
586e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
5878bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMCPY;
5888bcb0991SDimitry Andric     break;
589e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
5908bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMMOVE;
5918bcb0991SDimitry Andric     break;
592e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET:
593e8d8bef9SDimitry Andric     RTLibcall = RTLIB::MEMSET;
594e8d8bef9SDimitry Andric     break;
5958bcb0991SDimitry Andric   default:
5968bcb0991SDimitry Andric     return LegalizerHelper::UnableToLegalize;
5978bcb0991SDimitry Andric   }
5988bcb0991SDimitry Andric   const char *Name = TLI.getLibcallName(RTLibcall);
5998bcb0991SDimitry Andric 
6008bcb0991SDimitry Andric   CallLowering::CallLoweringInfo Info;
6018bcb0991SDimitry Andric   Info.CallConv = TLI.getLibcallCallingConv(RTLibcall);
6028bcb0991SDimitry Andric   Info.Callee = MachineOperand::CreateES(Name);
6038bcb0991SDimitry Andric   Info.OrigRet = CallLowering::ArgInfo({0}, Type::getVoidTy(Ctx));
604e8d8bef9SDimitry Andric   Info.IsTailCall = MI.getOperand(MI.getNumOperands() - 1).getImm() &&
605e8d8bef9SDimitry Andric                     isLibCallInTailPosition(MIRBuilder.getTII(), MI);
6068bcb0991SDimitry Andric 
6078bcb0991SDimitry Andric   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
6088bcb0991SDimitry Andric   if (!CLI.lowerCall(MIRBuilder, Info))
6098bcb0991SDimitry Andric     return LegalizerHelper::UnableToLegalize;
6108bcb0991SDimitry Andric 
6118bcb0991SDimitry Andric   if (Info.LoweredTailCall) {
6128bcb0991SDimitry Andric     assert(Info.IsTailCall && "Lowered tail call when it wasn't a tail call?");
6135ffd83dbSDimitry Andric     // We must have a return following the call (or debug insts) to get past
6148bcb0991SDimitry Andric     // isLibCallInTailPosition.
6155ffd83dbSDimitry Andric     do {
6165ffd83dbSDimitry Andric       MachineInstr *Next = MI.getNextNode();
6175ffd83dbSDimitry Andric       assert(Next && (Next->isReturn() || Next->isDebugInstr()) &&
6185ffd83dbSDimitry Andric              "Expected instr following MI to be return or debug inst?");
6198bcb0991SDimitry Andric       // We lowered a tail call, so the call is now the return from the block.
6208bcb0991SDimitry Andric       // Delete the old return.
6215ffd83dbSDimitry Andric       Next->eraseFromParent();
6225ffd83dbSDimitry Andric     } while (MI.getNextNode());
6238bcb0991SDimitry Andric   }
6248bcb0991SDimitry Andric 
6258bcb0991SDimitry Andric   return LegalizerHelper::Legalized;
6268bcb0991SDimitry Andric }
6278bcb0991SDimitry Andric 
6280b57cec5SDimitry Andric static RTLIB::Libcall getConvRTLibDesc(unsigned Opcode, Type *ToType,
6290b57cec5SDimitry Andric                                        Type *FromType) {
6300b57cec5SDimitry Andric   auto ToMVT = MVT::getVT(ToType);
6310b57cec5SDimitry Andric   auto FromMVT = MVT::getVT(FromType);
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   switch (Opcode) {
6340b57cec5SDimitry Andric   case TargetOpcode::G_FPEXT:
6350b57cec5SDimitry Andric     return RTLIB::getFPEXT(FromMVT, ToMVT);
6360b57cec5SDimitry Andric   case TargetOpcode::G_FPTRUNC:
6370b57cec5SDimitry Andric     return RTLIB::getFPROUND(FromMVT, ToMVT);
6380b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
6390b57cec5SDimitry Andric     return RTLIB::getFPTOSINT(FromMVT, ToMVT);
6400b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
6410b57cec5SDimitry Andric     return RTLIB::getFPTOUINT(FromMVT, ToMVT);
6420b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
6430b57cec5SDimitry Andric     return RTLIB::getSINTTOFP(FromMVT, ToMVT);
6440b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
6450b57cec5SDimitry Andric     return RTLIB::getUINTTOFP(FromMVT, ToMVT);
6460b57cec5SDimitry Andric   }
6470b57cec5SDimitry Andric   llvm_unreachable("Unsupported libcall function");
6480b57cec5SDimitry Andric }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric static LegalizerHelper::LegalizeResult
6510b57cec5SDimitry Andric conversionLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, Type *ToType,
6520b57cec5SDimitry Andric                   Type *FromType) {
6530b57cec5SDimitry Andric   RTLIB::Libcall Libcall = getConvRTLibDesc(MI.getOpcode(), ToType, FromType);
6540b57cec5SDimitry Andric   return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), ToType},
6550b57cec5SDimitry Andric                        {{MI.getOperand(1).getReg(), FromType}});
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
6590b57cec5SDimitry Andric LegalizerHelper::libcall(MachineInstr &MI) {
6600b57cec5SDimitry Andric   LLT LLTy = MRI.getType(MI.getOperand(0).getReg());
6610b57cec5SDimitry Andric   unsigned Size = LLTy.getSizeInBits();
6620b57cec5SDimitry Andric   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   switch (MI.getOpcode()) {
6650b57cec5SDimitry Andric   default:
6660b57cec5SDimitry Andric     return UnableToLegalize;
6670b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
6680b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
6690b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
6700b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
6710b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
6720b57cec5SDimitry Andric     Type *HLTy = IntegerType::get(Ctx, Size);
6730b57cec5SDimitry Andric     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
6740b57cec5SDimitry Andric     if (Status != Legalized)
6750b57cec5SDimitry Andric       return Status;
6760b57cec5SDimitry Andric     break;
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
6790b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
6800b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
6810b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
6820b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
6830b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
6840b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
6850b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
6860b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
6870b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
6880b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
6890b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
6900b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
6910b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
6920b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
6935ffd83dbSDimitry Andric   case TargetOpcode::G_FFLOOR:
6945ffd83dbSDimitry Andric   case TargetOpcode::G_FMINNUM:
6955ffd83dbSDimitry Andric   case TargetOpcode::G_FMAXNUM:
6965ffd83dbSDimitry Andric   case TargetOpcode::G_FSQRT:
6975ffd83dbSDimitry Andric   case TargetOpcode::G_FRINT:
698e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
699e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
7005ffd83dbSDimitry Andric     Type *HLTy = getFloatTypeForLLT(Ctx, LLTy);
701e8d8bef9SDimitry Andric     if (!HLTy || (Size != 32 && Size != 64 && Size != 80 && Size != 128)) {
702e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "No libcall available for type " << LLTy << ".\n");
7030b57cec5SDimitry Andric       return UnableToLegalize;
7040b57cec5SDimitry Andric     }
7050b57cec5SDimitry Andric     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
7060b57cec5SDimitry Andric     if (Status != Legalized)
7070b57cec5SDimitry Andric       return Status;
7080b57cec5SDimitry Andric     break;
7090b57cec5SDimitry Andric   }
7105ffd83dbSDimitry Andric   case TargetOpcode::G_FPEXT:
7110b57cec5SDimitry Andric   case TargetOpcode::G_FPTRUNC: {
7125ffd83dbSDimitry Andric     Type *FromTy = getFloatTypeForLLT(Ctx,  MRI.getType(MI.getOperand(1).getReg()));
7135ffd83dbSDimitry Andric     Type *ToTy = getFloatTypeForLLT(Ctx, MRI.getType(MI.getOperand(0).getReg()));
7145ffd83dbSDimitry Andric     if (!FromTy || !ToTy)
7150b57cec5SDimitry Andric       return UnableToLegalize;
7165ffd83dbSDimitry Andric     LegalizeResult Status = conversionLibcall(MI, MIRBuilder, ToTy, FromTy );
7170b57cec5SDimitry Andric     if (Status != Legalized)
7180b57cec5SDimitry Andric       return Status;
7190b57cec5SDimitry Andric     break;
7200b57cec5SDimitry Andric   }
7210b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
7220b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI: {
7230b57cec5SDimitry Andric     // FIXME: Support other types
7240b57cec5SDimitry Andric     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
7250b57cec5SDimitry Andric     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
7260b57cec5SDimitry Andric     if ((ToSize != 32 && ToSize != 64) || (FromSize != 32 && FromSize != 64))
7270b57cec5SDimitry Andric       return UnableToLegalize;
7280b57cec5SDimitry Andric     LegalizeResult Status = conversionLibcall(
7290b57cec5SDimitry Andric         MI, MIRBuilder,
7300b57cec5SDimitry Andric         ToSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx),
7310b57cec5SDimitry Andric         FromSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx));
7320b57cec5SDimitry Andric     if (Status != Legalized)
7330b57cec5SDimitry Andric       return Status;
7340b57cec5SDimitry Andric     break;
7350b57cec5SDimitry Andric   }
7360b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
7370b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP: {
7380b57cec5SDimitry Andric     // FIXME: Support other types
7390b57cec5SDimitry Andric     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
7400b57cec5SDimitry Andric     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
7410b57cec5SDimitry Andric     if ((FromSize != 32 && FromSize != 64) || (ToSize != 32 && ToSize != 64))
7420b57cec5SDimitry Andric       return UnableToLegalize;
7430b57cec5SDimitry Andric     LegalizeResult Status = conversionLibcall(
7440b57cec5SDimitry Andric         MI, MIRBuilder,
7450b57cec5SDimitry Andric         ToSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx),
7460b57cec5SDimitry Andric         FromSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx));
7470b57cec5SDimitry Andric     if (Status != Legalized)
7480b57cec5SDimitry Andric       return Status;
7490b57cec5SDimitry Andric     break;
7500b57cec5SDimitry Andric   }
751e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
752e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
753e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET: {
754e8d8bef9SDimitry Andric     LegalizeResult Result = createMemLibcall(MIRBuilder, *MIRBuilder.getMRI(), MI);
755e8d8bef9SDimitry Andric     MI.eraseFromParent();
756e8d8bef9SDimitry Andric     return Result;
757e8d8bef9SDimitry Andric   }
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   MI.eraseFromParent();
7610b57cec5SDimitry Andric   return Legalized;
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::narrowScalar(MachineInstr &MI,
7650b57cec5SDimitry Andric                                                               unsigned TypeIdx,
7660b57cec5SDimitry Andric                                                               LLT NarrowTy) {
7670b57cec5SDimitry Andric   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
7680b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   switch (MI.getOpcode()) {
7710b57cec5SDimitry Andric   default:
7720b57cec5SDimitry Andric     return UnableToLegalize;
7730b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
7745ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
7755ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
7765ffd83dbSDimitry Andric 
7775ffd83dbSDimitry Andric     // If SizeOp0 is not an exact multiple of NarrowSize, emit
7785ffd83dbSDimitry Andric     // G_ANYEXT(G_IMPLICIT_DEF). Cast result to vector if needed.
7795ffd83dbSDimitry Andric     // FIXME: Although this would also be legal for the general case, it causes
7805ffd83dbSDimitry Andric     //  a lot of regressions in the emitted code (superfluous COPYs, artifact
7815ffd83dbSDimitry Andric     //  combines not being hit). This seems to be a problem related to the
7825ffd83dbSDimitry Andric     //  artifact combiner.
7835ffd83dbSDimitry Andric     if (SizeOp0 % NarrowSize != 0) {
7845ffd83dbSDimitry Andric       LLT ImplicitTy = NarrowTy;
7855ffd83dbSDimitry Andric       if (DstTy.isVector())
7865ffd83dbSDimitry Andric         ImplicitTy = LLT::vector(DstTy.getNumElements(), ImplicitTy);
7875ffd83dbSDimitry Andric 
7885ffd83dbSDimitry Andric       Register ImplicitReg = MIRBuilder.buildUndef(ImplicitTy).getReg(0);
7895ffd83dbSDimitry Andric       MIRBuilder.buildAnyExt(DstReg, ImplicitReg);
7905ffd83dbSDimitry Andric 
7915ffd83dbSDimitry Andric       MI.eraseFromParent();
7925ffd83dbSDimitry Andric       return Legalized;
7935ffd83dbSDimitry Andric     }
7945ffd83dbSDimitry Andric 
7950b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric     SmallVector<Register, 2> DstRegs;
7980b57cec5SDimitry Andric     for (int i = 0; i < NumParts; ++i)
7995ffd83dbSDimitry Andric       DstRegs.push_back(MIRBuilder.buildUndef(NarrowTy).getReg(0));
8000b57cec5SDimitry Andric 
8015ffd83dbSDimitry Andric     if (DstTy.isVector())
8020b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, DstRegs);
8030b57cec5SDimitry Andric     else
8040b57cec5SDimitry Andric       MIRBuilder.buildMerge(DstReg, DstRegs);
8050b57cec5SDimitry Andric     MI.eraseFromParent();
8060b57cec5SDimitry Andric     return Legalized;
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
8090b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
8100b57cec5SDimitry Andric     const APInt &Val = MI.getOperand(1).getCImm()->getValue();
8110b57cec5SDimitry Andric     unsigned TotalSize = Ty.getSizeInBits();
8120b57cec5SDimitry Andric     unsigned NarrowSize = NarrowTy.getSizeInBits();
8130b57cec5SDimitry Andric     int NumParts = TotalSize / NarrowSize;
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric     SmallVector<Register, 4> PartRegs;
8160b57cec5SDimitry Andric     for (int I = 0; I != NumParts; ++I) {
8170b57cec5SDimitry Andric       unsigned Offset = I * NarrowSize;
8180b57cec5SDimitry Andric       auto K = MIRBuilder.buildConstant(NarrowTy,
8190b57cec5SDimitry Andric                                         Val.lshr(Offset).trunc(NarrowSize));
8200b57cec5SDimitry Andric       PartRegs.push_back(K.getReg(0));
8210b57cec5SDimitry Andric     }
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric     LLT LeftoverTy;
8240b57cec5SDimitry Andric     unsigned LeftoverBits = TotalSize - NumParts * NarrowSize;
8250b57cec5SDimitry Andric     SmallVector<Register, 1> LeftoverRegs;
8260b57cec5SDimitry Andric     if (LeftoverBits != 0) {
8270b57cec5SDimitry Andric       LeftoverTy = LLT::scalar(LeftoverBits);
8280b57cec5SDimitry Andric       auto K = MIRBuilder.buildConstant(
8290b57cec5SDimitry Andric         LeftoverTy,
8300b57cec5SDimitry Andric         Val.lshr(NumParts * NarrowSize).trunc(LeftoverBits));
8310b57cec5SDimitry Andric       LeftoverRegs.push_back(K.getReg(0));
8320b57cec5SDimitry Andric     }
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric     insertParts(MI.getOperand(0).getReg(),
8350b57cec5SDimitry Andric                 Ty, NarrowTy, PartRegs, LeftoverTy, LeftoverRegs);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric     MI.eraseFromParent();
8380b57cec5SDimitry Andric     return Legalized;
8390b57cec5SDimitry Andric   }
8405ffd83dbSDimitry Andric   case TargetOpcode::G_SEXT:
8415ffd83dbSDimitry Andric   case TargetOpcode::G_ZEXT:
8425ffd83dbSDimitry Andric   case TargetOpcode::G_ANYEXT:
8435ffd83dbSDimitry Andric     return narrowScalarExt(MI, TypeIdx, NarrowTy);
8448bcb0991SDimitry Andric   case TargetOpcode::G_TRUNC: {
8458bcb0991SDimitry Andric     if (TypeIdx != 1)
8468bcb0991SDimitry Andric       return UnableToLegalize;
8478bcb0991SDimitry Andric 
8488bcb0991SDimitry Andric     uint64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
8498bcb0991SDimitry Andric     if (NarrowTy.getSizeInBits() * 2 != SizeOp1) {
8508bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Can't narrow trunc to type " << NarrowTy << "\n");
8518bcb0991SDimitry Andric       return UnableToLegalize;
8528bcb0991SDimitry Andric     }
8538bcb0991SDimitry Andric 
8545ffd83dbSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
8555ffd83dbSDimitry Andric     MIRBuilder.buildCopy(MI.getOperand(0), Unmerge.getReg(0));
8568bcb0991SDimitry Andric     MI.eraseFromParent();
8578bcb0991SDimitry Andric     return Legalized;
8588bcb0991SDimitry Andric   }
8598bcb0991SDimitry Andric 
8605ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
8615ffd83dbSDimitry Andric     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
8625ffd83dbSDimitry Andric 
8630b57cec5SDimitry Andric   case TargetOpcode::G_ADD: {
8640b57cec5SDimitry Andric     // FIXME: add support for when SizeOp0 isn't an exact multiple of
8650b57cec5SDimitry Andric     // NarrowSize.
8660b57cec5SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
8670b57cec5SDimitry Andric       return UnableToLegalize;
8680b57cec5SDimitry Andric     // Expand in terms of carry-setting/consuming G_ADDE instructions.
8690b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowTy.getSizeInBits();
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric     SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
8720b57cec5SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
8730b57cec5SDimitry Andric     extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
8740b57cec5SDimitry Andric 
8758bcb0991SDimitry Andric     Register CarryIn;
8760b57cec5SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
8770b57cec5SDimitry Andric       Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
8780b57cec5SDimitry Andric       Register CarryOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
8790b57cec5SDimitry Andric 
8808bcb0991SDimitry Andric       if (i == 0)
8818bcb0991SDimitry Andric         MIRBuilder.buildUAddo(DstReg, CarryOut, Src1Regs[i], Src2Regs[i]);
8828bcb0991SDimitry Andric       else {
8830b57cec5SDimitry Andric         MIRBuilder.buildUAdde(DstReg, CarryOut, Src1Regs[i],
8840b57cec5SDimitry Andric                               Src2Regs[i], CarryIn);
8858bcb0991SDimitry Andric       }
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric       DstRegs.push_back(DstReg);
8880b57cec5SDimitry Andric       CarryIn = CarryOut;
8890b57cec5SDimitry Andric     }
8900b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
8910b57cec5SDimitry Andric     if(MRI.getType(DstReg).isVector())
8920b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, DstRegs);
8930b57cec5SDimitry Andric     else
8940b57cec5SDimitry Andric       MIRBuilder.buildMerge(DstReg, DstRegs);
8950b57cec5SDimitry Andric     MI.eraseFromParent();
8960b57cec5SDimitry Andric     return Legalized;
8970b57cec5SDimitry Andric   }
8980b57cec5SDimitry Andric   case TargetOpcode::G_SUB: {
8990b57cec5SDimitry Andric     // FIXME: add support for when SizeOp0 isn't an exact multiple of
9000b57cec5SDimitry Andric     // NarrowSize.
9010b57cec5SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
9020b57cec5SDimitry Andric       return UnableToLegalize;
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowTy.getSizeInBits();
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric     SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
9070b57cec5SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
9080b57cec5SDimitry Andric     extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
9110b57cec5SDimitry Andric     Register BorrowOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
9120b57cec5SDimitry Andric     MIRBuilder.buildInstr(TargetOpcode::G_USUBO, {DstReg, BorrowOut},
9130b57cec5SDimitry Andric                           {Src1Regs[0], Src2Regs[0]});
9140b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
9150b57cec5SDimitry Andric     Register BorrowIn = BorrowOut;
9160b57cec5SDimitry Andric     for (int i = 1; i < NumParts; ++i) {
9170b57cec5SDimitry Andric       DstReg = MRI.createGenericVirtualRegister(NarrowTy);
9180b57cec5SDimitry Andric       BorrowOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric       MIRBuilder.buildInstr(TargetOpcode::G_USUBE, {DstReg, BorrowOut},
9210b57cec5SDimitry Andric                             {Src1Regs[i], Src2Regs[i], BorrowIn});
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric       DstRegs.push_back(DstReg);
9240b57cec5SDimitry Andric       BorrowIn = BorrowOut;
9250b57cec5SDimitry Andric     }
9265ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
9270b57cec5SDimitry Andric     MI.eraseFromParent();
9280b57cec5SDimitry Andric     return Legalized;
9290b57cec5SDimitry Andric   }
9300b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
9310b57cec5SDimitry Andric   case TargetOpcode::G_UMULH:
9320b57cec5SDimitry Andric     return narrowScalarMul(MI, NarrowTy);
9330b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
9340b57cec5SDimitry Andric     return narrowScalarExtract(MI, TypeIdx, NarrowTy);
9350b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
9360b57cec5SDimitry Andric     return narrowScalarInsert(MI, TypeIdx, NarrowTy);
9370b57cec5SDimitry Andric   case TargetOpcode::G_LOAD: {
938e8d8bef9SDimitry Andric     auto &MMO = **MI.memoperands_begin();
9390b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
9400b57cec5SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
9410b57cec5SDimitry Andric     if (DstTy.isVector())
9420b57cec5SDimitry Andric       return UnableToLegalize;
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric     if (8 * MMO.getSize() != DstTy.getSizeInBits()) {
9450b57cec5SDimitry Andric       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
9465ffd83dbSDimitry Andric       MIRBuilder.buildLoad(TmpReg, MI.getOperand(1), MMO);
9470b57cec5SDimitry Andric       MIRBuilder.buildAnyExt(DstReg, TmpReg);
9480b57cec5SDimitry Andric       MI.eraseFromParent();
9490b57cec5SDimitry Andric       return Legalized;
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
9530b57cec5SDimitry Andric   }
9540b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
9550b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD: {
9560b57cec5SDimitry Andric     bool ZExt = MI.getOpcode() == TargetOpcode::G_ZEXTLOAD;
9570b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
9580b57cec5SDimitry Andric     Register PtrReg = MI.getOperand(1).getReg();
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric     Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
9610b57cec5SDimitry Andric     auto &MMO = **MI.memoperands_begin();
962e8d8bef9SDimitry Andric     unsigned MemSize = MMO.getSizeInBits();
963e8d8bef9SDimitry Andric 
964e8d8bef9SDimitry Andric     if (MemSize == NarrowSize) {
9650b57cec5SDimitry Andric       MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
966e8d8bef9SDimitry Andric     } else if (MemSize < NarrowSize) {
9675ffd83dbSDimitry Andric       MIRBuilder.buildLoadInstr(MI.getOpcode(), TmpReg, PtrReg, MMO);
968e8d8bef9SDimitry Andric     } else if (MemSize > NarrowSize) {
969e8d8bef9SDimitry Andric       // FIXME: Need to split the load.
970e8d8bef9SDimitry Andric       return UnableToLegalize;
9710b57cec5SDimitry Andric     }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric     if (ZExt)
9740b57cec5SDimitry Andric       MIRBuilder.buildZExt(DstReg, TmpReg);
9750b57cec5SDimitry Andric     else
9760b57cec5SDimitry Andric       MIRBuilder.buildSExt(DstReg, TmpReg);
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric     MI.eraseFromParent();
9790b57cec5SDimitry Andric     return Legalized;
9800b57cec5SDimitry Andric   }
9810b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
9820b57cec5SDimitry Andric     const auto &MMO = **MI.memoperands_begin();
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(0).getReg();
9850b57cec5SDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
9860b57cec5SDimitry Andric     if (SrcTy.isVector())
9870b57cec5SDimitry Andric       return UnableToLegalize;
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
9900b57cec5SDimitry Andric     unsigned HandledSize = NumParts * NarrowTy.getSizeInBits();
9910b57cec5SDimitry Andric     unsigned LeftoverBits = SrcTy.getSizeInBits() - HandledSize;
9920b57cec5SDimitry Andric     if (SrcTy.isVector() && LeftoverBits != 0)
9930b57cec5SDimitry Andric       return UnableToLegalize;
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric     if (8 * MMO.getSize() != SrcTy.getSizeInBits()) {
9960b57cec5SDimitry Andric       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
9970b57cec5SDimitry Andric       auto &MMO = **MI.memoperands_begin();
9980b57cec5SDimitry Andric       MIRBuilder.buildTrunc(TmpReg, SrcReg);
9995ffd83dbSDimitry Andric       MIRBuilder.buildStore(TmpReg, MI.getOperand(1), MMO);
10000b57cec5SDimitry Andric       MI.eraseFromParent();
10010b57cec5SDimitry Andric       return Legalized;
10020b57cec5SDimitry Andric     }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric     return reduceLoadStoreWidth(MI, 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: {
11080b57cec5SDimitry Andric     uint64_t SrcSize = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
11090b57cec5SDimitry Andric     if (NarrowSize * 2 != SrcSize)
11100b57cec5SDimitry Andric       return UnableToLegalize;
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric     Observer.changingInstr(MI);
11130b57cec5SDimitry Andric     Register LHSL = MRI.createGenericVirtualRegister(NarrowTy);
11140b57cec5SDimitry Andric     Register LHSH = MRI.createGenericVirtualRegister(NarrowTy);
11155ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge({LHSL, LHSH}, MI.getOperand(2));
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric     Register RHSL = MRI.createGenericVirtualRegister(NarrowTy);
11180b57cec5SDimitry Andric     Register RHSH = MRI.createGenericVirtualRegister(NarrowTy);
11195ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge({RHSL, RHSH}, MI.getOperand(3));
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric     CmpInst::Predicate Pred =
11220b57cec5SDimitry Andric         static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
11238bcb0991SDimitry Andric     LLT ResTy = MRI.getType(MI.getOperand(0).getReg());
11240b57cec5SDimitry Andric 
11250b57cec5SDimitry Andric     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
11260b57cec5SDimitry Andric       MachineInstrBuilder XorL = MIRBuilder.buildXor(NarrowTy, LHSL, RHSL);
11270b57cec5SDimitry Andric       MachineInstrBuilder XorH = MIRBuilder.buildXor(NarrowTy, LHSH, RHSH);
11280b57cec5SDimitry Andric       MachineInstrBuilder Or = MIRBuilder.buildOr(NarrowTy, XorL, XorH);
11290b57cec5SDimitry Andric       MachineInstrBuilder Zero = MIRBuilder.buildConstant(NarrowTy, 0);
11305ffd83dbSDimitry Andric       MIRBuilder.buildICmp(Pred, MI.getOperand(0), Or, Zero);
11310b57cec5SDimitry Andric     } else {
11328bcb0991SDimitry Andric       MachineInstrBuilder CmpH = MIRBuilder.buildICmp(Pred, ResTy, LHSH, RHSH);
11330b57cec5SDimitry Andric       MachineInstrBuilder CmpHEQ =
11348bcb0991SDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, ResTy, LHSH, RHSH);
11350b57cec5SDimitry Andric       MachineInstrBuilder CmpLU = MIRBuilder.buildICmp(
11368bcb0991SDimitry Andric           ICmpInst::getUnsignedPredicate(Pred), ResTy, LHSL, RHSL);
11375ffd83dbSDimitry Andric       MIRBuilder.buildSelect(MI.getOperand(0), CmpHEQ, CmpLU, CmpH);
11380b57cec5SDimitry Andric     }
11390b57cec5SDimitry Andric     Observer.changedInstr(MI);
11400b57cec5SDimitry Andric     MI.eraseFromParent();
11410b57cec5SDimitry Andric     return Legalized;
11420b57cec5SDimitry Andric   }
11438bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
11448bcb0991SDimitry Andric     if (TypeIdx != 0)
11458bcb0991SDimitry Andric       return UnableToLegalize;
11468bcb0991SDimitry Andric 
11478bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
11488bcb0991SDimitry Andric 
11498bcb0991SDimitry Andric     // So long as the new type has more bits than the bits we're extending we
11508bcb0991SDimitry Andric     // don't need to break it apart.
11518bcb0991SDimitry Andric     if (NarrowTy.getScalarSizeInBits() >= SizeInBits) {
11528bcb0991SDimitry Andric       Observer.changingInstr(MI);
11538bcb0991SDimitry Andric       // We don't lose any non-extension bits by truncating the src and
11548bcb0991SDimitry Andric       // sign-extending the dst.
11558bcb0991SDimitry Andric       MachineOperand &MO1 = MI.getOperand(1);
11565ffd83dbSDimitry Andric       auto TruncMIB = MIRBuilder.buildTrunc(NarrowTy, MO1);
11575ffd83dbSDimitry Andric       MO1.setReg(TruncMIB.getReg(0));
11588bcb0991SDimitry Andric 
11598bcb0991SDimitry Andric       MachineOperand &MO2 = MI.getOperand(0);
11608bcb0991SDimitry Andric       Register DstExt = MRI.createGenericVirtualRegister(NarrowTy);
11618bcb0991SDimitry Andric       MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
11625ffd83dbSDimitry Andric       MIRBuilder.buildSExt(MO2, DstExt);
11638bcb0991SDimitry Andric       MO2.setReg(DstExt);
11648bcb0991SDimitry Andric       Observer.changedInstr(MI);
11658bcb0991SDimitry Andric       return Legalized;
11668bcb0991SDimitry Andric     }
11678bcb0991SDimitry Andric 
11688bcb0991SDimitry Andric     // Break it apart. Components below the extension point are unmodified. The
11698bcb0991SDimitry Andric     // component containing the extension point becomes a narrower SEXT_INREG.
11708bcb0991SDimitry Andric     // Components above it are ashr'd from the component containing the
11718bcb0991SDimitry Andric     // extension point.
11728bcb0991SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
11738bcb0991SDimitry Andric       return UnableToLegalize;
11748bcb0991SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
11758bcb0991SDimitry Andric 
11768bcb0991SDimitry Andric     // List the registers where the destination will be scattered.
11778bcb0991SDimitry Andric     SmallVector<Register, 2> DstRegs;
11788bcb0991SDimitry Andric     // List the registers where the source will be split.
11798bcb0991SDimitry Andric     SmallVector<Register, 2> SrcRegs;
11808bcb0991SDimitry Andric 
11818bcb0991SDimitry Andric     // Create all the temporary registers.
11828bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
11838bcb0991SDimitry Andric       Register SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
11848bcb0991SDimitry Andric 
11858bcb0991SDimitry Andric       SrcRegs.push_back(SrcReg);
11868bcb0991SDimitry Andric     }
11878bcb0991SDimitry Andric 
11888bcb0991SDimitry Andric     // Explode the big arguments into smaller chunks.
11895ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge(SrcRegs, MI.getOperand(1));
11908bcb0991SDimitry Andric 
11918bcb0991SDimitry Andric     Register AshrCstReg =
11928bcb0991SDimitry Andric         MIRBuilder.buildConstant(NarrowTy, NarrowTy.getScalarSizeInBits() - 1)
11935ffd83dbSDimitry Andric             .getReg(0);
11948bcb0991SDimitry Andric     Register FullExtensionReg = 0;
11958bcb0991SDimitry Andric     Register PartialExtensionReg = 0;
11968bcb0991SDimitry Andric 
11978bcb0991SDimitry Andric     // Do the operation on each small part.
11988bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
11998bcb0991SDimitry Andric       if ((i + 1) * NarrowTy.getScalarSizeInBits() < SizeInBits)
12008bcb0991SDimitry Andric         DstRegs.push_back(SrcRegs[i]);
12018bcb0991SDimitry Andric       else if (i * NarrowTy.getScalarSizeInBits() > SizeInBits) {
12028bcb0991SDimitry Andric         assert(PartialExtensionReg &&
12038bcb0991SDimitry Andric                "Expected to visit partial extension before full");
12048bcb0991SDimitry Andric         if (FullExtensionReg) {
12058bcb0991SDimitry Andric           DstRegs.push_back(FullExtensionReg);
12068bcb0991SDimitry Andric           continue;
12078bcb0991SDimitry Andric         }
12085ffd83dbSDimitry Andric         DstRegs.push_back(
12095ffd83dbSDimitry Andric             MIRBuilder.buildAShr(NarrowTy, PartialExtensionReg, AshrCstReg)
12105ffd83dbSDimitry Andric                 .getReg(0));
12118bcb0991SDimitry Andric         FullExtensionReg = DstRegs.back();
12128bcb0991SDimitry Andric       } else {
12138bcb0991SDimitry Andric         DstRegs.push_back(
12148bcb0991SDimitry Andric             MIRBuilder
12158bcb0991SDimitry Andric                 .buildInstr(
12168bcb0991SDimitry Andric                     TargetOpcode::G_SEXT_INREG, {NarrowTy},
12178bcb0991SDimitry Andric                     {SrcRegs[i], SizeInBits % NarrowTy.getScalarSizeInBits()})
12185ffd83dbSDimitry Andric                 .getReg(0));
12198bcb0991SDimitry Andric         PartialExtensionReg = DstRegs.back();
12208bcb0991SDimitry Andric       }
12218bcb0991SDimitry Andric     }
12228bcb0991SDimitry Andric 
12238bcb0991SDimitry Andric     // Gather the destination registers into the final destination.
12248bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
12258bcb0991SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
12268bcb0991SDimitry Andric     MI.eraseFromParent();
12278bcb0991SDimitry Andric     return Legalized;
12288bcb0991SDimitry Andric   }
1229480093f4SDimitry Andric   case TargetOpcode::G_BSWAP:
1230480093f4SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
1231480093f4SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
1232480093f4SDimitry Andric       return UnableToLegalize;
1233480093f4SDimitry Andric 
1234480093f4SDimitry Andric     Observer.changingInstr(MI);
1235480093f4SDimitry Andric     SmallVector<Register, 2> SrcRegs, DstRegs;
1236480093f4SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
1237480093f4SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
1238480093f4SDimitry Andric 
1239480093f4SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
1240480093f4SDimitry Andric       auto DstPart = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
1241480093f4SDimitry Andric                                            {SrcRegs[NumParts - 1 - i]});
1242480093f4SDimitry Andric       DstRegs.push_back(DstPart.getReg(0));
1243480093f4SDimitry Andric     }
1244480093f4SDimitry Andric 
12455ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
1246480093f4SDimitry Andric 
1247480093f4SDimitry Andric     Observer.changedInstr(MI);
1248480093f4SDimitry Andric     MI.eraseFromParent();
1249480093f4SDimitry Andric     return Legalized;
1250480093f4SDimitry Andric   }
1251e8d8bef9SDimitry Andric   case TargetOpcode::G_PTR_ADD:
12525ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
12535ffd83dbSDimitry Andric     if (TypeIdx != 1)
12545ffd83dbSDimitry Andric       return UnableToLegalize;
12555ffd83dbSDimitry Andric     Observer.changingInstr(MI);
12565ffd83dbSDimitry Andric     narrowScalarSrc(MI, NarrowTy, 2);
12575ffd83dbSDimitry Andric     Observer.changedInstr(MI);
12585ffd83dbSDimitry Andric     return Legalized;
12590b57cec5SDimitry Andric   }
1260*23408297SDimitry Andric   case TargetOpcode::G_FPTOUI:
1261*23408297SDimitry Andric   case TargetOpcode::G_FPTOSI:
1262*23408297SDimitry Andric     return narrowScalarFPTOI(MI, TypeIdx, NarrowTy);
1263e8d8bef9SDimitry Andric   case TargetOpcode::G_FPEXT:
1264e8d8bef9SDimitry Andric     if (TypeIdx != 0)
1265e8d8bef9SDimitry Andric       return UnableToLegalize;
1266e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
1267e8d8bef9SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_FPEXT);
1268e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
1269e8d8bef9SDimitry Andric     return Legalized;
12700b57cec5SDimitry Andric   }
12715ffd83dbSDimitry Andric }
12725ffd83dbSDimitry Andric 
12735ffd83dbSDimitry Andric Register LegalizerHelper::coerceToScalar(Register Val) {
12745ffd83dbSDimitry Andric   LLT Ty = MRI.getType(Val);
12755ffd83dbSDimitry Andric   if (Ty.isScalar())
12765ffd83dbSDimitry Andric     return Val;
12775ffd83dbSDimitry Andric 
12785ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
12795ffd83dbSDimitry Andric   LLT NewTy = LLT::scalar(Ty.getSizeInBits());
12805ffd83dbSDimitry Andric   if (Ty.isPointer()) {
12815ffd83dbSDimitry Andric     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
12825ffd83dbSDimitry Andric       return Register();
12835ffd83dbSDimitry Andric     return MIRBuilder.buildPtrToInt(NewTy, Val).getReg(0);
12845ffd83dbSDimitry Andric   }
12855ffd83dbSDimitry Andric 
12865ffd83dbSDimitry Andric   Register NewVal = Val;
12875ffd83dbSDimitry Andric 
12885ffd83dbSDimitry Andric   assert(Ty.isVector());
12895ffd83dbSDimitry Andric   LLT EltTy = Ty.getElementType();
12905ffd83dbSDimitry Andric   if (EltTy.isPointer())
12915ffd83dbSDimitry Andric     NewVal = MIRBuilder.buildPtrToInt(NewTy, NewVal).getReg(0);
12925ffd83dbSDimitry Andric   return MIRBuilder.buildBitcast(NewTy, NewVal).getReg(0);
12935ffd83dbSDimitry Andric }
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric void LegalizerHelper::widenScalarSrc(MachineInstr &MI, LLT WideTy,
12960b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned ExtOpcode) {
12970b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
12985ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MO});
12995ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
13000b57cec5SDimitry Andric }
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric void LegalizerHelper::narrowScalarSrc(MachineInstr &MI, LLT NarrowTy,
13030b57cec5SDimitry Andric                                       unsigned OpIdx) {
13040b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13055ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildTrunc(NarrowTy, MO);
13065ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
13070b57cec5SDimitry Andric }
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric void LegalizerHelper::widenScalarDst(MachineInstr &MI, LLT WideTy,
13100b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned TruncOpcode) {
13110b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13120b57cec5SDimitry Andric   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
13130b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13145ffd83dbSDimitry Andric   MIRBuilder.buildInstr(TruncOpcode, {MO}, {DstExt});
13150b57cec5SDimitry Andric   MO.setReg(DstExt);
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric void LegalizerHelper::narrowScalarDst(MachineInstr &MI, LLT NarrowTy,
13190b57cec5SDimitry Andric                                       unsigned OpIdx, unsigned ExtOpcode) {
13200b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13210b57cec5SDimitry Andric   Register DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
13220b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13235ffd83dbSDimitry Andric   MIRBuilder.buildInstr(ExtOpcode, {MO}, {DstTrunc});
13240b57cec5SDimitry Andric   MO.setReg(DstTrunc);
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorDst(MachineInstr &MI, LLT WideTy,
13280b57cec5SDimitry Andric                                             unsigned OpIdx) {
13290b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13300b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1331e8d8bef9SDimitry Andric   MO.setReg(widenWithUnmerge(WideTy, MO.getReg()));
13320b57cec5SDimitry Andric }
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorSrc(MachineInstr &MI, LLT MoreTy,
13350b57cec5SDimitry Andric                                             unsigned OpIdx) {
13360b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric   LLT OldTy = MRI.getType(MO.getReg());
13390b57cec5SDimitry Andric   unsigned OldElts = OldTy.getNumElements();
13400b57cec5SDimitry Andric   unsigned NewElts = MoreTy.getNumElements();
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric   unsigned NumParts = NewElts / OldElts;
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric   // Use concat_vectors if the result is a multiple of the number of elements.
13450b57cec5SDimitry Andric   if (NumParts * OldElts == NewElts) {
13460b57cec5SDimitry Andric     SmallVector<Register, 8> Parts;
13470b57cec5SDimitry Andric     Parts.push_back(MO.getReg());
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric     Register ImpDef = MIRBuilder.buildUndef(OldTy).getReg(0);
13500b57cec5SDimitry Andric     for (unsigned I = 1; I != NumParts; ++I)
13510b57cec5SDimitry Andric       Parts.push_back(ImpDef);
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric     auto Concat = MIRBuilder.buildConcatVectors(MoreTy, Parts);
13540b57cec5SDimitry Andric     MO.setReg(Concat.getReg(0));
13550b57cec5SDimitry Andric     return;
13560b57cec5SDimitry Andric   }
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric   Register MoreReg = MRI.createGenericVirtualRegister(MoreTy);
13590b57cec5SDimitry Andric   Register ImpDef = MIRBuilder.buildUndef(MoreTy).getReg(0);
13600b57cec5SDimitry Andric   MIRBuilder.buildInsert(MoreReg, ImpDef, MO.getReg(), 0);
13610b57cec5SDimitry Andric   MO.setReg(MoreReg);
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric 
13645ffd83dbSDimitry Andric void LegalizerHelper::bitcastSrc(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
13655ffd83dbSDimitry Andric   MachineOperand &Op = MI.getOperand(OpIdx);
13665ffd83dbSDimitry Andric   Op.setReg(MIRBuilder.buildBitcast(CastTy, Op).getReg(0));
13675ffd83dbSDimitry Andric }
13685ffd83dbSDimitry Andric 
13695ffd83dbSDimitry Andric void LegalizerHelper::bitcastDst(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
13705ffd83dbSDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13715ffd83dbSDimitry Andric   Register CastDst = MRI.createGenericVirtualRegister(CastTy);
13725ffd83dbSDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13735ffd83dbSDimitry Andric   MIRBuilder.buildBitcast(MO, CastDst);
13745ffd83dbSDimitry Andric   MO.setReg(CastDst);
13755ffd83dbSDimitry Andric }
13765ffd83dbSDimitry Andric 
13770b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
13780b57cec5SDimitry Andric LegalizerHelper::widenScalarMergeValues(MachineInstr &MI, unsigned TypeIdx,
13790b57cec5SDimitry Andric                                         LLT WideTy) {
13800b57cec5SDimitry Andric   if (TypeIdx != 1)
13810b57cec5SDimitry Andric     return UnableToLegalize;
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
13840b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
13850b57cec5SDimitry Andric   if (DstTy.isVector())
13860b57cec5SDimitry Andric     return UnableToLegalize;
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
13890b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src1);
13900b57cec5SDimitry Andric   const int DstSize = DstTy.getSizeInBits();
13910b57cec5SDimitry Andric   const int SrcSize = SrcTy.getSizeInBits();
13920b57cec5SDimitry Andric   const int WideSize = WideTy.getSizeInBits();
13930b57cec5SDimitry Andric   const int NumMerge = (DstSize + WideSize - 1) / WideSize;
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric   unsigned NumOps = MI.getNumOperands();
13960b57cec5SDimitry Andric   unsigned NumSrc = MI.getNumOperands() - 1;
13970b57cec5SDimitry Andric   unsigned PartSize = DstTy.getSizeInBits() / NumSrc;
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric   if (WideSize >= DstSize) {
14000b57cec5SDimitry Andric     // Directly pack the bits in the target type.
14010b57cec5SDimitry Andric     Register ResultReg = MIRBuilder.buildZExt(WideTy, Src1).getReg(0);
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric     for (unsigned I = 2; I != NumOps; ++I) {
14040b57cec5SDimitry Andric       const unsigned Offset = (I - 1) * PartSize;
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric       Register SrcReg = MI.getOperand(I).getReg();
14070b57cec5SDimitry Andric       assert(MRI.getType(SrcReg) == LLT::scalar(PartSize));
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric       auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
14100b57cec5SDimitry Andric 
14118bcb0991SDimitry Andric       Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
14120b57cec5SDimitry Andric         MRI.createGenericVirtualRegister(WideTy);
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
14150b57cec5SDimitry Andric       auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
14160b57cec5SDimitry Andric       MIRBuilder.buildOr(NextResult, ResultReg, Shl);
14170b57cec5SDimitry Andric       ResultReg = NextResult;
14180b57cec5SDimitry Andric     }
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric     if (WideSize > DstSize)
14210b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg, ResultReg);
14228bcb0991SDimitry Andric     else if (DstTy.isPointer())
14238bcb0991SDimitry Andric       MIRBuilder.buildIntToPtr(DstReg, ResultReg);
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric     MI.eraseFromParent();
14260b57cec5SDimitry Andric     return Legalized;
14270b57cec5SDimitry Andric   }
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric   // Unmerge the original values to the GCD type, and recombine to the next
14300b57cec5SDimitry Andric   // multiple greater than the original type.
14310b57cec5SDimitry Andric   //
14320b57cec5SDimitry Andric   // %3:_(s12) = G_MERGE_VALUES %0:_(s4), %1:_(s4), %2:_(s4) -> s6
14330b57cec5SDimitry Andric   // %4:_(s2), %5:_(s2) = G_UNMERGE_VALUES %0
14340b57cec5SDimitry Andric   // %6:_(s2), %7:_(s2) = G_UNMERGE_VALUES %1
14350b57cec5SDimitry Andric   // %8:_(s2), %9:_(s2) = G_UNMERGE_VALUES %2
14360b57cec5SDimitry Andric   // %10:_(s6) = G_MERGE_VALUES %4, %5, %6
14370b57cec5SDimitry Andric   // %11:_(s6) = G_MERGE_VALUES %7, %8, %9
14380b57cec5SDimitry Andric   // %12:_(s12) = G_MERGE_VALUES %10, %11
14390b57cec5SDimitry Andric   //
14400b57cec5SDimitry Andric   // Padding with undef if necessary:
14410b57cec5SDimitry Andric   //
14420b57cec5SDimitry Andric   // %2:_(s8) = G_MERGE_VALUES %0:_(s4), %1:_(s4) -> s6
14430b57cec5SDimitry Andric   // %3:_(s2), %4:_(s2) = G_UNMERGE_VALUES %0
14440b57cec5SDimitry Andric   // %5:_(s2), %6:_(s2) = G_UNMERGE_VALUES %1
14450b57cec5SDimitry Andric   // %7:_(s2) = G_IMPLICIT_DEF
14460b57cec5SDimitry Andric   // %8:_(s6) = G_MERGE_VALUES %3, %4, %5
14470b57cec5SDimitry Andric   // %9:_(s6) = G_MERGE_VALUES %6, %7, %7
14480b57cec5SDimitry Andric   // %10:_(s12) = G_MERGE_VALUES %8, %9
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   const int GCD = greatestCommonDivisor(SrcSize, WideSize);
14510b57cec5SDimitry Andric   LLT GCDTy = LLT::scalar(GCD);
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   SmallVector<Register, 8> Parts;
14540b57cec5SDimitry Andric   SmallVector<Register, 8> NewMergeRegs;
14550b57cec5SDimitry Andric   SmallVector<Register, 8> Unmerges;
14560b57cec5SDimitry Andric   LLT WideDstTy = LLT::scalar(NumMerge * WideSize);
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   // Decompose the original operands if they don't evenly divide.
14590b57cec5SDimitry Andric   for (int I = 1, E = MI.getNumOperands(); I != E; ++I) {
14600b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
14610b57cec5SDimitry Andric     if (GCD == SrcSize) {
14620b57cec5SDimitry Andric       Unmerges.push_back(SrcReg);
14630b57cec5SDimitry Andric     } else {
14640b57cec5SDimitry Andric       auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
14650b57cec5SDimitry Andric       for (int J = 0, JE = Unmerge->getNumOperands() - 1; J != JE; ++J)
14660b57cec5SDimitry Andric         Unmerges.push_back(Unmerge.getReg(J));
14670b57cec5SDimitry Andric     }
14680b57cec5SDimitry Andric   }
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   // Pad with undef to the next size that is a multiple of the requested size.
14710b57cec5SDimitry Andric   if (static_cast<int>(Unmerges.size()) != NumMerge * WideSize) {
14720b57cec5SDimitry Andric     Register UndefReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
14730b57cec5SDimitry Andric     for (int I = Unmerges.size(); I != NumMerge * WideSize; ++I)
14740b57cec5SDimitry Andric       Unmerges.push_back(UndefReg);
14750b57cec5SDimitry Andric   }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   const int PartsPerGCD = WideSize / GCD;
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   // Build merges of each piece.
14800b57cec5SDimitry Andric   ArrayRef<Register> Slicer(Unmerges);
14810b57cec5SDimitry Andric   for (int I = 0; I != NumMerge; ++I, Slicer = Slicer.drop_front(PartsPerGCD)) {
14820b57cec5SDimitry Andric     auto Merge = MIRBuilder.buildMerge(WideTy, Slicer.take_front(PartsPerGCD));
14830b57cec5SDimitry Andric     NewMergeRegs.push_back(Merge.getReg(0));
14840b57cec5SDimitry Andric   }
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   // A truncate may be necessary if the requested type doesn't evenly divide the
14870b57cec5SDimitry Andric   // original result type.
14880b57cec5SDimitry Andric   if (DstTy.getSizeInBits() == WideDstTy.getSizeInBits()) {
14890b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, NewMergeRegs);
14900b57cec5SDimitry Andric   } else {
14910b57cec5SDimitry Andric     auto FinalMerge = MIRBuilder.buildMerge(WideDstTy, NewMergeRegs);
14920b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, FinalMerge.getReg(0));
14930b57cec5SDimitry Andric   }
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   MI.eraseFromParent();
14960b57cec5SDimitry Andric   return Legalized;
14970b57cec5SDimitry Andric }
14980b57cec5SDimitry Andric 
1499e8d8bef9SDimitry Andric Register LegalizerHelper::widenWithUnmerge(LLT WideTy, Register OrigReg) {
1500e8d8bef9SDimitry Andric   Register WideReg = MRI.createGenericVirtualRegister(WideTy);
1501e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(OrigReg);
1502e8d8bef9SDimitry Andric   LLT LCMTy = getLCMType(WideTy, OrigTy);
1503e8d8bef9SDimitry Andric 
1504e8d8bef9SDimitry Andric   const int NumMergeParts = LCMTy.getSizeInBits() / WideTy.getSizeInBits();
1505e8d8bef9SDimitry Andric   const int NumUnmergeParts = LCMTy.getSizeInBits() / OrigTy.getSizeInBits();
1506e8d8bef9SDimitry Andric 
1507e8d8bef9SDimitry Andric   Register UnmergeSrc = WideReg;
1508e8d8bef9SDimitry Andric 
1509e8d8bef9SDimitry Andric   // Create a merge to the LCM type, padding with undef
1510e8d8bef9SDimitry Andric   // %0:_(<3 x s32>) = G_FOO => <4 x s32>
1511e8d8bef9SDimitry Andric   // =>
1512e8d8bef9SDimitry Andric   // %1:_(<4 x s32>) = G_FOO
1513e8d8bef9SDimitry Andric   // %2:_(<4 x s32>) = G_IMPLICIT_DEF
1514e8d8bef9SDimitry Andric   // %3:_(<12 x s32>) = G_CONCAT_VECTORS %1, %2, %2
1515e8d8bef9SDimitry Andric   // %0:_(<3 x s32>), %4:_, %5:_, %6:_ = G_UNMERGE_VALUES %3
1516e8d8bef9SDimitry Andric   if (NumMergeParts > 1) {
1517e8d8bef9SDimitry Andric     Register Undef = MIRBuilder.buildUndef(WideTy).getReg(0);
1518e8d8bef9SDimitry Andric     SmallVector<Register, 8> MergeParts(NumMergeParts, Undef);
1519e8d8bef9SDimitry Andric     MergeParts[0] = WideReg;
1520e8d8bef9SDimitry Andric     UnmergeSrc = MIRBuilder.buildMerge(LCMTy, MergeParts).getReg(0);
1521e8d8bef9SDimitry Andric   }
1522e8d8bef9SDimitry Andric 
1523e8d8bef9SDimitry Andric   // Unmerge to the original register and pad with dead defs.
1524e8d8bef9SDimitry Andric   SmallVector<Register, 8> UnmergeResults(NumUnmergeParts);
1525e8d8bef9SDimitry Andric   UnmergeResults[0] = OrigReg;
1526e8d8bef9SDimitry Andric   for (int I = 1; I != NumUnmergeParts; ++I)
1527e8d8bef9SDimitry Andric     UnmergeResults[I] = MRI.createGenericVirtualRegister(OrigTy);
1528e8d8bef9SDimitry Andric 
1529e8d8bef9SDimitry Andric   MIRBuilder.buildUnmerge(UnmergeResults, UnmergeSrc);
1530e8d8bef9SDimitry Andric   return WideReg;
1531e8d8bef9SDimitry Andric }
1532e8d8bef9SDimitry Andric 
15330b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
15340b57cec5SDimitry Andric LegalizerHelper::widenScalarUnmergeValues(MachineInstr &MI, unsigned TypeIdx,
15350b57cec5SDimitry Andric                                           LLT WideTy) {
15360b57cec5SDimitry Andric   if (TypeIdx != 0)
15370b57cec5SDimitry Andric     return UnableToLegalize;
15380b57cec5SDimitry Andric 
15395ffd83dbSDimitry Andric   int NumDst = MI.getNumOperands() - 1;
15400b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
15410b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
15425ffd83dbSDimitry Andric   if (SrcTy.isVector())
15430b57cec5SDimitry Andric     return UnableToLegalize;
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
15460b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
15470b57cec5SDimitry Andric   if (!DstTy.isScalar())
15480b57cec5SDimitry Andric     return UnableToLegalize;
15490b57cec5SDimitry Andric 
15505ffd83dbSDimitry Andric   if (WideTy.getSizeInBits() >= SrcTy.getSizeInBits()) {
15515ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
15525ffd83dbSDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
15535ffd83dbSDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace())) {
15545ffd83dbSDimitry Andric         LLVM_DEBUG(
15555ffd83dbSDimitry Andric             dbgs() << "Not casting non-integral address space integer\n");
15565ffd83dbSDimitry Andric         return UnableToLegalize;
15570b57cec5SDimitry Andric       }
15580b57cec5SDimitry Andric 
15595ffd83dbSDimitry Andric       SrcTy = LLT::scalar(SrcTy.getSizeInBits());
15605ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildPtrToInt(SrcTy, SrcReg).getReg(0);
15615ffd83dbSDimitry Andric     }
15620b57cec5SDimitry Andric 
15635ffd83dbSDimitry Andric     // Widen SrcTy to WideTy. This does not affect the result, but since the
15645ffd83dbSDimitry Andric     // user requested this size, it is probably better handled than SrcTy and
15655ffd83dbSDimitry Andric     // should reduce the total number of legalization artifacts
15665ffd83dbSDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
15675ffd83dbSDimitry Andric       SrcTy = WideTy;
15685ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
15695ffd83dbSDimitry Andric     }
15700b57cec5SDimitry Andric 
15715ffd83dbSDimitry Andric     // Theres no unmerge type to target. Directly extract the bits from the
15725ffd83dbSDimitry Andric     // source type
15735ffd83dbSDimitry Andric     unsigned DstSize = DstTy.getSizeInBits();
15740b57cec5SDimitry Andric 
15755ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
15765ffd83dbSDimitry Andric     for (int I = 1; I != NumDst; ++I) {
15775ffd83dbSDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcTy, DstSize * I);
15785ffd83dbSDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcTy, SrcReg, ShiftAmt);
15795ffd83dbSDimitry Andric       MIRBuilder.buildTrunc(MI.getOperand(I), Shr);
15805ffd83dbSDimitry Andric     }
15815ffd83dbSDimitry Andric 
15825ffd83dbSDimitry Andric     MI.eraseFromParent();
15835ffd83dbSDimitry Andric     return Legalized;
15845ffd83dbSDimitry Andric   }
15855ffd83dbSDimitry Andric 
15865ffd83dbSDimitry Andric   // Extend the source to a wider type.
15875ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(SrcTy, WideTy);
15885ffd83dbSDimitry Andric 
15895ffd83dbSDimitry Andric   Register WideSrc = SrcReg;
15905ffd83dbSDimitry Andric   if (LCMTy.getSizeInBits() != SrcTy.getSizeInBits()) {
15915ffd83dbSDimitry Andric     // TODO: If this is an integral address space, cast to integer and anyext.
15925ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
15935ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Widening pointer source types not implemented\n");
15945ffd83dbSDimitry Andric       return UnableToLegalize;
15955ffd83dbSDimitry Andric     }
15965ffd83dbSDimitry Andric 
15975ffd83dbSDimitry Andric     WideSrc = MIRBuilder.buildAnyExt(LCMTy, WideSrc).getReg(0);
15985ffd83dbSDimitry Andric   }
15995ffd83dbSDimitry Andric 
16005ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(WideTy, WideSrc);
16015ffd83dbSDimitry Andric 
1602e8d8bef9SDimitry Andric   // Create a sequence of unmerges and merges to the original results. Since we
1603e8d8bef9SDimitry Andric   // may have widened the source, we will need to pad the results with dead defs
1604e8d8bef9SDimitry Andric   // to cover the source register.
1605e8d8bef9SDimitry Andric   // e.g. widen s48 to s64:
1606e8d8bef9SDimitry Andric   // %1:_(s48), %2:_(s48) = G_UNMERGE_VALUES %0:_(s96)
16075ffd83dbSDimitry Andric   //
16085ffd83dbSDimitry Andric   // =>
1609e8d8bef9SDimitry Andric   //  %4:_(s192) = G_ANYEXT %0:_(s96)
1610e8d8bef9SDimitry Andric   //  %5:_(s64), %6, %7 = G_UNMERGE_VALUES %4 ; Requested unmerge
1611e8d8bef9SDimitry Andric   //  ; unpack to GCD type, with extra dead defs
1612e8d8bef9SDimitry Andric   //  %8:_(s16), %9, %10, %11 = G_UNMERGE_VALUES %5:_(s64)
1613e8d8bef9SDimitry Andric   //  %12:_(s16), %13, dead %14, dead %15 = G_UNMERGE_VALUES %6:_(s64)
1614e8d8bef9SDimitry Andric   //  dead %16:_(s16), dead %17, dead %18, dead %18 = G_UNMERGE_VALUES %7:_(s64)
1615e8d8bef9SDimitry Andric   //  %1:_(s48) = G_MERGE_VALUES %8:_(s16), %9, %10   ; Remerge to destination
1616e8d8bef9SDimitry Andric   //  %2:_(s48) = G_MERGE_VALUES %11:_(s16), %12, %13 ; Remerge to destination
1617e8d8bef9SDimitry Andric   const LLT GCDTy = getGCDType(WideTy, DstTy);
16185ffd83dbSDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
1619e8d8bef9SDimitry Andric   const int PartsPerRemerge = DstTy.getSizeInBits() / GCDTy.getSizeInBits();
1620e8d8bef9SDimitry Andric 
1621e8d8bef9SDimitry Andric   // Directly unmerge to the destination without going through a GCD type
1622e8d8bef9SDimitry Andric   // if possible
1623e8d8bef9SDimitry Andric   if (PartsPerRemerge == 1) {
16245ffd83dbSDimitry Andric     const int PartsPerUnmerge = WideTy.getSizeInBits() / DstTy.getSizeInBits();
16255ffd83dbSDimitry Andric 
16265ffd83dbSDimitry Andric     for (int I = 0; I != NumUnmerge; ++I) {
16275ffd83dbSDimitry Andric       auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
16285ffd83dbSDimitry Andric 
16295ffd83dbSDimitry Andric       for (int J = 0; J != PartsPerUnmerge; ++J) {
16305ffd83dbSDimitry Andric         int Idx = I * PartsPerUnmerge + J;
16315ffd83dbSDimitry Andric         if (Idx < NumDst)
16325ffd83dbSDimitry Andric           MIB.addDef(MI.getOperand(Idx).getReg());
16335ffd83dbSDimitry Andric         else {
16345ffd83dbSDimitry Andric           // Create dead def for excess components.
16355ffd83dbSDimitry Andric           MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
16365ffd83dbSDimitry Andric         }
16375ffd83dbSDimitry Andric       }
16385ffd83dbSDimitry Andric 
16395ffd83dbSDimitry Andric       MIB.addUse(Unmerge.getReg(I));
16405ffd83dbSDimitry Andric     }
1641e8d8bef9SDimitry Andric   } else {
1642e8d8bef9SDimitry Andric     SmallVector<Register, 16> Parts;
1643e8d8bef9SDimitry Andric     for (int J = 0; J != NumUnmerge; ++J)
1644e8d8bef9SDimitry Andric       extractGCDType(Parts, GCDTy, Unmerge.getReg(J));
1645e8d8bef9SDimitry Andric 
1646e8d8bef9SDimitry Andric     SmallVector<Register, 8> RemergeParts;
1647e8d8bef9SDimitry Andric     for (int I = 0; I != NumDst; ++I) {
1648e8d8bef9SDimitry Andric       for (int J = 0; J < PartsPerRemerge; ++J) {
1649e8d8bef9SDimitry Andric         const int Idx = I * PartsPerRemerge + J;
1650e8d8bef9SDimitry Andric         RemergeParts.emplace_back(Parts[Idx]);
1651e8d8bef9SDimitry Andric       }
1652e8d8bef9SDimitry Andric 
1653e8d8bef9SDimitry Andric       MIRBuilder.buildMerge(MI.getOperand(I).getReg(), RemergeParts);
1654e8d8bef9SDimitry Andric       RemergeParts.clear();
1655e8d8bef9SDimitry Andric     }
1656e8d8bef9SDimitry Andric   }
16575ffd83dbSDimitry Andric 
16585ffd83dbSDimitry Andric   MI.eraseFromParent();
16590b57cec5SDimitry Andric   return Legalized;
16600b57cec5SDimitry Andric }
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
16630b57cec5SDimitry Andric LegalizerHelper::widenScalarExtract(MachineInstr &MI, unsigned TypeIdx,
16640b57cec5SDimitry Andric                                     LLT WideTy) {
16650b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
16660b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
16670b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
16700b57cec5SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   if (TypeIdx == 0) {
16730b57cec5SDimitry Andric     if (SrcTy.isVector() || DstTy.isVector())
16740b57cec5SDimitry Andric       return UnableToLegalize;
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric     SrcOp Src(SrcReg);
16770b57cec5SDimitry Andric     if (SrcTy.isPointer()) {
16780b57cec5SDimitry Andric       // Extracts from pointers can be handled only if they are really just
16790b57cec5SDimitry Andric       // simple integers.
16800b57cec5SDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
16810b57cec5SDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace()))
16820b57cec5SDimitry Andric         return UnableToLegalize;
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric       LLT SrcAsIntTy = LLT::scalar(SrcTy.getSizeInBits());
16850b57cec5SDimitry Andric       Src = MIRBuilder.buildPtrToInt(SrcAsIntTy, Src);
16860b57cec5SDimitry Andric       SrcTy = SrcAsIntTy;
16870b57cec5SDimitry Andric     }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric     if (DstTy.isPointer())
16900b57cec5SDimitry Andric       return UnableToLegalize;
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric     if (Offset == 0) {
16930b57cec5SDimitry Andric       // Avoid a shift in the degenerate case.
16940b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg,
16950b57cec5SDimitry Andric                             MIRBuilder.buildAnyExtOrTrunc(WideTy, Src));
16960b57cec5SDimitry Andric       MI.eraseFromParent();
16970b57cec5SDimitry Andric       return Legalized;
16980b57cec5SDimitry Andric     }
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric     // Do a shift in the source type.
17010b57cec5SDimitry Andric     LLT ShiftTy = SrcTy;
17020b57cec5SDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
17030b57cec5SDimitry Andric       Src = MIRBuilder.buildAnyExt(WideTy, Src);
17040b57cec5SDimitry Andric       ShiftTy = WideTy;
1705e8d8bef9SDimitry Andric     }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric     auto LShr = MIRBuilder.buildLShr(
17080b57cec5SDimitry Andric       ShiftTy, Src, MIRBuilder.buildConstant(ShiftTy, Offset));
17090b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, LShr);
17100b57cec5SDimitry Andric     MI.eraseFromParent();
17110b57cec5SDimitry Andric     return Legalized;
17120b57cec5SDimitry Andric   }
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric   if (SrcTy.isScalar()) {
17150b57cec5SDimitry Andric     Observer.changingInstr(MI);
17160b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17170b57cec5SDimitry Andric     Observer.changedInstr(MI);
17180b57cec5SDimitry Andric     return Legalized;
17190b57cec5SDimitry Andric   }
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric   if (!SrcTy.isVector())
17220b57cec5SDimitry Andric     return UnableToLegalize;
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric   if (DstTy != SrcTy.getElementType())
17250b57cec5SDimitry Andric     return UnableToLegalize;
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   if (Offset % SrcTy.getScalarSizeInBits() != 0)
17280b57cec5SDimitry Andric     return UnableToLegalize;
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric   Observer.changingInstr(MI);
17310b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   MI.getOperand(2).setImm((WideTy.getSizeInBits() / SrcTy.getSizeInBits()) *
17340b57cec5SDimitry Andric                           Offset);
17350b57cec5SDimitry Andric   widenScalarDst(MI, WideTy.getScalarType(), 0);
17360b57cec5SDimitry Andric   Observer.changedInstr(MI);
17370b57cec5SDimitry Andric   return Legalized;
17380b57cec5SDimitry Andric }
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
17410b57cec5SDimitry Andric LegalizerHelper::widenScalarInsert(MachineInstr &MI, unsigned TypeIdx,
17420b57cec5SDimitry Andric                                    LLT WideTy) {
1743e8d8bef9SDimitry Andric   if (TypeIdx != 0 || WideTy.isVector())
17440b57cec5SDimitry Andric     return UnableToLegalize;
17450b57cec5SDimitry Andric   Observer.changingInstr(MI);
17460b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17470b57cec5SDimitry Andric   widenScalarDst(MI, WideTy);
17480b57cec5SDimitry Andric   Observer.changedInstr(MI);
17490b57cec5SDimitry Andric   return Legalized;
17500b57cec5SDimitry Andric }
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
1753e8d8bef9SDimitry Andric LegalizerHelper::widenScalarAddoSubo(MachineInstr &MI, unsigned TypeIdx,
1754e8d8bef9SDimitry Andric                                      LLT WideTy) {
1755e8d8bef9SDimitry Andric   if (TypeIdx == 1)
1756e8d8bef9SDimitry Andric     return UnableToLegalize; // TODO
1757e8d8bef9SDimitry Andric   unsigned Op = MI.getOpcode();
1758e8d8bef9SDimitry Andric   unsigned Opcode = Op == TargetOpcode::G_UADDO || Op == TargetOpcode::G_SADDO
1759e8d8bef9SDimitry Andric                         ? TargetOpcode::G_ADD
1760e8d8bef9SDimitry Andric                         : TargetOpcode::G_SUB;
1761e8d8bef9SDimitry Andric   unsigned ExtOpcode =
1762e8d8bef9SDimitry Andric       Op == TargetOpcode::G_UADDO || Op == TargetOpcode::G_USUBO
1763e8d8bef9SDimitry Andric           ? TargetOpcode::G_ZEXT
1764e8d8bef9SDimitry Andric           : TargetOpcode::G_SEXT;
1765e8d8bef9SDimitry Andric   auto LHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(2)});
1766e8d8bef9SDimitry Andric   auto RHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(3)});
1767e8d8bef9SDimitry Andric   // Do the arithmetic in the larger type.
1768e8d8bef9SDimitry Andric   auto NewOp = MIRBuilder.buildInstr(Opcode, {WideTy}, {LHSExt, RHSExt});
1769e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(MI.getOperand(0).getReg());
1770e8d8bef9SDimitry Andric   auto TruncOp = MIRBuilder.buildTrunc(OrigTy, NewOp);
1771e8d8bef9SDimitry Andric   auto ExtOp = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {TruncOp});
1772e8d8bef9SDimitry Andric   // There is no overflow if the ExtOp is the same as NewOp.
1773e8d8bef9SDimitry Andric   MIRBuilder.buildICmp(CmpInst::ICMP_NE, MI.getOperand(1), NewOp, ExtOp);
1774e8d8bef9SDimitry Andric   // Now trunc the NewOp to the original result.
1775e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(MI.getOperand(0), NewOp);
1776e8d8bef9SDimitry Andric   MI.eraseFromParent();
1777e8d8bef9SDimitry Andric   return Legalized;
1778e8d8bef9SDimitry Andric }
1779e8d8bef9SDimitry Andric 
1780e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
1781e8d8bef9SDimitry Andric LegalizerHelper::widenScalarAddSubShlSat(MachineInstr &MI, unsigned TypeIdx,
17825ffd83dbSDimitry Andric                                          LLT WideTy) {
17835ffd83dbSDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SADDSAT ||
1784e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSUBSAT ||
1785e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSHLSAT;
1786e8d8bef9SDimitry Andric   bool IsShift = MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
1787e8d8bef9SDimitry Andric                  MI.getOpcode() == TargetOpcode::G_USHLSAT;
17885ffd83dbSDimitry Andric   // We can convert this to:
17895ffd83dbSDimitry Andric   //   1. Any extend iN to iM
17905ffd83dbSDimitry Andric   //   2. SHL by M-N
1791e8d8bef9SDimitry Andric   //   3. [US][ADD|SUB|SHL]SAT
17925ffd83dbSDimitry Andric   //   4. L/ASHR by M-N
17935ffd83dbSDimitry Andric   //
17945ffd83dbSDimitry Andric   // It may be more efficient to lower this to a min and a max operation in
17955ffd83dbSDimitry Andric   // the higher precision arithmetic if the promoted operation isn't legal,
17965ffd83dbSDimitry Andric   // but this decision is up to the target's lowering request.
17975ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
17980b57cec5SDimitry Andric 
17995ffd83dbSDimitry Andric   unsigned NewBits = WideTy.getScalarSizeInBits();
18005ffd83dbSDimitry Andric   unsigned SHLAmount = NewBits - MRI.getType(DstReg).getScalarSizeInBits();
18015ffd83dbSDimitry Andric 
1802e8d8bef9SDimitry Andric   // Shifts must zero-extend the RHS to preserve the unsigned quantity, and
1803e8d8bef9SDimitry Andric   // must not left shift the RHS to preserve the shift amount.
18045ffd83dbSDimitry Andric   auto LHS = MIRBuilder.buildAnyExt(WideTy, MI.getOperand(1));
1805e8d8bef9SDimitry Andric   auto RHS = IsShift ? MIRBuilder.buildZExt(WideTy, MI.getOperand(2))
1806e8d8bef9SDimitry Andric                      : MIRBuilder.buildAnyExt(WideTy, MI.getOperand(2));
18075ffd83dbSDimitry Andric   auto ShiftK = MIRBuilder.buildConstant(WideTy, SHLAmount);
18085ffd83dbSDimitry Andric   auto ShiftL = MIRBuilder.buildShl(WideTy, LHS, ShiftK);
1809e8d8bef9SDimitry Andric   auto ShiftR = IsShift ? RHS : MIRBuilder.buildShl(WideTy, RHS, ShiftK);
18105ffd83dbSDimitry Andric 
18115ffd83dbSDimitry Andric   auto WideInst = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy},
18125ffd83dbSDimitry Andric                                         {ShiftL, ShiftR}, MI.getFlags());
18135ffd83dbSDimitry Andric 
18145ffd83dbSDimitry Andric   // Use a shift that will preserve the number of sign bits when the trunc is
18155ffd83dbSDimitry Andric   // folded away.
18165ffd83dbSDimitry Andric   auto Result = IsSigned ? MIRBuilder.buildAShr(WideTy, WideInst, ShiftK)
18175ffd83dbSDimitry Andric                          : MIRBuilder.buildLShr(WideTy, WideInst, ShiftK);
18185ffd83dbSDimitry Andric 
18195ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(DstReg, Result);
18205ffd83dbSDimitry Andric   MI.eraseFromParent();
18215ffd83dbSDimitry Andric   return Legalized;
18225ffd83dbSDimitry Andric }
18235ffd83dbSDimitry Andric 
18245ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
18255ffd83dbSDimitry Andric LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
18260b57cec5SDimitry Andric   switch (MI.getOpcode()) {
18270b57cec5SDimitry Andric   default:
18280b57cec5SDimitry Andric     return UnableToLegalize;
18290b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
18300b57cec5SDimitry Andric     return widenScalarExtract(MI, TypeIdx, WideTy);
18310b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
18320b57cec5SDimitry Andric     return widenScalarInsert(MI, TypeIdx, WideTy);
18330b57cec5SDimitry Andric   case TargetOpcode::G_MERGE_VALUES:
18340b57cec5SDimitry Andric     return widenScalarMergeValues(MI, TypeIdx, WideTy);
18350b57cec5SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES:
18360b57cec5SDimitry Andric     return widenScalarUnmergeValues(MI, TypeIdx, WideTy);
1837e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
1838e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
18390b57cec5SDimitry Andric   case TargetOpcode::G_UADDO:
1840e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBO:
1841e8d8bef9SDimitry Andric     return widenScalarAddoSubo(MI, TypeIdx, WideTy);
18425ffd83dbSDimitry Andric   case TargetOpcode::G_SADDSAT:
18435ffd83dbSDimitry Andric   case TargetOpcode::G_SSUBSAT:
1844e8d8bef9SDimitry Andric   case TargetOpcode::G_SSHLSAT:
18455ffd83dbSDimitry Andric   case TargetOpcode::G_UADDSAT:
18465ffd83dbSDimitry Andric   case TargetOpcode::G_USUBSAT:
1847e8d8bef9SDimitry Andric   case TargetOpcode::G_USHLSAT:
1848e8d8bef9SDimitry Andric     return widenScalarAddSubShlSat(MI, TypeIdx, WideTy);
18490b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
18500b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
18510b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
18520b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
18530b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP: {
18540b57cec5SDimitry Andric     if (TypeIdx == 0) {
18550b57cec5SDimitry Andric       Observer.changingInstr(MI);
18560b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
18570b57cec5SDimitry Andric       Observer.changedInstr(MI);
18580b57cec5SDimitry Andric       return Legalized;
18590b57cec5SDimitry Andric     }
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric     // First ZEXT the input.
18640b57cec5SDimitry Andric     auto MIBSrc = MIRBuilder.buildZExt(WideTy, SrcReg);
18650b57cec5SDimitry Andric     LLT CurTy = MRI.getType(SrcReg);
18660b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTTZ) {
18670b57cec5SDimitry Andric       // The count is the same in the larger type except if the original
18680b57cec5SDimitry Andric       // value was zero.  This can be handled by setting the bit just off
18690b57cec5SDimitry Andric       // the top of the original type.
18700b57cec5SDimitry Andric       auto TopBit =
18710b57cec5SDimitry Andric           APInt::getOneBitSet(WideTy.getSizeInBits(), CurTy.getSizeInBits());
18720b57cec5SDimitry Andric       MIBSrc = MIRBuilder.buildOr(
18730b57cec5SDimitry Andric         WideTy, MIBSrc, MIRBuilder.buildConstant(WideTy, TopBit));
18740b57cec5SDimitry Andric     }
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric     // Perform the operation at the larger size.
18770b57cec5SDimitry Andric     auto MIBNewOp = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy}, {MIBSrc});
18780b57cec5SDimitry Andric     // This is already the correct result for CTPOP and CTTZs
18790b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTLZ ||
18800b57cec5SDimitry Andric         MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF) {
18810b57cec5SDimitry Andric       // The correct result is NewOp - (Difference in widety and current ty).
18820b57cec5SDimitry Andric       unsigned SizeDiff = WideTy.getSizeInBits() - CurTy.getSizeInBits();
18835ffd83dbSDimitry Andric       MIBNewOp = MIRBuilder.buildSub(
18845ffd83dbSDimitry Andric           WideTy, MIBNewOp, MIRBuilder.buildConstant(WideTy, SizeDiff));
18850b57cec5SDimitry Andric     }
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric     MIRBuilder.buildZExtOrTrunc(MI.getOperand(0), MIBNewOp);
18880b57cec5SDimitry Andric     MI.eraseFromParent();
18890b57cec5SDimitry Andric     return Legalized;
18900b57cec5SDimitry Andric   }
18910b57cec5SDimitry Andric   case TargetOpcode::G_BSWAP: {
18920b57cec5SDimitry Andric     Observer.changingInstr(MI);
18930b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric     Register ShrReg = MRI.createGenericVirtualRegister(WideTy);
18960b57cec5SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
18970b57cec5SDimitry Andric     Register ShiftAmtReg = MRI.createGenericVirtualRegister(WideTy);
18980b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
18990b57cec5SDimitry Andric 
19000b57cec5SDimitry Andric     MI.getOperand(0).setReg(DstExt);
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric     LLT Ty = MRI.getType(DstReg);
19050b57cec5SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
19060b57cec5SDimitry Andric     MIRBuilder.buildConstant(ShiftAmtReg, DiffBits);
19075ffd83dbSDimitry Andric     MIRBuilder.buildLShr(ShrReg, DstExt, ShiftAmtReg);
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, ShrReg);
19100b57cec5SDimitry Andric     Observer.changedInstr(MI);
19110b57cec5SDimitry Andric     return Legalized;
19120b57cec5SDimitry Andric   }
19138bcb0991SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
19148bcb0991SDimitry Andric     Observer.changingInstr(MI);
19158bcb0991SDimitry Andric 
19168bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
19178bcb0991SDimitry Andric     LLT Ty = MRI.getType(DstReg);
19188bcb0991SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
19198bcb0991SDimitry Andric 
19208bcb0991SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
19218bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19228bcb0991SDimitry Andric     MI.getOperand(0).setReg(DstExt);
19238bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
19248bcb0991SDimitry Andric 
19258bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, DiffBits);
19268bcb0991SDimitry Andric     auto Shift = MIRBuilder.buildLShr(WideTy, DstExt, ShiftAmt);
19278bcb0991SDimitry Andric     MIRBuilder.buildTrunc(DstReg, Shift);
19288bcb0991SDimitry Andric     Observer.changedInstr(MI);
19298bcb0991SDimitry Andric     return Legalized;
19308bcb0991SDimitry Andric   }
19315ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
19325ffd83dbSDimitry Andric     Observer.changingInstr(MI);
19335ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19345ffd83dbSDimitry Andric     widenScalarDst(MI, WideTy);
19355ffd83dbSDimitry Andric     Observer.changedInstr(MI);
19365ffd83dbSDimitry Andric     return Legalized;
19375ffd83dbSDimitry Andric 
19380b57cec5SDimitry Andric   case TargetOpcode::G_ADD:
19390b57cec5SDimitry Andric   case TargetOpcode::G_AND:
19400b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
19410b57cec5SDimitry Andric   case TargetOpcode::G_OR:
19420b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
19430b57cec5SDimitry Andric   case TargetOpcode::G_SUB:
19440b57cec5SDimitry Andric     // Perform operation at larger width (any extension is fines here, high bits
19450b57cec5SDimitry Andric     // don't affect the result) and then truncate the result back to the
19460b57cec5SDimitry Andric     // original type.
19470b57cec5SDimitry Andric     Observer.changingInstr(MI);
19480b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19490b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
19500b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
19510b57cec5SDimitry Andric     Observer.changedInstr(MI);
19520b57cec5SDimitry Andric     return Legalized;
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric   case TargetOpcode::G_SHL:
19550b57cec5SDimitry Andric     Observer.changingInstr(MI);
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric     if (TypeIdx == 0) {
19580b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19590b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
19600b57cec5SDimitry Andric     } else {
19610b57cec5SDimitry Andric       assert(TypeIdx == 1);
19620b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
19630b57cec5SDimitry Andric       // unsigned integer:
19640b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
19650b57cec5SDimitry Andric     }
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric     Observer.changedInstr(MI);
19680b57cec5SDimitry Andric     return Legalized;
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
19710b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
19720b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
19730b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
19740b57cec5SDimitry Andric     Observer.changingInstr(MI);
19750b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
19760b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
19770b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
19780b57cec5SDimitry Andric     Observer.changedInstr(MI);
19790b57cec5SDimitry Andric     return Legalized;
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric   case TargetOpcode::G_ASHR:
19820b57cec5SDimitry Andric   case TargetOpcode::G_LSHR:
19830b57cec5SDimitry Andric     Observer.changingInstr(MI);
19840b57cec5SDimitry Andric 
19850b57cec5SDimitry Andric     if (TypeIdx == 0) {
19860b57cec5SDimitry Andric       unsigned CvtOp = MI.getOpcode() == TargetOpcode::G_ASHR ?
19870b57cec5SDimitry Andric         TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, CvtOp);
19900b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
19910b57cec5SDimitry Andric     } else {
19920b57cec5SDimitry Andric       assert(TypeIdx == 1);
19930b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
19940b57cec5SDimitry Andric       // unsigned integer:
19950b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
19960b57cec5SDimitry Andric     }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric     Observer.changedInstr(MI);
19990b57cec5SDimitry Andric     return Legalized;
20000b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
20010b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
20020b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
20030b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
20040b57cec5SDimitry Andric     Observer.changingInstr(MI);
20050b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
20060b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
20070b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
20080b57cec5SDimitry Andric     Observer.changedInstr(MI);
20090b57cec5SDimitry Andric     return Legalized;
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
20120b57cec5SDimitry Andric     Observer.changingInstr(MI);
20130b57cec5SDimitry Andric     if (TypeIdx == 0) {
20140b57cec5SDimitry Andric       // Perform operation at larger width (any extension is fine here, high
20150b57cec5SDimitry Andric       // bits don't affect the result) and then truncate the result back to the
20160b57cec5SDimitry Andric       // original type.
20170b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
20180b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
20190b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
20200b57cec5SDimitry Andric     } else {
20210b57cec5SDimitry Andric       bool IsVec = MRI.getType(MI.getOperand(1).getReg()).isVector();
20220b57cec5SDimitry Andric       // Explicit extension is required here since high bits affect the result.
20230b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, MIRBuilder.getBoolExtOp(IsVec, false));
20240b57cec5SDimitry Andric     }
20250b57cec5SDimitry Andric     Observer.changedInstr(MI);
20260b57cec5SDimitry Andric     return Legalized;
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
20290b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
20300b57cec5SDimitry Andric     Observer.changingInstr(MI);
20318bcb0991SDimitry Andric 
20328bcb0991SDimitry Andric     if (TypeIdx == 0)
20330b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
20348bcb0991SDimitry Andric     else
20358bcb0991SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
20368bcb0991SDimitry Andric 
20370b57cec5SDimitry Andric     Observer.changedInstr(MI);
20380b57cec5SDimitry Andric     return Legalized;
20390b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
20400b57cec5SDimitry Andric     Observer.changingInstr(MI);
2041e8d8bef9SDimitry Andric 
2042e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2043e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2044e8d8bef9SDimitry Andric     else
20450b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
2046e8d8bef9SDimitry Andric 
20470b57cec5SDimitry Andric     Observer.changedInstr(MI);
20480b57cec5SDimitry Andric     return Legalized;
20490b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
20500b57cec5SDimitry Andric     Observer.changingInstr(MI);
2051e8d8bef9SDimitry Andric 
2052e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2053e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2054e8d8bef9SDimitry Andric     else
20550b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
2056e8d8bef9SDimitry Andric 
20570b57cec5SDimitry Andric     Observer.changedInstr(MI);
20580b57cec5SDimitry Andric     return Legalized;
20590b57cec5SDimitry Andric   case TargetOpcode::G_LOAD:
20600b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
20610b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
20620b57cec5SDimitry Andric     Observer.changingInstr(MI);
20630b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
20640b57cec5SDimitry Andric     Observer.changedInstr(MI);
20650b57cec5SDimitry Andric     return Legalized;
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
20680b57cec5SDimitry Andric     if (TypeIdx != 0)
20690b57cec5SDimitry Andric       return UnableToLegalize;
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2072e8d8bef9SDimitry Andric     if (!Ty.isScalar())
20730b57cec5SDimitry Andric       return UnableToLegalize;
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric     Observer.changingInstr(MI);
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric     unsigned ExtType = Ty.getScalarSizeInBits() == 1 ?
20780b57cec5SDimitry Andric       TargetOpcode::G_ZEXT : TargetOpcode::G_ANYEXT;
20790b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, ExtType);
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric     Observer.changedInstr(MI);
20820b57cec5SDimitry Andric     return Legalized;
20830b57cec5SDimitry Andric   }
20840b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
20850b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
20860b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
2087480093f4SDimitry Andric     unsigned ExtOpc = LI.getExtOpcodeForWideningConstant(
2088480093f4SDimitry Andric         MRI.getType(MI.getOperand(0).getReg()));
2089480093f4SDimitry Andric     assert((ExtOpc == TargetOpcode::G_ZEXT || ExtOpc == TargetOpcode::G_SEXT ||
2090480093f4SDimitry Andric             ExtOpc == TargetOpcode::G_ANYEXT) &&
2091480093f4SDimitry Andric            "Illegal Extend");
2092480093f4SDimitry Andric     const APInt &SrcVal = SrcMO.getCImm()->getValue();
2093480093f4SDimitry Andric     const APInt &Val = (ExtOpc == TargetOpcode::G_SEXT)
2094480093f4SDimitry Andric                            ? SrcVal.sext(WideTy.getSizeInBits())
2095480093f4SDimitry Andric                            : SrcVal.zext(WideTy.getSizeInBits());
20960b57cec5SDimitry Andric     Observer.changingInstr(MI);
20970b57cec5SDimitry Andric     SrcMO.setCImm(ConstantInt::get(Ctx, Val));
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21000b57cec5SDimitry Andric     Observer.changedInstr(MI);
21010b57cec5SDimitry Andric     return Legalized;
21020b57cec5SDimitry Andric   }
21030b57cec5SDimitry Andric   case TargetOpcode::G_FCONSTANT: {
21040b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
21050b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
21060b57cec5SDimitry Andric     APFloat Val = SrcMO.getFPImm()->getValueAPF();
21070b57cec5SDimitry Andric     bool LosesInfo;
21080b57cec5SDimitry Andric     switch (WideTy.getSizeInBits()) {
21090b57cec5SDimitry Andric     case 32:
21100b57cec5SDimitry Andric       Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
21110b57cec5SDimitry Andric                   &LosesInfo);
21120b57cec5SDimitry Andric       break;
21130b57cec5SDimitry Andric     case 64:
21140b57cec5SDimitry Andric       Val.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
21150b57cec5SDimitry Andric                   &LosesInfo);
21160b57cec5SDimitry Andric       break;
21170b57cec5SDimitry Andric     default:
21180b57cec5SDimitry Andric       return UnableToLegalize;
21190b57cec5SDimitry Andric     }
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric     assert(!LosesInfo && "extend should always be lossless");
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric     Observer.changingInstr(MI);
21240b57cec5SDimitry Andric     SrcMO.setFPImm(ConstantFP::get(Ctx, Val));
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
21270b57cec5SDimitry Andric     Observer.changedInstr(MI);
21280b57cec5SDimitry Andric     return Legalized;
21290b57cec5SDimitry Andric   }
21300b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
21310b57cec5SDimitry Andric     Observer.changingInstr(MI);
21320b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21330b57cec5SDimitry Andric     Observer.changedInstr(MI);
21340b57cec5SDimitry Andric     return Legalized;
21350b57cec5SDimitry Andric   }
21360b57cec5SDimitry Andric   case TargetOpcode::G_BRCOND:
21370b57cec5SDimitry Andric     Observer.changingInstr(MI);
21380b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, MIRBuilder.getBoolExtOp(false, false));
21390b57cec5SDimitry Andric     Observer.changedInstr(MI);
21400b57cec5SDimitry Andric     return Legalized;
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric   case TargetOpcode::G_FCMP:
21430b57cec5SDimitry Andric     Observer.changingInstr(MI);
21440b57cec5SDimitry Andric     if (TypeIdx == 0)
21450b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
21460b57cec5SDimitry Andric     else {
21470b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
21480b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_FPEXT);
21490b57cec5SDimitry Andric     }
21500b57cec5SDimitry Andric     Observer.changedInstr(MI);
21510b57cec5SDimitry Andric     return Legalized;
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric   case TargetOpcode::G_ICMP:
21540b57cec5SDimitry Andric     Observer.changingInstr(MI);
21550b57cec5SDimitry Andric     if (TypeIdx == 0)
21560b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
21570b57cec5SDimitry Andric     else {
21580b57cec5SDimitry Andric       unsigned ExtOpcode = CmpInst::isSigned(static_cast<CmpInst::Predicate>(
21590b57cec5SDimitry Andric                                MI.getOperand(1).getPredicate()))
21600b57cec5SDimitry Andric                                ? TargetOpcode::G_SEXT
21610b57cec5SDimitry Andric                                : TargetOpcode::G_ZEXT;
21620b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, ExtOpcode);
21630b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, ExtOpcode);
21640b57cec5SDimitry Andric     }
21650b57cec5SDimitry Andric     Observer.changedInstr(MI);
21660b57cec5SDimitry Andric     return Legalized;
21670b57cec5SDimitry Andric 
2168480093f4SDimitry Andric   case TargetOpcode::G_PTR_ADD:
2169480093f4SDimitry Andric     assert(TypeIdx == 1 && "unable to legalize pointer of G_PTR_ADD");
21700b57cec5SDimitry Andric     Observer.changingInstr(MI);
21710b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
21720b57cec5SDimitry Andric     Observer.changedInstr(MI);
21730b57cec5SDimitry Andric     return Legalized;
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric   case TargetOpcode::G_PHI: {
21760b57cec5SDimitry Andric     assert(TypeIdx == 0 && "Expecting only Idx 0");
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric     Observer.changingInstr(MI);
21790b57cec5SDimitry Andric     for (unsigned I = 1; I < MI.getNumOperands(); I += 2) {
21800b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
21810b57cec5SDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
21820b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_ANYEXT);
21830b57cec5SDimitry Andric     }
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
21860b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
21870b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21880b57cec5SDimitry Andric     Observer.changedInstr(MI);
21890b57cec5SDimitry Andric     return Legalized;
21900b57cec5SDimitry Andric   }
21910b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
21920b57cec5SDimitry Andric     if (TypeIdx == 0) {
21930b57cec5SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
21940b57cec5SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
21950b57cec5SDimitry Andric       Observer.changingInstr(MI);
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric       widenScalarSrc(MI, LLT::vector(VecTy.getNumElements(),
21980b57cec5SDimitry Andric                                      WideTy.getSizeInBits()),
21990b57cec5SDimitry Andric                      1, TargetOpcode::G_SEXT);
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
22020b57cec5SDimitry Andric       Observer.changedInstr(MI);
22030b57cec5SDimitry Andric       return Legalized;
22040b57cec5SDimitry Andric     }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric     if (TypeIdx != 2)
22070b57cec5SDimitry Andric       return UnableToLegalize;
22080b57cec5SDimitry Andric     Observer.changingInstr(MI);
2209480093f4SDimitry Andric     // TODO: Probably should be zext
22100b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
22110b57cec5SDimitry Andric     Observer.changedInstr(MI);
22120b57cec5SDimitry Andric     return Legalized;
22130b57cec5SDimitry Andric   }
2214480093f4SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
2215480093f4SDimitry Andric     if (TypeIdx == 1) {
2216480093f4SDimitry Andric       Observer.changingInstr(MI);
2217480093f4SDimitry Andric 
2218480093f4SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
2219480093f4SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
2220480093f4SDimitry Andric       LLT WideVecTy = LLT::vector(VecTy.getNumElements(), WideTy);
2221480093f4SDimitry Andric 
2222480093f4SDimitry Andric       widenScalarSrc(MI, WideVecTy, 1, TargetOpcode::G_ANYEXT);
2223480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2224480093f4SDimitry Andric       widenScalarDst(MI, WideVecTy, 0);
2225480093f4SDimitry Andric       Observer.changedInstr(MI);
2226480093f4SDimitry Andric       return Legalized;
2227480093f4SDimitry Andric     }
2228480093f4SDimitry Andric 
2229480093f4SDimitry Andric     if (TypeIdx == 2) {
2230480093f4SDimitry Andric       Observer.changingInstr(MI);
2231480093f4SDimitry Andric       // TODO: Probably should be zext
2232480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2233480093f4SDimitry Andric       Observer.changedInstr(MI);
22345ffd83dbSDimitry Andric       return Legalized;
2235480093f4SDimitry Andric     }
2236480093f4SDimitry Andric 
22375ffd83dbSDimitry Andric     return UnableToLegalize;
2238480093f4SDimitry Andric   }
22390b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
22400b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
22410b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
22420b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
22438bcb0991SDimitry Andric   case TargetOpcode::G_FMAD:
22440b57cec5SDimitry Andric   case TargetOpcode::G_FNEG:
22450b57cec5SDimitry Andric   case TargetOpcode::G_FABS:
22460b57cec5SDimitry Andric   case TargetOpcode::G_FCANONICALIZE:
22470b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM:
22480b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM:
22490b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
22500b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
22510b57cec5SDimitry Andric   case TargetOpcode::G_FMINIMUM:
22520b57cec5SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
22530b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
22540b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
22550b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
22560b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
22570b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
22580b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
22590b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
22600b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
22610b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
22620b57cec5SDimitry Andric   case TargetOpcode::G_FRINT:
22630b57cec5SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
22640b57cec5SDimitry Andric   case TargetOpcode::G_FSQRT:
22650b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
22660b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
22670b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
22680b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_TRUNC:
22690b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
2270e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
22710b57cec5SDimitry Andric     assert(TypeIdx == 0);
22720b57cec5SDimitry Andric     Observer.changingInstr(MI);
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
22750b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_FPEXT);
22760b57cec5SDimitry Andric 
22770b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
22780b57cec5SDimitry Andric     Observer.changedInstr(MI);
22790b57cec5SDimitry Andric     return Legalized;
2280e8d8bef9SDimitry Andric   case TargetOpcode::G_FPOWI: {
2281e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2282e8d8bef9SDimitry Andric       return UnableToLegalize;
2283e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2284e8d8bef9SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
2285e8d8bef9SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2286e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2287e8d8bef9SDimitry Andric     return Legalized;
2288e8d8bef9SDimitry Andric   }
22890b57cec5SDimitry Andric   case TargetOpcode::G_INTTOPTR:
22900b57cec5SDimitry Andric     if (TypeIdx != 1)
22910b57cec5SDimitry Andric       return UnableToLegalize;
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric     Observer.changingInstr(MI);
22940b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
22950b57cec5SDimitry Andric     Observer.changedInstr(MI);
22960b57cec5SDimitry Andric     return Legalized;
22970b57cec5SDimitry Andric   case TargetOpcode::G_PTRTOINT:
22980b57cec5SDimitry Andric     if (TypeIdx != 0)
22990b57cec5SDimitry Andric       return UnableToLegalize;
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric     Observer.changingInstr(MI);
23020b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0);
23030b57cec5SDimitry Andric     Observer.changedInstr(MI);
23040b57cec5SDimitry Andric     return Legalized;
23050b57cec5SDimitry Andric   case TargetOpcode::G_BUILD_VECTOR: {
23060b57cec5SDimitry Andric     Observer.changingInstr(MI);
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric     const LLT WideEltTy = TypeIdx == 1 ? WideTy : WideTy.getElementType();
23090b57cec5SDimitry Andric     for (int I = 1, E = MI.getNumOperands(); I != E; ++I)
23100b57cec5SDimitry Andric       widenScalarSrc(MI, WideEltTy, I, TargetOpcode::G_ANYEXT);
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric     // Avoid changing the result vector type if the source element type was
23130b57cec5SDimitry Andric     // requested.
23140b57cec5SDimitry Andric     if (TypeIdx == 1) {
2315e8d8bef9SDimitry Andric       MI.setDesc(MIRBuilder.getTII().get(TargetOpcode::G_BUILD_VECTOR_TRUNC));
23160b57cec5SDimitry Andric     } else {
23170b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
23180b57cec5SDimitry Andric     }
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric     Observer.changedInstr(MI);
23210b57cec5SDimitry Andric     return Legalized;
23220b57cec5SDimitry Andric   }
23238bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG:
23248bcb0991SDimitry Andric     if (TypeIdx != 0)
23258bcb0991SDimitry Andric       return UnableToLegalize;
23268bcb0991SDimitry Andric 
23278bcb0991SDimitry Andric     Observer.changingInstr(MI);
23288bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
23298bcb0991SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_TRUNC);
23308bcb0991SDimitry Andric     Observer.changedInstr(MI);
23318bcb0991SDimitry Andric     return Legalized;
23325ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
23335ffd83dbSDimitry Andric     if (TypeIdx != 1)
23345ffd83dbSDimitry Andric       return UnableToLegalize;
23355ffd83dbSDimitry Andric     Observer.changingInstr(MI);
23365ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
23375ffd83dbSDimitry Andric     Observer.changedInstr(MI);
23385ffd83dbSDimitry Andric     return Legalized;
23395ffd83dbSDimitry Andric   }
23405ffd83dbSDimitry Andric   }
23415ffd83dbSDimitry Andric }
23425ffd83dbSDimitry Andric 
23435ffd83dbSDimitry Andric static void getUnmergePieces(SmallVectorImpl<Register> &Pieces,
23445ffd83dbSDimitry Andric                              MachineIRBuilder &B, Register Src, LLT Ty) {
23455ffd83dbSDimitry Andric   auto Unmerge = B.buildUnmerge(Ty, Src);
23465ffd83dbSDimitry Andric   for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
23475ffd83dbSDimitry Andric     Pieces.push_back(Unmerge.getReg(I));
23485ffd83dbSDimitry Andric }
23495ffd83dbSDimitry Andric 
23505ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
23515ffd83dbSDimitry Andric LegalizerHelper::lowerBitcast(MachineInstr &MI) {
23525ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
23535ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
23545ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
23555ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
23565ffd83dbSDimitry Andric 
23575ffd83dbSDimitry Andric   if (SrcTy.isVector()) {
23585ffd83dbSDimitry Andric     LLT SrcEltTy = SrcTy.getElementType();
23595ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
23605ffd83dbSDimitry Andric 
23615ffd83dbSDimitry Andric     if (DstTy.isVector()) {
23625ffd83dbSDimitry Andric       int NumDstElt = DstTy.getNumElements();
23635ffd83dbSDimitry Andric       int NumSrcElt = SrcTy.getNumElements();
23645ffd83dbSDimitry Andric 
23655ffd83dbSDimitry Andric       LLT DstEltTy = DstTy.getElementType();
23665ffd83dbSDimitry Andric       LLT DstCastTy = DstEltTy; // Intermediate bitcast result type
23675ffd83dbSDimitry Andric       LLT SrcPartTy = SrcEltTy; // Original unmerge result type.
23685ffd83dbSDimitry Andric 
23695ffd83dbSDimitry Andric       // If there's an element size mismatch, insert intermediate casts to match
23705ffd83dbSDimitry Andric       // the result element type.
23715ffd83dbSDimitry Andric       if (NumSrcElt < NumDstElt) { // Source element type is larger.
23725ffd83dbSDimitry Andric         // %1:_(<4 x s8>) = G_BITCAST %0:_(<2 x s16>)
23735ffd83dbSDimitry Andric         //
23745ffd83dbSDimitry Andric         // =>
23755ffd83dbSDimitry Andric         //
23765ffd83dbSDimitry Andric         // %2:_(s16), %3:_(s16) = G_UNMERGE_VALUES %0
23775ffd83dbSDimitry Andric         // %3:_(<2 x s8>) = G_BITCAST %2
23785ffd83dbSDimitry Andric         // %4:_(<2 x s8>) = G_BITCAST %3
23795ffd83dbSDimitry Andric         // %1:_(<4 x s16>) = G_CONCAT_VECTORS %3, %4
23805ffd83dbSDimitry Andric         DstCastTy = LLT::vector(NumDstElt / NumSrcElt, DstEltTy);
23815ffd83dbSDimitry Andric         SrcPartTy = SrcEltTy;
23825ffd83dbSDimitry Andric       } else if (NumSrcElt > NumDstElt) { // Source element type is smaller.
23835ffd83dbSDimitry Andric         //
23845ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BITCAST %0:_(<4 x s8>)
23855ffd83dbSDimitry Andric         //
23865ffd83dbSDimitry Andric         // =>
23875ffd83dbSDimitry Andric         //
23885ffd83dbSDimitry Andric         // %2:_(<2 x s8>), %3:_(<2 x s8>) = G_UNMERGE_VALUES %0
23895ffd83dbSDimitry Andric         // %3:_(s16) = G_BITCAST %2
23905ffd83dbSDimitry Andric         // %4:_(s16) = G_BITCAST %3
23915ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BUILD_VECTOR %3, %4
23925ffd83dbSDimitry Andric         SrcPartTy = LLT::vector(NumSrcElt / NumDstElt, SrcEltTy);
23935ffd83dbSDimitry Andric         DstCastTy = DstEltTy;
23945ffd83dbSDimitry Andric       }
23955ffd83dbSDimitry Andric 
23965ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcPartTy);
23975ffd83dbSDimitry Andric       for (Register &SrcReg : SrcRegs)
23985ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(DstCastTy, SrcReg).getReg(0);
23995ffd83dbSDimitry Andric     } else
24005ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcEltTy);
24015ffd83dbSDimitry Andric 
24025ffd83dbSDimitry Andric     MIRBuilder.buildMerge(Dst, SrcRegs);
24035ffd83dbSDimitry Andric     MI.eraseFromParent();
24045ffd83dbSDimitry Andric     return Legalized;
24055ffd83dbSDimitry Andric   }
24065ffd83dbSDimitry Andric 
24075ffd83dbSDimitry Andric   if (DstTy.isVector()) {
24085ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
24095ffd83dbSDimitry Andric     getUnmergePieces(SrcRegs, MIRBuilder, Src, DstTy.getElementType());
24105ffd83dbSDimitry Andric     MIRBuilder.buildMerge(Dst, SrcRegs);
24115ffd83dbSDimitry Andric     MI.eraseFromParent();
24125ffd83dbSDimitry Andric     return Legalized;
24135ffd83dbSDimitry Andric   }
24145ffd83dbSDimitry Andric 
24155ffd83dbSDimitry Andric   return UnableToLegalize;
24165ffd83dbSDimitry Andric }
24175ffd83dbSDimitry Andric 
2418e8d8bef9SDimitry Andric /// Figure out the bit offset into a register when coercing a vector index for
2419e8d8bef9SDimitry Andric /// the wide element type. This is only for the case when promoting vector to
2420e8d8bef9SDimitry Andric /// one with larger elements.
2421e8d8bef9SDimitry Andric //
2422e8d8bef9SDimitry Andric ///
2423e8d8bef9SDimitry Andric /// %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2424e8d8bef9SDimitry Andric /// %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2425e8d8bef9SDimitry Andric static Register getBitcastWiderVectorElementOffset(MachineIRBuilder &B,
2426e8d8bef9SDimitry Andric                                                    Register Idx,
2427e8d8bef9SDimitry Andric                                                    unsigned NewEltSize,
2428e8d8bef9SDimitry Andric                                                    unsigned OldEltSize) {
2429e8d8bef9SDimitry Andric   const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2430e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(Idx);
2431e8d8bef9SDimitry Andric 
2432e8d8bef9SDimitry Andric   // Now figure out the amount we need to shift to get the target bits.
2433e8d8bef9SDimitry Andric   auto OffsetMask = B.buildConstant(
2434e8d8bef9SDimitry Andric     IdxTy, ~(APInt::getAllOnesValue(IdxTy.getSizeInBits()) << Log2EltRatio));
2435e8d8bef9SDimitry Andric   auto OffsetIdx = B.buildAnd(IdxTy, Idx, OffsetMask);
2436e8d8bef9SDimitry Andric   return B.buildShl(IdxTy, OffsetIdx,
2437e8d8bef9SDimitry Andric                     B.buildConstant(IdxTy, Log2_32(OldEltSize))).getReg(0);
2438e8d8bef9SDimitry Andric }
2439e8d8bef9SDimitry Andric 
2440e8d8bef9SDimitry Andric /// Perform a G_EXTRACT_VECTOR_ELT in a different sized vector element. If this
2441e8d8bef9SDimitry Andric /// is casting to a vector with a smaller element size, perform multiple element
2442e8d8bef9SDimitry Andric /// extracts and merge the results. If this is coercing to a vector with larger
2443e8d8bef9SDimitry Andric /// elements, index the bitcasted vector and extract the target element with bit
2444e8d8bef9SDimitry Andric /// operations. This is intended to force the indexing in the native register
2445e8d8bef9SDimitry Andric /// size for architectures that can dynamically index the register file.
24465ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
2447e8d8bef9SDimitry Andric LegalizerHelper::bitcastExtractVectorElt(MachineInstr &MI, unsigned TypeIdx,
2448e8d8bef9SDimitry Andric                                          LLT CastTy) {
2449e8d8bef9SDimitry Andric   if (TypeIdx != 1)
2450e8d8bef9SDimitry Andric     return UnableToLegalize;
2451e8d8bef9SDimitry Andric 
2452e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2453e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
2454e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(2).getReg();
2455e8d8bef9SDimitry Andric   LLT SrcVecTy = MRI.getType(SrcVec);
2456e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Idx);
2457e8d8bef9SDimitry Andric 
2458e8d8bef9SDimitry Andric   LLT SrcEltTy = SrcVecTy.getElementType();
2459e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2460e8d8bef9SDimitry Andric   unsigned OldNumElts = SrcVecTy.getNumElements();
2461e8d8bef9SDimitry Andric 
2462e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2463e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2464e8d8bef9SDimitry Andric 
2465e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2466e8d8bef9SDimitry Andric   const unsigned OldEltSize = SrcEltTy.getSizeInBits();
2467e8d8bef9SDimitry Andric   if (NewNumElts > OldNumElts) {
2468e8d8bef9SDimitry Andric     // Decreasing the vector element size
2469e8d8bef9SDimitry Andric     //
2470e8d8bef9SDimitry Andric     // e.g. i64 = extract_vector_elt x:v2i64, y:i32
2471e8d8bef9SDimitry Andric     //  =>
2472e8d8bef9SDimitry Andric     //  v4i32:castx = bitcast x:v2i64
2473e8d8bef9SDimitry Andric     //
2474e8d8bef9SDimitry Andric     // i64 = bitcast
2475e8d8bef9SDimitry Andric     //   (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
2476e8d8bef9SDimitry Andric     //                       (i32 (extract_vector_elt castx, (2 * y + 1)))
2477e8d8bef9SDimitry Andric     //
2478e8d8bef9SDimitry Andric     if (NewNumElts % OldNumElts != 0)
2479e8d8bef9SDimitry Andric       return UnableToLegalize;
2480e8d8bef9SDimitry Andric 
2481e8d8bef9SDimitry Andric     // Type of the intermediate result vector.
2482e8d8bef9SDimitry Andric     const unsigned NewEltsPerOldElt = NewNumElts / OldNumElts;
2483e8d8bef9SDimitry Andric     LLT MidTy = LLT::scalarOrVector(NewEltsPerOldElt, NewEltTy);
2484e8d8bef9SDimitry Andric 
2485e8d8bef9SDimitry Andric     auto NewEltsPerOldEltK = MIRBuilder.buildConstant(IdxTy, NewEltsPerOldElt);
2486e8d8bef9SDimitry Andric 
2487e8d8bef9SDimitry Andric     SmallVector<Register, 8> NewOps(NewEltsPerOldElt);
2488e8d8bef9SDimitry Andric     auto NewBaseIdx = MIRBuilder.buildMul(IdxTy, Idx, NewEltsPerOldEltK);
2489e8d8bef9SDimitry Andric 
2490e8d8bef9SDimitry Andric     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
2491e8d8bef9SDimitry Andric       auto IdxOffset = MIRBuilder.buildConstant(IdxTy, I);
2492e8d8bef9SDimitry Andric       auto TmpIdx = MIRBuilder.buildAdd(IdxTy, NewBaseIdx, IdxOffset);
2493e8d8bef9SDimitry Andric       auto Elt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec, TmpIdx);
2494e8d8bef9SDimitry Andric       NewOps[I] = Elt.getReg(0);
2495e8d8bef9SDimitry Andric     }
2496e8d8bef9SDimitry Andric 
2497e8d8bef9SDimitry Andric     auto NewVec = MIRBuilder.buildBuildVector(MidTy, NewOps);
2498e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, NewVec);
2499e8d8bef9SDimitry Andric     MI.eraseFromParent();
2500e8d8bef9SDimitry Andric     return Legalized;
2501e8d8bef9SDimitry Andric   }
2502e8d8bef9SDimitry Andric 
2503e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2504e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
2505e8d8bef9SDimitry Andric       return UnableToLegalize;
2506e8d8bef9SDimitry Andric 
2507e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2508e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2509e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2510e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
2511e8d8bef9SDimitry Andric       return UnableToLegalize;
2512e8d8bef9SDimitry Andric 
2513e8d8bef9SDimitry Andric     // Increasing the vector element size.
2514e8d8bef9SDimitry Andric     // %elt:_(small_elt) = G_EXTRACT_VECTOR_ELT %vec:_(<N x small_elt>), %idx
2515e8d8bef9SDimitry Andric     //
2516e8d8bef9SDimitry Andric     //   =>
2517e8d8bef9SDimitry Andric     //
2518e8d8bef9SDimitry Andric     // %cast = G_BITCAST %vec
2519e8d8bef9SDimitry Andric     // %scaled_idx = G_LSHR %idx, Log2(DstEltSize / SrcEltSize)
2520e8d8bef9SDimitry Andric     // %wide_elt  = G_EXTRACT_VECTOR_ELT %cast, %scaled_idx
2521e8d8bef9SDimitry Andric     // %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2522e8d8bef9SDimitry Andric     // %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2523e8d8bef9SDimitry Andric     // %elt_bits = G_LSHR %wide_elt, %offset_bits
2524e8d8bef9SDimitry Andric     // %elt = G_TRUNC %elt_bits
2525e8d8bef9SDimitry Andric 
2526e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2527e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2528e8d8bef9SDimitry Andric 
2529e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2530e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2531e8d8bef9SDimitry Andric 
2532e8d8bef9SDimitry Andric     Register WideElt = CastVec;
2533e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2534e8d8bef9SDimitry Andric       WideElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2535e8d8bef9SDimitry Andric                                                      ScaledIdx).getReg(0);
2536e8d8bef9SDimitry Andric     }
2537e8d8bef9SDimitry Andric 
2538e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2539e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2540e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2541e8d8bef9SDimitry Andric 
2542e8d8bef9SDimitry Andric     // Shift the wide element to get the target element.
2543e8d8bef9SDimitry Andric     auto ExtractedBits = MIRBuilder.buildLShr(NewEltTy, WideElt, OffsetBits);
2544e8d8bef9SDimitry Andric     MIRBuilder.buildTrunc(Dst, ExtractedBits);
2545e8d8bef9SDimitry Andric     MI.eraseFromParent();
2546e8d8bef9SDimitry Andric     return Legalized;
2547e8d8bef9SDimitry Andric   }
2548e8d8bef9SDimitry Andric 
2549e8d8bef9SDimitry Andric   return UnableToLegalize;
2550e8d8bef9SDimitry Andric }
2551e8d8bef9SDimitry Andric 
2552e8d8bef9SDimitry Andric /// Emit code to insert \p InsertReg into \p TargetRet at \p OffsetBits in \p
2553e8d8bef9SDimitry Andric /// TargetReg, while preserving other bits in \p TargetReg.
2554e8d8bef9SDimitry Andric ///
2555e8d8bef9SDimitry Andric /// (InsertReg << Offset) | (TargetReg & ~(-1 >> InsertReg.size()) << Offset)
2556e8d8bef9SDimitry Andric static Register buildBitFieldInsert(MachineIRBuilder &B,
2557e8d8bef9SDimitry Andric                                     Register TargetReg, Register InsertReg,
2558e8d8bef9SDimitry Andric                                     Register OffsetBits) {
2559e8d8bef9SDimitry Andric   LLT TargetTy = B.getMRI()->getType(TargetReg);
2560e8d8bef9SDimitry Andric   LLT InsertTy = B.getMRI()->getType(InsertReg);
2561e8d8bef9SDimitry Andric   auto ZextVal = B.buildZExt(TargetTy, InsertReg);
2562e8d8bef9SDimitry Andric   auto ShiftedInsertVal = B.buildShl(TargetTy, ZextVal, OffsetBits);
2563e8d8bef9SDimitry Andric 
2564e8d8bef9SDimitry Andric   // Produce a bitmask of the value to insert
2565e8d8bef9SDimitry Andric   auto EltMask = B.buildConstant(
2566e8d8bef9SDimitry Andric     TargetTy, APInt::getLowBitsSet(TargetTy.getSizeInBits(),
2567e8d8bef9SDimitry Andric                                    InsertTy.getSizeInBits()));
2568e8d8bef9SDimitry Andric   // Shift it into position
2569e8d8bef9SDimitry Andric   auto ShiftedMask = B.buildShl(TargetTy, EltMask, OffsetBits);
2570e8d8bef9SDimitry Andric   auto InvShiftedMask = B.buildNot(TargetTy, ShiftedMask);
2571e8d8bef9SDimitry Andric 
2572e8d8bef9SDimitry Andric   // Clear out the bits in the wide element
2573e8d8bef9SDimitry Andric   auto MaskedOldElt = B.buildAnd(TargetTy, TargetReg, InvShiftedMask);
2574e8d8bef9SDimitry Andric 
2575e8d8bef9SDimitry Andric   // The value to insert has all zeros already, so stick it into the masked
2576e8d8bef9SDimitry Andric   // wide element.
2577e8d8bef9SDimitry Andric   return B.buildOr(TargetTy, MaskedOldElt, ShiftedInsertVal).getReg(0);
2578e8d8bef9SDimitry Andric }
2579e8d8bef9SDimitry Andric 
2580e8d8bef9SDimitry Andric /// Perform a G_INSERT_VECTOR_ELT in a different sized vector element. If this
2581e8d8bef9SDimitry Andric /// is increasing the element size, perform the indexing in the target element
2582e8d8bef9SDimitry Andric /// type, and use bit operations to insert at the element position. This is
2583e8d8bef9SDimitry Andric /// intended for architectures that can dynamically index the register file and
2584e8d8bef9SDimitry Andric /// want to force indexing in the native register size.
2585e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2586e8d8bef9SDimitry Andric LegalizerHelper::bitcastInsertVectorElt(MachineInstr &MI, unsigned TypeIdx,
2587e8d8bef9SDimitry Andric                                         LLT CastTy) {
25885ffd83dbSDimitry Andric   if (TypeIdx != 0)
25895ffd83dbSDimitry Andric     return UnableToLegalize;
25905ffd83dbSDimitry Andric 
2591e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2592e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
2593e8d8bef9SDimitry Andric   Register Val = MI.getOperand(2).getReg();
2594e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(3).getReg();
2595e8d8bef9SDimitry Andric 
2596e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(Dst);
2597e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Idx);
2598e8d8bef9SDimitry Andric 
2599e8d8bef9SDimitry Andric   LLT VecEltTy = VecTy.getElementType();
2600e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2601e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2602e8d8bef9SDimitry Andric   const unsigned OldEltSize = VecEltTy.getSizeInBits();
2603e8d8bef9SDimitry Andric 
2604e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2605e8d8bef9SDimitry Andric   unsigned OldNumElts = VecTy.getNumElements();
2606e8d8bef9SDimitry Andric 
2607e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2608e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2609e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
26105ffd83dbSDimitry Andric       return UnableToLegalize;
26115ffd83dbSDimitry Andric 
2612e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2613e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2614e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2615e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
26165ffd83dbSDimitry Andric       return UnableToLegalize;
26175ffd83dbSDimitry Andric 
2618e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2619e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2620e8d8bef9SDimitry Andric 
2621e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2622e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2623e8d8bef9SDimitry Andric 
2624e8d8bef9SDimitry Andric     Register ExtractedElt = CastVec;
2625e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2626e8d8bef9SDimitry Andric       ExtractedElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2627e8d8bef9SDimitry Andric                                                           ScaledIdx).getReg(0);
26285ffd83dbSDimitry Andric     }
26295ffd83dbSDimitry Andric 
2630e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2631e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2632e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2633e8d8bef9SDimitry Andric 
2634e8d8bef9SDimitry Andric     Register InsertedElt = buildBitFieldInsert(MIRBuilder, ExtractedElt,
2635e8d8bef9SDimitry Andric                                                Val, OffsetBits);
2636e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2637e8d8bef9SDimitry Andric       InsertedElt = MIRBuilder.buildInsertVectorElement(
2638e8d8bef9SDimitry Andric         CastTy, CastVec, InsertedElt, ScaledIdx).getReg(0);
2639e8d8bef9SDimitry Andric     }
2640e8d8bef9SDimitry Andric 
2641e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, InsertedElt);
2642e8d8bef9SDimitry Andric     MI.eraseFromParent();
26435ffd83dbSDimitry Andric     return Legalized;
26445ffd83dbSDimitry Andric   }
2645e8d8bef9SDimitry Andric 
26465ffd83dbSDimitry Andric   return UnableToLegalize;
26470b57cec5SDimitry Andric }
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
2650e8d8bef9SDimitry Andric LegalizerHelper::lowerLoad(MachineInstr &MI) {
26510b57cec5SDimitry Andric   // Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
26520b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
26530b57cec5SDimitry Andric   Register PtrReg = MI.getOperand(1).getReg();
26540b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
26550b57cec5SDimitry Andric   auto &MMO = **MI.memoperands_begin();
26560b57cec5SDimitry Andric 
26578bcb0991SDimitry Andric   if (DstTy.getSizeInBits() == MMO.getSizeInBits()) {
26588bcb0991SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_LOAD) {
26598bcb0991SDimitry Andric       // This load needs splitting into power of 2 sized loads.
26608bcb0991SDimitry Andric       if (DstTy.isVector())
26610b57cec5SDimitry Andric         return UnableToLegalize;
26628bcb0991SDimitry Andric       if (isPowerOf2_32(DstTy.getSizeInBits()))
26638bcb0991SDimitry Andric         return UnableToLegalize; // Don't know what we're being asked to do.
26648bcb0991SDimitry Andric 
26658bcb0991SDimitry Andric       // Our strategy here is to generate anyextending loads for the smaller
26668bcb0991SDimitry Andric       // types up to next power-2 result type, and then combine the two larger
26678bcb0991SDimitry Andric       // result values together, before truncating back down to the non-pow-2
26688bcb0991SDimitry Andric       // type.
26698bcb0991SDimitry Andric       // E.g. v1 = i24 load =>
26705ffd83dbSDimitry Andric       // v2 = i32 zextload (2 byte)
26718bcb0991SDimitry Andric       // v3 = i32 load (1 byte)
26728bcb0991SDimitry Andric       // v4 = i32 shl v3, 16
26738bcb0991SDimitry Andric       // v5 = i32 or v4, v2
26748bcb0991SDimitry Andric       // v1 = i24 trunc v5
26758bcb0991SDimitry Andric       // By doing this we generate the correct truncate which should get
26768bcb0991SDimitry Andric       // combined away as an artifact with a matching extend.
26778bcb0991SDimitry Andric       uint64_t LargeSplitSize = PowerOf2Floor(DstTy.getSizeInBits());
26788bcb0991SDimitry Andric       uint64_t SmallSplitSize = DstTy.getSizeInBits() - LargeSplitSize;
26798bcb0991SDimitry Andric 
26808bcb0991SDimitry Andric       MachineFunction &MF = MIRBuilder.getMF();
26818bcb0991SDimitry Andric       MachineMemOperand *LargeMMO =
26828bcb0991SDimitry Andric         MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
26838bcb0991SDimitry Andric       MachineMemOperand *SmallMMO = MF.getMachineMemOperand(
26848bcb0991SDimitry Andric         &MMO, LargeSplitSize / 8, SmallSplitSize / 8);
26858bcb0991SDimitry Andric 
26868bcb0991SDimitry Andric       LLT PtrTy = MRI.getType(PtrReg);
26878bcb0991SDimitry Andric       unsigned AnyExtSize = NextPowerOf2(DstTy.getSizeInBits());
26888bcb0991SDimitry Andric       LLT AnyExtTy = LLT::scalar(AnyExtSize);
26898bcb0991SDimitry Andric       Register LargeLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
26908bcb0991SDimitry Andric       Register SmallLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
26915ffd83dbSDimitry Andric       auto LargeLoad = MIRBuilder.buildLoadInstr(
26925ffd83dbSDimitry Andric         TargetOpcode::G_ZEXTLOAD, LargeLdReg, PtrReg, *LargeMMO);
26938bcb0991SDimitry Andric 
26945ffd83dbSDimitry Andric       auto OffsetCst = MIRBuilder.buildConstant(
26955ffd83dbSDimitry Andric         LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2696480093f4SDimitry Andric       Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2697480093f4SDimitry Andric       auto SmallPtr =
2698480093f4SDimitry Andric         MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
26998bcb0991SDimitry Andric       auto SmallLoad = MIRBuilder.buildLoad(SmallLdReg, SmallPtr.getReg(0),
27008bcb0991SDimitry Andric                                             *SmallMMO);
27018bcb0991SDimitry Andric 
27028bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(AnyExtTy, LargeSplitSize);
27038bcb0991SDimitry Andric       auto Shift = MIRBuilder.buildShl(AnyExtTy, SmallLoad, ShiftAmt);
27048bcb0991SDimitry Andric       auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
27058bcb0991SDimitry Andric       MIRBuilder.buildTrunc(DstReg, {Or.getReg(0)});
27068bcb0991SDimitry Andric       MI.eraseFromParent();
27078bcb0991SDimitry Andric       return Legalized;
27088bcb0991SDimitry Andric     }
2709e8d8bef9SDimitry Andric 
27100b57cec5SDimitry Andric     MIRBuilder.buildLoad(DstReg, PtrReg, MMO);
27110b57cec5SDimitry Andric     MI.eraseFromParent();
27120b57cec5SDimitry Andric     return Legalized;
27130b57cec5SDimitry Andric   }
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric   if (DstTy.isScalar()) {
27160b57cec5SDimitry Andric     Register TmpReg =
27170b57cec5SDimitry Andric       MRI.createGenericVirtualRegister(LLT::scalar(MMO.getSizeInBits()));
27180b57cec5SDimitry Andric     MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
27190b57cec5SDimitry Andric     switch (MI.getOpcode()) {
27200b57cec5SDimitry Andric     default:
27210b57cec5SDimitry Andric       llvm_unreachable("Unexpected opcode");
27220b57cec5SDimitry Andric     case TargetOpcode::G_LOAD:
2723e8d8bef9SDimitry Andric       MIRBuilder.buildAnyExtOrTrunc(DstReg, TmpReg);
27240b57cec5SDimitry Andric       break;
27250b57cec5SDimitry Andric     case TargetOpcode::G_SEXTLOAD:
27260b57cec5SDimitry Andric       MIRBuilder.buildSExt(DstReg, TmpReg);
27270b57cec5SDimitry Andric       break;
27280b57cec5SDimitry Andric     case TargetOpcode::G_ZEXTLOAD:
27290b57cec5SDimitry Andric       MIRBuilder.buildZExt(DstReg, TmpReg);
27300b57cec5SDimitry Andric       break;
27310b57cec5SDimitry Andric     }
2732e8d8bef9SDimitry Andric 
27330b57cec5SDimitry Andric     MI.eraseFromParent();
27340b57cec5SDimitry Andric     return Legalized;
27350b57cec5SDimitry Andric   }
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric   return UnableToLegalize;
27380b57cec5SDimitry Andric }
2739e8d8bef9SDimitry Andric 
2740e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2741e8d8bef9SDimitry Andric LegalizerHelper::lowerStore(MachineInstr &MI) {
27428bcb0991SDimitry Andric   // Lower a non-power of 2 store into multiple pow-2 stores.
27438bcb0991SDimitry Andric   // E.g. split an i24 store into an i16 store + i8 store.
27448bcb0991SDimitry Andric   // We do this by first extending the stored value to the next largest power
27458bcb0991SDimitry Andric   // of 2 type, and then using truncating stores to store the components.
27468bcb0991SDimitry Andric   // By doing this, likewise with G_LOAD, generate an extend that can be
27478bcb0991SDimitry Andric   // artifact-combined away instead of leaving behind extracts.
27488bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(0).getReg();
27498bcb0991SDimitry Andric   Register PtrReg = MI.getOperand(1).getReg();
27508bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
27518bcb0991SDimitry Andric   MachineMemOperand &MMO = **MI.memoperands_begin();
27528bcb0991SDimitry Andric   if (SrcTy.getSizeInBits() != MMO.getSizeInBits())
27538bcb0991SDimitry Andric     return UnableToLegalize;
27548bcb0991SDimitry Andric   if (SrcTy.isVector())
27558bcb0991SDimitry Andric     return UnableToLegalize;
27568bcb0991SDimitry Andric   if (isPowerOf2_32(SrcTy.getSizeInBits()))
27578bcb0991SDimitry Andric     return UnableToLegalize; // Don't know what we're being asked to do.
27588bcb0991SDimitry Andric 
27598bcb0991SDimitry Andric   // Extend to the next pow-2.
27608bcb0991SDimitry Andric   const LLT ExtendTy = LLT::scalar(NextPowerOf2(SrcTy.getSizeInBits()));
27618bcb0991SDimitry Andric   auto ExtVal = MIRBuilder.buildAnyExt(ExtendTy, SrcReg);
27628bcb0991SDimitry Andric 
27638bcb0991SDimitry Andric   // Obtain the smaller value by shifting away the larger value.
27648bcb0991SDimitry Andric   uint64_t LargeSplitSize = PowerOf2Floor(SrcTy.getSizeInBits());
27658bcb0991SDimitry Andric   uint64_t SmallSplitSize = SrcTy.getSizeInBits() - LargeSplitSize;
27668bcb0991SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(ExtendTy, LargeSplitSize);
27678bcb0991SDimitry Andric   auto SmallVal = MIRBuilder.buildLShr(ExtendTy, ExtVal, ShiftAmt);
27688bcb0991SDimitry Andric 
2769480093f4SDimitry Andric   // Generate the PtrAdd and truncating stores.
27708bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(PtrReg);
27715ffd83dbSDimitry Andric   auto OffsetCst = MIRBuilder.buildConstant(
27725ffd83dbSDimitry Andric     LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2773480093f4SDimitry Andric   Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2774480093f4SDimitry Andric   auto SmallPtr =
2775480093f4SDimitry Andric     MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
27768bcb0991SDimitry Andric 
27778bcb0991SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
27788bcb0991SDimitry Andric   MachineMemOperand *LargeMMO =
27798bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
27808bcb0991SDimitry Andric   MachineMemOperand *SmallMMO =
27818bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
27828bcb0991SDimitry Andric   MIRBuilder.buildStore(ExtVal.getReg(0), PtrReg, *LargeMMO);
27838bcb0991SDimitry Andric   MIRBuilder.buildStore(SmallVal.getReg(0), SmallPtr.getReg(0), *SmallMMO);
27848bcb0991SDimitry Andric   MI.eraseFromParent();
27858bcb0991SDimitry Andric   return Legalized;
27868bcb0991SDimitry Andric }
2787e8d8bef9SDimitry Andric 
2788e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2789e8d8bef9SDimitry Andric LegalizerHelper::bitcast(MachineInstr &MI, unsigned TypeIdx, LLT CastTy) {
2790e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
2791e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD: {
2792e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2793e8d8bef9SDimitry Andric       return UnableToLegalize;
2794e8d8bef9SDimitry Andric 
2795e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2796e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
2797e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2798e8d8bef9SDimitry Andric     return Legalized;
2799e8d8bef9SDimitry Andric   }
2800e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE: {
2801e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2802e8d8bef9SDimitry Andric       return UnableToLegalize;
2803e8d8bef9SDimitry Andric 
2804e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2805e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 0);
2806e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2807e8d8bef9SDimitry Andric     return Legalized;
2808e8d8bef9SDimitry Andric   }
2809e8d8bef9SDimitry Andric   case TargetOpcode::G_SELECT: {
2810e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2811e8d8bef9SDimitry Andric       return UnableToLegalize;
2812e8d8bef9SDimitry Andric 
2813e8d8bef9SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector()) {
2814e8d8bef9SDimitry Andric       LLVM_DEBUG(
2815e8d8bef9SDimitry Andric           dbgs() << "bitcast action not implemented for vector select\n");
2816e8d8bef9SDimitry Andric       return UnableToLegalize;
2817e8d8bef9SDimitry Andric     }
2818e8d8bef9SDimitry Andric 
2819e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2820e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
2821e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 3);
2822e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
2823e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2824e8d8bef9SDimitry Andric     return Legalized;
2825e8d8bef9SDimitry Andric   }
2826e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
2827e8d8bef9SDimitry Andric   case TargetOpcode::G_OR:
2828e8d8bef9SDimitry Andric   case TargetOpcode::G_XOR: {
2829e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2830e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 1);
2831e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
2832e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
2833e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2834e8d8bef9SDimitry Andric     return Legalized;
2835e8d8bef9SDimitry Andric   }
2836e8d8bef9SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
2837e8d8bef9SDimitry Andric     return bitcastExtractVectorElt(MI, TypeIdx, CastTy);
2838e8d8bef9SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT:
2839e8d8bef9SDimitry Andric     return bitcastInsertVectorElt(MI, TypeIdx, CastTy);
2840e8d8bef9SDimitry Andric   default:
2841e8d8bef9SDimitry Andric     return UnableToLegalize;
2842e8d8bef9SDimitry Andric   }
2843e8d8bef9SDimitry Andric }
2844e8d8bef9SDimitry Andric 
2845e8d8bef9SDimitry Andric // Legalize an instruction by changing the opcode in place.
2846e8d8bef9SDimitry Andric void LegalizerHelper::changeOpcode(MachineInstr &MI, unsigned NewOpcode) {
2847e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2848e8d8bef9SDimitry Andric     MI.setDesc(MIRBuilder.getTII().get(NewOpcode));
2849e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2850e8d8bef9SDimitry Andric }
2851e8d8bef9SDimitry Andric 
2852e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2853e8d8bef9SDimitry Andric LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT LowerHintTy) {
2854e8d8bef9SDimitry Andric   using namespace TargetOpcode;
2855e8d8bef9SDimitry Andric 
2856e8d8bef9SDimitry Andric   switch(MI.getOpcode()) {
2857e8d8bef9SDimitry Andric   default:
2858e8d8bef9SDimitry Andric     return UnableToLegalize;
2859e8d8bef9SDimitry Andric   case TargetOpcode::G_BITCAST:
2860e8d8bef9SDimitry Andric     return lowerBitcast(MI);
2861e8d8bef9SDimitry Andric   case TargetOpcode::G_SREM:
2862e8d8bef9SDimitry Andric   case TargetOpcode::G_UREM: {
2863e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2864e8d8bef9SDimitry Andric     auto Quot =
2865e8d8bef9SDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV, {Ty},
2866e8d8bef9SDimitry Andric                               {MI.getOperand(1), MI.getOperand(2)});
2867e8d8bef9SDimitry Andric 
2868e8d8bef9SDimitry Andric     auto Prod = MIRBuilder.buildMul(Ty, Quot, MI.getOperand(2));
2869e8d8bef9SDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MI.getOperand(1), Prod);
2870e8d8bef9SDimitry Andric     MI.eraseFromParent();
2871e8d8bef9SDimitry Andric     return Legalized;
2872e8d8bef9SDimitry Andric   }
2873e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
2874e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
2875e8d8bef9SDimitry Andric     return lowerSADDO_SSUBO(MI);
2876e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULH:
2877e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULH:
2878e8d8bef9SDimitry Andric     return lowerSMULH_UMULH(MI);
2879e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULO:
2880e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULO: {
2881e8d8bef9SDimitry Andric     // Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
2882e8d8bef9SDimitry Andric     // result.
2883e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
2884e8d8bef9SDimitry Andric     Register Overflow = MI.getOperand(1).getReg();
2885e8d8bef9SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
2886e8d8bef9SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
2887e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
2888e8d8bef9SDimitry Andric 
2889e8d8bef9SDimitry Andric     unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
2890e8d8bef9SDimitry Andric                           ? TargetOpcode::G_SMULH
2891e8d8bef9SDimitry Andric                           : TargetOpcode::G_UMULH;
2892e8d8bef9SDimitry Andric 
2893e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2894e8d8bef9SDimitry Andric     const auto &TII = MIRBuilder.getTII();
2895e8d8bef9SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_MUL));
2896e8d8bef9SDimitry Andric     MI.RemoveOperand(1);
2897e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2898e8d8bef9SDimitry Andric 
2899e8d8bef9SDimitry Andric     auto HiPart = MIRBuilder.buildInstr(Opcode, {Ty}, {LHS, RHS});
2900e8d8bef9SDimitry Andric     auto Zero = MIRBuilder.buildConstant(Ty, 0);
2901e8d8bef9SDimitry Andric 
2902e8d8bef9SDimitry Andric     // Move insert point forward so we can use the Res register if needed.
2903e8d8bef9SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
2904e8d8bef9SDimitry Andric 
2905e8d8bef9SDimitry Andric     // For *signed* multiply, overflow is detected by checking:
2906e8d8bef9SDimitry Andric     // (hi != (lo >> bitwidth-1))
2907e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SMULH) {
2908e8d8bef9SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(Ty, Ty.getSizeInBits() - 1);
2909e8d8bef9SDimitry Andric       auto Shifted = MIRBuilder.buildAShr(Ty, Res, ShiftAmt);
2910e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
2911e8d8bef9SDimitry Andric     } else {
2912e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
2913e8d8bef9SDimitry Andric     }
2914e8d8bef9SDimitry Andric     return Legalized;
2915e8d8bef9SDimitry Andric   }
2916e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
2917e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
2918e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
2919e8d8bef9SDimitry Andric 
2920e8d8bef9SDimitry Andric     // TODO: Handle vector types once we are able to
2921e8d8bef9SDimitry Andric     // represent them.
2922e8d8bef9SDimitry Andric     if (Ty.isVector())
2923e8d8bef9SDimitry Andric       return UnableToLegalize;
2924e8d8bef9SDimitry Andric     auto SignMask =
2925e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignMask(Ty.getSizeInBits()));
2926e8d8bef9SDimitry Andric     Register SubByReg = MI.getOperand(1).getReg();
2927e8d8bef9SDimitry Andric     MIRBuilder.buildXor(Res, SubByReg, SignMask);
2928e8d8bef9SDimitry Andric     MI.eraseFromParent();
2929e8d8bef9SDimitry Andric     return Legalized;
2930e8d8bef9SDimitry Andric   }
2931e8d8bef9SDimitry Andric   case TargetOpcode::G_FSUB: {
2932e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
2933e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
2934e8d8bef9SDimitry Andric 
2935e8d8bef9SDimitry Andric     // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
2936e8d8bef9SDimitry Andric     // First, check if G_FNEG is marked as Lower. If so, we may
2937e8d8bef9SDimitry Andric     // end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
2938e8d8bef9SDimitry Andric     if (LI.getAction({G_FNEG, {Ty}}).Action == Lower)
2939e8d8bef9SDimitry Andric       return UnableToLegalize;
2940e8d8bef9SDimitry Andric     Register LHS = MI.getOperand(1).getReg();
2941e8d8bef9SDimitry Andric     Register RHS = MI.getOperand(2).getReg();
2942e8d8bef9SDimitry Andric     Register Neg = MRI.createGenericVirtualRegister(Ty);
2943e8d8bef9SDimitry Andric     MIRBuilder.buildFNeg(Neg, RHS);
2944e8d8bef9SDimitry Andric     MIRBuilder.buildFAdd(Res, LHS, Neg, MI.getFlags());
2945e8d8bef9SDimitry Andric     MI.eraseFromParent();
2946e8d8bef9SDimitry Andric     return Legalized;
2947e8d8bef9SDimitry Andric   }
2948e8d8bef9SDimitry Andric   case TargetOpcode::G_FMAD:
2949e8d8bef9SDimitry Andric     return lowerFMad(MI);
2950e8d8bef9SDimitry Andric   case TargetOpcode::G_FFLOOR:
2951e8d8bef9SDimitry Andric     return lowerFFloor(MI);
2952e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
2953e8d8bef9SDimitry Andric     return lowerIntrinsicRound(MI);
2954e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
2955e8d8bef9SDimitry Andric     // Since round even is the assumed rounding mode for unconstrained FP
2956e8d8bef9SDimitry Andric     // operations, rint and roundeven are the same operation.
2957e8d8bef9SDimitry Andric     changeOpcode(MI, TargetOpcode::G_FRINT);
2958e8d8bef9SDimitry Andric     return Legalized;
2959e8d8bef9SDimitry Andric   }
2960e8d8bef9SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
2961e8d8bef9SDimitry Andric     Register OldValRes = MI.getOperand(0).getReg();
2962e8d8bef9SDimitry Andric     Register SuccessRes = MI.getOperand(1).getReg();
2963e8d8bef9SDimitry Andric     Register Addr = MI.getOperand(2).getReg();
2964e8d8bef9SDimitry Andric     Register CmpVal = MI.getOperand(3).getReg();
2965e8d8bef9SDimitry Andric     Register NewVal = MI.getOperand(4).getReg();
2966e8d8bef9SDimitry Andric     MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
2967e8d8bef9SDimitry Andric                                   **MI.memoperands_begin());
2968e8d8bef9SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
2969e8d8bef9SDimitry Andric     MI.eraseFromParent();
2970e8d8bef9SDimitry Andric     return Legalized;
2971e8d8bef9SDimitry Andric   }
2972e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD:
2973e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
2974e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
2975e8d8bef9SDimitry Andric     return lowerLoad(MI);
2976e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE:
2977e8d8bef9SDimitry Andric     return lowerStore(MI);
29780b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
29790b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
29800b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
29810b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
29820b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP:
2983e8d8bef9SDimitry Andric     return lowerBitCount(MI);
29840b57cec5SDimitry Andric   case G_UADDO: {
29850b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
29860b57cec5SDimitry Andric     Register CarryOut = MI.getOperand(1).getReg();
29870b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
29880b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, LHS, RHS);
29910b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, RHS);
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric     MI.eraseFromParent();
29940b57cec5SDimitry Andric     return Legalized;
29950b57cec5SDimitry Andric   }
29960b57cec5SDimitry Andric   case G_UADDE: {
29970b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
29980b57cec5SDimitry Andric     Register CarryOut = MI.getOperand(1).getReg();
29990b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
30000b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
30010b57cec5SDimitry Andric     Register CarryIn = MI.getOperand(4).getReg();
30025ffd83dbSDimitry Andric     LLT Ty = MRI.getType(Res);
30030b57cec5SDimitry Andric 
30045ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildAdd(Ty, LHS, RHS);
30055ffd83dbSDimitry Andric     auto ZExtCarryIn = MIRBuilder.buildZExt(Ty, CarryIn);
30060b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
30070b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
30080b57cec5SDimitry Andric 
30090b57cec5SDimitry Andric     MI.eraseFromParent();
30100b57cec5SDimitry Andric     return Legalized;
30110b57cec5SDimitry Andric   }
30120b57cec5SDimitry Andric   case G_USUBO: {
30130b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
30140b57cec5SDimitry Andric     Register BorrowOut = MI.getOperand(1).getReg();
30150b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
30160b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, LHS, RHS);
30190b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric     MI.eraseFromParent();
30220b57cec5SDimitry Andric     return Legalized;
30230b57cec5SDimitry Andric   }
30240b57cec5SDimitry Andric   case G_USUBE: {
30250b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
30260b57cec5SDimitry Andric     Register BorrowOut = MI.getOperand(1).getReg();
30270b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
30280b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
30290b57cec5SDimitry Andric     Register BorrowIn = MI.getOperand(4).getReg();
30305ffd83dbSDimitry Andric     const LLT CondTy = MRI.getType(BorrowOut);
30315ffd83dbSDimitry Andric     const LLT Ty = MRI.getType(Res);
30320b57cec5SDimitry Andric 
30335ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildSub(Ty, LHS, RHS);
30345ffd83dbSDimitry Andric     auto ZExtBorrowIn = MIRBuilder.buildZExt(Ty, BorrowIn);
30350b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
30365ffd83dbSDimitry Andric 
30375ffd83dbSDimitry Andric     auto LHS_EQ_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, CondTy, LHS, RHS);
30385ffd83dbSDimitry Andric     auto LHS_ULT_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CondTy, LHS, RHS);
30390b57cec5SDimitry Andric     MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
30400b57cec5SDimitry Andric 
30410b57cec5SDimitry Andric     MI.eraseFromParent();
30420b57cec5SDimitry Andric     return Legalized;
30430b57cec5SDimitry Andric   }
30440b57cec5SDimitry Andric   case G_UITOFP:
3045e8d8bef9SDimitry Andric     return lowerUITOFP(MI);
30460b57cec5SDimitry Andric   case G_SITOFP:
3047e8d8bef9SDimitry Andric     return lowerSITOFP(MI);
30488bcb0991SDimitry Andric   case G_FPTOUI:
3049e8d8bef9SDimitry Andric     return lowerFPTOUI(MI);
30505ffd83dbSDimitry Andric   case G_FPTOSI:
30515ffd83dbSDimitry Andric     return lowerFPTOSI(MI);
30525ffd83dbSDimitry Andric   case G_FPTRUNC:
3053e8d8bef9SDimitry Andric     return lowerFPTRUNC(MI);
3054e8d8bef9SDimitry Andric   case G_FPOWI:
3055e8d8bef9SDimitry Andric     return lowerFPOWI(MI);
30560b57cec5SDimitry Andric   case G_SMIN:
30570b57cec5SDimitry Andric   case G_SMAX:
30580b57cec5SDimitry Andric   case G_UMIN:
30590b57cec5SDimitry Andric   case G_UMAX:
3060e8d8bef9SDimitry Andric     return lowerMinMax(MI);
30610b57cec5SDimitry Andric   case G_FCOPYSIGN:
3062e8d8bef9SDimitry Andric     return lowerFCopySign(MI);
30630b57cec5SDimitry Andric   case G_FMINNUM:
30640b57cec5SDimitry Andric   case G_FMAXNUM:
30650b57cec5SDimitry Andric     return lowerFMinNumMaxNum(MI);
30665ffd83dbSDimitry Andric   case G_MERGE_VALUES:
30675ffd83dbSDimitry Andric     return lowerMergeValues(MI);
30688bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
30698bcb0991SDimitry Andric     return lowerUnmergeValues(MI);
30708bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
30718bcb0991SDimitry Andric     assert(MI.getOperand(2).isImm() && "Expected immediate");
30728bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
30738bcb0991SDimitry Andric 
30748bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
30758bcb0991SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
30768bcb0991SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
30778bcb0991SDimitry Andric     Register TmpRes = MRI.createGenericVirtualRegister(DstTy);
30788bcb0991SDimitry Andric 
30798bcb0991SDimitry Andric     auto MIBSz = MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - SizeInBits);
30805ffd83dbSDimitry Andric     MIRBuilder.buildShl(TmpRes, SrcReg, MIBSz->getOperand(0));
30815ffd83dbSDimitry Andric     MIRBuilder.buildAShr(DstReg, TmpRes, MIBSz->getOperand(0));
30828bcb0991SDimitry Andric     MI.eraseFromParent();
30838bcb0991SDimitry Andric     return Legalized;
30848bcb0991SDimitry Andric   }
3085e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
3086e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
3087e8d8bef9SDimitry Andric     return lowerExtractInsertVectorElt(MI);
30888bcb0991SDimitry Andric   case G_SHUFFLE_VECTOR:
30898bcb0991SDimitry Andric     return lowerShuffleVector(MI);
30908bcb0991SDimitry Andric   case G_DYN_STACKALLOC:
30918bcb0991SDimitry Andric     return lowerDynStackAlloc(MI);
30928bcb0991SDimitry Andric   case G_EXTRACT:
30938bcb0991SDimitry Andric     return lowerExtract(MI);
30948bcb0991SDimitry Andric   case G_INSERT:
30958bcb0991SDimitry Andric     return lowerInsert(MI);
3096480093f4SDimitry Andric   case G_BSWAP:
3097480093f4SDimitry Andric     return lowerBswap(MI);
3098480093f4SDimitry Andric   case G_BITREVERSE:
3099480093f4SDimitry Andric     return lowerBitreverse(MI);
3100480093f4SDimitry Andric   case G_READ_REGISTER:
31015ffd83dbSDimitry Andric   case G_WRITE_REGISTER:
31025ffd83dbSDimitry Andric     return lowerReadWriteRegister(MI);
3103e8d8bef9SDimitry Andric   case G_UADDSAT:
3104e8d8bef9SDimitry Andric   case G_USUBSAT: {
3105e8d8bef9SDimitry Andric     // Try to make a reasonable guess about which lowering strategy to use. The
3106e8d8bef9SDimitry Andric     // target can override this with custom lowering and calling the
3107e8d8bef9SDimitry Andric     // implementation functions.
3108e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3109e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_UMIN, Ty}))
3110e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3111e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
31120b57cec5SDimitry Andric   }
3113e8d8bef9SDimitry Andric   case G_SADDSAT:
3114e8d8bef9SDimitry Andric   case G_SSUBSAT: {
3115e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3116e8d8bef9SDimitry Andric 
3117e8d8bef9SDimitry Andric     // FIXME: It would probably make more sense to see if G_SADDO is preferred,
3118e8d8bef9SDimitry Andric     // since it's a shorter expansion. However, we would need to figure out the
3119e8d8bef9SDimitry Andric     // preferred boolean type for the carry out for the query.
3120e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_SMIN, Ty}) && LI.isLegalOrCustom({G_SMAX, Ty}))
3121e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3122e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
3123e8d8bef9SDimitry Andric   }
3124e8d8bef9SDimitry Andric   case G_SSHLSAT:
3125e8d8bef9SDimitry Andric   case G_USHLSAT:
3126e8d8bef9SDimitry Andric     return lowerShlSat(MI);
3127e8d8bef9SDimitry Andric   case G_ABS: {
3128e8d8bef9SDimitry Andric     // Expand %res = G_ABS %a into:
3129e8d8bef9SDimitry Andric     // %v1 = G_ASHR %a, scalar_size-1
3130e8d8bef9SDimitry Andric     // %v2 = G_ADD %a, %v1
3131e8d8bef9SDimitry Andric     // %res = G_XOR %v2, %v1
3132e8d8bef9SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3133e8d8bef9SDimitry Andric     Register OpReg = MI.getOperand(1).getReg();
3134e8d8bef9SDimitry Andric     auto ShiftAmt =
3135e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - 1);
3136e8d8bef9SDimitry Andric     auto Shift =
3137e8d8bef9SDimitry Andric         MIRBuilder.buildAShr(DstTy, OpReg, ShiftAmt);
3138e8d8bef9SDimitry Andric     auto Add = MIRBuilder.buildAdd(DstTy, OpReg, Shift);
3139e8d8bef9SDimitry Andric     MIRBuilder.buildXor(MI.getOperand(0).getReg(), Add, Shift);
3140e8d8bef9SDimitry Andric     MI.eraseFromParent();
3141e8d8bef9SDimitry Andric     return Legalized;
3142e8d8bef9SDimitry Andric   }
3143e8d8bef9SDimitry Andric   case G_SELECT:
3144e8d8bef9SDimitry Andric     return lowerSelect(MI);
3145e8d8bef9SDimitry Andric   }
3146e8d8bef9SDimitry Andric }
3147e8d8bef9SDimitry Andric 
3148e8d8bef9SDimitry Andric Align LegalizerHelper::getStackTemporaryAlignment(LLT Ty,
3149e8d8bef9SDimitry Andric                                                   Align MinAlign) const {
3150e8d8bef9SDimitry Andric   // FIXME: We're missing a way to go back from LLT to llvm::Type to query the
3151e8d8bef9SDimitry Andric   // datalayout for the preferred alignment. Also there should be a target hook
3152e8d8bef9SDimitry Andric   // for this to allow targets to reduce the alignment and ignore the
3153e8d8bef9SDimitry Andric   // datalayout. e.g. AMDGPU should always use a 4-byte alignment, regardless of
3154e8d8bef9SDimitry Andric   // the type.
3155e8d8bef9SDimitry Andric   return std::max(Align(PowerOf2Ceil(Ty.getSizeInBytes())), MinAlign);
3156e8d8bef9SDimitry Andric }
3157e8d8bef9SDimitry Andric 
3158e8d8bef9SDimitry Andric MachineInstrBuilder
3159e8d8bef9SDimitry Andric LegalizerHelper::createStackTemporary(TypeSize Bytes, Align Alignment,
3160e8d8bef9SDimitry Andric                                       MachinePointerInfo &PtrInfo) {
3161e8d8bef9SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
3162e8d8bef9SDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
3163e8d8bef9SDimitry Andric   int FrameIdx = MF.getFrameInfo().CreateStackObject(Bytes, Alignment, false);
3164e8d8bef9SDimitry Andric 
3165e8d8bef9SDimitry Andric   unsigned AddrSpace = DL.getAllocaAddrSpace();
3166e8d8bef9SDimitry Andric   LLT FramePtrTy = LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace));
3167e8d8bef9SDimitry Andric 
3168e8d8bef9SDimitry Andric   PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIdx);
3169e8d8bef9SDimitry Andric   return MIRBuilder.buildFrameIndex(FramePtrTy, FrameIdx);
3170e8d8bef9SDimitry Andric }
3171e8d8bef9SDimitry Andric 
3172e8d8bef9SDimitry Andric static Register clampDynamicVectorIndex(MachineIRBuilder &B, Register IdxReg,
3173e8d8bef9SDimitry Andric                                         LLT VecTy) {
3174e8d8bef9SDimitry Andric   int64_t IdxVal;
3175e8d8bef9SDimitry Andric   if (mi_match(IdxReg, *B.getMRI(), m_ICst(IdxVal)))
3176e8d8bef9SDimitry Andric     return IdxReg;
3177e8d8bef9SDimitry Andric 
3178e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(IdxReg);
3179e8d8bef9SDimitry Andric   unsigned NElts = VecTy.getNumElements();
3180e8d8bef9SDimitry Andric   if (isPowerOf2_32(NElts)) {
3181e8d8bef9SDimitry Andric     APInt Imm = APInt::getLowBitsSet(IdxTy.getSizeInBits(), Log2_32(NElts));
3182e8d8bef9SDimitry Andric     return B.buildAnd(IdxTy, IdxReg, B.buildConstant(IdxTy, Imm)).getReg(0);
3183e8d8bef9SDimitry Andric   }
3184e8d8bef9SDimitry Andric 
3185e8d8bef9SDimitry Andric   return B.buildUMin(IdxTy, IdxReg, B.buildConstant(IdxTy, NElts - 1))
3186e8d8bef9SDimitry Andric       .getReg(0);
3187e8d8bef9SDimitry Andric }
3188e8d8bef9SDimitry Andric 
3189e8d8bef9SDimitry Andric Register LegalizerHelper::getVectorElementPointer(Register VecPtr, LLT VecTy,
3190e8d8bef9SDimitry Andric                                                   Register Index) {
3191e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
3192e8d8bef9SDimitry Andric 
3193e8d8bef9SDimitry Andric   // Calculate the element offset and add it to the pointer.
3194e8d8bef9SDimitry Andric   unsigned EltSize = EltTy.getSizeInBits() / 8; // FIXME: should be ABI size.
3195e8d8bef9SDimitry Andric   assert(EltSize * 8 == EltTy.getSizeInBits() &&
3196e8d8bef9SDimitry Andric          "Converting bits to bytes lost precision");
3197e8d8bef9SDimitry Andric 
3198e8d8bef9SDimitry Andric   Index = clampDynamicVectorIndex(MIRBuilder, Index, VecTy);
3199e8d8bef9SDimitry Andric 
3200e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Index);
3201e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(IdxTy, Index,
3202e8d8bef9SDimitry Andric                                  MIRBuilder.buildConstant(IdxTy, EltSize));
3203e8d8bef9SDimitry Andric 
3204e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(VecPtr);
3205e8d8bef9SDimitry Andric   return MIRBuilder.buildPtrAdd(PtrTy, VecPtr, Mul).getReg(0);
32060b57cec5SDimitry Andric }
32070b57cec5SDimitry Andric 
32080b57cec5SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorImplicitDef(
32090b57cec5SDimitry Andric     MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy) {
32100b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3211e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3212e8d8bef9SDimitry Andric   LLT LCMTy = getLCMType(DstTy, NarrowTy);
32130b57cec5SDimitry Andric 
3214e8d8bef9SDimitry Andric   unsigned NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
32150b57cec5SDimitry Andric 
3216e8d8bef9SDimitry Andric   auto NewUndef = MIRBuilder.buildUndef(NarrowTy);
3217e8d8bef9SDimitry Andric   SmallVector<Register, 8> Parts(NumParts, NewUndef.getReg(0));
32180b57cec5SDimitry Andric 
3219e8d8bef9SDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
32200b57cec5SDimitry Andric   MI.eraseFromParent();
32210b57cec5SDimitry Andric   return Legalized;
32220b57cec5SDimitry Andric }
32230b57cec5SDimitry Andric 
32240b57cec5SDimitry Andric // Handle splitting vector operations which need to have the same number of
32250b57cec5SDimitry Andric // elements in each type index, but each type index may have a different element
32260b57cec5SDimitry Andric // type.
32270b57cec5SDimitry Andric //
32280b57cec5SDimitry Andric // e.g.  <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
32290b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
32300b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
32310b57cec5SDimitry Andric //
32320b57cec5SDimitry Andric // Also handles some irregular breakdown cases, e.g.
32330b57cec5SDimitry Andric // e.g.  <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
32340b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
32350b57cec5SDimitry Andric //             s64 = G_SHL s64, s32
32360b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
32370b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorMultiEltType(
32380b57cec5SDimitry Andric   MachineInstr &MI, unsigned TypeIdx, LLT NarrowTyArg) {
32390b57cec5SDimitry Andric   if (TypeIdx != 0)
32400b57cec5SDimitry Andric     return UnableToLegalize;
32410b57cec5SDimitry Andric 
32420b57cec5SDimitry Andric   const LLT NarrowTy0 = NarrowTyArg;
32430b57cec5SDimitry Andric   const unsigned NewNumElts =
32440b57cec5SDimitry Andric       NarrowTy0.isVector() ? NarrowTy0.getNumElements() : 1;
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
32470b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
32480b57cec5SDimitry Andric   LLT LeftoverTy0;
32490b57cec5SDimitry Andric 
32500b57cec5SDimitry Andric   // All of the operands need to have the same number of elements, so if we can
32510b57cec5SDimitry Andric   // determine a type breakdown for the result type, we can for all of the
32520b57cec5SDimitry Andric   // source types.
32530b57cec5SDimitry Andric   int NumParts = getNarrowTypeBreakDown(DstTy, NarrowTy0, LeftoverTy0).first;
32540b57cec5SDimitry Andric   if (NumParts < 0)
32550b57cec5SDimitry Andric     return UnableToLegalize;
32560b57cec5SDimitry Andric 
32570b57cec5SDimitry Andric   SmallVector<MachineInstrBuilder, 4> NewInsts;
32580b57cec5SDimitry Andric 
32590b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
32600b57cec5SDimitry Andric   SmallVector<Register, 4> PartRegs, LeftoverRegs;
32610b57cec5SDimitry Andric 
32620b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
32630b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
32640b57cec5SDimitry Andric     LLT SrcTyI = MRI.getType(SrcReg);
32650b57cec5SDimitry Andric     LLT NarrowTyI = LLT::scalarOrVector(NewNumElts, SrcTyI.getScalarType());
32660b57cec5SDimitry Andric     LLT LeftoverTyI;
32670b57cec5SDimitry Andric 
32680b57cec5SDimitry Andric     // Split this operand into the requested typed registers, and any leftover
32690b57cec5SDimitry Andric     // required to reproduce the original type.
32700b57cec5SDimitry Andric     if (!extractParts(SrcReg, SrcTyI, NarrowTyI, LeftoverTyI, PartRegs,
32710b57cec5SDimitry Andric                       LeftoverRegs))
32720b57cec5SDimitry Andric       return UnableToLegalize;
32730b57cec5SDimitry Andric 
32740b57cec5SDimitry Andric     if (I == 1) {
32750b57cec5SDimitry Andric       // For the first operand, create an instruction for each part and setup
32760b57cec5SDimitry Andric       // the result.
32770b57cec5SDimitry Andric       for (Register PartReg : PartRegs) {
32780b57cec5SDimitry Andric         Register PartDstReg = MRI.createGenericVirtualRegister(NarrowTy0);
32790b57cec5SDimitry Andric         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
32800b57cec5SDimitry Andric                                .addDef(PartDstReg)
32810b57cec5SDimitry Andric                                .addUse(PartReg));
32820b57cec5SDimitry Andric         DstRegs.push_back(PartDstReg);
32830b57cec5SDimitry Andric       }
32840b57cec5SDimitry Andric 
32850b57cec5SDimitry Andric       for (Register LeftoverReg : LeftoverRegs) {
32860b57cec5SDimitry Andric         Register PartDstReg = MRI.createGenericVirtualRegister(LeftoverTy0);
32870b57cec5SDimitry Andric         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
32880b57cec5SDimitry Andric                                .addDef(PartDstReg)
32890b57cec5SDimitry Andric                                .addUse(LeftoverReg));
32900b57cec5SDimitry Andric         LeftoverDstRegs.push_back(PartDstReg);
32910b57cec5SDimitry Andric       }
32920b57cec5SDimitry Andric     } else {
32930b57cec5SDimitry Andric       assert(NewInsts.size() == PartRegs.size() + LeftoverRegs.size());
32940b57cec5SDimitry Andric 
32950b57cec5SDimitry Andric       // Add the newly created operand splits to the existing instructions. The
32960b57cec5SDimitry Andric       // odd-sized pieces are ordered after the requested NarrowTyArg sized
32970b57cec5SDimitry Andric       // pieces.
32980b57cec5SDimitry Andric       unsigned InstCount = 0;
32990b57cec5SDimitry Andric       for (unsigned J = 0, JE = PartRegs.size(); J != JE; ++J)
33000b57cec5SDimitry Andric         NewInsts[InstCount++].addUse(PartRegs[J]);
33010b57cec5SDimitry Andric       for (unsigned J = 0, JE = LeftoverRegs.size(); J != JE; ++J)
33020b57cec5SDimitry Andric         NewInsts[InstCount++].addUse(LeftoverRegs[J]);
33030b57cec5SDimitry Andric     }
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric     PartRegs.clear();
33060b57cec5SDimitry Andric     LeftoverRegs.clear();
33070b57cec5SDimitry Andric   }
33080b57cec5SDimitry Andric 
33090b57cec5SDimitry Andric   // Insert the newly built operations and rebuild the result register.
33100b57cec5SDimitry Andric   for (auto &MIB : NewInsts)
33110b57cec5SDimitry Andric     MIRBuilder.insertInstr(MIB);
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy0, DstRegs, LeftoverTy0, LeftoverDstRegs);
33140b57cec5SDimitry Andric 
33150b57cec5SDimitry Andric   MI.eraseFromParent();
33160b57cec5SDimitry Andric   return Legalized;
33170b57cec5SDimitry Andric }
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
33200b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorCasts(MachineInstr &MI, unsigned TypeIdx,
33210b57cec5SDimitry Andric                                           LLT NarrowTy) {
33220b57cec5SDimitry Andric   if (TypeIdx != 0)
33230b57cec5SDimitry Andric     return UnableToLegalize;
33240b57cec5SDimitry Andric 
33250b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
33260b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
33270b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
33280b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
33290b57cec5SDimitry Andric 
33300b57cec5SDimitry Andric   LLT NarrowTy0 = NarrowTy;
33310b57cec5SDimitry Andric   LLT NarrowTy1;
33320b57cec5SDimitry Andric   unsigned NumParts;
33330b57cec5SDimitry Andric 
33340b57cec5SDimitry Andric   if (NarrowTy.isVector()) {
33350b57cec5SDimitry Andric     // Uneven breakdown not handled.
33360b57cec5SDimitry Andric     NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
33370b57cec5SDimitry Andric     if (NumParts * NarrowTy.getNumElements() != DstTy.getNumElements())
33380b57cec5SDimitry Andric       return UnableToLegalize;
33390b57cec5SDimitry Andric 
3340e8d8bef9SDimitry Andric     NarrowTy1 = LLT::vector(NarrowTy.getNumElements(), SrcTy.getElementType());
33410b57cec5SDimitry Andric   } else {
33420b57cec5SDimitry Andric     NumParts = DstTy.getNumElements();
33430b57cec5SDimitry Andric     NarrowTy1 = SrcTy.getElementType();
33440b57cec5SDimitry Andric   }
33450b57cec5SDimitry Andric 
33460b57cec5SDimitry Andric   SmallVector<Register, 4> SrcRegs, DstRegs;
33470b57cec5SDimitry Andric   extractParts(SrcReg, NarrowTy1, NumParts, SrcRegs);
33480b57cec5SDimitry Andric 
33490b57cec5SDimitry Andric   for (unsigned I = 0; I < NumParts; ++I) {
33500b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
33515ffd83dbSDimitry Andric     MachineInstr *NewInst =
33525ffd83dbSDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode(), {DstReg}, {SrcRegs[I]});
33530b57cec5SDimitry Andric 
33540b57cec5SDimitry Andric     NewInst->setFlags(MI.getFlags());
33550b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
33560b57cec5SDimitry Andric   }
33570b57cec5SDimitry Andric 
33580b57cec5SDimitry Andric   if (NarrowTy.isVector())
33590b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
33600b57cec5SDimitry Andric   else
33610b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric   MI.eraseFromParent();
33640b57cec5SDimitry Andric   return Legalized;
33650b57cec5SDimitry Andric }
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
33680b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorCmp(MachineInstr &MI, unsigned TypeIdx,
33690b57cec5SDimitry Andric                                         LLT NarrowTy) {
33700b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
33710b57cec5SDimitry Andric   Register Src0Reg = MI.getOperand(2).getReg();
33720b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
33730b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src0Reg);
33740b57cec5SDimitry Andric 
33750b57cec5SDimitry Andric   unsigned NumParts;
33760b57cec5SDimitry Andric   LLT NarrowTy0, NarrowTy1;
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric   if (TypeIdx == 0) {
33790b57cec5SDimitry Andric     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
33800b57cec5SDimitry Andric     unsigned OldElts = DstTy.getNumElements();
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric     NarrowTy0 = NarrowTy;
33830b57cec5SDimitry Andric     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) : DstTy.getNumElements();
33840b57cec5SDimitry Andric     NarrowTy1 = NarrowTy.isVector() ?
33850b57cec5SDimitry Andric       LLT::vector(NarrowTy.getNumElements(), SrcTy.getScalarSizeInBits()) :
33860b57cec5SDimitry Andric       SrcTy.getElementType();
33870b57cec5SDimitry Andric 
33880b57cec5SDimitry Andric   } else {
33890b57cec5SDimitry Andric     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
33900b57cec5SDimitry Andric     unsigned OldElts = SrcTy.getNumElements();
33910b57cec5SDimitry Andric 
33920b57cec5SDimitry Andric     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) :
33930b57cec5SDimitry Andric       NarrowTy.getNumElements();
33940b57cec5SDimitry Andric     NarrowTy0 = LLT::vector(NarrowTy.getNumElements(),
33950b57cec5SDimitry Andric                             DstTy.getScalarSizeInBits());
33960b57cec5SDimitry Andric     NarrowTy1 = NarrowTy;
33970b57cec5SDimitry Andric   }
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric   // FIXME: Don't know how to handle the situation where the small vectors
34000b57cec5SDimitry Andric   // aren't all the same size yet.
34010b57cec5SDimitry Andric   if (NarrowTy1.isVector() &&
34020b57cec5SDimitry Andric       NarrowTy1.getNumElements() * NumParts != DstTy.getNumElements())
34030b57cec5SDimitry Andric     return UnableToLegalize;
34040b57cec5SDimitry Andric 
34050b57cec5SDimitry Andric   CmpInst::Predicate Pred
34060b57cec5SDimitry Andric     = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
34070b57cec5SDimitry Andric 
34080b57cec5SDimitry Andric   SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
34090b57cec5SDimitry Andric   extractParts(MI.getOperand(2).getReg(), NarrowTy1, NumParts, Src1Regs);
34100b57cec5SDimitry Andric   extractParts(MI.getOperand(3).getReg(), NarrowTy1, NumParts, Src2Regs);
34110b57cec5SDimitry Andric 
34120b57cec5SDimitry Andric   for (unsigned I = 0; I < NumParts; ++I) {
34130b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
34140b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_ICMP)
34170b57cec5SDimitry Andric       MIRBuilder.buildICmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
34180b57cec5SDimitry Andric     else {
34190b57cec5SDimitry Andric       MachineInstr *NewCmp
34200b57cec5SDimitry Andric         = MIRBuilder.buildFCmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
34210b57cec5SDimitry Andric       NewCmp->setFlags(MI.getFlags());
34220b57cec5SDimitry Andric     }
34230b57cec5SDimitry Andric   }
34240b57cec5SDimitry Andric 
34250b57cec5SDimitry Andric   if (NarrowTy1.isVector())
34260b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
34270b57cec5SDimitry Andric   else
34280b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
34290b57cec5SDimitry Andric 
34300b57cec5SDimitry Andric   MI.eraseFromParent();
34310b57cec5SDimitry Andric   return Legalized;
34320b57cec5SDimitry Andric }
34330b57cec5SDimitry Andric 
34340b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
34350b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorSelect(MachineInstr &MI, unsigned TypeIdx,
34360b57cec5SDimitry Andric                                            LLT NarrowTy) {
34370b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
34380b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric   unsigned NumParts = 0;
34410b57cec5SDimitry Andric   LLT NarrowTy0, NarrowTy1;
34420b57cec5SDimitry Andric 
34430b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
34440b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
34450b57cec5SDimitry Andric   unsigned Size = DstTy.getSizeInBits();
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric   assert(TypeIdx == 0 || CondTy.isVector());
34480b57cec5SDimitry Andric 
34490b57cec5SDimitry Andric   if (TypeIdx == 0) {
34500b57cec5SDimitry Andric     NarrowTy0 = NarrowTy;
34510b57cec5SDimitry Andric     NarrowTy1 = CondTy;
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric     unsigned NarrowSize = NarrowTy0.getSizeInBits();
34540b57cec5SDimitry Andric     // FIXME: Don't know how to handle the situation where the small vectors
34550b57cec5SDimitry Andric     // aren't all the same size yet.
34560b57cec5SDimitry Andric     if (Size % NarrowSize != 0)
34570b57cec5SDimitry Andric       return UnableToLegalize;
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric     NumParts = Size / NarrowSize;
34600b57cec5SDimitry Andric 
34610b57cec5SDimitry Andric     // Need to break down the condition type
34620b57cec5SDimitry Andric     if (CondTy.isVector()) {
34630b57cec5SDimitry Andric       if (CondTy.getNumElements() == NumParts)
34640b57cec5SDimitry Andric         NarrowTy1 = CondTy.getElementType();
34650b57cec5SDimitry Andric       else
34660b57cec5SDimitry Andric         NarrowTy1 = LLT::vector(CondTy.getNumElements() / NumParts,
34670b57cec5SDimitry Andric                                 CondTy.getScalarSizeInBits());
34680b57cec5SDimitry Andric     }
34690b57cec5SDimitry Andric   } else {
34700b57cec5SDimitry Andric     NumParts = CondTy.getNumElements();
34710b57cec5SDimitry Andric     if (NarrowTy.isVector()) {
34720b57cec5SDimitry Andric       // TODO: Handle uneven breakdown.
34730b57cec5SDimitry Andric       if (NumParts * NarrowTy.getNumElements() != CondTy.getNumElements())
34740b57cec5SDimitry Andric         return UnableToLegalize;
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric       return UnableToLegalize;
34770b57cec5SDimitry Andric     } else {
34780b57cec5SDimitry Andric       NarrowTy0 = DstTy.getElementType();
34790b57cec5SDimitry Andric       NarrowTy1 = NarrowTy;
34800b57cec5SDimitry Andric     }
34810b57cec5SDimitry Andric   }
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric   SmallVector<Register, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
34840b57cec5SDimitry Andric   if (CondTy.isVector())
34850b57cec5SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy1, NumParts, Src0Regs);
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric   extractParts(MI.getOperand(2).getReg(), NarrowTy0, NumParts, Src1Regs);
34880b57cec5SDimitry Andric   extractParts(MI.getOperand(3).getReg(), NarrowTy0, NumParts, Src2Regs);
34890b57cec5SDimitry Andric 
34900b57cec5SDimitry Andric   for (unsigned i = 0; i < NumParts; ++i) {
34910b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
34920b57cec5SDimitry Andric     MIRBuilder.buildSelect(DstReg, CondTy.isVector() ? Src0Regs[i] : CondReg,
34930b57cec5SDimitry Andric                            Src1Regs[i], Src2Regs[i]);
34940b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
34950b57cec5SDimitry Andric   }
34960b57cec5SDimitry Andric 
34970b57cec5SDimitry Andric   if (NarrowTy0.isVector())
34980b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
34990b57cec5SDimitry Andric   else
35000b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric   MI.eraseFromParent();
35030b57cec5SDimitry Andric   return Legalized;
35040b57cec5SDimitry Andric }
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
35070b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
35080b57cec5SDimitry Andric                                         LLT NarrowTy) {
35090b57cec5SDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
35100b57cec5SDimitry Andric   LLT PhiTy = MRI.getType(DstReg);
35110b57cec5SDimitry Andric   LLT LeftoverTy;
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric   // All of the operands need to have the same number of elements, so if we can
35140b57cec5SDimitry Andric   // determine a type breakdown for the result type, we can for all of the
35150b57cec5SDimitry Andric   // source types.
35160b57cec5SDimitry Andric   int NumParts, NumLeftover;
35170b57cec5SDimitry Andric   std::tie(NumParts, NumLeftover)
35180b57cec5SDimitry Andric     = getNarrowTypeBreakDown(PhiTy, NarrowTy, LeftoverTy);
35190b57cec5SDimitry Andric   if (NumParts < 0)
35200b57cec5SDimitry Andric     return UnableToLegalize;
35210b57cec5SDimitry Andric 
35220b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
35230b57cec5SDimitry Andric   SmallVector<MachineInstrBuilder, 4> NewInsts;
35240b57cec5SDimitry Andric 
35250b57cec5SDimitry Andric   const int TotalNumParts = NumParts + NumLeftover;
35260b57cec5SDimitry Andric 
35270b57cec5SDimitry Andric   // Insert the new phis in the result block first.
35280b57cec5SDimitry Andric   for (int I = 0; I != TotalNumParts; ++I) {
35290b57cec5SDimitry Andric     LLT Ty = I < NumParts ? NarrowTy : LeftoverTy;
35300b57cec5SDimitry Andric     Register PartDstReg = MRI.createGenericVirtualRegister(Ty);
35310b57cec5SDimitry Andric     NewInsts.push_back(MIRBuilder.buildInstr(TargetOpcode::G_PHI)
35320b57cec5SDimitry Andric                        .addDef(PartDstReg));
35330b57cec5SDimitry Andric     if (I < NumParts)
35340b57cec5SDimitry Andric       DstRegs.push_back(PartDstReg);
35350b57cec5SDimitry Andric     else
35360b57cec5SDimitry Andric       LeftoverDstRegs.push_back(PartDstReg);
35370b57cec5SDimitry Andric   }
35380b57cec5SDimitry Andric 
35390b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
35400b57cec5SDimitry Andric   MIRBuilder.setInsertPt(*MBB, MBB->getFirstNonPHI());
35410b57cec5SDimitry Andric   insertParts(DstReg, PhiTy, NarrowTy, DstRegs, LeftoverTy, LeftoverDstRegs);
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric   SmallVector<Register, 4> PartRegs, LeftoverRegs;
35440b57cec5SDimitry Andric 
35450b57cec5SDimitry Andric   // Insert code to extract the incoming values in each predecessor block.
35460b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
35470b57cec5SDimitry Andric     PartRegs.clear();
35480b57cec5SDimitry Andric     LeftoverRegs.clear();
35490b57cec5SDimitry Andric 
35500b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
35510b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
35520b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric     LLT Unused;
35550b57cec5SDimitry Andric     if (!extractParts(SrcReg, PhiTy, NarrowTy, Unused, PartRegs,
35560b57cec5SDimitry Andric                       LeftoverRegs))
35570b57cec5SDimitry Andric       return UnableToLegalize;
35580b57cec5SDimitry Andric 
35590b57cec5SDimitry Andric     // Add the newly created operand splits to the existing instructions. The
35600b57cec5SDimitry Andric     // odd-sized pieces are ordered after the requested NarrowTyArg sized
35610b57cec5SDimitry Andric     // pieces.
35620b57cec5SDimitry Andric     for (int J = 0; J != TotalNumParts; ++J) {
35630b57cec5SDimitry Andric       MachineInstrBuilder MIB = NewInsts[J];
35640b57cec5SDimitry Andric       MIB.addUse(J < NumParts ? PartRegs[J] : LeftoverRegs[J - NumParts]);
35650b57cec5SDimitry Andric       MIB.addMBB(&OpMBB);
35660b57cec5SDimitry Andric     }
35670b57cec5SDimitry Andric   }
35680b57cec5SDimitry Andric 
35690b57cec5SDimitry Andric   MI.eraseFromParent();
35700b57cec5SDimitry Andric   return Legalized;
35710b57cec5SDimitry Andric }
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
35748bcb0991SDimitry Andric LegalizerHelper::fewerElementsVectorUnmergeValues(MachineInstr &MI,
35758bcb0991SDimitry Andric                                                   unsigned TypeIdx,
35768bcb0991SDimitry Andric                                                   LLT NarrowTy) {
35778bcb0991SDimitry Andric   if (TypeIdx != 1)
35788bcb0991SDimitry Andric     return UnableToLegalize;
35798bcb0991SDimitry Andric 
35808bcb0991SDimitry Andric   const int NumDst = MI.getNumOperands() - 1;
35818bcb0991SDimitry Andric   const Register SrcReg = MI.getOperand(NumDst).getReg();
35828bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
35838bcb0991SDimitry Andric 
35848bcb0991SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
35858bcb0991SDimitry Andric 
35868bcb0991SDimitry Andric   // TODO: Create sequence of extracts.
35878bcb0991SDimitry Andric   if (DstTy == NarrowTy)
35888bcb0991SDimitry Andric     return UnableToLegalize;
35898bcb0991SDimitry Andric 
35908bcb0991SDimitry Andric   LLT GCDTy = getGCDType(SrcTy, NarrowTy);
35918bcb0991SDimitry Andric   if (DstTy == GCDTy) {
35928bcb0991SDimitry Andric     // This would just be a copy of the same unmerge.
35938bcb0991SDimitry Andric     // TODO: Create extracts, pad with undef and create intermediate merges.
35948bcb0991SDimitry Andric     return UnableToLegalize;
35958bcb0991SDimitry Andric   }
35968bcb0991SDimitry Andric 
35978bcb0991SDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
35988bcb0991SDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
35998bcb0991SDimitry Andric   const int PartsPerUnmerge = NumDst / NumUnmerge;
36008bcb0991SDimitry Andric 
36018bcb0991SDimitry Andric   for (int I = 0; I != NumUnmerge; ++I) {
36028bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
36038bcb0991SDimitry Andric 
36048bcb0991SDimitry Andric     for (int J = 0; J != PartsPerUnmerge; ++J)
36058bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I * PartsPerUnmerge + J).getReg());
36068bcb0991SDimitry Andric     MIB.addUse(Unmerge.getReg(I));
36078bcb0991SDimitry Andric   }
36088bcb0991SDimitry Andric 
36098bcb0991SDimitry Andric   MI.eraseFromParent();
36108bcb0991SDimitry Andric   return Legalized;
36118bcb0991SDimitry Andric }
36128bcb0991SDimitry Andric 
3613e8d8bef9SDimitry Andric // Handle FewerElementsVector a G_BUILD_VECTOR or G_CONCAT_VECTORS that produces
3614e8d8bef9SDimitry Andric // a vector
3615e8d8bef9SDimitry Andric //
3616e8d8bef9SDimitry Andric // Create a G_BUILD_VECTOR or G_CONCAT_VECTORS of NarrowTy pieces, padding with
3617e8d8bef9SDimitry Andric // undef as necessary.
36188bcb0991SDimitry Andric //
36198bcb0991SDimitry Andric // %3:_(<3 x s16>) = G_BUILD_VECTOR %0, %1, %2
36208bcb0991SDimitry Andric //   -> <2 x s16>
36218bcb0991SDimitry Andric //
36228bcb0991SDimitry Andric // %4:_(s16) = G_IMPLICIT_DEF
36238bcb0991SDimitry Andric // %5:_(<2 x s16>) = G_BUILD_VECTOR %0, %1
36248bcb0991SDimitry Andric // %6:_(<2 x s16>) = G_BUILD_VECTOR %2, %4
3625e8d8bef9SDimitry Andric // %7:_(<2 x s16>) = G_IMPLICIT_DEF
3626e8d8bef9SDimitry Andric // %8:_(<6 x s16>) = G_CONCAT_VECTORS %5, %6, %7
3627e8d8bef9SDimitry Andric // %3:_(<3 x s16>), %8:_(<3 x s16>) = G_UNMERGE_VALUES %8
3628e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3629e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorMerge(MachineInstr &MI, unsigned TypeIdx,
3630e8d8bef9SDimitry Andric                                           LLT NarrowTy) {
3631e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3632e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3633e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
3634e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
36358bcb0991SDimitry Andric 
3636e8d8bef9SDimitry Andric   // Break into a common type
3637e8d8bef9SDimitry Andric   SmallVector<Register, 16> Parts;
3638e8d8bef9SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3639e8d8bef9SDimitry Andric     extractGCDType(Parts, GCDTy, MI.getOperand(I).getReg());
3640e8d8bef9SDimitry Andric 
3641e8d8bef9SDimitry Andric   // Build the requested new merge, padding with undef.
3642e8d8bef9SDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts,
3643e8d8bef9SDimitry Andric                                   TargetOpcode::G_ANYEXT);
3644e8d8bef9SDimitry Andric 
3645e8d8bef9SDimitry Andric   // Pack into the original result register.
3646e8d8bef9SDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
3647e8d8bef9SDimitry Andric 
3648e8d8bef9SDimitry Andric   MI.eraseFromParent();
3649e8d8bef9SDimitry Andric   return Legalized;
36508bcb0991SDimitry Andric }
36518bcb0991SDimitry Andric 
3652e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3653e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorExtractInsertVectorElt(MachineInstr &MI,
3654e8d8bef9SDimitry Andric                                                            unsigned TypeIdx,
3655e8d8bef9SDimitry Andric                                                            LLT NarrowVecTy) {
3656e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3657e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
3658e8d8bef9SDimitry Andric   Register InsertVal;
3659e8d8bef9SDimitry Andric   bool IsInsert = MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT;
3660e8d8bef9SDimitry Andric 
3661e8d8bef9SDimitry Andric   assert((IsInsert ? TypeIdx == 0 : TypeIdx == 1) && "not a vector type index");
3662e8d8bef9SDimitry Andric   if (IsInsert)
3663e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
3664e8d8bef9SDimitry Andric 
3665e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
3666e8d8bef9SDimitry Andric 
3667e8d8bef9SDimitry Andric   // TODO: Handle total scalarization case.
3668e8d8bef9SDimitry Andric   if (!NarrowVecTy.isVector())
3669e8d8bef9SDimitry Andric     return UnableToLegalize;
3670e8d8bef9SDimitry Andric 
3671e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
3672e8d8bef9SDimitry Andric 
3673e8d8bef9SDimitry Andric   // If the index is a constant, we can really break this down as you would
3674e8d8bef9SDimitry Andric   // expect, and index into the target size pieces.
3675e8d8bef9SDimitry Andric   int64_t IdxVal;
3676e8d8bef9SDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal))) {
3677e8d8bef9SDimitry Andric     // Avoid out of bounds indexing the pieces.
3678e8d8bef9SDimitry Andric     if (IdxVal >= VecTy.getNumElements()) {
3679e8d8bef9SDimitry Andric       MIRBuilder.buildUndef(DstReg);
3680e8d8bef9SDimitry Andric       MI.eraseFromParent();
3681e8d8bef9SDimitry Andric       return Legalized;
36828bcb0991SDimitry Andric     }
36838bcb0991SDimitry Andric 
3684e8d8bef9SDimitry Andric     SmallVector<Register, 8> VecParts;
3685e8d8bef9SDimitry Andric     LLT GCDTy = extractGCDType(VecParts, VecTy, NarrowVecTy, SrcVec);
3686e8d8bef9SDimitry Andric 
3687e8d8bef9SDimitry Andric     // Build a sequence of NarrowTy pieces in VecParts for this operand.
3688e8d8bef9SDimitry Andric     LLT LCMTy = buildLCMMergePieces(VecTy, NarrowVecTy, GCDTy, VecParts,
3689e8d8bef9SDimitry Andric                                     TargetOpcode::G_ANYEXT);
3690e8d8bef9SDimitry Andric 
3691e8d8bef9SDimitry Andric     unsigned NewNumElts = NarrowVecTy.getNumElements();
3692e8d8bef9SDimitry Andric 
3693e8d8bef9SDimitry Andric     LLT IdxTy = MRI.getType(Idx);
3694e8d8bef9SDimitry Andric     int64_t PartIdx = IdxVal / NewNumElts;
3695e8d8bef9SDimitry Andric     auto NewIdx =
3696e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(IdxTy, IdxVal - NewNumElts * PartIdx);
3697e8d8bef9SDimitry Andric 
3698e8d8bef9SDimitry Andric     if (IsInsert) {
3699e8d8bef9SDimitry Andric       LLT PartTy = MRI.getType(VecParts[PartIdx]);
3700e8d8bef9SDimitry Andric 
3701e8d8bef9SDimitry Andric       // Use the adjusted index to insert into one of the subvectors.
3702e8d8bef9SDimitry Andric       auto InsertPart = MIRBuilder.buildInsertVectorElement(
3703e8d8bef9SDimitry Andric           PartTy, VecParts[PartIdx], InsertVal, NewIdx);
3704e8d8bef9SDimitry Andric       VecParts[PartIdx] = InsertPart.getReg(0);
3705e8d8bef9SDimitry Andric 
3706e8d8bef9SDimitry Andric       // Recombine the inserted subvector with the others to reform the result
3707e8d8bef9SDimitry Andric       // vector.
3708e8d8bef9SDimitry Andric       buildWidenedRemergeToDst(DstReg, LCMTy, VecParts);
3709e8d8bef9SDimitry Andric     } else {
3710e8d8bef9SDimitry Andric       MIRBuilder.buildExtractVectorElement(DstReg, VecParts[PartIdx], NewIdx);
37118bcb0991SDimitry Andric     }
37128bcb0991SDimitry Andric 
37138bcb0991SDimitry Andric     MI.eraseFromParent();
37148bcb0991SDimitry Andric     return Legalized;
37158bcb0991SDimitry Andric   }
37168bcb0991SDimitry Andric 
3717e8d8bef9SDimitry Andric   // With a variable index, we can't perform the operation in a smaller type, so
3718e8d8bef9SDimitry Andric   // we're forced to expand this.
3719e8d8bef9SDimitry Andric   //
3720e8d8bef9SDimitry Andric   // TODO: We could emit a chain of compare/select to figure out which piece to
3721e8d8bef9SDimitry Andric   // index.
3722e8d8bef9SDimitry Andric   return lowerExtractInsertVectorElt(MI);
3723e8d8bef9SDimitry Andric }
3724e8d8bef9SDimitry Andric 
37258bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
37260b57cec5SDimitry Andric LegalizerHelper::reduceLoadStoreWidth(MachineInstr &MI, unsigned TypeIdx,
37270b57cec5SDimitry Andric                                       LLT NarrowTy) {
37280b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
37290b57cec5SDimitry Andric   if (TypeIdx != 0)
37300b57cec5SDimitry Andric     return UnableToLegalize;
37310b57cec5SDimitry Andric 
37320b57cec5SDimitry Andric   MachineMemOperand *MMO = *MI.memoperands_begin();
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric   // This implementation doesn't work for atomics. Give up instead of doing
37350b57cec5SDimitry Andric   // something invalid.
37360b57cec5SDimitry Andric   if (MMO->getOrdering() != AtomicOrdering::NotAtomic ||
37370b57cec5SDimitry Andric       MMO->getFailureOrdering() != AtomicOrdering::NotAtomic)
37380b57cec5SDimitry Andric     return UnableToLegalize;
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric   bool IsLoad = MI.getOpcode() == TargetOpcode::G_LOAD;
37410b57cec5SDimitry Andric   Register ValReg = MI.getOperand(0).getReg();
37420b57cec5SDimitry Andric   Register AddrReg = MI.getOperand(1).getReg();
37430b57cec5SDimitry Andric   LLT ValTy = MRI.getType(ValReg);
37440b57cec5SDimitry Andric 
37455ffd83dbSDimitry Andric   // FIXME: Do we need a distinct NarrowMemory legalize action?
37465ffd83dbSDimitry Andric   if (ValTy.getSizeInBits() != 8 * MMO->getSize()) {
37475ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Can't narrow extload/truncstore\n");
37485ffd83dbSDimitry Andric     return UnableToLegalize;
37495ffd83dbSDimitry Andric   }
37505ffd83dbSDimitry Andric 
37510b57cec5SDimitry Andric   int NumParts = -1;
37520b57cec5SDimitry Andric   int NumLeftover = -1;
37530b57cec5SDimitry Andric   LLT LeftoverTy;
37540b57cec5SDimitry Andric   SmallVector<Register, 8> NarrowRegs, NarrowLeftoverRegs;
37550b57cec5SDimitry Andric   if (IsLoad) {
37560b57cec5SDimitry Andric     std::tie(NumParts, NumLeftover) = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
37570b57cec5SDimitry Andric   } else {
37580b57cec5SDimitry Andric     if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
37590b57cec5SDimitry Andric                      NarrowLeftoverRegs)) {
37600b57cec5SDimitry Andric       NumParts = NarrowRegs.size();
37610b57cec5SDimitry Andric       NumLeftover = NarrowLeftoverRegs.size();
37620b57cec5SDimitry Andric     }
37630b57cec5SDimitry Andric   }
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   if (NumParts == -1)
37660b57cec5SDimitry Andric     return UnableToLegalize;
37670b57cec5SDimitry Andric 
3768e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(AddrReg);
3769e8d8bef9SDimitry Andric   const LLT OffsetTy = LLT::scalar(PtrTy.getSizeInBits());
37700b57cec5SDimitry Andric 
37710b57cec5SDimitry Andric   unsigned TotalSize = ValTy.getSizeInBits();
37720b57cec5SDimitry Andric 
37730b57cec5SDimitry Andric   // Split the load/store into PartTy sized pieces starting at Offset. If this
37740b57cec5SDimitry Andric   // is a load, return the new registers in ValRegs. For a store, each elements
37750b57cec5SDimitry Andric   // of ValRegs should be PartTy. Returns the next offset that needs to be
37760b57cec5SDimitry Andric   // handled.
37770b57cec5SDimitry Andric   auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<Register> &ValRegs,
37780b57cec5SDimitry Andric                              unsigned Offset) -> unsigned {
37790b57cec5SDimitry Andric     MachineFunction &MF = MIRBuilder.getMF();
37800b57cec5SDimitry Andric     unsigned PartSize = PartTy.getSizeInBits();
37810b57cec5SDimitry Andric     for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
37820b57cec5SDimitry Andric          Offset += PartSize, ++Idx) {
37830b57cec5SDimitry Andric       unsigned ByteSize = PartSize / 8;
37840b57cec5SDimitry Andric       unsigned ByteOffset = Offset / 8;
37850b57cec5SDimitry Andric       Register NewAddrReg;
37860b57cec5SDimitry Andric 
3787480093f4SDimitry Andric       MIRBuilder.materializePtrAdd(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric       MachineMemOperand *NewMMO =
37900b57cec5SDimitry Andric         MF.getMachineMemOperand(MMO, ByteOffset, ByteSize);
37910b57cec5SDimitry Andric 
37920b57cec5SDimitry Andric       if (IsLoad) {
37930b57cec5SDimitry Andric         Register Dst = MRI.createGenericVirtualRegister(PartTy);
37940b57cec5SDimitry Andric         ValRegs.push_back(Dst);
37950b57cec5SDimitry Andric         MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
37960b57cec5SDimitry Andric       } else {
37970b57cec5SDimitry Andric         MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
37980b57cec5SDimitry Andric       }
37990b57cec5SDimitry Andric     }
38000b57cec5SDimitry Andric 
38010b57cec5SDimitry Andric     return Offset;
38020b57cec5SDimitry Andric   };
38030b57cec5SDimitry Andric 
38040b57cec5SDimitry Andric   unsigned HandledOffset = splitTypePieces(NarrowTy, NarrowRegs, 0);
38050b57cec5SDimitry Andric 
38060b57cec5SDimitry Andric   // Handle the rest of the register if this isn't an even type breakdown.
38070b57cec5SDimitry Andric   if (LeftoverTy.isValid())
38080b57cec5SDimitry Andric     splitTypePieces(LeftoverTy, NarrowLeftoverRegs, HandledOffset);
38090b57cec5SDimitry Andric 
38100b57cec5SDimitry Andric   if (IsLoad) {
38110b57cec5SDimitry Andric     insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
38120b57cec5SDimitry Andric                 LeftoverTy, NarrowLeftoverRegs);
38130b57cec5SDimitry Andric   }
38140b57cec5SDimitry Andric 
38150b57cec5SDimitry Andric   MI.eraseFromParent();
38160b57cec5SDimitry Andric   return Legalized;
38170b57cec5SDimitry Andric }
38180b57cec5SDimitry Andric 
38190b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
38205ffd83dbSDimitry Andric LegalizerHelper::reduceOperationWidth(MachineInstr &MI, unsigned int TypeIdx,
38215ffd83dbSDimitry Andric                                       LLT NarrowTy) {
38225ffd83dbSDimitry Andric   assert(TypeIdx == 0 && "only one type index expected");
38235ffd83dbSDimitry Andric 
38245ffd83dbSDimitry Andric   const unsigned Opc = MI.getOpcode();
38255ffd83dbSDimitry Andric   const int NumOps = MI.getNumOperands() - 1;
38265ffd83dbSDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
38275ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
38285ffd83dbSDimitry Andric   const unsigned NarrowSize = NarrowTy.getSizeInBits();
38295ffd83dbSDimitry Andric   const LLT NarrowScalarTy = LLT::scalar(NarrowSize);
38305ffd83dbSDimitry Andric 
38315ffd83dbSDimitry Andric   assert(NumOps <= 3 && "expected instruction with 1 result and 1-3 sources");
38325ffd83dbSDimitry Andric 
38335ffd83dbSDimitry Andric   // First of all check whether we are narrowing (changing the element type)
38345ffd83dbSDimitry Andric   // or reducing the vector elements
38355ffd83dbSDimitry Andric   const LLT DstTy = MRI.getType(DstReg);
38365ffd83dbSDimitry Andric   const bool IsNarrow = NarrowTy.getScalarType() != DstTy.getScalarType();
38375ffd83dbSDimitry Andric 
38385ffd83dbSDimitry Andric   SmallVector<Register, 8> ExtractedRegs[3];
38395ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
38405ffd83dbSDimitry Andric 
38415ffd83dbSDimitry Andric   unsigned NarrowElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
38425ffd83dbSDimitry Andric 
38435ffd83dbSDimitry Andric   // Break down all the sources into NarrowTy pieces we can operate on. This may
38445ffd83dbSDimitry Andric   // involve creating merges to a wider type, padded with undef.
38455ffd83dbSDimitry Andric   for (int I = 0; I != NumOps; ++I) {
38465ffd83dbSDimitry Andric     Register SrcReg = MI.getOperand(I + 1).getReg();
38475ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
38485ffd83dbSDimitry Andric 
38495ffd83dbSDimitry Andric     // The type to narrow SrcReg to. For narrowing, this is a smaller scalar.
38505ffd83dbSDimitry Andric     // For fewerElements, this is a smaller vector with the same element type.
38515ffd83dbSDimitry Andric     LLT OpNarrowTy;
38525ffd83dbSDimitry Andric     if (IsNarrow) {
38535ffd83dbSDimitry Andric       OpNarrowTy = NarrowScalarTy;
38545ffd83dbSDimitry Andric 
38555ffd83dbSDimitry Andric       // In case of narrowing, we need to cast vectors to scalars for this to
38565ffd83dbSDimitry Andric       // work properly
38575ffd83dbSDimitry Andric       // FIXME: Can we do without the bitcast here if we're narrowing?
38585ffd83dbSDimitry Andric       if (SrcTy.isVector()) {
38595ffd83dbSDimitry Andric         SrcTy = LLT::scalar(SrcTy.getSizeInBits());
38605ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(SrcTy, SrcReg).getReg(0);
38615ffd83dbSDimitry Andric       }
38625ffd83dbSDimitry Andric     } else {
38635ffd83dbSDimitry Andric       OpNarrowTy = LLT::scalarOrVector(NarrowElts, SrcTy.getScalarType());
38645ffd83dbSDimitry Andric     }
38655ffd83dbSDimitry Andric 
38665ffd83dbSDimitry Andric     LLT GCDTy = extractGCDType(ExtractedRegs[I], SrcTy, OpNarrowTy, SrcReg);
38675ffd83dbSDimitry Andric 
38685ffd83dbSDimitry Andric     // Build a sequence of NarrowTy pieces in ExtractedRegs for this operand.
38695ffd83dbSDimitry Andric     buildLCMMergePieces(SrcTy, OpNarrowTy, GCDTy, ExtractedRegs[I],
38705ffd83dbSDimitry Andric                         TargetOpcode::G_ANYEXT);
38715ffd83dbSDimitry Andric   }
38725ffd83dbSDimitry Andric 
38735ffd83dbSDimitry Andric   SmallVector<Register, 8> ResultRegs;
38745ffd83dbSDimitry Andric 
38755ffd83dbSDimitry Andric   // Input operands for each sub-instruction.
38765ffd83dbSDimitry Andric   SmallVector<SrcOp, 4> InputRegs(NumOps, Register());
38775ffd83dbSDimitry Andric 
38785ffd83dbSDimitry Andric   int NumParts = ExtractedRegs[0].size();
38795ffd83dbSDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
38805ffd83dbSDimitry Andric   const LLT DstScalarTy = LLT::scalar(DstSize);
38815ffd83dbSDimitry Andric 
38825ffd83dbSDimitry Andric   // Narrowing needs to use scalar types
38835ffd83dbSDimitry Andric   LLT DstLCMTy, NarrowDstTy;
38845ffd83dbSDimitry Andric   if (IsNarrow) {
38855ffd83dbSDimitry Andric     DstLCMTy = getLCMType(DstScalarTy, NarrowScalarTy);
38865ffd83dbSDimitry Andric     NarrowDstTy = NarrowScalarTy;
38875ffd83dbSDimitry Andric   } else {
38885ffd83dbSDimitry Andric     DstLCMTy = getLCMType(DstTy, NarrowTy);
38895ffd83dbSDimitry Andric     NarrowDstTy = NarrowTy;
38905ffd83dbSDimitry Andric   }
38915ffd83dbSDimitry Andric 
38925ffd83dbSDimitry Andric   // We widened the source registers to satisfy merge/unmerge size
38935ffd83dbSDimitry Andric   // constraints. We'll have some extra fully undef parts.
38945ffd83dbSDimitry Andric   const int NumRealParts = (DstSize + NarrowSize - 1) / NarrowSize;
38955ffd83dbSDimitry Andric 
38965ffd83dbSDimitry Andric   for (int I = 0; I != NumRealParts; ++I) {
38975ffd83dbSDimitry Andric     // Emit this instruction on each of the split pieces.
38985ffd83dbSDimitry Andric     for (int J = 0; J != NumOps; ++J)
38995ffd83dbSDimitry Andric       InputRegs[J] = ExtractedRegs[J][I];
39005ffd83dbSDimitry Andric 
39015ffd83dbSDimitry Andric     auto Inst = MIRBuilder.buildInstr(Opc, {NarrowDstTy}, InputRegs, Flags);
39025ffd83dbSDimitry Andric     ResultRegs.push_back(Inst.getReg(0));
39035ffd83dbSDimitry Andric   }
39045ffd83dbSDimitry Andric 
39055ffd83dbSDimitry Andric   // Fill out the widened result with undef instead of creating instructions
39065ffd83dbSDimitry Andric   // with undef inputs.
39075ffd83dbSDimitry Andric   int NumUndefParts = NumParts - NumRealParts;
39085ffd83dbSDimitry Andric   if (NumUndefParts != 0)
39095ffd83dbSDimitry Andric     ResultRegs.append(NumUndefParts,
39105ffd83dbSDimitry Andric                       MIRBuilder.buildUndef(NarrowDstTy).getReg(0));
39115ffd83dbSDimitry Andric 
39125ffd83dbSDimitry Andric   // Extract the possibly padded result. Use a scratch register if we need to do
39135ffd83dbSDimitry Andric   // a final bitcast, otherwise use the original result register.
39145ffd83dbSDimitry Andric   Register MergeDstReg;
39155ffd83dbSDimitry Andric   if (IsNarrow && DstTy.isVector())
39165ffd83dbSDimitry Andric     MergeDstReg = MRI.createGenericVirtualRegister(DstScalarTy);
39175ffd83dbSDimitry Andric   else
39185ffd83dbSDimitry Andric     MergeDstReg = DstReg;
39195ffd83dbSDimitry Andric 
39205ffd83dbSDimitry Andric   buildWidenedRemergeToDst(MergeDstReg, DstLCMTy, ResultRegs);
39215ffd83dbSDimitry Andric 
39225ffd83dbSDimitry Andric   // Recast to vector if we narrowed a vector
39235ffd83dbSDimitry Andric   if (IsNarrow && DstTy.isVector())
39245ffd83dbSDimitry Andric     MIRBuilder.buildBitcast(DstReg, MergeDstReg);
39255ffd83dbSDimitry Andric 
39265ffd83dbSDimitry Andric   MI.eraseFromParent();
39275ffd83dbSDimitry Andric   return Legalized;
39285ffd83dbSDimitry Andric }
39295ffd83dbSDimitry Andric 
39305ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
39315ffd83dbSDimitry Andric LegalizerHelper::fewerElementsVectorSextInReg(MachineInstr &MI, unsigned TypeIdx,
39325ffd83dbSDimitry Andric                                               LLT NarrowTy) {
39335ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
39345ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
39355ffd83dbSDimitry Andric   int64_t Imm = MI.getOperand(2).getImm();
39365ffd83dbSDimitry Andric 
39375ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
39385ffd83dbSDimitry Andric 
39395ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
39405ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
39415ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts);
39425ffd83dbSDimitry Andric 
39435ffd83dbSDimitry Andric   for (Register &R : Parts)
39445ffd83dbSDimitry Andric     R = MIRBuilder.buildSExtInReg(NarrowTy, R, Imm).getReg(0);
39455ffd83dbSDimitry Andric 
39465ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
39475ffd83dbSDimitry Andric 
39485ffd83dbSDimitry Andric   MI.eraseFromParent();
39495ffd83dbSDimitry Andric   return Legalized;
39505ffd83dbSDimitry Andric }
39515ffd83dbSDimitry Andric 
39525ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
39530b57cec5SDimitry Andric LegalizerHelper::fewerElementsVector(MachineInstr &MI, unsigned TypeIdx,
39540b57cec5SDimitry Andric                                      LLT NarrowTy) {
39550b57cec5SDimitry Andric   using namespace TargetOpcode;
39560b57cec5SDimitry Andric 
39570b57cec5SDimitry Andric   switch (MI.getOpcode()) {
39580b57cec5SDimitry Andric   case G_IMPLICIT_DEF:
39590b57cec5SDimitry Andric     return fewerElementsVectorImplicitDef(MI, TypeIdx, NarrowTy);
39605ffd83dbSDimitry Andric   case G_TRUNC:
39610b57cec5SDimitry Andric   case G_AND:
39620b57cec5SDimitry Andric   case G_OR:
39630b57cec5SDimitry Andric   case G_XOR:
39640b57cec5SDimitry Andric   case G_ADD:
39650b57cec5SDimitry Andric   case G_SUB:
39660b57cec5SDimitry Andric   case G_MUL:
3967e8d8bef9SDimitry Andric   case G_PTR_ADD:
39680b57cec5SDimitry Andric   case G_SMULH:
39690b57cec5SDimitry Andric   case G_UMULH:
39700b57cec5SDimitry Andric   case G_FADD:
39710b57cec5SDimitry Andric   case G_FMUL:
39720b57cec5SDimitry Andric   case G_FSUB:
39730b57cec5SDimitry Andric   case G_FNEG:
39740b57cec5SDimitry Andric   case G_FABS:
39750b57cec5SDimitry Andric   case G_FCANONICALIZE:
39760b57cec5SDimitry Andric   case G_FDIV:
39770b57cec5SDimitry Andric   case G_FREM:
39780b57cec5SDimitry Andric   case G_FMA:
39798bcb0991SDimitry Andric   case G_FMAD:
39800b57cec5SDimitry Andric   case G_FPOW:
39810b57cec5SDimitry Andric   case G_FEXP:
39820b57cec5SDimitry Andric   case G_FEXP2:
39830b57cec5SDimitry Andric   case G_FLOG:
39840b57cec5SDimitry Andric   case G_FLOG2:
39850b57cec5SDimitry Andric   case G_FLOG10:
39860b57cec5SDimitry Andric   case G_FNEARBYINT:
39870b57cec5SDimitry Andric   case G_FCEIL:
39880b57cec5SDimitry Andric   case G_FFLOOR:
39890b57cec5SDimitry Andric   case G_FRINT:
39900b57cec5SDimitry Andric   case G_INTRINSIC_ROUND:
3991e8d8bef9SDimitry Andric   case G_INTRINSIC_ROUNDEVEN:
39920b57cec5SDimitry Andric   case G_INTRINSIC_TRUNC:
39930b57cec5SDimitry Andric   case G_FCOS:
39940b57cec5SDimitry Andric   case G_FSIN:
39950b57cec5SDimitry Andric   case G_FSQRT:
39960b57cec5SDimitry Andric   case G_BSWAP:
39978bcb0991SDimitry Andric   case G_BITREVERSE:
39980b57cec5SDimitry Andric   case G_SDIV:
3999480093f4SDimitry Andric   case G_UDIV:
4000480093f4SDimitry Andric   case G_SREM:
4001480093f4SDimitry Andric   case G_UREM:
40020b57cec5SDimitry Andric   case G_SMIN:
40030b57cec5SDimitry Andric   case G_SMAX:
40040b57cec5SDimitry Andric   case G_UMIN:
40050b57cec5SDimitry Andric   case G_UMAX:
40060b57cec5SDimitry Andric   case G_FMINNUM:
40070b57cec5SDimitry Andric   case G_FMAXNUM:
40080b57cec5SDimitry Andric   case G_FMINNUM_IEEE:
40090b57cec5SDimitry Andric   case G_FMAXNUM_IEEE:
40100b57cec5SDimitry Andric   case G_FMINIMUM:
40110b57cec5SDimitry Andric   case G_FMAXIMUM:
40125ffd83dbSDimitry Andric   case G_FSHL:
40135ffd83dbSDimitry Andric   case G_FSHR:
40145ffd83dbSDimitry Andric   case G_FREEZE:
40155ffd83dbSDimitry Andric   case G_SADDSAT:
40165ffd83dbSDimitry Andric   case G_SSUBSAT:
40175ffd83dbSDimitry Andric   case G_UADDSAT:
40185ffd83dbSDimitry Andric   case G_USUBSAT:
40195ffd83dbSDimitry Andric     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
40200b57cec5SDimitry Andric   case G_SHL:
40210b57cec5SDimitry Andric   case G_LSHR:
40220b57cec5SDimitry Andric   case G_ASHR:
4023e8d8bef9SDimitry Andric   case G_SSHLSAT:
4024e8d8bef9SDimitry Andric   case G_USHLSAT:
40250b57cec5SDimitry Andric   case G_CTLZ:
40260b57cec5SDimitry Andric   case G_CTLZ_ZERO_UNDEF:
40270b57cec5SDimitry Andric   case G_CTTZ:
40280b57cec5SDimitry Andric   case G_CTTZ_ZERO_UNDEF:
40290b57cec5SDimitry Andric   case G_CTPOP:
40300b57cec5SDimitry Andric   case G_FCOPYSIGN:
40310b57cec5SDimitry Andric     return fewerElementsVectorMultiEltType(MI, TypeIdx, NarrowTy);
40320b57cec5SDimitry Andric   case G_ZEXT:
40330b57cec5SDimitry Andric   case G_SEXT:
40340b57cec5SDimitry Andric   case G_ANYEXT:
40350b57cec5SDimitry Andric   case G_FPEXT:
40360b57cec5SDimitry Andric   case G_FPTRUNC:
40370b57cec5SDimitry Andric   case G_SITOFP:
40380b57cec5SDimitry Andric   case G_UITOFP:
40390b57cec5SDimitry Andric   case G_FPTOSI:
40400b57cec5SDimitry Andric   case G_FPTOUI:
40410b57cec5SDimitry Andric   case G_INTTOPTR:
40420b57cec5SDimitry Andric   case G_PTRTOINT:
40430b57cec5SDimitry Andric   case G_ADDRSPACE_CAST:
40440b57cec5SDimitry Andric     return fewerElementsVectorCasts(MI, TypeIdx, NarrowTy);
40450b57cec5SDimitry Andric   case G_ICMP:
40460b57cec5SDimitry Andric   case G_FCMP:
40470b57cec5SDimitry Andric     return fewerElementsVectorCmp(MI, TypeIdx, NarrowTy);
40480b57cec5SDimitry Andric   case G_SELECT:
40490b57cec5SDimitry Andric     return fewerElementsVectorSelect(MI, TypeIdx, NarrowTy);
40500b57cec5SDimitry Andric   case G_PHI:
40510b57cec5SDimitry Andric     return fewerElementsVectorPhi(MI, TypeIdx, NarrowTy);
40528bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
40538bcb0991SDimitry Andric     return fewerElementsVectorUnmergeValues(MI, TypeIdx, NarrowTy);
40548bcb0991SDimitry Andric   case G_BUILD_VECTOR:
4055e8d8bef9SDimitry Andric     assert(TypeIdx == 0 && "not a vector type index");
4056e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4057e8d8bef9SDimitry Andric   case G_CONCAT_VECTORS:
4058e8d8bef9SDimitry Andric     if (TypeIdx != 1) // TODO: This probably does work as expected already.
4059e8d8bef9SDimitry Andric       return UnableToLegalize;
4060e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4061e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
4062e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
4063e8d8bef9SDimitry Andric     return fewerElementsVectorExtractInsertVectorElt(MI, TypeIdx, NarrowTy);
40640b57cec5SDimitry Andric   case G_LOAD:
40650b57cec5SDimitry Andric   case G_STORE:
40660b57cec5SDimitry Andric     return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
40675ffd83dbSDimitry Andric   case G_SEXT_INREG:
40685ffd83dbSDimitry Andric     return fewerElementsVectorSextInReg(MI, TypeIdx, NarrowTy);
40690b57cec5SDimitry Andric   default:
40700b57cec5SDimitry Andric     return UnableToLegalize;
40710b57cec5SDimitry Andric   }
40720b57cec5SDimitry Andric }
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
40750b57cec5SDimitry Andric LegalizerHelper::narrowScalarShiftByConstant(MachineInstr &MI, const APInt &Amt,
40760b57cec5SDimitry Andric                                              const LLT HalfTy, const LLT AmtTy) {
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
40790b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
40805ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric   if (Amt.isNullValue()) {
40835ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), {InL, InH});
40840b57cec5SDimitry Andric     MI.eraseFromParent();
40850b57cec5SDimitry Andric     return Legalized;
40860b57cec5SDimitry Andric   }
40870b57cec5SDimitry Andric 
40880b57cec5SDimitry Andric   LLT NVT = HalfTy;
40890b57cec5SDimitry Andric   unsigned NVTBits = HalfTy.getSizeInBits();
40900b57cec5SDimitry Andric   unsigned VTBits = 2 * NVTBits;
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric   SrcOp Lo(Register(0)), Hi(Register(0));
40930b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_SHL) {
40940b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
40950b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
40960b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
40970b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
40980b57cec5SDimitry Andric       Hi = MIRBuilder.buildShl(NVT, InL,
40990b57cec5SDimitry Andric                                MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
41000b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
41010b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
41020b57cec5SDimitry Andric       Hi = InL;
41030b57cec5SDimitry Andric     } else {
41040b57cec5SDimitry Andric       Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
41050b57cec5SDimitry Andric       auto OrLHS =
41060b57cec5SDimitry Andric           MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
41070b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildLShr(
41080b57cec5SDimitry Andric           NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
41090b57cec5SDimitry Andric       Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
41100b57cec5SDimitry Andric     }
41110b57cec5SDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
41120b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
41130b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
41140b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
41150b57cec5SDimitry Andric       Lo = MIRBuilder.buildLShr(NVT, InH,
41160b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
41170b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
41180b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
41190b57cec5SDimitry Andric       Lo = InH;
41200b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
41210b57cec5SDimitry Andric     } else {
41220b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
41250b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
41260b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
41270b57cec5SDimitry Andric 
41280b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
41290b57cec5SDimitry Andric       Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
41300b57cec5SDimitry Andric     }
41310b57cec5SDimitry Andric   } else {
41320b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
41330b57cec5SDimitry Andric       Hi = Lo = MIRBuilder.buildAShr(
41340b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
41350b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
41360b57cec5SDimitry Andric       Lo = MIRBuilder.buildAShr(NVT, InH,
41370b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
41380b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
41390b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
41400b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
41410b57cec5SDimitry Andric       Lo = InH;
41420b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
41430b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
41440b57cec5SDimitry Andric     } else {
41450b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
41460b57cec5SDimitry Andric 
41470b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
41480b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
41490b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
41500b57cec5SDimitry Andric 
41510b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
41520b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
41530b57cec5SDimitry Andric     }
41540b57cec5SDimitry Andric   }
41550b57cec5SDimitry Andric 
41565ffd83dbSDimitry Andric   MIRBuilder.buildMerge(MI.getOperand(0), {Lo, Hi});
41570b57cec5SDimitry Andric   MI.eraseFromParent();
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric   return Legalized;
41600b57cec5SDimitry Andric }
41610b57cec5SDimitry Andric 
41620b57cec5SDimitry Andric // TODO: Optimize if constant shift amount.
41630b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
41640b57cec5SDimitry Andric LegalizerHelper::narrowScalarShift(MachineInstr &MI, unsigned TypeIdx,
41650b57cec5SDimitry Andric                                    LLT RequestedTy) {
41660b57cec5SDimitry Andric   if (TypeIdx == 1) {
41670b57cec5SDimitry Andric     Observer.changingInstr(MI);
41680b57cec5SDimitry Andric     narrowScalarSrc(MI, RequestedTy, 2);
41690b57cec5SDimitry Andric     Observer.changedInstr(MI);
41700b57cec5SDimitry Andric     return Legalized;
41710b57cec5SDimitry Andric   }
41720b57cec5SDimitry Andric 
41730b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
41740b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
41750b57cec5SDimitry Andric   if (DstTy.isVector())
41760b57cec5SDimitry Andric     return UnableToLegalize;
41770b57cec5SDimitry Andric 
41780b57cec5SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
41790b57cec5SDimitry Andric   LLT ShiftAmtTy = MRI.getType(Amt);
41800b57cec5SDimitry Andric   const unsigned DstEltSize = DstTy.getScalarSizeInBits();
41810b57cec5SDimitry Andric   if (DstEltSize % 2 != 0)
41820b57cec5SDimitry Andric     return UnableToLegalize;
41830b57cec5SDimitry Andric 
41840b57cec5SDimitry Andric   // Ignore the input type. We can only go to exactly half the size of the
41850b57cec5SDimitry Andric   // input. If that isn't small enough, the resulting pieces will be further
41860b57cec5SDimitry Andric   // legalized.
41870b57cec5SDimitry Andric   const unsigned NewBitSize = DstEltSize / 2;
41880b57cec5SDimitry Andric   const LLT HalfTy = LLT::scalar(NewBitSize);
41890b57cec5SDimitry Andric   const LLT CondTy = LLT::scalar(1);
41900b57cec5SDimitry Andric 
41910b57cec5SDimitry Andric   if (const MachineInstr *KShiftAmt =
41920b57cec5SDimitry Andric           getOpcodeDef(TargetOpcode::G_CONSTANT, Amt, MRI)) {
41930b57cec5SDimitry Andric     return narrowScalarShiftByConstant(
41940b57cec5SDimitry Andric         MI, KShiftAmt->getOperand(1).getCImm()->getValue(), HalfTy, ShiftAmtTy);
41950b57cec5SDimitry Andric   }
41960b57cec5SDimitry Andric 
41970b57cec5SDimitry Andric   // TODO: Expand with known bits.
41980b57cec5SDimitry Andric 
41990b57cec5SDimitry Andric   // Handle the fully general expansion by an unknown amount.
42000b57cec5SDimitry Andric   auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
42010b57cec5SDimitry Andric 
42020b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
42030b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
42045ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
42050b57cec5SDimitry Andric 
42060b57cec5SDimitry Andric   auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
42070b57cec5SDimitry Andric   auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
42080b57cec5SDimitry Andric 
42090b57cec5SDimitry Andric   auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
42100b57cec5SDimitry Andric   auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
42110b57cec5SDimitry Andric   auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric   Register ResultRegs[2];
42140b57cec5SDimitry Andric   switch (MI.getOpcode()) {
42150b57cec5SDimitry Andric   case TargetOpcode::G_SHL: {
42160b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
42178bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildShl(HalfTy, InL, Amt);
42180b57cec5SDimitry Andric 
42198bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
42208bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, Amt);
42218bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
42220b57cec5SDimitry Andric 
42230b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
42240b57cec5SDimitry Andric     auto LoL = MIRBuilder.buildConstant(HalfTy, 0);         // Lo part is zero.
42250b57cec5SDimitry Andric     auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
42260b57cec5SDimitry Andric 
42270b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
42280b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(
42290b57cec5SDimitry Andric         HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
42320b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
42330b57cec5SDimitry Andric     break;
42340b57cec5SDimitry Andric   }
42358bcb0991SDimitry Andric   case TargetOpcode::G_LSHR:
42360b57cec5SDimitry Andric   case TargetOpcode::G_ASHR: {
42370b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
42388bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy}, {InH, Amt});
42390b57cec5SDimitry Andric 
42408bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, Amt);
42418bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
42428bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
42430b57cec5SDimitry Andric 
42440b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
42458bcb0991SDimitry Andric     MachineInstrBuilder HiL;
42468bcb0991SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_LSHR) {
42478bcb0991SDimitry Andric       HiL = MIRBuilder.buildConstant(HalfTy, 0);            // Hi part is zero.
42488bcb0991SDimitry Andric     } else {
42498bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1);
42508bcb0991SDimitry Andric       HiL = MIRBuilder.buildAShr(HalfTy, InH, ShiftAmt);    // Sign of Hi part.
42518bcb0991SDimitry Andric     }
42528bcb0991SDimitry Andric     auto LoL = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy},
42538bcb0991SDimitry Andric                                      {InH, AmtExcess});     // Lo from Hi part.
42540b57cec5SDimitry Andric 
42550b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(
42560b57cec5SDimitry Andric         HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
42570b57cec5SDimitry Andric 
42580b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
42590b57cec5SDimitry Andric 
42600b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
42610b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
42620b57cec5SDimitry Andric     break;
42630b57cec5SDimitry Andric   }
42640b57cec5SDimitry Andric   default:
42650b57cec5SDimitry Andric     llvm_unreachable("not a shift");
42660b57cec5SDimitry Andric   }
42670b57cec5SDimitry Andric 
42680b57cec5SDimitry Andric   MIRBuilder.buildMerge(DstReg, ResultRegs);
42690b57cec5SDimitry Andric   MI.eraseFromParent();
42700b57cec5SDimitry Andric   return Legalized;
42710b57cec5SDimitry Andric }
42720b57cec5SDimitry Andric 
42730b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
42740b57cec5SDimitry Andric LegalizerHelper::moreElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
42750b57cec5SDimitry Andric                                        LLT MoreTy) {
42760b57cec5SDimitry Andric   assert(TypeIdx == 0 && "Expecting only Idx 0");
42770b57cec5SDimitry Andric 
42780b57cec5SDimitry Andric   Observer.changingInstr(MI);
42790b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
42800b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
42810b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
42820b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, I);
42830b57cec5SDimitry Andric   }
42840b57cec5SDimitry Andric 
42850b57cec5SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
42860b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
42870b57cec5SDimitry Andric   moreElementsVectorDst(MI, MoreTy, 0);
42880b57cec5SDimitry Andric   Observer.changedInstr(MI);
42890b57cec5SDimitry Andric   return Legalized;
42900b57cec5SDimitry Andric }
42910b57cec5SDimitry Andric 
42920b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
42930b57cec5SDimitry Andric LegalizerHelper::moreElementsVector(MachineInstr &MI, unsigned TypeIdx,
42940b57cec5SDimitry Andric                                     LLT MoreTy) {
42950b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
42960b57cec5SDimitry Andric   switch (Opc) {
42978bcb0991SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF:
42988bcb0991SDimitry Andric   case TargetOpcode::G_LOAD: {
42998bcb0991SDimitry Andric     if (TypeIdx != 0)
43008bcb0991SDimitry Andric       return UnableToLegalize;
43010b57cec5SDimitry Andric     Observer.changingInstr(MI);
43020b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43030b57cec5SDimitry Andric     Observer.changedInstr(MI);
43040b57cec5SDimitry Andric     return Legalized;
43050b57cec5SDimitry Andric   }
43068bcb0991SDimitry Andric   case TargetOpcode::G_STORE:
43078bcb0991SDimitry Andric     if (TypeIdx != 0)
43088bcb0991SDimitry Andric       return UnableToLegalize;
43098bcb0991SDimitry Andric     Observer.changingInstr(MI);
43108bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 0);
43118bcb0991SDimitry Andric     Observer.changedInstr(MI);
43128bcb0991SDimitry Andric     return Legalized;
43130b57cec5SDimitry Andric   case TargetOpcode::G_AND:
43140b57cec5SDimitry Andric   case TargetOpcode::G_OR:
43150b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
43160b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
43170b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
43180b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
4319480093f4SDimitry Andric   case TargetOpcode::G_UMAX:
4320480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM:
4321480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM:
4322480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
4323480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
4324480093f4SDimitry Andric   case TargetOpcode::G_FMINIMUM:
4325480093f4SDimitry Andric   case TargetOpcode::G_FMAXIMUM: {
43260b57cec5SDimitry Andric     Observer.changingInstr(MI);
43270b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
43280b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
43290b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43300b57cec5SDimitry Andric     Observer.changedInstr(MI);
43310b57cec5SDimitry Andric     return Legalized;
43320b57cec5SDimitry Andric   }
43330b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
43340b57cec5SDimitry Andric     if (TypeIdx != 1)
43350b57cec5SDimitry Andric       return UnableToLegalize;
43360b57cec5SDimitry Andric     Observer.changingInstr(MI);
43370b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
43380b57cec5SDimitry Andric     Observer.changedInstr(MI);
43390b57cec5SDimitry Andric     return Legalized;
43400b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
43415ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
43420b57cec5SDimitry Andric     if (TypeIdx != 0)
43430b57cec5SDimitry Andric       return UnableToLegalize;
43440b57cec5SDimitry Andric     Observer.changingInstr(MI);
43450b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
43460b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43470b57cec5SDimitry Andric     Observer.changedInstr(MI);
43480b57cec5SDimitry Andric     return Legalized;
43490b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
43500b57cec5SDimitry Andric     if (TypeIdx != 0)
43510b57cec5SDimitry Andric       return UnableToLegalize;
43520b57cec5SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector())
43530b57cec5SDimitry Andric       return UnableToLegalize;
43540b57cec5SDimitry Andric 
43550b57cec5SDimitry Andric     Observer.changingInstr(MI);
43560b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
43570b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 3);
43580b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43590b57cec5SDimitry Andric     Observer.changedInstr(MI);
43600b57cec5SDimitry Andric     return Legalized;
43618bcb0991SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES: {
43628bcb0991SDimitry Andric     if (TypeIdx != 1)
43638bcb0991SDimitry Andric       return UnableToLegalize;
43648bcb0991SDimitry Andric 
43658bcb0991SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
43668bcb0991SDimitry Andric     int NumDst = MI.getNumOperands() - 1;
43678bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, NumDst);
43688bcb0991SDimitry Andric 
43698bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
43708bcb0991SDimitry Andric     for (int I = 0; I != NumDst; ++I)
43718bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I).getReg());
43728bcb0991SDimitry Andric 
43738bcb0991SDimitry Andric     int NewNumDst = MoreTy.getSizeInBits() / DstTy.getSizeInBits();
43748bcb0991SDimitry Andric     for (int I = NumDst; I != NewNumDst; ++I)
43758bcb0991SDimitry Andric       MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
43768bcb0991SDimitry Andric 
43778bcb0991SDimitry Andric     MIB.addUse(MI.getOperand(NumDst).getReg());
43788bcb0991SDimitry Andric     MI.eraseFromParent();
43798bcb0991SDimitry Andric     return Legalized;
43808bcb0991SDimitry Andric   }
43810b57cec5SDimitry Andric   case TargetOpcode::G_PHI:
43820b57cec5SDimitry Andric     return moreElementsVectorPhi(MI, TypeIdx, MoreTy);
43830b57cec5SDimitry Andric   default:
43840b57cec5SDimitry Andric     return UnableToLegalize;
43850b57cec5SDimitry Andric   }
43860b57cec5SDimitry Andric }
43870b57cec5SDimitry Andric 
43880b57cec5SDimitry Andric void LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
43890b57cec5SDimitry Andric                                         ArrayRef<Register> Src1Regs,
43900b57cec5SDimitry Andric                                         ArrayRef<Register> Src2Regs,
43910b57cec5SDimitry Andric                                         LLT NarrowTy) {
43920b57cec5SDimitry Andric   MachineIRBuilder &B = MIRBuilder;
43930b57cec5SDimitry Andric   unsigned SrcParts = Src1Regs.size();
43940b57cec5SDimitry Andric   unsigned DstParts = DstRegs.size();
43950b57cec5SDimitry Andric 
43960b57cec5SDimitry Andric   unsigned DstIdx = 0; // Low bits of the result.
43970b57cec5SDimitry Andric   Register FactorSum =
43980b57cec5SDimitry Andric       B.buildMul(NarrowTy, Src1Regs[DstIdx], Src2Regs[DstIdx]).getReg(0);
43990b57cec5SDimitry Andric   DstRegs[DstIdx] = FactorSum;
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric   unsigned CarrySumPrevDstIdx;
44020b57cec5SDimitry Andric   SmallVector<Register, 4> Factors;
44030b57cec5SDimitry Andric 
44040b57cec5SDimitry Andric   for (DstIdx = 1; DstIdx < DstParts; DstIdx++) {
44050b57cec5SDimitry Andric     // Collect low parts of muls for DstIdx.
44060b57cec5SDimitry Andric     for (unsigned i = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
44070b57cec5SDimitry Andric          i <= std::min(DstIdx, SrcParts - 1); ++i) {
44080b57cec5SDimitry Andric       MachineInstrBuilder Mul =
44090b57cec5SDimitry Andric           B.buildMul(NarrowTy, Src1Regs[DstIdx - i], Src2Regs[i]);
44100b57cec5SDimitry Andric       Factors.push_back(Mul.getReg(0));
44110b57cec5SDimitry Andric     }
44120b57cec5SDimitry Andric     // Collect high parts of muls from previous DstIdx.
44130b57cec5SDimitry Andric     for (unsigned i = DstIdx < SrcParts ? 0 : DstIdx - SrcParts;
44140b57cec5SDimitry Andric          i <= std::min(DstIdx - 1, SrcParts - 1); ++i) {
44150b57cec5SDimitry Andric       MachineInstrBuilder Umulh =
44160b57cec5SDimitry Andric           B.buildUMulH(NarrowTy, Src1Regs[DstIdx - 1 - i], Src2Regs[i]);
44170b57cec5SDimitry Andric       Factors.push_back(Umulh.getReg(0));
44180b57cec5SDimitry Andric     }
4419480093f4SDimitry Andric     // Add CarrySum from additions calculated for previous DstIdx.
44200b57cec5SDimitry Andric     if (DstIdx != 1) {
44210b57cec5SDimitry Andric       Factors.push_back(CarrySumPrevDstIdx);
44220b57cec5SDimitry Andric     }
44230b57cec5SDimitry Andric 
44240b57cec5SDimitry Andric     Register CarrySum;
44250b57cec5SDimitry Andric     // Add all factors and accumulate all carries into CarrySum.
44260b57cec5SDimitry Andric     if (DstIdx != DstParts - 1) {
44270b57cec5SDimitry Andric       MachineInstrBuilder Uaddo =
44280b57cec5SDimitry Andric           B.buildUAddo(NarrowTy, LLT::scalar(1), Factors[0], Factors[1]);
44290b57cec5SDimitry Andric       FactorSum = Uaddo.getReg(0);
44300b57cec5SDimitry Andric       CarrySum = B.buildZExt(NarrowTy, Uaddo.getReg(1)).getReg(0);
44310b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i) {
44320b57cec5SDimitry Andric         MachineInstrBuilder Uaddo =
44330b57cec5SDimitry Andric             B.buildUAddo(NarrowTy, LLT::scalar(1), FactorSum, Factors[i]);
44340b57cec5SDimitry Andric         FactorSum = Uaddo.getReg(0);
44350b57cec5SDimitry Andric         MachineInstrBuilder Carry = B.buildZExt(NarrowTy, Uaddo.getReg(1));
44360b57cec5SDimitry Andric         CarrySum = B.buildAdd(NarrowTy, CarrySum, Carry).getReg(0);
44370b57cec5SDimitry Andric       }
44380b57cec5SDimitry Andric     } else {
44390b57cec5SDimitry Andric       // Since value for the next index is not calculated, neither is CarrySum.
44400b57cec5SDimitry Andric       FactorSum = B.buildAdd(NarrowTy, Factors[0], Factors[1]).getReg(0);
44410b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i)
44420b57cec5SDimitry Andric         FactorSum = B.buildAdd(NarrowTy, FactorSum, Factors[i]).getReg(0);
44430b57cec5SDimitry Andric     }
44440b57cec5SDimitry Andric 
44450b57cec5SDimitry Andric     CarrySumPrevDstIdx = CarrySum;
44460b57cec5SDimitry Andric     DstRegs[DstIdx] = FactorSum;
44470b57cec5SDimitry Andric     Factors.clear();
44480b57cec5SDimitry Andric   }
44490b57cec5SDimitry Andric }
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
44520b57cec5SDimitry Andric LegalizerHelper::narrowScalarMul(MachineInstr &MI, LLT NarrowTy) {
44530b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
44540b57cec5SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
44550b57cec5SDimitry Andric   Register Src2 = MI.getOperand(2).getReg();
44560b57cec5SDimitry Andric 
44570b57cec5SDimitry Andric   LLT Ty = MRI.getType(DstReg);
44580b57cec5SDimitry Andric   if (Ty.isVector())
44590b57cec5SDimitry Andric     return UnableToLegalize;
44600b57cec5SDimitry Andric 
44610b57cec5SDimitry Andric   unsigned SrcSize = MRI.getType(Src1).getSizeInBits();
44620b57cec5SDimitry Andric   unsigned DstSize = Ty.getSizeInBits();
44630b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
44640b57cec5SDimitry Andric   if (DstSize % NarrowSize != 0 || SrcSize % NarrowSize != 0)
44650b57cec5SDimitry Andric     return UnableToLegalize;
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric   unsigned NumDstParts = DstSize / NarrowSize;
44680b57cec5SDimitry Andric   unsigned NumSrcParts = SrcSize / NarrowSize;
44690b57cec5SDimitry Andric   bool IsMulHigh = MI.getOpcode() == TargetOpcode::G_UMULH;
44700b57cec5SDimitry Andric   unsigned DstTmpParts = NumDstParts * (IsMulHigh ? 2 : 1);
44710b57cec5SDimitry Andric 
44725ffd83dbSDimitry Andric   SmallVector<Register, 2> Src1Parts, Src2Parts;
44735ffd83dbSDimitry Andric   SmallVector<Register, 2> DstTmpRegs(DstTmpParts);
44740b57cec5SDimitry Andric   extractParts(Src1, NarrowTy, NumSrcParts, Src1Parts);
44750b57cec5SDimitry Andric   extractParts(Src2, NarrowTy, NumSrcParts, Src2Parts);
44760b57cec5SDimitry Andric   multiplyRegisters(DstTmpRegs, Src1Parts, Src2Parts, NarrowTy);
44770b57cec5SDimitry Andric 
44780b57cec5SDimitry Andric   // Take only high half of registers if this is high mul.
44790b57cec5SDimitry Andric   ArrayRef<Register> DstRegs(
44800b57cec5SDimitry Andric       IsMulHigh ? &DstTmpRegs[DstTmpParts / 2] : &DstTmpRegs[0], NumDstParts);
44810b57cec5SDimitry Andric   MIRBuilder.buildMerge(DstReg, DstRegs);
44820b57cec5SDimitry Andric   MI.eraseFromParent();
44830b57cec5SDimitry Andric   return Legalized;
44840b57cec5SDimitry Andric }
44850b57cec5SDimitry Andric 
44860b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
4487*23408297SDimitry Andric LegalizerHelper::narrowScalarFPTOI(MachineInstr &MI, unsigned TypeIdx,
4488*23408297SDimitry Andric                                    LLT NarrowTy) {
4489*23408297SDimitry Andric   if (TypeIdx != 0)
4490*23408297SDimitry Andric     return UnableToLegalize;
4491*23408297SDimitry Andric 
4492*23408297SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_FPTOSI;
4493*23408297SDimitry Andric 
4494*23408297SDimitry Andric   Register Src = MI.getOperand(1).getReg();
4495*23408297SDimitry Andric   LLT SrcTy = MRI.getType(Src);
4496*23408297SDimitry Andric 
4497*23408297SDimitry Andric   // If all finite floats fit into the narrowed integer type, we can just swap
4498*23408297SDimitry Andric   // out the result type. This is practically only useful for conversions from
4499*23408297SDimitry Andric   // half to at least 16-bits, so just handle the one case.
4500*23408297SDimitry Andric   if (SrcTy.getScalarType() != LLT::scalar(16) ||
4501*23408297SDimitry Andric       NarrowTy.getScalarSizeInBits() < (IsSigned ? 17 : 16))
4502*23408297SDimitry Andric     return UnableToLegalize;
4503*23408297SDimitry Andric 
4504*23408297SDimitry Andric   Observer.changingInstr(MI);
4505*23408297SDimitry Andric   narrowScalarDst(MI, NarrowTy, 0,
4506*23408297SDimitry Andric                   IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT);
4507*23408297SDimitry Andric   Observer.changedInstr(MI);
4508*23408297SDimitry Andric   return Legalized;
4509*23408297SDimitry Andric }
4510*23408297SDimitry Andric 
4511*23408297SDimitry Andric LegalizerHelper::LegalizeResult
45120b57cec5SDimitry Andric LegalizerHelper::narrowScalarExtract(MachineInstr &MI, unsigned TypeIdx,
45130b57cec5SDimitry Andric                                      LLT NarrowTy) {
45140b57cec5SDimitry Andric   if (TypeIdx != 1)
45150b57cec5SDimitry Andric     return UnableToLegalize;
45160b57cec5SDimitry Andric 
45170b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
45180b57cec5SDimitry Andric 
45190b57cec5SDimitry Andric   int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
45200b57cec5SDimitry Andric   // FIXME: add support for when SizeOp1 isn't an exact multiple of
45210b57cec5SDimitry Andric   // NarrowSize.
45220b57cec5SDimitry Andric   if (SizeOp1 % NarrowSize != 0)
45230b57cec5SDimitry Andric     return UnableToLegalize;
45240b57cec5SDimitry Andric   int NumParts = SizeOp1 / NarrowSize;
45250b57cec5SDimitry Andric 
45260b57cec5SDimitry Andric   SmallVector<Register, 2> SrcRegs, DstRegs;
45270b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
45280b57cec5SDimitry Andric   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric   Register OpReg = MI.getOperand(0).getReg();
45310b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(2).getImm();
45320b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
45330b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i) {
45340b57cec5SDimitry Andric     unsigned SrcStart = i * NarrowSize;
45350b57cec5SDimitry Andric 
45360b57cec5SDimitry Andric     if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
45370b57cec5SDimitry Andric       // No part of the extract uses this subregister, ignore it.
45380b57cec5SDimitry Andric       continue;
45390b57cec5SDimitry Andric     } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
45400b57cec5SDimitry Andric       // The entire subregister is extracted, forward the value.
45410b57cec5SDimitry Andric       DstRegs.push_back(SrcRegs[i]);
45420b57cec5SDimitry Andric       continue;
45430b57cec5SDimitry Andric     }
45440b57cec5SDimitry Andric 
45450b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
45460b57cec5SDimitry Andric     // extended infinitely in both directions.
45470b57cec5SDimitry Andric     int64_t ExtractOffset;
45480b57cec5SDimitry Andric     uint64_t SegSize;
45490b57cec5SDimitry Andric     if (OpStart < SrcStart) {
45500b57cec5SDimitry Andric       ExtractOffset = 0;
45510b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
45520b57cec5SDimitry Andric     } else {
45530b57cec5SDimitry Andric       ExtractOffset = OpStart - SrcStart;
45540b57cec5SDimitry Andric       SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
45550b57cec5SDimitry Andric     }
45560b57cec5SDimitry Andric 
45570b57cec5SDimitry Andric     Register SegReg = SrcRegs[i];
45580b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != NarrowSize) {
45590b57cec5SDimitry Andric       // A genuine extract is needed.
45600b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
45610b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
45620b57cec5SDimitry Andric     }
45630b57cec5SDimitry Andric 
45640b57cec5SDimitry Andric     DstRegs.push_back(SegReg);
45650b57cec5SDimitry Andric   }
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
45680b57cec5SDimitry Andric   if (MRI.getType(DstReg).isVector())
45690b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
45705ffd83dbSDimitry Andric   else if (DstRegs.size() > 1)
45710b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
45725ffd83dbSDimitry Andric   else
45735ffd83dbSDimitry Andric     MIRBuilder.buildCopy(DstReg, DstRegs[0]);
45740b57cec5SDimitry Andric   MI.eraseFromParent();
45750b57cec5SDimitry Andric   return Legalized;
45760b57cec5SDimitry Andric }
45770b57cec5SDimitry Andric 
45780b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
45790b57cec5SDimitry Andric LegalizerHelper::narrowScalarInsert(MachineInstr &MI, unsigned TypeIdx,
45800b57cec5SDimitry Andric                                     LLT NarrowTy) {
45810b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
45820b57cec5SDimitry Andric   if (TypeIdx != 0)
45830b57cec5SDimitry Andric     return UnableToLegalize;
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
45860b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
45870b57cec5SDimitry Andric 
45880b57cec5SDimitry Andric   // FIXME: add support for when SizeOp0 isn't an exact multiple of
45890b57cec5SDimitry Andric   // NarrowSize.
45900b57cec5SDimitry Andric   if (SizeOp0 % NarrowSize != 0)
45910b57cec5SDimitry Andric     return UnableToLegalize;
45920b57cec5SDimitry Andric 
45930b57cec5SDimitry Andric   int NumParts = SizeOp0 / NarrowSize;
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric   SmallVector<Register, 2> SrcRegs, DstRegs;
45960b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
45970b57cec5SDimitry Andric   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
45980b57cec5SDimitry Andric 
45990b57cec5SDimitry Andric   Register OpReg = MI.getOperand(2).getReg();
46000b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(3).getImm();
46010b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
46020b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i) {
46030b57cec5SDimitry Andric     unsigned DstStart = i * NarrowSize;
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric     if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
46060b57cec5SDimitry Andric       // No part of the insert affects this subregister, forward the original.
46070b57cec5SDimitry Andric       DstRegs.push_back(SrcRegs[i]);
46080b57cec5SDimitry Andric       continue;
46090b57cec5SDimitry Andric     } else if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
46100b57cec5SDimitry Andric       // The entire subregister is defined by this insert, forward the new
46110b57cec5SDimitry Andric       // value.
46120b57cec5SDimitry Andric       DstRegs.push_back(OpReg);
46130b57cec5SDimitry Andric       continue;
46140b57cec5SDimitry Andric     }
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
46170b57cec5SDimitry Andric     // extended infinitely in both directions.
46180b57cec5SDimitry Andric     int64_t ExtractOffset, InsertOffset;
46190b57cec5SDimitry Andric     uint64_t SegSize;
46200b57cec5SDimitry Andric     if (OpStart < DstStart) {
46210b57cec5SDimitry Andric       InsertOffset = 0;
46220b57cec5SDimitry Andric       ExtractOffset = DstStart - OpStart;
46230b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
46240b57cec5SDimitry Andric     } else {
46250b57cec5SDimitry Andric       InsertOffset = OpStart - DstStart;
46260b57cec5SDimitry Andric       ExtractOffset = 0;
46270b57cec5SDimitry Andric       SegSize =
46280b57cec5SDimitry Andric         std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
46290b57cec5SDimitry Andric     }
46300b57cec5SDimitry Andric 
46310b57cec5SDimitry Andric     Register SegReg = OpReg;
46320b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != OpSize) {
46330b57cec5SDimitry Andric       // A genuine extract is needed.
46340b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
46350b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
46360b57cec5SDimitry Andric     }
46370b57cec5SDimitry Andric 
46380b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
46390b57cec5SDimitry Andric     MIRBuilder.buildInsert(DstReg, SrcRegs[i], SegReg, InsertOffset);
46400b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
46410b57cec5SDimitry Andric   }
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric   assert(DstRegs.size() == (unsigned)NumParts && "not all parts covered");
46440b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
46450b57cec5SDimitry Andric   if(MRI.getType(DstReg).isVector())
46460b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
46470b57cec5SDimitry Andric   else
46480b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
46490b57cec5SDimitry Andric   MI.eraseFromParent();
46500b57cec5SDimitry Andric   return Legalized;
46510b57cec5SDimitry Andric }
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
46540b57cec5SDimitry Andric LegalizerHelper::narrowScalarBasic(MachineInstr &MI, unsigned TypeIdx,
46550b57cec5SDimitry Andric                                    LLT NarrowTy) {
46560b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
46570b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
46580b57cec5SDimitry Andric 
46590b57cec5SDimitry Andric   assert(MI.getNumOperands() == 3 && TypeIdx == 0);
46600b57cec5SDimitry Andric 
46610b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
46620b57cec5SDimitry Andric   SmallVector<Register, 4> Src0Regs, Src0LeftoverRegs;
46630b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
46640b57cec5SDimitry Andric   LLT LeftoverTy;
46650b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(1).getReg(), DstTy, NarrowTy, LeftoverTy,
46660b57cec5SDimitry Andric                     Src0Regs, Src0LeftoverRegs))
46670b57cec5SDimitry Andric     return UnableToLegalize;
46680b57cec5SDimitry Andric 
46690b57cec5SDimitry Andric   LLT Unused;
46700b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, Unused,
46710b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
46720b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
46730b57cec5SDimitry Andric 
46740b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
46750b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
46760b57cec5SDimitry Andric                                         {Src0Regs[I], Src1Regs[I]});
46775ffd83dbSDimitry Andric     DstRegs.push_back(Inst.getReg(0));
46780b57cec5SDimitry Andric   }
46790b57cec5SDimitry Andric 
46800b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
46810b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(
46820b57cec5SDimitry Andric       MI.getOpcode(),
46830b57cec5SDimitry Andric       {LeftoverTy}, {Src0LeftoverRegs[I], Src1LeftoverRegs[I]});
46845ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Inst.getReg(0));
46850b57cec5SDimitry Andric   }
46860b57cec5SDimitry Andric 
46870b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
46880b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric   MI.eraseFromParent();
46910b57cec5SDimitry Andric   return Legalized;
46920b57cec5SDimitry Andric }
46930b57cec5SDimitry Andric 
46940b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
46955ffd83dbSDimitry Andric LegalizerHelper::narrowScalarExt(MachineInstr &MI, unsigned TypeIdx,
46965ffd83dbSDimitry Andric                                  LLT NarrowTy) {
46975ffd83dbSDimitry Andric   if (TypeIdx != 0)
46985ffd83dbSDimitry Andric     return UnableToLegalize;
46995ffd83dbSDimitry Andric 
47005ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
47015ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
47025ffd83dbSDimitry Andric 
47035ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
47045ffd83dbSDimitry Andric   if (DstTy.isVector())
47055ffd83dbSDimitry Andric     return UnableToLegalize;
47065ffd83dbSDimitry Andric 
47075ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
47085ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
47095ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts, MI.getOpcode());
47105ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
47115ffd83dbSDimitry Andric 
47125ffd83dbSDimitry Andric   MI.eraseFromParent();
47135ffd83dbSDimitry Andric   return Legalized;
47145ffd83dbSDimitry Andric }
47155ffd83dbSDimitry Andric 
47165ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
47170b57cec5SDimitry Andric LegalizerHelper::narrowScalarSelect(MachineInstr &MI, unsigned TypeIdx,
47180b57cec5SDimitry Andric                                     LLT NarrowTy) {
47190b57cec5SDimitry Andric   if (TypeIdx != 0)
47200b57cec5SDimitry Andric     return UnableToLegalize;
47210b57cec5SDimitry Andric 
47220b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
47230b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
47240b57cec5SDimitry Andric   if (CondTy.isVector()) // TODO: Handle vselect
47250b57cec5SDimitry Andric     return UnableToLegalize;
47260b57cec5SDimitry Andric 
47270b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
47280b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
47290b57cec5SDimitry Andric 
47300b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
47310b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
47320b57cec5SDimitry Andric   SmallVector<Register, 4> Src2Regs, Src2LeftoverRegs;
47330b57cec5SDimitry Andric   LLT LeftoverTy;
47340b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
47350b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
47360b57cec5SDimitry Andric     return UnableToLegalize;
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric   LLT Unused;
47390b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
47400b57cec5SDimitry Andric                     Src2Regs, Src2LeftoverRegs))
47410b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
47440b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(NarrowTy,
47450b57cec5SDimitry Andric                                          CondReg, Src1Regs[I], Src2Regs[I]);
47465ffd83dbSDimitry Andric     DstRegs.push_back(Select.getReg(0));
47470b57cec5SDimitry Andric   }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
47500b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(
47510b57cec5SDimitry Andric       LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
47525ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Select.getReg(0));
47530b57cec5SDimitry Andric   }
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
47560b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
47570b57cec5SDimitry Andric 
47580b57cec5SDimitry Andric   MI.eraseFromParent();
47590b57cec5SDimitry Andric   return Legalized;
47600b57cec5SDimitry Andric }
47610b57cec5SDimitry Andric 
47620b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
47635ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTLZ(MachineInstr &MI, unsigned TypeIdx,
47645ffd83dbSDimitry Andric                                   LLT NarrowTy) {
47655ffd83dbSDimitry Andric   if (TypeIdx != 1)
47665ffd83dbSDimitry Andric     return UnableToLegalize;
47675ffd83dbSDimitry Andric 
47685ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
47695ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
47705ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
47715ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
47725ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
47735ffd83dbSDimitry Andric 
47745ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
47755ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF;
47765ffd83dbSDimitry Andric 
47775ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
47785ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
47795ffd83dbSDimitry Andric     // ctlz(Hi:Lo) -> Hi == 0 ? (NarrowSize + ctlz(Lo)) : ctlz(Hi)
47805ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
47815ffd83dbSDimitry Andric     auto HiIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
47825ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(1), C_0);
47835ffd83dbSDimitry Andric     auto LoCTLZ = IsUndef ?
47845ffd83dbSDimitry Andric       B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0)) :
47855ffd83dbSDimitry Andric       B.buildCTLZ(DstTy, UnmergeSrc.getReg(0));
47865ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
47875ffd83dbSDimitry Andric     auto HiIsZeroCTLZ = B.buildAdd(DstTy, LoCTLZ, C_NarrowSize);
47885ffd83dbSDimitry Andric     auto HiCTLZ = B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1));
47895ffd83dbSDimitry Andric     B.buildSelect(DstReg, HiIsZero, HiIsZeroCTLZ, HiCTLZ);
47905ffd83dbSDimitry Andric 
47915ffd83dbSDimitry Andric     MI.eraseFromParent();
47925ffd83dbSDimitry Andric     return Legalized;
47935ffd83dbSDimitry Andric   }
47945ffd83dbSDimitry Andric 
47955ffd83dbSDimitry Andric   return UnableToLegalize;
47965ffd83dbSDimitry Andric }
47975ffd83dbSDimitry Andric 
47985ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
47995ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTTZ(MachineInstr &MI, unsigned TypeIdx,
48005ffd83dbSDimitry Andric                                   LLT NarrowTy) {
48015ffd83dbSDimitry Andric   if (TypeIdx != 1)
48025ffd83dbSDimitry Andric     return UnableToLegalize;
48035ffd83dbSDimitry Andric 
48045ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
48055ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
48065ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
48075ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
48085ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
48095ffd83dbSDimitry Andric 
48105ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
48115ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF;
48125ffd83dbSDimitry Andric 
48135ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
48145ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
48155ffd83dbSDimitry Andric     // cttz(Hi:Lo) -> Lo == 0 ? (cttz(Hi) + NarrowSize) : cttz(Lo)
48165ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
48175ffd83dbSDimitry Andric     auto LoIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
48185ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(0), C_0);
48195ffd83dbSDimitry Andric     auto HiCTTZ = IsUndef ?
48205ffd83dbSDimitry Andric       B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1)) :
48215ffd83dbSDimitry Andric       B.buildCTTZ(DstTy, UnmergeSrc.getReg(1));
48225ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
48235ffd83dbSDimitry Andric     auto LoIsZeroCTTZ = B.buildAdd(DstTy, HiCTTZ, C_NarrowSize);
48245ffd83dbSDimitry Andric     auto LoCTTZ = B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0));
48255ffd83dbSDimitry Andric     B.buildSelect(DstReg, LoIsZero, LoIsZeroCTTZ, LoCTTZ);
48265ffd83dbSDimitry Andric 
48275ffd83dbSDimitry Andric     MI.eraseFromParent();
48285ffd83dbSDimitry Andric     return Legalized;
48295ffd83dbSDimitry Andric   }
48305ffd83dbSDimitry Andric 
48315ffd83dbSDimitry Andric   return UnableToLegalize;
48325ffd83dbSDimitry Andric }
48335ffd83dbSDimitry Andric 
48345ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
48355ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTPOP(MachineInstr &MI, unsigned TypeIdx,
48365ffd83dbSDimitry Andric                                    LLT NarrowTy) {
48375ffd83dbSDimitry Andric   if (TypeIdx != 1)
48385ffd83dbSDimitry Andric     return UnableToLegalize;
48395ffd83dbSDimitry Andric 
48405ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
48415ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
48425ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
48435ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
48445ffd83dbSDimitry Andric 
48455ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
48465ffd83dbSDimitry Andric     auto UnmergeSrc = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
48475ffd83dbSDimitry Andric 
48485ffd83dbSDimitry Andric     auto LoCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(0));
48495ffd83dbSDimitry Andric     auto HiCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(1));
48505ffd83dbSDimitry Andric     MIRBuilder.buildAdd(DstReg, HiCTPOP, LoCTPOP);
48515ffd83dbSDimitry Andric 
48525ffd83dbSDimitry Andric     MI.eraseFromParent();
48535ffd83dbSDimitry Andric     return Legalized;
48545ffd83dbSDimitry Andric   }
48555ffd83dbSDimitry Andric 
48565ffd83dbSDimitry Andric   return UnableToLegalize;
48575ffd83dbSDimitry Andric }
48585ffd83dbSDimitry Andric 
48595ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
4860e8d8bef9SDimitry Andric LegalizerHelper::lowerBitCount(MachineInstr &MI) {
48610b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
4862e8d8bef9SDimitry Andric   const auto &TII = MIRBuilder.getTII();
48630b57cec5SDimitry Andric   auto isSupported = [this](const LegalityQuery &Q) {
48640b57cec5SDimitry Andric     auto QAction = LI.getAction(Q).Action;
48650b57cec5SDimitry Andric     return QAction == Legal || QAction == Libcall || QAction == Custom;
48660b57cec5SDimitry Andric   };
48670b57cec5SDimitry Andric   switch (Opc) {
48680b57cec5SDimitry Andric   default:
48690b57cec5SDimitry Andric     return UnableToLegalize;
48700b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
48710b57cec5SDimitry Andric     // This trivially expands to CTLZ.
48720b57cec5SDimitry Andric     Observer.changingInstr(MI);
48730b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
48740b57cec5SDimitry Andric     Observer.changedInstr(MI);
48750b57cec5SDimitry Andric     return Legalized;
48760b57cec5SDimitry Andric   }
48770b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ: {
48785ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
48790b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
48805ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
48815ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
48825ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
48835ffd83dbSDimitry Andric 
48845ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
48850b57cec5SDimitry Andric       // If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
48865ffd83dbSDimitry Andric       auto CtlzZU = MIRBuilder.buildCTLZ_ZERO_UNDEF(DstTy, SrcReg);
48875ffd83dbSDimitry Andric       auto ZeroSrc = MIRBuilder.buildConstant(SrcTy, 0);
48885ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
48895ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, SrcTy.changeElementSize(1), SrcReg, ZeroSrc);
48905ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
48915ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CtlzZU);
48920b57cec5SDimitry Andric       MI.eraseFromParent();
48930b57cec5SDimitry Andric       return Legalized;
48940b57cec5SDimitry Andric     }
48950b57cec5SDimitry Andric     // for now, we do this:
48960b57cec5SDimitry Andric     // NewLen = NextPowerOf2(Len);
48970b57cec5SDimitry Andric     // x = x | (x >> 1);
48980b57cec5SDimitry Andric     // x = x | (x >> 2);
48990b57cec5SDimitry Andric     // ...
49000b57cec5SDimitry Andric     // x = x | (x >>16);
49010b57cec5SDimitry Andric     // x = x | (x >>32); // for 64-bit input
49020b57cec5SDimitry Andric     // Upto NewLen/2
49030b57cec5SDimitry Andric     // return Len - popcount(x);
49040b57cec5SDimitry Andric     //
49050b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
49060b57cec5SDimitry Andric     Register Op = SrcReg;
49070b57cec5SDimitry Andric     unsigned NewLen = PowerOf2Ceil(Len);
49080b57cec5SDimitry Andric     for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
49095ffd83dbSDimitry Andric       auto MIBShiftAmt = MIRBuilder.buildConstant(SrcTy, 1ULL << i);
49105ffd83dbSDimitry Andric       auto MIBOp = MIRBuilder.buildOr(
49115ffd83dbSDimitry Andric           SrcTy, Op, MIRBuilder.buildLShr(SrcTy, Op, MIBShiftAmt));
49125ffd83dbSDimitry Andric       Op = MIBOp.getReg(0);
49130b57cec5SDimitry Andric     }
49145ffd83dbSDimitry Andric     auto MIBPop = MIRBuilder.buildCTPOP(DstTy, Op);
49155ffd83dbSDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MIRBuilder.buildConstant(DstTy, Len),
49165ffd83dbSDimitry Andric                         MIBPop);
49170b57cec5SDimitry Andric     MI.eraseFromParent();
49180b57cec5SDimitry Andric     return Legalized;
49190b57cec5SDimitry Andric   }
49200b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
49210b57cec5SDimitry Andric     // This trivially expands to CTTZ.
49220b57cec5SDimitry Andric     Observer.changingInstr(MI);
49230b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
49240b57cec5SDimitry Andric     Observer.changedInstr(MI);
49250b57cec5SDimitry Andric     return Legalized;
49260b57cec5SDimitry Andric   }
49270b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ: {
49285ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
49290b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
49305ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
49315ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
49325ffd83dbSDimitry Andric 
49335ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
49345ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
49350b57cec5SDimitry Andric       // If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
49360b57cec5SDimitry Andric       // zero.
49375ffd83dbSDimitry Andric       auto CttzZU = MIRBuilder.buildCTTZ_ZERO_UNDEF(DstTy, SrcReg);
49385ffd83dbSDimitry Andric       auto Zero = MIRBuilder.buildConstant(SrcTy, 0);
49395ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
49405ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, DstTy.changeElementSize(1), SrcReg, Zero);
49415ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
49425ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CttzZU);
49430b57cec5SDimitry Andric       MI.eraseFromParent();
49440b57cec5SDimitry Andric       return Legalized;
49450b57cec5SDimitry Andric     }
49460b57cec5SDimitry Andric     // for now, we use: { return popcount(~x & (x - 1)); }
49470b57cec5SDimitry Andric     // unless the target has ctlz but not ctpop, in which case we use:
49480b57cec5SDimitry Andric     // { return 32 - nlz(~x & (x-1)); }
49490b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
4950e8d8bef9SDimitry Andric     auto MIBCstNeg1 = MIRBuilder.buildConstant(SrcTy, -1);
4951e8d8bef9SDimitry Andric     auto MIBNot = MIRBuilder.buildXor(SrcTy, SrcReg, MIBCstNeg1);
49525ffd83dbSDimitry Andric     auto MIBTmp = MIRBuilder.buildAnd(
4953e8d8bef9SDimitry Andric         SrcTy, MIBNot, MIRBuilder.buildAdd(SrcTy, SrcReg, MIBCstNeg1));
4954e8d8bef9SDimitry Andric     if (!isSupported({TargetOpcode::G_CTPOP, {SrcTy, SrcTy}}) &&
4955e8d8bef9SDimitry Andric         isSupported({TargetOpcode::G_CTLZ, {SrcTy, SrcTy}})) {
4956e8d8bef9SDimitry Andric       auto MIBCstLen = MIRBuilder.buildConstant(SrcTy, Len);
49575ffd83dbSDimitry Andric       MIRBuilder.buildSub(MI.getOperand(0), MIBCstLen,
4958e8d8bef9SDimitry Andric                           MIRBuilder.buildCTLZ(SrcTy, MIBTmp));
49590b57cec5SDimitry Andric       MI.eraseFromParent();
49600b57cec5SDimitry Andric       return Legalized;
49610b57cec5SDimitry Andric     }
49620b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
49635ffd83dbSDimitry Andric     MI.getOperand(1).setReg(MIBTmp.getReg(0));
49645ffd83dbSDimitry Andric     return Legalized;
49655ffd83dbSDimitry Andric   }
49665ffd83dbSDimitry Andric   case TargetOpcode::G_CTPOP: {
4967e8d8bef9SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
4968e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(SrcReg);
49695ffd83dbSDimitry Andric     unsigned Size = Ty.getSizeInBits();
49705ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
49715ffd83dbSDimitry Andric 
49725ffd83dbSDimitry Andric     // Count set bits in blocks of 2 bits. Default approach would be
49735ffd83dbSDimitry Andric     // B2Count = { val & 0x55555555 } + { (val >> 1) & 0x55555555 }
49745ffd83dbSDimitry Andric     // We use following formula instead:
49755ffd83dbSDimitry Andric     // B2Count = val - { (val >> 1) & 0x55555555 }
49765ffd83dbSDimitry Andric     // since it gives same result in blocks of 2 with one instruction less.
49775ffd83dbSDimitry Andric     auto C_1 = B.buildConstant(Ty, 1);
4978e8d8bef9SDimitry Andric     auto B2Set1LoTo1Hi = B.buildLShr(Ty, SrcReg, C_1);
49795ffd83dbSDimitry Andric     APInt B2Mask1HiTo0 = APInt::getSplat(Size, APInt(8, 0x55));
49805ffd83dbSDimitry Andric     auto C_B2Mask1HiTo0 = B.buildConstant(Ty, B2Mask1HiTo0);
49815ffd83dbSDimitry Andric     auto B2Count1Hi = B.buildAnd(Ty, B2Set1LoTo1Hi, C_B2Mask1HiTo0);
4982e8d8bef9SDimitry Andric     auto B2Count = B.buildSub(Ty, SrcReg, B2Count1Hi);
49835ffd83dbSDimitry Andric 
49845ffd83dbSDimitry Andric     // In order to get count in blocks of 4 add values from adjacent block of 2.
49855ffd83dbSDimitry Andric     // B4Count = { B2Count & 0x33333333 } + { (B2Count >> 2) & 0x33333333 }
49865ffd83dbSDimitry Andric     auto C_2 = B.buildConstant(Ty, 2);
49875ffd83dbSDimitry Andric     auto B4Set2LoTo2Hi = B.buildLShr(Ty, B2Count, C_2);
49885ffd83dbSDimitry Andric     APInt B4Mask2HiTo0 = APInt::getSplat(Size, APInt(8, 0x33));
49895ffd83dbSDimitry Andric     auto C_B4Mask2HiTo0 = B.buildConstant(Ty, B4Mask2HiTo0);
49905ffd83dbSDimitry Andric     auto B4HiB2Count = B.buildAnd(Ty, B4Set2LoTo2Hi, C_B4Mask2HiTo0);
49915ffd83dbSDimitry Andric     auto B4LoB2Count = B.buildAnd(Ty, B2Count, C_B4Mask2HiTo0);
49925ffd83dbSDimitry Andric     auto B4Count = B.buildAdd(Ty, B4HiB2Count, B4LoB2Count);
49935ffd83dbSDimitry Andric 
49945ffd83dbSDimitry Andric     // For count in blocks of 8 bits we don't have to mask high 4 bits before
49955ffd83dbSDimitry Andric     // addition since count value sits in range {0,...,8} and 4 bits are enough
49965ffd83dbSDimitry Andric     // to hold such binary values. After addition high 4 bits still hold count
49975ffd83dbSDimitry Andric     // of set bits in high 4 bit block, set them to zero and get 8 bit result.
49985ffd83dbSDimitry Andric     // B8Count = { B4Count + (B4Count >> 4) } & 0x0F0F0F0F
49995ffd83dbSDimitry Andric     auto C_4 = B.buildConstant(Ty, 4);
50005ffd83dbSDimitry Andric     auto B8HiB4Count = B.buildLShr(Ty, B4Count, C_4);
50015ffd83dbSDimitry Andric     auto B8CountDirty4Hi = B.buildAdd(Ty, B8HiB4Count, B4Count);
50025ffd83dbSDimitry Andric     APInt B8Mask4HiTo0 = APInt::getSplat(Size, APInt(8, 0x0F));
50035ffd83dbSDimitry Andric     auto C_B8Mask4HiTo0 = B.buildConstant(Ty, B8Mask4HiTo0);
50045ffd83dbSDimitry Andric     auto B8Count = B.buildAnd(Ty, B8CountDirty4Hi, C_B8Mask4HiTo0);
50055ffd83dbSDimitry Andric 
50065ffd83dbSDimitry Andric     assert(Size<=128 && "Scalar size is too large for CTPOP lower algorithm");
50075ffd83dbSDimitry Andric     // 8 bits can hold CTPOP result of 128 bit int or smaller. Mul with this
50085ffd83dbSDimitry Andric     // bitmask will set 8 msb in ResTmp to sum of all B8Counts in 8 bit blocks.
50095ffd83dbSDimitry Andric     auto MulMask = B.buildConstant(Ty, APInt::getSplat(Size, APInt(8, 0x01)));
50105ffd83dbSDimitry Andric     auto ResTmp = B.buildMul(Ty, B8Count, MulMask);
50115ffd83dbSDimitry Andric 
50125ffd83dbSDimitry Andric     // Shift count result from 8 high bits to low bits.
50135ffd83dbSDimitry Andric     auto C_SizeM8 = B.buildConstant(Ty, Size - 8);
50145ffd83dbSDimitry Andric     B.buildLShr(MI.getOperand(0).getReg(), ResTmp, C_SizeM8);
50155ffd83dbSDimitry Andric 
50165ffd83dbSDimitry Andric     MI.eraseFromParent();
50170b57cec5SDimitry Andric     return Legalized;
50180b57cec5SDimitry Andric   }
50190b57cec5SDimitry Andric   }
50200b57cec5SDimitry Andric }
50210b57cec5SDimitry Andric 
50220b57cec5SDimitry Andric // Expand s32 = G_UITOFP s64 using bit operations to an IEEE float
50230b57cec5SDimitry Andric // representation.
50240b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
50250b57cec5SDimitry Andric LegalizerHelper::lowerU64ToF32BitOps(MachineInstr &MI) {
50260b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
50270b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
50280b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
50290b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
50300b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric   assert(MRI.getType(Src) == S64 && MRI.getType(Dst) == S32);
50330b57cec5SDimitry Andric 
50340b57cec5SDimitry Andric   // unsigned cul2f(ulong u) {
50350b57cec5SDimitry Andric   //   uint lz = clz(u);
50360b57cec5SDimitry Andric   //   uint e = (u != 0) ? 127U + 63U - lz : 0;
50370b57cec5SDimitry Andric   //   u = (u << lz) & 0x7fffffffffffffffUL;
50380b57cec5SDimitry Andric   //   ulong t = u & 0xffffffffffUL;
50390b57cec5SDimitry Andric   //   uint v = (e << 23) | (uint)(u >> 40);
50400b57cec5SDimitry Andric   //   uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
50410b57cec5SDimitry Andric   //   return as_float(v + r);
50420b57cec5SDimitry Andric   // }
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric   auto Zero32 = MIRBuilder.buildConstant(S32, 0);
50450b57cec5SDimitry Andric   auto Zero64 = MIRBuilder.buildConstant(S64, 0);
50460b57cec5SDimitry Andric 
50470b57cec5SDimitry Andric   auto LZ = MIRBuilder.buildCTLZ_ZERO_UNDEF(S32, Src);
50480b57cec5SDimitry Andric 
50490b57cec5SDimitry Andric   auto K = MIRBuilder.buildConstant(S32, 127U + 63U);
50500b57cec5SDimitry Andric   auto Sub = MIRBuilder.buildSub(S32, K, LZ);
50510b57cec5SDimitry Andric 
50520b57cec5SDimitry Andric   auto NotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, Src, Zero64);
50530b57cec5SDimitry Andric   auto E = MIRBuilder.buildSelect(S32, NotZero, Sub, Zero32);
50540b57cec5SDimitry Andric 
50550b57cec5SDimitry Andric   auto Mask0 = MIRBuilder.buildConstant(S64, (-1ULL) >> 1);
50560b57cec5SDimitry Andric   auto ShlLZ = MIRBuilder.buildShl(S64, Src, LZ);
50570b57cec5SDimitry Andric 
50580b57cec5SDimitry Andric   auto U = MIRBuilder.buildAnd(S64, ShlLZ, Mask0);
50590b57cec5SDimitry Andric 
50600b57cec5SDimitry Andric   auto Mask1 = MIRBuilder.buildConstant(S64, 0xffffffffffULL);
50610b57cec5SDimitry Andric   auto T = MIRBuilder.buildAnd(S64, U, Mask1);
50620b57cec5SDimitry Andric 
50630b57cec5SDimitry Andric   auto UShl = MIRBuilder.buildLShr(S64, U, MIRBuilder.buildConstant(S64, 40));
50640b57cec5SDimitry Andric   auto ShlE = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 23));
50650b57cec5SDimitry Andric   auto V = MIRBuilder.buildOr(S32, ShlE, MIRBuilder.buildTrunc(S32, UShl));
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric   auto C = MIRBuilder.buildConstant(S64, 0x8000000000ULL);
50680b57cec5SDimitry Andric   auto RCmp = MIRBuilder.buildICmp(CmpInst::ICMP_UGT, S1, T, C);
50690b57cec5SDimitry Andric   auto TCmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, T, C);
50700b57cec5SDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric   auto VTrunc1 = MIRBuilder.buildAnd(S32, V, One);
50730b57cec5SDimitry Andric   auto Select0 = MIRBuilder.buildSelect(S32, TCmp, VTrunc1, Zero32);
50740b57cec5SDimitry Andric   auto R = MIRBuilder.buildSelect(S32, RCmp, One, Select0);
50750b57cec5SDimitry Andric   MIRBuilder.buildAdd(Dst, V, R);
50760b57cec5SDimitry Andric 
50775ffd83dbSDimitry Andric   MI.eraseFromParent();
50780b57cec5SDimitry Andric   return Legalized;
50790b57cec5SDimitry Andric }
50800b57cec5SDimitry Andric 
5081e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerUITOFP(MachineInstr &MI) {
50820b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
50830b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
50840b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst);
50850b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src);
50860b57cec5SDimitry Andric 
5087480093f4SDimitry Andric   if (SrcTy == LLT::scalar(1)) {
5088480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, 1.0);
5089480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
5090480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
5091480093f4SDimitry Andric     MI.eraseFromParent();
5092480093f4SDimitry Andric     return Legalized;
5093480093f4SDimitry Andric   }
5094480093f4SDimitry Andric 
50950b57cec5SDimitry Andric   if (SrcTy != LLT::scalar(64))
50960b57cec5SDimitry Andric     return UnableToLegalize;
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric   if (DstTy == LLT::scalar(32)) {
50990b57cec5SDimitry Andric     // TODO: SelectionDAG has several alternative expansions to port which may
51000b57cec5SDimitry Andric     // be more reasonble depending on the available instructions. If a target
51010b57cec5SDimitry Andric     // has sitofp, does not have CTLZ, or can efficiently use f64 as an
51020b57cec5SDimitry Andric     // intermediate type, this is probably worse.
51030b57cec5SDimitry Andric     return lowerU64ToF32BitOps(MI);
51040b57cec5SDimitry Andric   }
51050b57cec5SDimitry Andric 
51060b57cec5SDimitry Andric   return UnableToLegalize;
51070b57cec5SDimitry Andric }
51080b57cec5SDimitry Andric 
5109e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSITOFP(MachineInstr &MI) {
51100b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
51110b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
51120b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst);
51130b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src);
51140b57cec5SDimitry Andric 
51150b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
51160b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
51170b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
51180b57cec5SDimitry Andric 
5119480093f4SDimitry Andric   if (SrcTy == S1) {
5120480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, -1.0);
5121480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
5122480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
5123480093f4SDimitry Andric     MI.eraseFromParent();
5124480093f4SDimitry Andric     return Legalized;
5125480093f4SDimitry Andric   }
5126480093f4SDimitry Andric 
51270b57cec5SDimitry Andric   if (SrcTy != S64)
51280b57cec5SDimitry Andric     return UnableToLegalize;
51290b57cec5SDimitry Andric 
51300b57cec5SDimitry Andric   if (DstTy == S32) {
51310b57cec5SDimitry Andric     // signed cl2f(long l) {
51320b57cec5SDimitry Andric     //   long s = l >> 63;
51330b57cec5SDimitry Andric     //   float r = cul2f((l + s) ^ s);
51340b57cec5SDimitry Andric     //   return s ? -r : r;
51350b57cec5SDimitry Andric     // }
51360b57cec5SDimitry Andric     Register L = Src;
51370b57cec5SDimitry Andric     auto SignBit = MIRBuilder.buildConstant(S64, 63);
51380b57cec5SDimitry Andric     auto S = MIRBuilder.buildAShr(S64, L, SignBit);
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric     auto LPlusS = MIRBuilder.buildAdd(S64, L, S);
51410b57cec5SDimitry Andric     auto Xor = MIRBuilder.buildXor(S64, LPlusS, S);
51420b57cec5SDimitry Andric     auto R = MIRBuilder.buildUITOFP(S32, Xor);
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric     auto RNeg = MIRBuilder.buildFNeg(S32, R);
51450b57cec5SDimitry Andric     auto SignNotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, S,
51460b57cec5SDimitry Andric                                             MIRBuilder.buildConstant(S64, 0));
51470b57cec5SDimitry Andric     MIRBuilder.buildSelect(Dst, SignNotZero, RNeg, R);
51485ffd83dbSDimitry Andric     MI.eraseFromParent();
51490b57cec5SDimitry Andric     return Legalized;
51500b57cec5SDimitry Andric   }
51510b57cec5SDimitry Andric 
51520b57cec5SDimitry Andric   return UnableToLegalize;
51530b57cec5SDimitry Andric }
51540b57cec5SDimitry Andric 
5155e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOUI(MachineInstr &MI) {
51568bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
51578bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
51588bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst);
51598bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(Src);
51608bcb0991SDimitry Andric   const LLT S64 = LLT::scalar(64);
51618bcb0991SDimitry Andric   const LLT S32 = LLT::scalar(32);
51628bcb0991SDimitry Andric 
51638bcb0991SDimitry Andric   if (SrcTy != S64 && SrcTy != S32)
51648bcb0991SDimitry Andric     return UnableToLegalize;
51658bcb0991SDimitry Andric   if (DstTy != S32 && DstTy != S64)
51668bcb0991SDimitry Andric     return UnableToLegalize;
51678bcb0991SDimitry Andric 
51688bcb0991SDimitry Andric   // FPTOSI gives same result as FPTOUI for positive signed integers.
51698bcb0991SDimitry Andric   // FPTOUI needs to deal with fp values that convert to unsigned integers
51708bcb0991SDimitry Andric   // greater or equal to 2^31 for float or 2^63 for double. For brevity 2^Exp.
51718bcb0991SDimitry Andric 
51728bcb0991SDimitry Andric   APInt TwoPExpInt = APInt::getSignMask(DstTy.getSizeInBits());
51738bcb0991SDimitry Andric   APFloat TwoPExpFP(SrcTy.getSizeInBits() == 32 ? APFloat::IEEEsingle()
51748bcb0991SDimitry Andric                                                 : APFloat::IEEEdouble(),
51758bcb0991SDimitry Andric                     APInt::getNullValue(SrcTy.getSizeInBits()));
51768bcb0991SDimitry Andric   TwoPExpFP.convertFromAPInt(TwoPExpInt, false, APFloat::rmNearestTiesToEven);
51778bcb0991SDimitry Andric 
51788bcb0991SDimitry Andric   MachineInstrBuilder FPTOSI = MIRBuilder.buildFPTOSI(DstTy, Src);
51798bcb0991SDimitry Andric 
51808bcb0991SDimitry Andric   MachineInstrBuilder Threshold = MIRBuilder.buildFConstant(SrcTy, TwoPExpFP);
51818bcb0991SDimitry Andric   // For fp Value greater or equal to Threshold(2^Exp), we use FPTOSI on
51828bcb0991SDimitry Andric   // (Value - 2^Exp) and add 2^Exp by setting highest bit in result to 1.
51838bcb0991SDimitry Andric   MachineInstrBuilder FSub = MIRBuilder.buildFSub(SrcTy, Src, Threshold);
51848bcb0991SDimitry Andric   MachineInstrBuilder ResLowBits = MIRBuilder.buildFPTOSI(DstTy, FSub);
51858bcb0991SDimitry Andric   MachineInstrBuilder ResHighBit = MIRBuilder.buildConstant(DstTy, TwoPExpInt);
51868bcb0991SDimitry Andric   MachineInstrBuilder Res = MIRBuilder.buildXor(DstTy, ResLowBits, ResHighBit);
51878bcb0991SDimitry Andric 
5188480093f4SDimitry Andric   const LLT S1 = LLT::scalar(1);
5189480093f4SDimitry Andric 
51908bcb0991SDimitry Andric   MachineInstrBuilder FCMP =
5191480093f4SDimitry Andric       MIRBuilder.buildFCmp(CmpInst::FCMP_ULT, S1, Src, Threshold);
51928bcb0991SDimitry Andric   MIRBuilder.buildSelect(Dst, FCMP, FPTOSI, Res);
51938bcb0991SDimitry Andric 
51948bcb0991SDimitry Andric   MI.eraseFromParent();
51958bcb0991SDimitry Andric   return Legalized;
51968bcb0991SDimitry Andric }
51978bcb0991SDimitry Andric 
51985ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOSI(MachineInstr &MI) {
51995ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
52005ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
52015ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
52025ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
52035ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
52045ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
52055ffd83dbSDimitry Andric 
52065ffd83dbSDimitry Andric   // FIXME: Only f32 to i64 conversions are supported.
52075ffd83dbSDimitry Andric   if (SrcTy.getScalarType() != S32 || DstTy.getScalarType() != S64)
52085ffd83dbSDimitry Andric     return UnableToLegalize;
52095ffd83dbSDimitry Andric 
52105ffd83dbSDimitry Andric   // Expand f32 -> i64 conversion
52115ffd83dbSDimitry Andric   // This algorithm comes from compiler-rt's implementation of fixsfdi:
52125ffd83dbSDimitry Andric   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
52135ffd83dbSDimitry Andric 
52145ffd83dbSDimitry Andric   unsigned SrcEltBits = SrcTy.getScalarSizeInBits();
52155ffd83dbSDimitry Andric 
52165ffd83dbSDimitry Andric   auto ExponentMask = MIRBuilder.buildConstant(SrcTy, 0x7F800000);
52175ffd83dbSDimitry Andric   auto ExponentLoBit = MIRBuilder.buildConstant(SrcTy, 23);
52185ffd83dbSDimitry Andric 
52195ffd83dbSDimitry Andric   auto AndExpMask = MIRBuilder.buildAnd(SrcTy, Src, ExponentMask);
52205ffd83dbSDimitry Andric   auto ExponentBits = MIRBuilder.buildLShr(SrcTy, AndExpMask, ExponentLoBit);
52215ffd83dbSDimitry Andric 
52225ffd83dbSDimitry Andric   auto SignMask = MIRBuilder.buildConstant(SrcTy,
52235ffd83dbSDimitry Andric                                            APInt::getSignMask(SrcEltBits));
52245ffd83dbSDimitry Andric   auto AndSignMask = MIRBuilder.buildAnd(SrcTy, Src, SignMask);
52255ffd83dbSDimitry Andric   auto SignLowBit = MIRBuilder.buildConstant(SrcTy, SrcEltBits - 1);
52265ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildAShr(SrcTy, AndSignMask, SignLowBit);
52275ffd83dbSDimitry Andric   Sign = MIRBuilder.buildSExt(DstTy, Sign);
52285ffd83dbSDimitry Andric 
52295ffd83dbSDimitry Andric   auto MantissaMask = MIRBuilder.buildConstant(SrcTy, 0x007FFFFF);
52305ffd83dbSDimitry Andric   auto AndMantissaMask = MIRBuilder.buildAnd(SrcTy, Src, MantissaMask);
52315ffd83dbSDimitry Andric   auto K = MIRBuilder.buildConstant(SrcTy, 0x00800000);
52325ffd83dbSDimitry Andric 
52335ffd83dbSDimitry Andric   auto R = MIRBuilder.buildOr(SrcTy, AndMantissaMask, K);
52345ffd83dbSDimitry Andric   R = MIRBuilder.buildZExt(DstTy, R);
52355ffd83dbSDimitry Andric 
52365ffd83dbSDimitry Andric   auto Bias = MIRBuilder.buildConstant(SrcTy, 127);
52375ffd83dbSDimitry Andric   auto Exponent = MIRBuilder.buildSub(SrcTy, ExponentBits, Bias);
52385ffd83dbSDimitry Andric   auto SubExponent = MIRBuilder.buildSub(SrcTy, Exponent, ExponentLoBit);
52395ffd83dbSDimitry Andric   auto ExponentSub = MIRBuilder.buildSub(SrcTy, ExponentLoBit, Exponent);
52405ffd83dbSDimitry Andric 
52415ffd83dbSDimitry Andric   auto Shl = MIRBuilder.buildShl(DstTy, R, SubExponent);
52425ffd83dbSDimitry Andric   auto Srl = MIRBuilder.buildLShr(DstTy, R, ExponentSub);
52435ffd83dbSDimitry Andric 
52445ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
52455ffd83dbSDimitry Andric   auto CmpGt = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,
52465ffd83dbSDimitry Andric                                     S1, Exponent, ExponentLoBit);
52475ffd83dbSDimitry Andric 
52485ffd83dbSDimitry Andric   R = MIRBuilder.buildSelect(DstTy, CmpGt, Shl, Srl);
52495ffd83dbSDimitry Andric 
52505ffd83dbSDimitry Andric   auto XorSign = MIRBuilder.buildXor(DstTy, R, Sign);
52515ffd83dbSDimitry Andric   auto Ret = MIRBuilder.buildSub(DstTy, XorSign, Sign);
52525ffd83dbSDimitry Andric 
52535ffd83dbSDimitry Andric   auto ZeroSrcTy = MIRBuilder.buildConstant(SrcTy, 0);
52545ffd83dbSDimitry Andric 
52555ffd83dbSDimitry Andric   auto ExponentLt0 = MIRBuilder.buildICmp(CmpInst::ICMP_SLT,
52565ffd83dbSDimitry Andric                                           S1, Exponent, ZeroSrcTy);
52575ffd83dbSDimitry Andric 
52585ffd83dbSDimitry Andric   auto ZeroDstTy = MIRBuilder.buildConstant(DstTy, 0);
52595ffd83dbSDimitry Andric   MIRBuilder.buildSelect(Dst, ExponentLt0, ZeroDstTy, Ret);
52605ffd83dbSDimitry Andric 
52615ffd83dbSDimitry Andric   MI.eraseFromParent();
52625ffd83dbSDimitry Andric   return Legalized;
52635ffd83dbSDimitry Andric }
52645ffd83dbSDimitry Andric 
52655ffd83dbSDimitry Andric // f64 -> f16 conversion using round-to-nearest-even rounding mode.
52665ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
52675ffd83dbSDimitry Andric LegalizerHelper::lowerFPTRUNC_F64_TO_F16(MachineInstr &MI) {
52685ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
52695ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
52705ffd83dbSDimitry Andric 
52715ffd83dbSDimitry Andric   if (MRI.getType(Src).isVector()) // TODO: Handle vectors directly.
52725ffd83dbSDimitry Andric     return UnableToLegalize;
52735ffd83dbSDimitry Andric 
52745ffd83dbSDimitry Andric   const unsigned ExpMask = 0x7ff;
52755ffd83dbSDimitry Andric   const unsigned ExpBiasf64 = 1023;
52765ffd83dbSDimitry Andric   const unsigned ExpBiasf16 = 15;
52775ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
52785ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
52795ffd83dbSDimitry Andric 
52805ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(S32, Src);
52815ffd83dbSDimitry Andric   Register U = Unmerge.getReg(0);
52825ffd83dbSDimitry Andric   Register UH = Unmerge.getReg(1);
52835ffd83dbSDimitry Andric 
52845ffd83dbSDimitry Andric   auto E = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 20));
52855ffd83dbSDimitry Andric   E = MIRBuilder.buildAnd(S32, E, MIRBuilder.buildConstant(S32, ExpMask));
52865ffd83dbSDimitry Andric 
52875ffd83dbSDimitry Andric   // Subtract the fp64 exponent bias (1023) to get the real exponent and
52885ffd83dbSDimitry Andric   // add the f16 bias (15) to get the biased exponent for the f16 format.
52895ffd83dbSDimitry Andric   E = MIRBuilder.buildAdd(
52905ffd83dbSDimitry Andric     S32, E, MIRBuilder.buildConstant(S32, -ExpBiasf64 + ExpBiasf16));
52915ffd83dbSDimitry Andric 
52925ffd83dbSDimitry Andric   auto M = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 8));
52935ffd83dbSDimitry Andric   M = MIRBuilder.buildAnd(S32, M, MIRBuilder.buildConstant(S32, 0xffe));
52945ffd83dbSDimitry Andric 
52955ffd83dbSDimitry Andric   auto MaskedSig = MIRBuilder.buildAnd(S32, UH,
52965ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1ff));
52975ffd83dbSDimitry Andric   MaskedSig = MIRBuilder.buildOr(S32, MaskedSig, U);
52985ffd83dbSDimitry Andric 
52995ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildConstant(S32, 0);
53005ffd83dbSDimitry Andric   auto SigCmpNE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, MaskedSig, Zero);
53015ffd83dbSDimitry Andric   auto Lo40Set = MIRBuilder.buildZExt(S32, SigCmpNE0);
53025ffd83dbSDimitry Andric   M = MIRBuilder.buildOr(S32, M, Lo40Set);
53035ffd83dbSDimitry Andric 
53045ffd83dbSDimitry Andric   // (M != 0 ? 0x0200 : 0) | 0x7c00;
53055ffd83dbSDimitry Andric   auto Bits0x200 = MIRBuilder.buildConstant(S32, 0x0200);
53065ffd83dbSDimitry Andric   auto CmpM_NE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, M, Zero);
53075ffd83dbSDimitry Andric   auto SelectCC = MIRBuilder.buildSelect(S32, CmpM_NE0, Bits0x200, Zero);
53085ffd83dbSDimitry Andric 
53095ffd83dbSDimitry Andric   auto Bits0x7c00 = MIRBuilder.buildConstant(S32, 0x7c00);
53105ffd83dbSDimitry Andric   auto I = MIRBuilder.buildOr(S32, SelectCC, Bits0x7c00);
53115ffd83dbSDimitry Andric 
53125ffd83dbSDimitry Andric   // N = M | (E << 12);
53135ffd83dbSDimitry Andric   auto EShl12 = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 12));
53145ffd83dbSDimitry Andric   auto N = MIRBuilder.buildOr(S32, M, EShl12);
53155ffd83dbSDimitry Andric 
53165ffd83dbSDimitry Andric   // B = clamp(1-E, 0, 13);
53175ffd83dbSDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
53185ffd83dbSDimitry Andric   auto OneSubExp = MIRBuilder.buildSub(S32, One, E);
53195ffd83dbSDimitry Andric   auto B = MIRBuilder.buildSMax(S32, OneSubExp, Zero);
53205ffd83dbSDimitry Andric   B = MIRBuilder.buildSMin(S32, B, MIRBuilder.buildConstant(S32, 13));
53215ffd83dbSDimitry Andric 
53225ffd83dbSDimitry Andric   auto SigSetHigh = MIRBuilder.buildOr(S32, M,
53235ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1000));
53245ffd83dbSDimitry Andric 
53255ffd83dbSDimitry Andric   auto D = MIRBuilder.buildLShr(S32, SigSetHigh, B);
53265ffd83dbSDimitry Andric   auto D0 = MIRBuilder.buildShl(S32, D, B);
53275ffd83dbSDimitry Andric 
53285ffd83dbSDimitry Andric   auto D0_NE_SigSetHigh = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1,
53295ffd83dbSDimitry Andric                                              D0, SigSetHigh);
53305ffd83dbSDimitry Andric   auto D1 = MIRBuilder.buildZExt(S32, D0_NE_SigSetHigh);
53315ffd83dbSDimitry Andric   D = MIRBuilder.buildOr(S32, D, D1);
53325ffd83dbSDimitry Andric 
53335ffd83dbSDimitry Andric   auto CmpELtOne = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, S1, E, One);
53345ffd83dbSDimitry Andric   auto V = MIRBuilder.buildSelect(S32, CmpELtOne, D, N);
53355ffd83dbSDimitry Andric 
53365ffd83dbSDimitry Andric   auto VLow3 = MIRBuilder.buildAnd(S32, V, MIRBuilder.buildConstant(S32, 7));
53375ffd83dbSDimitry Andric   V = MIRBuilder.buildLShr(S32, V, MIRBuilder.buildConstant(S32, 2));
53385ffd83dbSDimitry Andric 
53395ffd83dbSDimitry Andric   auto VLow3Eq3 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, VLow3,
53405ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 3));
53415ffd83dbSDimitry Andric   auto V0 = MIRBuilder.buildZExt(S32, VLow3Eq3);
53425ffd83dbSDimitry Andric 
53435ffd83dbSDimitry Andric   auto VLow3Gt5 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT, S1, VLow3,
53445ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 5));
53455ffd83dbSDimitry Andric   auto V1 = MIRBuilder.buildZExt(S32, VLow3Gt5);
53465ffd83dbSDimitry Andric 
53475ffd83dbSDimitry Andric   V1 = MIRBuilder.buildOr(S32, V0, V1);
53485ffd83dbSDimitry Andric   V = MIRBuilder.buildAdd(S32, V, V1);
53495ffd83dbSDimitry Andric 
53505ffd83dbSDimitry Andric   auto CmpEGt30 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,  S1,
53515ffd83dbSDimitry Andric                                        E, MIRBuilder.buildConstant(S32, 30));
53525ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt30,
53535ffd83dbSDimitry Andric                              MIRBuilder.buildConstant(S32, 0x7c00), V);
53545ffd83dbSDimitry Andric 
53555ffd83dbSDimitry Andric   auto CmpEGt1039 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1,
53565ffd83dbSDimitry Andric                                          E, MIRBuilder.buildConstant(S32, 1039));
53575ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt1039, I, V);
53585ffd83dbSDimitry Andric 
53595ffd83dbSDimitry Andric   // Extract the sign bit.
53605ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 16));
53615ffd83dbSDimitry Andric   Sign = MIRBuilder.buildAnd(S32, Sign, MIRBuilder.buildConstant(S32, 0x8000));
53625ffd83dbSDimitry Andric 
53635ffd83dbSDimitry Andric   // Insert the sign bit
53645ffd83dbSDimitry Andric   V = MIRBuilder.buildOr(S32, Sign, V);
53655ffd83dbSDimitry Andric 
53665ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst, V);
53675ffd83dbSDimitry Andric   MI.eraseFromParent();
53685ffd83dbSDimitry Andric   return Legalized;
53695ffd83dbSDimitry Andric }
53705ffd83dbSDimitry Andric 
53715ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
5372e8d8bef9SDimitry Andric LegalizerHelper::lowerFPTRUNC(MachineInstr &MI) {
53735ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
53745ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
53755ffd83dbSDimitry Andric 
53765ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
53775ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
53785ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
53795ffd83dbSDimitry Andric   const LLT S16 = LLT::scalar(16);
53805ffd83dbSDimitry Andric 
53815ffd83dbSDimitry Andric   if (DstTy.getScalarType() == S16 && SrcTy.getScalarType() == S64)
53825ffd83dbSDimitry Andric     return lowerFPTRUNC_F64_TO_F16(MI);
53835ffd83dbSDimitry Andric 
53845ffd83dbSDimitry Andric   return UnableToLegalize;
53855ffd83dbSDimitry Andric }
53865ffd83dbSDimitry Andric 
5387e8d8bef9SDimitry Andric // TODO: If RHS is a constant SelectionDAGBuilder expands this into a
5388e8d8bef9SDimitry Andric // multiplication tree.
5389e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPOWI(MachineInstr &MI) {
5390e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5391e8d8bef9SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
5392e8d8bef9SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
5393e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
5394e8d8bef9SDimitry Andric 
5395e8d8bef9SDimitry Andric   auto CvtSrc1 = MIRBuilder.buildSITOFP(Ty, Src1);
5396e8d8bef9SDimitry Andric   MIRBuilder.buildFPow(Dst, Src0, CvtSrc1, MI.getFlags());
5397e8d8bef9SDimitry Andric   MI.eraseFromParent();
5398e8d8bef9SDimitry Andric   return Legalized;
5399e8d8bef9SDimitry Andric }
5400e8d8bef9SDimitry Andric 
54010b57cec5SDimitry Andric static CmpInst::Predicate minMaxToCompare(unsigned Opc) {
54020b57cec5SDimitry Andric   switch (Opc) {
54030b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
54040b57cec5SDimitry Andric     return CmpInst::ICMP_SLT;
54050b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
54060b57cec5SDimitry Andric     return CmpInst::ICMP_SGT;
54070b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
54080b57cec5SDimitry Andric     return CmpInst::ICMP_ULT;
54090b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
54100b57cec5SDimitry Andric     return CmpInst::ICMP_UGT;
54110b57cec5SDimitry Andric   default:
54120b57cec5SDimitry Andric     llvm_unreachable("not in integer min/max");
54130b57cec5SDimitry Andric   }
54140b57cec5SDimitry Andric }
54150b57cec5SDimitry Andric 
5416e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerMinMax(MachineInstr &MI) {
54170b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
54180b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
54190b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
54200b57cec5SDimitry Andric 
54210b57cec5SDimitry Andric   const CmpInst::Predicate Pred = minMaxToCompare(MI.getOpcode());
54220b57cec5SDimitry Andric   LLT CmpType = MRI.getType(Dst).changeElementSize(1);
54230b57cec5SDimitry Andric 
54240b57cec5SDimitry Andric   auto Cmp = MIRBuilder.buildICmp(Pred, CmpType, Src0, Src1);
54250b57cec5SDimitry Andric   MIRBuilder.buildSelect(Dst, Cmp, Src0, Src1);
54260b57cec5SDimitry Andric 
54270b57cec5SDimitry Andric   MI.eraseFromParent();
54280b57cec5SDimitry Andric   return Legalized;
54290b57cec5SDimitry Andric }
54300b57cec5SDimitry Andric 
54310b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
5432e8d8bef9SDimitry Andric LegalizerHelper::lowerFCopySign(MachineInstr &MI) {
54330b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
54340b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
54350b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
54360b57cec5SDimitry Andric 
54370b57cec5SDimitry Andric   const LLT Src0Ty = MRI.getType(Src0);
54380b57cec5SDimitry Andric   const LLT Src1Ty = MRI.getType(Src1);
54390b57cec5SDimitry Andric 
54400b57cec5SDimitry Andric   const int Src0Size = Src0Ty.getScalarSizeInBits();
54410b57cec5SDimitry Andric   const int Src1Size = Src1Ty.getScalarSizeInBits();
54420b57cec5SDimitry Andric 
54430b57cec5SDimitry Andric   auto SignBitMask = MIRBuilder.buildConstant(
54440b57cec5SDimitry Andric     Src0Ty, APInt::getSignMask(Src0Size));
54450b57cec5SDimitry Andric 
54460b57cec5SDimitry Andric   auto NotSignBitMask = MIRBuilder.buildConstant(
54470b57cec5SDimitry Andric     Src0Ty, APInt::getLowBitsSet(Src0Size, Src0Size - 1));
54480b57cec5SDimitry Andric 
54490b57cec5SDimitry Andric   auto And0 = MIRBuilder.buildAnd(Src0Ty, Src0, NotSignBitMask);
54500b57cec5SDimitry Andric   MachineInstr *Or;
54510b57cec5SDimitry Andric 
54520b57cec5SDimitry Andric   if (Src0Ty == Src1Ty) {
54535ffd83dbSDimitry Andric     auto And1 = MIRBuilder.buildAnd(Src1Ty, Src1, SignBitMask);
54540b57cec5SDimitry Andric     Or = MIRBuilder.buildOr(Dst, And0, And1);
54550b57cec5SDimitry Andric   } else if (Src0Size > Src1Size) {
54560b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src0Ty, Src0Size - Src1Size);
54570b57cec5SDimitry Andric     auto Zext = MIRBuilder.buildZExt(Src0Ty, Src1);
54580b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildShl(Src0Ty, Zext, ShiftAmt);
54590b57cec5SDimitry Andric     auto And1 = MIRBuilder.buildAnd(Src0Ty, Shift, SignBitMask);
54600b57cec5SDimitry Andric     Or = MIRBuilder.buildOr(Dst, And0, And1);
54610b57cec5SDimitry Andric   } else {
54620b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src1Ty, Src1Size - Src0Size);
54630b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildLShr(Src1Ty, Src1, ShiftAmt);
54640b57cec5SDimitry Andric     auto Trunc = MIRBuilder.buildTrunc(Src0Ty, Shift);
54650b57cec5SDimitry Andric     auto And1 = MIRBuilder.buildAnd(Src0Ty, Trunc, SignBitMask);
54660b57cec5SDimitry Andric     Or = MIRBuilder.buildOr(Dst, And0, And1);
54670b57cec5SDimitry Andric   }
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric   // Be careful about setting nsz/nnan/ninf on every instruction, since the
54700b57cec5SDimitry Andric   // constants are a nan and -0.0, but the final result should preserve
54710b57cec5SDimitry Andric   // everything.
54720b57cec5SDimitry Andric   if (unsigned Flags = MI.getFlags())
54730b57cec5SDimitry Andric     Or->setFlags(Flags);
54740b57cec5SDimitry Andric 
54750b57cec5SDimitry Andric   MI.eraseFromParent();
54760b57cec5SDimitry Andric   return Legalized;
54770b57cec5SDimitry Andric }
54780b57cec5SDimitry Andric 
54790b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
54800b57cec5SDimitry Andric LegalizerHelper::lowerFMinNumMaxNum(MachineInstr &MI) {
54810b57cec5SDimitry Andric   unsigned NewOp = MI.getOpcode() == TargetOpcode::G_FMINNUM ?
54820b57cec5SDimitry Andric     TargetOpcode::G_FMINNUM_IEEE : TargetOpcode::G_FMAXNUM_IEEE;
54830b57cec5SDimitry Andric 
54840b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
54850b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
54860b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
54870b57cec5SDimitry Andric   LLT Ty = MRI.getType(Dst);
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric   if (!MI.getFlag(MachineInstr::FmNoNans)) {
54900b57cec5SDimitry Andric     // Insert canonicalizes if it's possible we need to quiet to get correct
54910b57cec5SDimitry Andric     // sNaN behavior.
54920b57cec5SDimitry Andric 
54930b57cec5SDimitry Andric     // Note this must be done here, and not as an optimization combine in the
54940b57cec5SDimitry Andric     // absence of a dedicate quiet-snan instruction as we're using an
54950b57cec5SDimitry Andric     // omni-purpose G_FCANONICALIZE.
54960b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src0, MRI))
54970b57cec5SDimitry Andric       Src0 = MIRBuilder.buildFCanonicalize(Ty, Src0, MI.getFlags()).getReg(0);
54980b57cec5SDimitry Andric 
54990b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src1, MRI))
55000b57cec5SDimitry Andric       Src1 = MIRBuilder.buildFCanonicalize(Ty, Src1, MI.getFlags()).getReg(0);
55010b57cec5SDimitry Andric   }
55020b57cec5SDimitry Andric 
55030b57cec5SDimitry Andric   // If there are no nans, it's safe to simply replace this with the non-IEEE
55040b57cec5SDimitry Andric   // version.
55050b57cec5SDimitry Andric   MIRBuilder.buildInstr(NewOp, {Dst}, {Src0, Src1}, MI.getFlags());
55060b57cec5SDimitry Andric   MI.eraseFromParent();
55070b57cec5SDimitry Andric   return Legalized;
55080b57cec5SDimitry Andric }
55098bcb0991SDimitry Andric 
55108bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFMad(MachineInstr &MI) {
55118bcb0991SDimitry Andric   // Expand G_FMAD a, b, c -> G_FADD (G_FMUL a, b), c
55128bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55138bcb0991SDimitry Andric   LLT Ty = MRI.getType(DstReg);
55148bcb0991SDimitry Andric   unsigned Flags = MI.getFlags();
55158bcb0991SDimitry Andric 
55168bcb0991SDimitry Andric   auto Mul = MIRBuilder.buildFMul(Ty, MI.getOperand(1), MI.getOperand(2),
55178bcb0991SDimitry Andric                                   Flags);
55188bcb0991SDimitry Andric   MIRBuilder.buildFAdd(DstReg, Mul, MI.getOperand(3), Flags);
55198bcb0991SDimitry Andric   MI.eraseFromParent();
55208bcb0991SDimitry Andric   return Legalized;
55218bcb0991SDimitry Andric }
55228bcb0991SDimitry Andric 
55238bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
5524480093f4SDimitry Andric LegalizerHelper::lowerIntrinsicRound(MachineInstr &MI) {
5525480093f4SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55265ffd83dbSDimitry Andric   Register X = MI.getOperand(1).getReg();
55275ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
55285ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(DstReg);
55295ffd83dbSDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
55305ffd83dbSDimitry Andric 
55315ffd83dbSDimitry Andric   // round(x) =>
55325ffd83dbSDimitry Andric   //  t = trunc(x);
55335ffd83dbSDimitry Andric   //  d = fabs(x - t);
55345ffd83dbSDimitry Andric   //  o = copysign(1.0f, x);
55355ffd83dbSDimitry Andric   //  return t + (d >= 0.5 ? o : 0.0);
55365ffd83dbSDimitry Andric 
55375ffd83dbSDimitry Andric   auto T = MIRBuilder.buildIntrinsicTrunc(Ty, X, Flags);
55385ffd83dbSDimitry Andric 
55395ffd83dbSDimitry Andric   auto Diff = MIRBuilder.buildFSub(Ty, X, T, Flags);
55405ffd83dbSDimitry Andric   auto AbsDiff = MIRBuilder.buildFAbs(Ty, Diff, Flags);
55415ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
55425ffd83dbSDimitry Andric   auto One = MIRBuilder.buildFConstant(Ty, 1.0);
55435ffd83dbSDimitry Andric   auto Half = MIRBuilder.buildFConstant(Ty, 0.5);
55445ffd83dbSDimitry Andric   auto SignOne = MIRBuilder.buildFCopysign(Ty, One, X);
55455ffd83dbSDimitry Andric 
55465ffd83dbSDimitry Andric   auto Cmp = MIRBuilder.buildFCmp(CmpInst::FCMP_OGE, CondTy, AbsDiff, Half,
55475ffd83dbSDimitry Andric                                   Flags);
55485ffd83dbSDimitry Andric   auto Sel = MIRBuilder.buildSelect(Ty, Cmp, SignOne, Zero, Flags);
55495ffd83dbSDimitry Andric 
55505ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, T, Sel, Flags);
55515ffd83dbSDimitry Andric 
55525ffd83dbSDimitry Andric   MI.eraseFromParent();
55535ffd83dbSDimitry Andric   return Legalized;
55545ffd83dbSDimitry Andric }
55555ffd83dbSDimitry Andric 
55565ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55575ffd83dbSDimitry Andric LegalizerHelper::lowerFFloor(MachineInstr &MI) {
55585ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5559480093f4SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
5560480093f4SDimitry Andric   unsigned Flags = MI.getFlags();
5561480093f4SDimitry Andric   LLT Ty = MRI.getType(DstReg);
5562480093f4SDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
5563480093f4SDimitry Andric 
5564480093f4SDimitry Andric   // result = trunc(src);
5565480093f4SDimitry Andric   // if (src < 0.0 && src != result)
5566480093f4SDimitry Andric   //   result += -1.0.
5567480093f4SDimitry Andric 
5568480093f4SDimitry Andric   auto Trunc = MIRBuilder.buildIntrinsicTrunc(Ty, SrcReg, Flags);
55695ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
5570480093f4SDimitry Andric 
5571480093f4SDimitry Andric   auto Lt0 = MIRBuilder.buildFCmp(CmpInst::FCMP_OLT, CondTy,
5572480093f4SDimitry Andric                                   SrcReg, Zero, Flags);
5573480093f4SDimitry Andric   auto NeTrunc = MIRBuilder.buildFCmp(CmpInst::FCMP_ONE, CondTy,
5574480093f4SDimitry Andric                                       SrcReg, Trunc, Flags);
5575480093f4SDimitry Andric   auto And = MIRBuilder.buildAnd(CondTy, Lt0, NeTrunc);
5576480093f4SDimitry Andric   auto AddVal = MIRBuilder.buildSITOFP(Ty, And);
5577480093f4SDimitry Andric 
55785ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, Trunc, AddVal, Flags);
55795ffd83dbSDimitry Andric   MI.eraseFromParent();
55805ffd83dbSDimitry Andric   return Legalized;
55815ffd83dbSDimitry Andric }
55825ffd83dbSDimitry Andric 
55835ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55845ffd83dbSDimitry Andric LegalizerHelper::lowerMergeValues(MachineInstr &MI) {
55855ffd83dbSDimitry Andric   const unsigned NumOps = MI.getNumOperands();
55865ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55875ffd83dbSDimitry Andric   Register Src0Reg = MI.getOperand(1).getReg();
55885ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
55895ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src0Reg);
55905ffd83dbSDimitry Andric   unsigned PartSize = SrcTy.getSizeInBits();
55915ffd83dbSDimitry Andric 
55925ffd83dbSDimitry Andric   LLT WideTy = LLT::scalar(DstTy.getSizeInBits());
55935ffd83dbSDimitry Andric   Register ResultReg = MIRBuilder.buildZExt(WideTy, Src0Reg).getReg(0);
55945ffd83dbSDimitry Andric 
55955ffd83dbSDimitry Andric   for (unsigned I = 2; I != NumOps; ++I) {
55965ffd83dbSDimitry Andric     const unsigned Offset = (I - 1) * PartSize;
55975ffd83dbSDimitry Andric 
55985ffd83dbSDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
55995ffd83dbSDimitry Andric     auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
56005ffd83dbSDimitry Andric 
56015ffd83dbSDimitry Andric     Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
56025ffd83dbSDimitry Andric       MRI.createGenericVirtualRegister(WideTy);
56035ffd83dbSDimitry Andric 
56045ffd83dbSDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
56055ffd83dbSDimitry Andric     auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
56065ffd83dbSDimitry Andric     MIRBuilder.buildOr(NextResult, ResultReg, Shl);
56075ffd83dbSDimitry Andric     ResultReg = NextResult;
56085ffd83dbSDimitry Andric   }
56095ffd83dbSDimitry Andric 
56105ffd83dbSDimitry Andric   if (DstTy.isPointer()) {
56115ffd83dbSDimitry Andric     if (MIRBuilder.getDataLayout().isNonIntegralAddressSpace(
56125ffd83dbSDimitry Andric           DstTy.getAddressSpace())) {
56135ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Not casting nonintegral address space\n");
56145ffd83dbSDimitry Andric       return UnableToLegalize;
56155ffd83dbSDimitry Andric     }
56165ffd83dbSDimitry Andric 
56175ffd83dbSDimitry Andric     MIRBuilder.buildIntToPtr(DstReg, ResultReg);
56185ffd83dbSDimitry Andric   }
56195ffd83dbSDimitry Andric 
5620480093f4SDimitry Andric   MI.eraseFromParent();
5621480093f4SDimitry Andric   return Legalized;
5622480093f4SDimitry Andric }
5623480093f4SDimitry Andric 
5624480093f4SDimitry Andric LegalizerHelper::LegalizeResult
56258bcb0991SDimitry Andric LegalizerHelper::lowerUnmergeValues(MachineInstr &MI) {
56268bcb0991SDimitry Andric   const unsigned NumDst = MI.getNumOperands() - 1;
56275ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
56288bcb0991SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
56298bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
56305ffd83dbSDimitry Andric   if (DstTy.isPointer())
56315ffd83dbSDimitry Andric     return UnableToLegalize; // TODO
56328bcb0991SDimitry Andric 
56335ffd83dbSDimitry Andric   SrcReg = coerceToScalar(SrcReg);
56345ffd83dbSDimitry Andric   if (!SrcReg)
56355ffd83dbSDimitry Andric     return UnableToLegalize;
56368bcb0991SDimitry Andric 
56378bcb0991SDimitry Andric   // Expand scalarizing unmerge as bitcast to integer and shift.
56385ffd83dbSDimitry Andric   LLT IntTy = MRI.getType(SrcReg);
56398bcb0991SDimitry Andric 
56405ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
56418bcb0991SDimitry Andric 
56428bcb0991SDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
56438bcb0991SDimitry Andric   unsigned Offset = DstSize;
56448bcb0991SDimitry Andric   for (unsigned I = 1; I != NumDst; ++I, Offset += DstSize) {
56458bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntTy, Offset);
56465ffd83dbSDimitry Andric     auto Shift = MIRBuilder.buildLShr(IntTy, SrcReg, ShiftAmt);
56478bcb0991SDimitry Andric     MIRBuilder.buildTrunc(MI.getOperand(I), Shift);
56488bcb0991SDimitry Andric   }
56498bcb0991SDimitry Andric 
56508bcb0991SDimitry Andric   MI.eraseFromParent();
56518bcb0991SDimitry Andric   return Legalized;
56528bcb0991SDimitry Andric }
56538bcb0991SDimitry Andric 
5654e8d8bef9SDimitry Andric /// Lower a vector extract or insert by writing the vector to a stack temporary
5655e8d8bef9SDimitry Andric /// and reloading the element or vector.
5656e8d8bef9SDimitry Andric ///
5657e8d8bef9SDimitry Andric /// %dst = G_EXTRACT_VECTOR_ELT %vec, %idx
5658e8d8bef9SDimitry Andric ///  =>
5659e8d8bef9SDimitry Andric ///  %stack_temp = G_FRAME_INDEX
5660e8d8bef9SDimitry Andric ///  G_STORE %vec, %stack_temp
5661e8d8bef9SDimitry Andric ///  %idx = clamp(%idx, %vec.getNumElements())
5662e8d8bef9SDimitry Andric ///  %element_ptr = G_PTR_ADD %stack_temp, %idx
5663e8d8bef9SDimitry Andric ///  %dst = G_LOAD %element_ptr
5664e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
5665e8d8bef9SDimitry Andric LegalizerHelper::lowerExtractInsertVectorElt(MachineInstr &MI) {
5666e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5667e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
5668e8d8bef9SDimitry Andric   Register InsertVal;
5669e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
5670e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
5671e8d8bef9SDimitry Andric 
5672e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
5673e8d8bef9SDimitry Andric 
5674e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
5675e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
5676e8d8bef9SDimitry Andric   if (!EltTy.isByteSized()) { // Not implemented.
5677e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-byte element vectors yet\n");
5678e8d8bef9SDimitry Andric     return UnableToLegalize;
5679e8d8bef9SDimitry Andric   }
5680e8d8bef9SDimitry Andric 
5681e8d8bef9SDimitry Andric   unsigned EltBytes = EltTy.getSizeInBytes();
5682e8d8bef9SDimitry Andric   Align VecAlign = getStackTemporaryAlignment(VecTy);
5683e8d8bef9SDimitry Andric   Align EltAlign;
5684e8d8bef9SDimitry Andric 
5685e8d8bef9SDimitry Andric   MachinePointerInfo PtrInfo;
5686e8d8bef9SDimitry Andric   auto StackTemp = createStackTemporary(TypeSize::Fixed(VecTy.getSizeInBytes()),
5687e8d8bef9SDimitry Andric                                         VecAlign, PtrInfo);
5688e8d8bef9SDimitry Andric   MIRBuilder.buildStore(SrcVec, StackTemp, PtrInfo, VecAlign);
5689e8d8bef9SDimitry Andric 
5690e8d8bef9SDimitry Andric   // Get the pointer to the element, and be sure not to hit undefined behavior
5691e8d8bef9SDimitry Andric   // if the index is out of bounds.
5692e8d8bef9SDimitry Andric   Register EltPtr = getVectorElementPointer(StackTemp.getReg(0), VecTy, Idx);
5693e8d8bef9SDimitry Andric 
5694e8d8bef9SDimitry Andric   int64_t IdxVal;
5695e8d8bef9SDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal))) {
5696e8d8bef9SDimitry Andric     int64_t Offset = IdxVal * EltBytes;
5697e8d8bef9SDimitry Andric     PtrInfo = PtrInfo.getWithOffset(Offset);
5698e8d8bef9SDimitry Andric     EltAlign = commonAlignment(VecAlign, Offset);
5699e8d8bef9SDimitry Andric   } else {
5700e8d8bef9SDimitry Andric     // We lose information with a variable offset.
5701e8d8bef9SDimitry Andric     EltAlign = getStackTemporaryAlignment(EltTy);
5702e8d8bef9SDimitry Andric     PtrInfo = MachinePointerInfo(MRI.getType(EltPtr).getAddressSpace());
5703e8d8bef9SDimitry Andric   }
5704e8d8bef9SDimitry Andric 
5705e8d8bef9SDimitry Andric   if (InsertVal) {
5706e8d8bef9SDimitry Andric     // Write the inserted element
5707e8d8bef9SDimitry Andric     MIRBuilder.buildStore(InsertVal, EltPtr, PtrInfo, EltAlign);
5708e8d8bef9SDimitry Andric 
5709e8d8bef9SDimitry Andric     // Reload the whole vector.
5710e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, StackTemp, PtrInfo, VecAlign);
5711e8d8bef9SDimitry Andric   } else {
5712e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, EltPtr, PtrInfo, EltAlign);
5713e8d8bef9SDimitry Andric   }
5714e8d8bef9SDimitry Andric 
5715e8d8bef9SDimitry Andric   MI.eraseFromParent();
5716e8d8bef9SDimitry Andric   return Legalized;
5717e8d8bef9SDimitry Andric }
5718e8d8bef9SDimitry Andric 
57198bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
57208bcb0991SDimitry Andric LegalizerHelper::lowerShuffleVector(MachineInstr &MI) {
57218bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
57228bcb0991SDimitry Andric   Register Src0Reg = MI.getOperand(1).getReg();
57238bcb0991SDimitry Andric   Register Src1Reg = MI.getOperand(2).getReg();
57248bcb0991SDimitry Andric   LLT Src0Ty = MRI.getType(Src0Reg);
57258bcb0991SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
57268bcb0991SDimitry Andric   LLT IdxTy = LLT::scalar(32);
57278bcb0991SDimitry Andric 
5728480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
57298bcb0991SDimitry Andric 
57308bcb0991SDimitry Andric   if (DstTy.isScalar()) {
57318bcb0991SDimitry Andric     if (Src0Ty.isVector())
57328bcb0991SDimitry Andric       return UnableToLegalize;
57338bcb0991SDimitry Andric 
57348bcb0991SDimitry Andric     // This is just a SELECT.
57358bcb0991SDimitry Andric     assert(Mask.size() == 1 && "Expected a single mask element");
57368bcb0991SDimitry Andric     Register Val;
57378bcb0991SDimitry Andric     if (Mask[0] < 0 || Mask[0] > 1)
57388bcb0991SDimitry Andric       Val = MIRBuilder.buildUndef(DstTy).getReg(0);
57398bcb0991SDimitry Andric     else
57408bcb0991SDimitry Andric       Val = Mask[0] == 0 ? Src0Reg : Src1Reg;
57418bcb0991SDimitry Andric     MIRBuilder.buildCopy(DstReg, Val);
57428bcb0991SDimitry Andric     MI.eraseFromParent();
57438bcb0991SDimitry Andric     return Legalized;
57448bcb0991SDimitry Andric   }
57458bcb0991SDimitry Andric 
57468bcb0991SDimitry Andric   Register Undef;
57478bcb0991SDimitry Andric   SmallVector<Register, 32> BuildVec;
57488bcb0991SDimitry Andric   LLT EltTy = DstTy.getElementType();
57498bcb0991SDimitry Andric 
57508bcb0991SDimitry Andric   for (int Idx : Mask) {
57518bcb0991SDimitry Andric     if (Idx < 0) {
57528bcb0991SDimitry Andric       if (!Undef.isValid())
57538bcb0991SDimitry Andric         Undef = MIRBuilder.buildUndef(EltTy).getReg(0);
57548bcb0991SDimitry Andric       BuildVec.push_back(Undef);
57558bcb0991SDimitry Andric       continue;
57568bcb0991SDimitry Andric     }
57578bcb0991SDimitry Andric 
57588bcb0991SDimitry Andric     if (Src0Ty.isScalar()) {
57598bcb0991SDimitry Andric       BuildVec.push_back(Idx == 0 ? Src0Reg : Src1Reg);
57608bcb0991SDimitry Andric     } else {
57618bcb0991SDimitry Andric       int NumElts = Src0Ty.getNumElements();
57628bcb0991SDimitry Andric       Register SrcVec = Idx < NumElts ? Src0Reg : Src1Reg;
57638bcb0991SDimitry Andric       int ExtractIdx = Idx < NumElts ? Idx : Idx - NumElts;
57648bcb0991SDimitry Andric       auto IdxK = MIRBuilder.buildConstant(IdxTy, ExtractIdx);
57658bcb0991SDimitry Andric       auto Extract = MIRBuilder.buildExtractVectorElement(EltTy, SrcVec, IdxK);
57668bcb0991SDimitry Andric       BuildVec.push_back(Extract.getReg(0));
57678bcb0991SDimitry Andric     }
57688bcb0991SDimitry Andric   }
57698bcb0991SDimitry Andric 
57708bcb0991SDimitry Andric   MIRBuilder.buildBuildVector(DstReg, BuildVec);
57718bcb0991SDimitry Andric   MI.eraseFromParent();
57728bcb0991SDimitry Andric   return Legalized;
57738bcb0991SDimitry Andric }
57748bcb0991SDimitry Andric 
57758bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
57768bcb0991SDimitry Andric LegalizerHelper::lowerDynStackAlloc(MachineInstr &MI) {
57775ffd83dbSDimitry Andric   const auto &MF = *MI.getMF();
57785ffd83dbSDimitry Andric   const auto &TFI = *MF.getSubtarget().getFrameLowering();
57795ffd83dbSDimitry Andric   if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
57805ffd83dbSDimitry Andric     return UnableToLegalize;
57815ffd83dbSDimitry Andric 
57828bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
57838bcb0991SDimitry Andric   Register AllocSize = MI.getOperand(1).getReg();
57845ffd83dbSDimitry Andric   Align Alignment = assumeAligned(MI.getOperand(2).getImm());
57858bcb0991SDimitry Andric 
57868bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(Dst);
57878bcb0991SDimitry Andric   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
57888bcb0991SDimitry Andric 
57898bcb0991SDimitry Andric   Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
57908bcb0991SDimitry Andric   auto SPTmp = MIRBuilder.buildCopy(PtrTy, SPReg);
57918bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(IntPtrTy, SPTmp);
57928bcb0991SDimitry Andric 
57938bcb0991SDimitry Andric   // Subtract the final alloc from the SP. We use G_PTRTOINT here so we don't
57948bcb0991SDimitry Andric   // have to generate an extra instruction to negate the alloc and then use
5795480093f4SDimitry Andric   // G_PTR_ADD to add the negative offset.
57968bcb0991SDimitry Andric   auto Alloc = MIRBuilder.buildSub(IntPtrTy, SPTmp, AllocSize);
57975ffd83dbSDimitry Andric   if (Alignment > Align(1)) {
57985ffd83dbSDimitry Andric     APInt AlignMask(IntPtrTy.getSizeInBits(), Alignment.value(), true);
57998bcb0991SDimitry Andric     AlignMask.negate();
58008bcb0991SDimitry Andric     auto AlignCst = MIRBuilder.buildConstant(IntPtrTy, AlignMask);
58018bcb0991SDimitry Andric     Alloc = MIRBuilder.buildAnd(IntPtrTy, Alloc, AlignCst);
58028bcb0991SDimitry Andric   }
58038bcb0991SDimitry Andric 
58048bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(PtrTy, Alloc);
58058bcb0991SDimitry Andric   MIRBuilder.buildCopy(SPReg, SPTmp);
58068bcb0991SDimitry Andric   MIRBuilder.buildCopy(Dst, SPTmp);
58078bcb0991SDimitry Andric 
58088bcb0991SDimitry Andric   MI.eraseFromParent();
58098bcb0991SDimitry Andric   return Legalized;
58108bcb0991SDimitry Andric }
58118bcb0991SDimitry Andric 
58128bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
58138bcb0991SDimitry Andric LegalizerHelper::lowerExtract(MachineInstr &MI) {
58148bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
58158bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
58168bcb0991SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
58178bcb0991SDimitry Andric 
58188bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst);
58198bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(Src);
58208bcb0991SDimitry Andric 
58218bcb0991SDimitry Andric   if (DstTy.isScalar() &&
58228bcb0991SDimitry Andric       (SrcTy.isScalar() ||
58238bcb0991SDimitry Andric        (SrcTy.isVector() && DstTy == SrcTy.getElementType()))) {
58248bcb0991SDimitry Andric     LLT SrcIntTy = SrcTy;
58258bcb0991SDimitry Andric     if (!SrcTy.isScalar()) {
58268bcb0991SDimitry Andric       SrcIntTy = LLT::scalar(SrcTy.getSizeInBits());
58278bcb0991SDimitry Andric       Src = MIRBuilder.buildBitcast(SrcIntTy, Src).getReg(0);
58288bcb0991SDimitry Andric     }
58298bcb0991SDimitry Andric 
58308bcb0991SDimitry Andric     if (Offset == 0)
58318bcb0991SDimitry Andric       MIRBuilder.buildTrunc(Dst, Src);
58328bcb0991SDimitry Andric     else {
58338bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcIntTy, Offset);
58348bcb0991SDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcIntTy, Src, ShiftAmt);
58358bcb0991SDimitry Andric       MIRBuilder.buildTrunc(Dst, Shr);
58368bcb0991SDimitry Andric     }
58378bcb0991SDimitry Andric 
58388bcb0991SDimitry Andric     MI.eraseFromParent();
58398bcb0991SDimitry Andric     return Legalized;
58408bcb0991SDimitry Andric   }
58418bcb0991SDimitry Andric 
58428bcb0991SDimitry Andric   return UnableToLegalize;
58438bcb0991SDimitry Andric }
58448bcb0991SDimitry Andric 
58458bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerInsert(MachineInstr &MI) {
58468bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
58478bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
58488bcb0991SDimitry Andric   Register InsertSrc = MI.getOperand(2).getReg();
58498bcb0991SDimitry Andric   uint64_t Offset = MI.getOperand(3).getImm();
58508bcb0991SDimitry Andric 
58518bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Src);
58528bcb0991SDimitry Andric   LLT InsertTy = MRI.getType(InsertSrc);
58538bcb0991SDimitry Andric 
58545ffd83dbSDimitry Andric   if (InsertTy.isVector() ||
58555ffd83dbSDimitry Andric       (DstTy.isVector() && DstTy.getElementType() != InsertTy))
58565ffd83dbSDimitry Andric     return UnableToLegalize;
58575ffd83dbSDimitry Andric 
58585ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
58595ffd83dbSDimitry Andric   if ((DstTy.isPointer() &&
58605ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(DstTy.getAddressSpace())) ||
58615ffd83dbSDimitry Andric       (InsertTy.isPointer() &&
58625ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(InsertTy.getAddressSpace()))) {
58635ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Not casting non-integral address space integer\n");
58645ffd83dbSDimitry Andric     return UnableToLegalize;
58655ffd83dbSDimitry Andric   }
58665ffd83dbSDimitry Andric 
58678bcb0991SDimitry Andric   LLT IntDstTy = DstTy;
58685ffd83dbSDimitry Andric 
58698bcb0991SDimitry Andric   if (!DstTy.isScalar()) {
58708bcb0991SDimitry Andric     IntDstTy = LLT::scalar(DstTy.getSizeInBits());
58715ffd83dbSDimitry Andric     Src = MIRBuilder.buildCast(IntDstTy, Src).getReg(0);
58725ffd83dbSDimitry Andric   }
58735ffd83dbSDimitry Andric 
58745ffd83dbSDimitry Andric   if (!InsertTy.isScalar()) {
58755ffd83dbSDimitry Andric     const LLT IntInsertTy = LLT::scalar(InsertTy.getSizeInBits());
58765ffd83dbSDimitry Andric     InsertSrc = MIRBuilder.buildPtrToInt(IntInsertTy, InsertSrc).getReg(0);
58778bcb0991SDimitry Andric   }
58788bcb0991SDimitry Andric 
58798bcb0991SDimitry Andric   Register ExtInsSrc = MIRBuilder.buildZExt(IntDstTy, InsertSrc).getReg(0);
58808bcb0991SDimitry Andric   if (Offset != 0) {
58818bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntDstTy, Offset);
58828bcb0991SDimitry Andric     ExtInsSrc = MIRBuilder.buildShl(IntDstTy, ExtInsSrc, ShiftAmt).getReg(0);
58838bcb0991SDimitry Andric   }
58848bcb0991SDimitry Andric 
58855ffd83dbSDimitry Andric   APInt MaskVal = APInt::getBitsSetWithWrap(
58865ffd83dbSDimitry Andric       DstTy.getSizeInBits(), Offset + InsertTy.getSizeInBits(), Offset);
58878bcb0991SDimitry Andric 
58888bcb0991SDimitry Andric   auto Mask = MIRBuilder.buildConstant(IntDstTy, MaskVal);
58898bcb0991SDimitry Andric   auto MaskedSrc = MIRBuilder.buildAnd(IntDstTy, Src, Mask);
58908bcb0991SDimitry Andric   auto Or = MIRBuilder.buildOr(IntDstTy, MaskedSrc, ExtInsSrc);
58918bcb0991SDimitry Andric 
58925ffd83dbSDimitry Andric   MIRBuilder.buildCast(Dst, Or);
58938bcb0991SDimitry Andric   MI.eraseFromParent();
58948bcb0991SDimitry Andric   return Legalized;
58958bcb0991SDimitry Andric }
58968bcb0991SDimitry Andric 
58978bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
58988bcb0991SDimitry Andric LegalizerHelper::lowerSADDO_SSUBO(MachineInstr &MI) {
58998bcb0991SDimitry Andric   Register Dst0 = MI.getOperand(0).getReg();
59008bcb0991SDimitry Andric   Register Dst1 = MI.getOperand(1).getReg();
59018bcb0991SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
59028bcb0991SDimitry Andric   Register RHS = MI.getOperand(3).getReg();
59038bcb0991SDimitry Andric   const bool IsAdd = MI.getOpcode() == TargetOpcode::G_SADDO;
59048bcb0991SDimitry Andric 
59058bcb0991SDimitry Andric   LLT Ty = MRI.getType(Dst0);
59068bcb0991SDimitry Andric   LLT BoolTy = MRI.getType(Dst1);
59078bcb0991SDimitry Andric 
59088bcb0991SDimitry Andric   if (IsAdd)
59098bcb0991SDimitry Andric     MIRBuilder.buildAdd(Dst0, LHS, RHS);
59108bcb0991SDimitry Andric   else
59118bcb0991SDimitry Andric     MIRBuilder.buildSub(Dst0, LHS, RHS);
59128bcb0991SDimitry Andric 
59138bcb0991SDimitry Andric   // TODO: If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
59148bcb0991SDimitry Andric 
59158bcb0991SDimitry Andric   auto Zero = MIRBuilder.buildConstant(Ty, 0);
59168bcb0991SDimitry Andric 
59178bcb0991SDimitry Andric   // For an addition, the result should be less than one of the operands (LHS)
59188bcb0991SDimitry Andric   // if and only if the other operand (RHS) is negative, otherwise there will
59198bcb0991SDimitry Andric   // be overflow.
59208bcb0991SDimitry Andric   // For a subtraction, the result should be less than one of the operands
59218bcb0991SDimitry Andric   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
59228bcb0991SDimitry Andric   // otherwise there will be overflow.
59238bcb0991SDimitry Andric   auto ResultLowerThanLHS =
59248bcb0991SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, Dst0, LHS);
59258bcb0991SDimitry Andric   auto ConditionRHS = MIRBuilder.buildICmp(
59268bcb0991SDimitry Andric       IsAdd ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGT, BoolTy, RHS, Zero);
59278bcb0991SDimitry Andric 
59288bcb0991SDimitry Andric   MIRBuilder.buildXor(Dst1, ConditionRHS, ResultLowerThanLHS);
59298bcb0991SDimitry Andric   MI.eraseFromParent();
59308bcb0991SDimitry Andric   return Legalized;
59318bcb0991SDimitry Andric }
5932480093f4SDimitry Andric 
5933480093f4SDimitry Andric LegalizerHelper::LegalizeResult
5934e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToMinMax(MachineInstr &MI) {
5935e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
5936e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5937e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5938e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
5939e8d8bef9SDimitry Andric   bool IsSigned;
5940e8d8bef9SDimitry Andric   bool IsAdd;
5941e8d8bef9SDimitry Andric   unsigned BaseOp;
5942e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
5943e8d8bef9SDimitry Andric   default:
5944e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
5945e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
5946e8d8bef9SDimitry Andric     IsSigned = false;
5947e8d8bef9SDimitry Andric     IsAdd = true;
5948e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
5949e8d8bef9SDimitry Andric     break;
5950e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
5951e8d8bef9SDimitry Andric     IsSigned = true;
5952e8d8bef9SDimitry Andric     IsAdd = true;
5953e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
5954e8d8bef9SDimitry Andric     break;
5955e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
5956e8d8bef9SDimitry Andric     IsSigned = false;
5957e8d8bef9SDimitry Andric     IsAdd = false;
5958e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
5959e8d8bef9SDimitry Andric     break;
5960e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
5961e8d8bef9SDimitry Andric     IsSigned = true;
5962e8d8bef9SDimitry Andric     IsAdd = false;
5963e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
5964e8d8bef9SDimitry Andric     break;
5965e8d8bef9SDimitry Andric   }
5966e8d8bef9SDimitry Andric 
5967e8d8bef9SDimitry Andric   if (IsSigned) {
5968e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
5969e8d8bef9SDimitry Andric     //   hi = 0x7fffffff - smax(a, 0)
5970e8d8bef9SDimitry Andric     //   lo = 0x80000000 - smin(a, 0)
5971e8d8bef9SDimitry Andric     //   a + smin(smax(lo, b), hi)
5972e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
5973e8d8bef9SDimitry Andric     //   lo = smax(a, -1) - 0x7fffffff
5974e8d8bef9SDimitry Andric     //   hi = smin(a, -1) - 0x80000000
5975e8d8bef9SDimitry Andric     //   a - smin(smax(lo, b), hi)
5976e8d8bef9SDimitry Andric     // TODO: AMDGPU can use a "median of 3" instruction here:
5977e8d8bef9SDimitry Andric     //   a +/- med3(lo, b, hi)
5978e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
5979e8d8bef9SDimitry Andric     auto MaxVal =
5980e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(NumBits));
5981e8d8bef9SDimitry Andric     auto MinVal =
5982e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
5983e8d8bef9SDimitry Andric     MachineInstrBuilder Hi, Lo;
5984e8d8bef9SDimitry Andric     if (IsAdd) {
5985e8d8bef9SDimitry Andric       auto Zero = MIRBuilder.buildConstant(Ty, 0);
5986e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MaxVal, MIRBuilder.buildSMax(Ty, LHS, Zero));
5987e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MinVal, MIRBuilder.buildSMin(Ty, LHS, Zero));
5988e8d8bef9SDimitry Andric     } else {
5989e8d8bef9SDimitry Andric       auto NegOne = MIRBuilder.buildConstant(Ty, -1);
5990e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMax(Ty, LHS, NegOne),
5991e8d8bef9SDimitry Andric                                MaxVal);
5992e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMin(Ty, LHS, NegOne),
5993e8d8bef9SDimitry Andric                                MinVal);
5994e8d8bef9SDimitry Andric     }
5995e8d8bef9SDimitry Andric     auto RHSClamped =
5996e8d8bef9SDimitry Andric         MIRBuilder.buildSMin(Ty, MIRBuilder.buildSMax(Ty, Lo, RHS), Hi);
5997e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, RHSClamped});
5998e8d8bef9SDimitry Andric   } else {
5999e8d8bef9SDimitry Andric     // uadd.sat(a, b) -> a + umin(~a, b)
6000e8d8bef9SDimitry Andric     // usub.sat(a, b) -> a - umin(a, b)
6001e8d8bef9SDimitry Andric     Register Not = IsAdd ? MIRBuilder.buildNot(Ty, LHS).getReg(0) : LHS;
6002e8d8bef9SDimitry Andric     auto Min = MIRBuilder.buildUMin(Ty, Not, RHS);
6003e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, Min});
6004e8d8bef9SDimitry Andric   }
6005e8d8bef9SDimitry Andric 
6006e8d8bef9SDimitry Andric   MI.eraseFromParent();
6007e8d8bef9SDimitry Andric   return Legalized;
6008e8d8bef9SDimitry Andric }
6009e8d8bef9SDimitry Andric 
6010e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6011e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToAddoSubo(MachineInstr &MI) {
6012e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
6013e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
6014e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
6015e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
6016e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
6017e8d8bef9SDimitry Andric   bool IsSigned;
6018e8d8bef9SDimitry Andric   bool IsAdd;
6019e8d8bef9SDimitry Andric   unsigned OverflowOp;
6020e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
6021e8d8bef9SDimitry Andric   default:
6022e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
6023e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
6024e8d8bef9SDimitry Andric     IsSigned = false;
6025e8d8bef9SDimitry Andric     IsAdd = true;
6026e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_UADDO;
6027e8d8bef9SDimitry Andric     break;
6028e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
6029e8d8bef9SDimitry Andric     IsSigned = true;
6030e8d8bef9SDimitry Andric     IsAdd = true;
6031e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SADDO;
6032e8d8bef9SDimitry Andric     break;
6033e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
6034e8d8bef9SDimitry Andric     IsSigned = false;
6035e8d8bef9SDimitry Andric     IsAdd = false;
6036e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_USUBO;
6037e8d8bef9SDimitry Andric     break;
6038e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
6039e8d8bef9SDimitry Andric     IsSigned = true;
6040e8d8bef9SDimitry Andric     IsAdd = false;
6041e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SSUBO;
6042e8d8bef9SDimitry Andric     break;
6043e8d8bef9SDimitry Andric   }
6044e8d8bef9SDimitry Andric 
6045e8d8bef9SDimitry Andric   auto OverflowRes =
6046e8d8bef9SDimitry Andric       MIRBuilder.buildInstr(OverflowOp, {Ty, BoolTy}, {LHS, RHS});
6047e8d8bef9SDimitry Andric   Register Tmp = OverflowRes.getReg(0);
6048e8d8bef9SDimitry Andric   Register Ov = OverflowRes.getReg(1);
6049e8d8bef9SDimitry Andric   MachineInstrBuilder Clamp;
6050e8d8bef9SDimitry Andric   if (IsSigned) {
6051e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
6052e8d8bef9SDimitry Andric     //   {tmp, ov} = saddo(a, b)
6053e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
6054e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
6055e8d8bef9SDimitry Andric     //   {tmp, ov} = ssubo(a, b)
6056e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
6057e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
6058e8d8bef9SDimitry Andric     auto ShiftAmount = MIRBuilder.buildConstant(Ty, NumBits - 1);
6059e8d8bef9SDimitry Andric     auto Sign = MIRBuilder.buildAShr(Ty, Tmp, ShiftAmount);
6060e8d8bef9SDimitry Andric     auto MinVal =
6061e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
6062e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildAdd(Ty, Sign, MinVal);
6063e8d8bef9SDimitry Andric   } else {
6064e8d8bef9SDimitry Andric     // uadd.sat(a, b) ->
6065e8d8bef9SDimitry Andric     //   {tmp, ov} = uaddo(a, b)
6066e8d8bef9SDimitry Andric     //   ov ? 0xffffffff : tmp
6067e8d8bef9SDimitry Andric     // usub.sat(a, b) ->
6068e8d8bef9SDimitry Andric     //   {tmp, ov} = usubo(a, b)
6069e8d8bef9SDimitry Andric     //   ov ? 0 : tmp
6070e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildConstant(Ty, IsAdd ? -1 : 0);
6071e8d8bef9SDimitry Andric   }
6072e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, Clamp, Tmp);
6073e8d8bef9SDimitry Andric 
6074e8d8bef9SDimitry Andric   MI.eraseFromParent();
6075e8d8bef9SDimitry Andric   return Legalized;
6076e8d8bef9SDimitry Andric }
6077e8d8bef9SDimitry Andric 
6078e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6079e8d8bef9SDimitry Andric LegalizerHelper::lowerShlSat(MachineInstr &MI) {
6080e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
6081e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_USHLSAT) &&
6082e8d8bef9SDimitry Andric          "Expected shlsat opcode!");
6083e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SSHLSAT;
6084e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
6085e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
6086e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
6087e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
6088e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
6089e8d8bef9SDimitry Andric 
6090e8d8bef9SDimitry Andric   unsigned BW = Ty.getScalarSizeInBits();
6091e8d8bef9SDimitry Andric   auto Result = MIRBuilder.buildShl(Ty, LHS, RHS);
6092e8d8bef9SDimitry Andric   auto Orig = IsSigned ? MIRBuilder.buildAShr(Ty, Result, RHS)
6093e8d8bef9SDimitry Andric                        : MIRBuilder.buildLShr(Ty, Result, RHS);
6094e8d8bef9SDimitry Andric 
6095e8d8bef9SDimitry Andric   MachineInstrBuilder SatVal;
6096e8d8bef9SDimitry Andric   if (IsSigned) {
6097e8d8bef9SDimitry Andric     auto SatMin = MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(BW));
6098e8d8bef9SDimitry Andric     auto SatMax = MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(BW));
6099e8d8bef9SDimitry Andric     auto Cmp = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, LHS,
6100e8d8bef9SDimitry Andric                                     MIRBuilder.buildConstant(Ty, 0));
6101e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildSelect(Ty, Cmp, SatMin, SatMax);
6102e8d8bef9SDimitry Andric   } else {
6103e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildConstant(Ty, APInt::getMaxValue(BW));
6104e8d8bef9SDimitry Andric   }
6105e8d8bef9SDimitry Andric   auto Ov = MIRBuilder.buildICmp(CmpInst::ICMP_NE, BoolTy, LHS, Orig);
6106e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, SatVal, Result);
6107e8d8bef9SDimitry Andric 
6108e8d8bef9SDimitry Andric   MI.eraseFromParent();
6109e8d8bef9SDimitry Andric   return Legalized;
6110e8d8bef9SDimitry Andric }
6111e8d8bef9SDimitry Andric 
6112e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6113480093f4SDimitry Andric LegalizerHelper::lowerBswap(MachineInstr &MI) {
6114480093f4SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6115480093f4SDimitry Andric   Register Src = MI.getOperand(1).getReg();
6116480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
61175ffd83dbSDimitry Andric   unsigned SizeInBytes = (Ty.getScalarSizeInBits() + 7) / 8;
6118480093f4SDimitry Andric   unsigned BaseShiftAmt = (SizeInBytes - 1) * 8;
6119480093f4SDimitry Andric 
6120480093f4SDimitry Andric   // Swap most and least significant byte, set remaining bytes in Res to zero.
6121480093f4SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt);
6122480093f4SDimitry Andric   auto LSByteShiftedLeft = MIRBuilder.buildShl(Ty, Src, ShiftAmt);
6123480093f4SDimitry Andric   auto MSByteShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
6124480093f4SDimitry Andric   auto Res = MIRBuilder.buildOr(Ty, MSByteShiftedRight, LSByteShiftedLeft);
6125480093f4SDimitry Andric 
6126480093f4SDimitry Andric   // Set i-th high/low byte in Res to i-th low/high byte from Src.
6127480093f4SDimitry Andric   for (unsigned i = 1; i < SizeInBytes / 2; ++i) {
6128480093f4SDimitry Andric     // AND with Mask leaves byte i unchanged and sets remaining bytes to 0.
6129480093f4SDimitry Andric     APInt APMask(SizeInBytes * 8, 0xFF << (i * 8));
6130480093f4SDimitry Andric     auto Mask = MIRBuilder.buildConstant(Ty, APMask);
6131480093f4SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt - 16 * i);
6132480093f4SDimitry Andric     // Low byte shifted left to place of high byte: (Src & Mask) << ShiftAmt.
6133480093f4SDimitry Andric     auto LoByte = MIRBuilder.buildAnd(Ty, Src, Mask);
6134480093f4SDimitry Andric     auto LoShiftedLeft = MIRBuilder.buildShl(Ty, LoByte, ShiftAmt);
6135480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, LoShiftedLeft);
6136480093f4SDimitry Andric     // High byte shifted right to place of low byte: (Src >> ShiftAmt) & Mask.
6137480093f4SDimitry Andric     auto SrcShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
6138480093f4SDimitry Andric     auto HiShiftedRight = MIRBuilder.buildAnd(Ty, SrcShiftedRight, Mask);
6139480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, HiShiftedRight);
6140480093f4SDimitry Andric   }
6141480093f4SDimitry Andric   Res.getInstr()->getOperand(0).setReg(Dst);
6142480093f4SDimitry Andric 
6143480093f4SDimitry Andric   MI.eraseFromParent();
6144480093f4SDimitry Andric   return Legalized;
6145480093f4SDimitry Andric }
6146480093f4SDimitry Andric 
6147480093f4SDimitry Andric //{ (Src & Mask) >> N } | { (Src << N) & Mask }
6148480093f4SDimitry Andric static MachineInstrBuilder SwapN(unsigned N, DstOp Dst, MachineIRBuilder &B,
6149480093f4SDimitry Andric                                  MachineInstrBuilder Src, APInt Mask) {
6150480093f4SDimitry Andric   const LLT Ty = Dst.getLLTTy(*B.getMRI());
6151480093f4SDimitry Andric   MachineInstrBuilder C_N = B.buildConstant(Ty, N);
6152480093f4SDimitry Andric   MachineInstrBuilder MaskLoNTo0 = B.buildConstant(Ty, Mask);
6153480093f4SDimitry Andric   auto LHS = B.buildLShr(Ty, B.buildAnd(Ty, Src, MaskLoNTo0), C_N);
6154480093f4SDimitry Andric   auto RHS = B.buildAnd(Ty, B.buildShl(Ty, Src, C_N), MaskLoNTo0);
6155480093f4SDimitry Andric   return B.buildOr(Dst, LHS, RHS);
6156480093f4SDimitry Andric }
6157480093f4SDimitry Andric 
6158480093f4SDimitry Andric LegalizerHelper::LegalizeResult
6159480093f4SDimitry Andric LegalizerHelper::lowerBitreverse(MachineInstr &MI) {
6160480093f4SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6161480093f4SDimitry Andric   Register Src = MI.getOperand(1).getReg();
6162480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
6163480093f4SDimitry Andric   unsigned Size = Ty.getSizeInBits();
6164480093f4SDimitry Andric 
6165480093f4SDimitry Andric   MachineInstrBuilder BSWAP =
6166480093f4SDimitry Andric       MIRBuilder.buildInstr(TargetOpcode::G_BSWAP, {Ty}, {Src});
6167480093f4SDimitry Andric 
6168480093f4SDimitry Andric   // swap high and low 4 bits in 8 bit blocks 7654|3210 -> 3210|7654
6169480093f4SDimitry Andric   //    [(val & 0xF0F0F0F0) >> 4] | [(val & 0x0F0F0F0F) << 4]
6170480093f4SDimitry Andric   // -> [(val & 0xF0F0F0F0) >> 4] | [(val << 4) & 0xF0F0F0F0]
6171480093f4SDimitry Andric   MachineInstrBuilder Swap4 =
6172480093f4SDimitry Andric       SwapN(4, Ty, MIRBuilder, BSWAP, APInt::getSplat(Size, APInt(8, 0xF0)));
6173480093f4SDimitry Andric 
6174480093f4SDimitry Andric   // swap high and low 2 bits in 4 bit blocks 32|10 76|54 -> 10|32 54|76
6175480093f4SDimitry Andric   //    [(val & 0xCCCCCCCC) >> 2] & [(val & 0x33333333) << 2]
6176480093f4SDimitry Andric   // -> [(val & 0xCCCCCCCC) >> 2] & [(val << 2) & 0xCCCCCCCC]
6177480093f4SDimitry Andric   MachineInstrBuilder Swap2 =
6178480093f4SDimitry Andric       SwapN(2, Ty, MIRBuilder, Swap4, APInt::getSplat(Size, APInt(8, 0xCC)));
6179480093f4SDimitry Andric 
6180480093f4SDimitry 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
6181480093f4SDimitry Andric   //    [(val & 0xAAAAAAAA) >> 1] & [(val & 0x55555555) << 1]
6182480093f4SDimitry Andric   // -> [(val & 0xAAAAAAAA) >> 1] & [(val << 1) & 0xAAAAAAAA]
6183480093f4SDimitry Andric   SwapN(1, Dst, MIRBuilder, Swap2, APInt::getSplat(Size, APInt(8, 0xAA)));
6184480093f4SDimitry Andric 
6185480093f4SDimitry Andric   MI.eraseFromParent();
6186480093f4SDimitry Andric   return Legalized;
6187480093f4SDimitry Andric }
6188480093f4SDimitry Andric 
6189480093f4SDimitry Andric LegalizerHelper::LegalizeResult
61905ffd83dbSDimitry Andric LegalizerHelper::lowerReadWriteRegister(MachineInstr &MI) {
6191480093f4SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
61925ffd83dbSDimitry Andric 
61935ffd83dbSDimitry Andric   bool IsRead = MI.getOpcode() == TargetOpcode::G_READ_REGISTER;
61945ffd83dbSDimitry Andric   int NameOpIdx = IsRead ? 1 : 0;
61955ffd83dbSDimitry Andric   int ValRegIndex = IsRead ? 0 : 1;
61965ffd83dbSDimitry Andric 
61975ffd83dbSDimitry Andric   Register ValReg = MI.getOperand(ValRegIndex).getReg();
61985ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(ValReg);
61995ffd83dbSDimitry Andric   const MDString *RegStr = cast<MDString>(
62005ffd83dbSDimitry Andric     cast<MDNode>(MI.getOperand(NameOpIdx).getMetadata())->getOperand(0));
62015ffd83dbSDimitry Andric 
6202e8d8bef9SDimitry Andric   Register PhysReg = TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
62035ffd83dbSDimitry Andric   if (!PhysReg.isValid())
6204480093f4SDimitry Andric     return UnableToLegalize;
6205480093f4SDimitry Andric 
62065ffd83dbSDimitry Andric   if (IsRead)
62075ffd83dbSDimitry Andric     MIRBuilder.buildCopy(ValReg, PhysReg);
62085ffd83dbSDimitry Andric   else
62095ffd83dbSDimitry Andric     MIRBuilder.buildCopy(PhysReg, ValReg);
62105ffd83dbSDimitry Andric 
6211480093f4SDimitry Andric   MI.eraseFromParent();
6212480093f4SDimitry Andric   return Legalized;
6213480093f4SDimitry Andric }
6214e8d8bef9SDimitry Andric 
6215e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6216e8d8bef9SDimitry Andric LegalizerHelper::lowerSMULH_UMULH(MachineInstr &MI) {
6217e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SMULH;
6218e8d8bef9SDimitry Andric   unsigned ExtOp = IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
6219e8d8bef9SDimitry Andric   Register Result = MI.getOperand(0).getReg();
6220e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(Result);
6221e8d8bef9SDimitry Andric   auto SizeInBits = OrigTy.getScalarSizeInBits();
6222e8d8bef9SDimitry Andric   LLT WideTy = OrigTy.changeElementSize(SizeInBits * 2);
6223e8d8bef9SDimitry Andric 
6224e8d8bef9SDimitry Andric   auto LHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(1)});
6225e8d8bef9SDimitry Andric   auto RHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(2)});
6226e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(WideTy, LHS, RHS);
6227e8d8bef9SDimitry Andric   unsigned ShiftOp = IsSigned ? TargetOpcode::G_ASHR : TargetOpcode::G_LSHR;
6228e8d8bef9SDimitry Andric 
6229e8d8bef9SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(WideTy, SizeInBits);
6230e8d8bef9SDimitry Andric   auto Shifted = MIRBuilder.buildInstr(ShiftOp, {WideTy}, {Mul, ShiftAmt});
6231e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(Result, Shifted);
6232e8d8bef9SDimitry Andric 
6233e8d8bef9SDimitry Andric   MI.eraseFromParent();
6234e8d8bef9SDimitry Andric   return Legalized;
6235e8d8bef9SDimitry Andric }
6236e8d8bef9SDimitry Andric 
6237e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSelect(MachineInstr &MI) {
6238e8d8bef9SDimitry Andric   // Implement vector G_SELECT in terms of XOR, AND, OR.
6239e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
6240e8d8bef9SDimitry Andric   Register MaskReg = MI.getOperand(1).getReg();
6241e8d8bef9SDimitry Andric   Register Op1Reg = MI.getOperand(2).getReg();
6242e8d8bef9SDimitry Andric   Register Op2Reg = MI.getOperand(3).getReg();
6243e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
6244e8d8bef9SDimitry Andric   LLT MaskTy = MRI.getType(MaskReg);
6245e8d8bef9SDimitry Andric   LLT Op1Ty = MRI.getType(Op1Reg);
6246e8d8bef9SDimitry Andric   if (!DstTy.isVector())
6247e8d8bef9SDimitry Andric     return UnableToLegalize;
6248e8d8bef9SDimitry Andric 
6249e8d8bef9SDimitry Andric   // Vector selects can have a scalar predicate. If so, splat into a vector and
6250e8d8bef9SDimitry Andric   // finish for later legalization attempts to try again.
6251e8d8bef9SDimitry Andric   if (MaskTy.isScalar()) {
6252e8d8bef9SDimitry Andric     Register MaskElt = MaskReg;
6253e8d8bef9SDimitry Andric     if (MaskTy.getSizeInBits() < DstTy.getScalarSizeInBits())
6254e8d8bef9SDimitry Andric       MaskElt = MIRBuilder.buildSExt(DstTy.getElementType(), MaskElt).getReg(0);
6255e8d8bef9SDimitry Andric     // Generate a vector splat idiom to be pattern matched later.
6256e8d8bef9SDimitry Andric     auto ShufSplat = MIRBuilder.buildShuffleSplat(DstTy, MaskElt);
6257e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
6258e8d8bef9SDimitry Andric     MI.getOperand(1).setReg(ShufSplat.getReg(0));
6259e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
6260e8d8bef9SDimitry Andric     return Legalized;
6261e8d8bef9SDimitry Andric   }
6262e8d8bef9SDimitry Andric 
6263e8d8bef9SDimitry Andric   if (MaskTy.getSizeInBits() != Op1Ty.getSizeInBits()) {
6264e8d8bef9SDimitry Andric     return UnableToLegalize;
6265e8d8bef9SDimitry Andric   }
6266e8d8bef9SDimitry Andric 
6267e8d8bef9SDimitry Andric   auto NotMask = MIRBuilder.buildNot(MaskTy, MaskReg);
6268e8d8bef9SDimitry Andric   auto NewOp1 = MIRBuilder.buildAnd(MaskTy, Op1Reg, MaskReg);
6269e8d8bef9SDimitry Andric   auto NewOp2 = MIRBuilder.buildAnd(MaskTy, Op2Reg, NotMask);
6270e8d8bef9SDimitry Andric   MIRBuilder.buildOr(DstReg, NewOp1, NewOp2);
6271e8d8bef9SDimitry Andric   MI.eraseFromParent();
6272e8d8bef9SDimitry Andric   return Legalized;
6273e8d8bef9SDimitry Andric }
6274