xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===-- llvm/CodeGen/GlobalISel/LegalizerHelper.cpp -----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file This file implements the LegalizerHelper class to legalize
100b57cec5SDimitry Andric /// individual instructions and the LegalizeMachineIR wrapper pass for the
110b57cec5SDimitry Andric /// primary legalization.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
160b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/CallLowering.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
19*e8d8bef9SDimitry 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;
33*e8d8bef9SDimitry 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);
80*e8d8bef9SDimitry Andric   case 80:
81*e8d8bef9SDimitry 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()),
93*e8d8bef9SDimitry Andric       LI(*MF.getSubtarget().getLegalizerInfo()),
94*e8d8bef9SDimitry Andric       TLI(*MF.getSubtarget().getTargetLowering()) { }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF, const LegalizerInfo &LI,
970b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
980b57cec5SDimitry Andric                                  MachineIRBuilder &B)
99*e8d8bef9SDimitry Andric   : MIRBuilder(B), Observer(Observer), MRI(MF.getRegInfo()), LI(LI),
100*e8d8bef9SDimitry Andric     TLI(*MF.getSubtarget().getTargetLowering()) { }
101*e8d8bef9SDimitry 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 
243*e8d8bef9SDimitry 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 
248*e8d8bef9SDimitry Andric   const int StartIdx = Regs.size();
2495ffd83dbSDimitry Andric   const int NumResults = MI.getNumOperands() - 1;
250*e8d8bef9SDimitry Andric   Regs.resize(Regs.size() + NumResults);
2515ffd83dbSDimitry Andric   for (int I = 0; I != NumResults; ++I)
252*e8d8bef9SDimitry Andric     Regs[StartIdx + I] = MI.getOperand(I).getReg();
2535ffd83dbSDimitry Andric }
2545ffd83dbSDimitry Andric 
255*e8d8bef9SDimitry Andric void LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts,
256*e8d8bef9SDimitry 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   }
267*e8d8bef9SDimitry Andric }
2685ffd83dbSDimitry Andric 
269*e8d8bef9SDimitry Andric LLT LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts, LLT DstTy,
270*e8d8bef9SDimitry Andric                                     LLT NarrowTy, Register SrcReg) {
271*e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
272*e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
273*e8d8bef9SDimitry 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()) {
387*e8d8bef9SDimitry Andric     unsigned NumDefs = LCMTy.getSizeInBits() / DstTy.getSizeInBits();
388*e8d8bef9SDimitry Andric     SmallVector<Register, 8> UnmergeDefs(NumDefs);
389*e8d8bef9SDimitry Andric     UnmergeDefs[0] = DstReg;
390*e8d8bef9SDimitry Andric     for (unsigned I = 1; I != NumDefs; ++I)
391*e8d8bef9SDimitry Andric       UnmergeDefs[I] = MRI.createGenericVirtualRegister(DstTy);
392*e8d8bef9SDimitry Andric 
393*e8d8bef9SDimitry Andric     MIRBuilder.buildUnmerge(UnmergeDefs,
394*e8d8bef9SDimitry 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) {
402*e8d8bef9SDimitry 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 
416*e8d8bef9SDimitry Andric #define RTLIBCASE(LibcallPrefix)                                               \
417*e8d8bef9SDimitry Andric   do {                                                                         \
418*e8d8bef9SDimitry Andric     switch (Size) {                                                            \
419*e8d8bef9SDimitry Andric     case 32:                                                                   \
420*e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
421*e8d8bef9SDimitry Andric     case 64:                                                                   \
422*e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
423*e8d8bef9SDimitry Andric     case 80:                                                                   \
424*e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##80;                                         \
425*e8d8bef9SDimitry Andric     case 128:                                                                  \
426*e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
427*e8d8bef9SDimitry Andric     default:                                                                   \
428*e8d8bef9SDimitry Andric       llvm_unreachable("unexpected size");                                     \
429*e8d8bef9SDimitry Andric     }                                                                          \
430*e8d8bef9SDimitry Andric   } while (0)
4315ffd83dbSDimitry Andric 
4320b57cec5SDimitry Andric   switch (Opcode) {
4330b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
434*e8d8bef9SDimitry Andric     RTLIBCASE_INT(SDIV_I);
4350b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
436*e8d8bef9SDimitry Andric     RTLIBCASE_INT(UDIV_I);
4370b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
438*e8d8bef9SDimitry Andric     RTLIBCASE_INT(SREM_I);
4390b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
440*e8d8bef9SDimitry Andric     RTLIBCASE_INT(UREM_I);
4410b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
442*e8d8bef9SDimitry 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);
485*e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
486*e8d8bef9SDimitry 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.
493*e8d8bef9SDimitry Andric static bool isLibCallInTailPosition(const TargetInstrInfo &TII,
494*e8d8bef9SDimitry 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'.
569*e8d8bef9SDimitry 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;
585*e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
586*e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
5878bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMCPY;
5888bcb0991SDimitry Andric     break;
589*e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
5908bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMMOVE;
5918bcb0991SDimitry Andric     break;
592*e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET:
593*e8d8bef9SDimitry Andric     RTLibcall = RTLIB::MEMSET;
594*e8d8bef9SDimitry 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));
604*e8d8bef9SDimitry Andric   Info.IsTailCall = MI.getOperand(MI.getNumOperands() - 1).getImm() &&
605*e8d8bef9SDimitry 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:
698*e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
699*e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
7005ffd83dbSDimitry Andric     Type *HLTy = getFloatTypeForLLT(Ctx, LLTy);
701*e8d8bef9SDimitry Andric     if (!HLTy || (Size != 32 && Size != 64 && Size != 80 && Size != 128)) {
702*e8d8bef9SDimitry 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   }
751*e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
752*e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
753*e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET: {
754*e8d8bef9SDimitry Andric     LegalizeResult Result = createMemLibcall(MIRBuilder, *MIRBuilder.getMRI(), MI);
755*e8d8bef9SDimitry Andric     MI.eraseFromParent();
756*e8d8bef9SDimitry Andric     return Result;
757*e8d8bef9SDimitry 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: {
938*e8d8bef9SDimitry 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();
962*e8d8bef9SDimitry Andric     unsigned MemSize = MMO.getSizeInBits();
963*e8d8bef9SDimitry Andric 
964*e8d8bef9SDimitry Andric     if (MemSize == NarrowSize) {
9650b57cec5SDimitry Andric       MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
966*e8d8bef9SDimitry Andric     } else if (MemSize < NarrowSize) {
9675ffd83dbSDimitry Andric       MIRBuilder.buildLoadInstr(MI.getOpcode(), TmpReg, PtrReg, MMO);
968*e8d8bef9SDimitry Andric     } else if (MemSize > NarrowSize) {
969*e8d8bef9SDimitry Andric       // FIXME: Need to split the load.
970*e8d8bef9SDimitry 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: {
10660b57cec5SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
10675ffd83dbSDimitry Andric     SmallVector<Register, 2> DstRegs(NumParts);
10685ffd83dbSDimitry Andric     SmallVector<SmallVector<Register, 2>, 2> SrcRegs(MI.getNumOperands() / 2);
10690b57cec5SDimitry Andric     Observer.changingInstr(MI);
10700b57cec5SDimitry Andric     for (unsigned i = 1; i < MI.getNumOperands(); i += 2) {
10710b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(i + 1).getMBB();
10720b57cec5SDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
10730b57cec5SDimitry Andric       extractParts(MI.getOperand(i).getReg(), NarrowTy, NumParts,
10740b57cec5SDimitry Andric                    SrcRegs[i / 2]);
10750b57cec5SDimitry Andric     }
10760b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
10770b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, MI);
10780b57cec5SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
10790b57cec5SDimitry Andric       DstRegs[i] = MRI.createGenericVirtualRegister(NarrowTy);
10800b57cec5SDimitry Andric       MachineInstrBuilder MIB =
10810b57cec5SDimitry Andric           MIRBuilder.buildInstr(TargetOpcode::G_PHI).addDef(DstRegs[i]);
10820b57cec5SDimitry Andric       for (unsigned j = 1; j < MI.getNumOperands(); j += 2)
10830b57cec5SDimitry Andric         MIB.addUse(SrcRegs[j / 2][i]).add(MI.getOperand(j + 1));
10840b57cec5SDimitry Andric     }
10858bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MBB, MBB.getFirstNonPHI());
10865ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
10870b57cec5SDimitry Andric     Observer.changedInstr(MI);
10880b57cec5SDimitry Andric     MI.eraseFromParent();
10890b57cec5SDimitry Andric     return Legalized;
10900b57cec5SDimitry Andric   }
10910b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
10920b57cec5SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
10930b57cec5SDimitry Andric     if (TypeIdx != 2)
10940b57cec5SDimitry Andric       return UnableToLegalize;
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric     int OpIdx = MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
10970b57cec5SDimitry Andric     Observer.changingInstr(MI);
10980b57cec5SDimitry Andric     narrowScalarSrc(MI, NarrowTy, OpIdx);
10990b57cec5SDimitry Andric     Observer.changedInstr(MI);
11000b57cec5SDimitry Andric     return Legalized;
11010b57cec5SDimitry Andric   }
11020b57cec5SDimitry Andric   case TargetOpcode::G_ICMP: {
11030b57cec5SDimitry Andric     uint64_t SrcSize = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
11040b57cec5SDimitry Andric     if (NarrowSize * 2 != SrcSize)
11050b57cec5SDimitry Andric       return UnableToLegalize;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric     Observer.changingInstr(MI);
11080b57cec5SDimitry Andric     Register LHSL = MRI.createGenericVirtualRegister(NarrowTy);
11090b57cec5SDimitry Andric     Register LHSH = MRI.createGenericVirtualRegister(NarrowTy);
11105ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge({LHSL, LHSH}, MI.getOperand(2));
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric     Register RHSL = MRI.createGenericVirtualRegister(NarrowTy);
11130b57cec5SDimitry Andric     Register RHSH = MRI.createGenericVirtualRegister(NarrowTy);
11145ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge({RHSL, RHSH}, MI.getOperand(3));
11150b57cec5SDimitry Andric 
11160b57cec5SDimitry Andric     CmpInst::Predicate Pred =
11170b57cec5SDimitry Andric         static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
11188bcb0991SDimitry Andric     LLT ResTy = MRI.getType(MI.getOperand(0).getReg());
11190b57cec5SDimitry Andric 
11200b57cec5SDimitry Andric     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
11210b57cec5SDimitry Andric       MachineInstrBuilder XorL = MIRBuilder.buildXor(NarrowTy, LHSL, RHSL);
11220b57cec5SDimitry Andric       MachineInstrBuilder XorH = MIRBuilder.buildXor(NarrowTy, LHSH, RHSH);
11230b57cec5SDimitry Andric       MachineInstrBuilder Or = MIRBuilder.buildOr(NarrowTy, XorL, XorH);
11240b57cec5SDimitry Andric       MachineInstrBuilder Zero = MIRBuilder.buildConstant(NarrowTy, 0);
11255ffd83dbSDimitry Andric       MIRBuilder.buildICmp(Pred, MI.getOperand(0), Or, Zero);
11260b57cec5SDimitry Andric     } else {
11278bcb0991SDimitry Andric       MachineInstrBuilder CmpH = MIRBuilder.buildICmp(Pred, ResTy, LHSH, RHSH);
11280b57cec5SDimitry Andric       MachineInstrBuilder CmpHEQ =
11298bcb0991SDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, ResTy, LHSH, RHSH);
11300b57cec5SDimitry Andric       MachineInstrBuilder CmpLU = MIRBuilder.buildICmp(
11318bcb0991SDimitry Andric           ICmpInst::getUnsignedPredicate(Pred), ResTy, LHSL, RHSL);
11325ffd83dbSDimitry Andric       MIRBuilder.buildSelect(MI.getOperand(0), CmpHEQ, CmpLU, CmpH);
11330b57cec5SDimitry Andric     }
11340b57cec5SDimitry Andric     Observer.changedInstr(MI);
11350b57cec5SDimitry Andric     MI.eraseFromParent();
11360b57cec5SDimitry Andric     return Legalized;
11370b57cec5SDimitry Andric   }
11388bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
11398bcb0991SDimitry Andric     if (TypeIdx != 0)
11408bcb0991SDimitry Andric       return UnableToLegalize;
11418bcb0991SDimitry Andric 
11428bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
11438bcb0991SDimitry Andric 
11448bcb0991SDimitry Andric     // So long as the new type has more bits than the bits we're extending we
11458bcb0991SDimitry Andric     // don't need to break it apart.
11468bcb0991SDimitry Andric     if (NarrowTy.getScalarSizeInBits() >= SizeInBits) {
11478bcb0991SDimitry Andric       Observer.changingInstr(MI);
11488bcb0991SDimitry Andric       // We don't lose any non-extension bits by truncating the src and
11498bcb0991SDimitry Andric       // sign-extending the dst.
11508bcb0991SDimitry Andric       MachineOperand &MO1 = MI.getOperand(1);
11515ffd83dbSDimitry Andric       auto TruncMIB = MIRBuilder.buildTrunc(NarrowTy, MO1);
11525ffd83dbSDimitry Andric       MO1.setReg(TruncMIB.getReg(0));
11538bcb0991SDimitry Andric 
11548bcb0991SDimitry Andric       MachineOperand &MO2 = MI.getOperand(0);
11558bcb0991SDimitry Andric       Register DstExt = MRI.createGenericVirtualRegister(NarrowTy);
11568bcb0991SDimitry Andric       MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
11575ffd83dbSDimitry Andric       MIRBuilder.buildSExt(MO2, DstExt);
11588bcb0991SDimitry Andric       MO2.setReg(DstExt);
11598bcb0991SDimitry Andric       Observer.changedInstr(MI);
11608bcb0991SDimitry Andric       return Legalized;
11618bcb0991SDimitry Andric     }
11628bcb0991SDimitry Andric 
11638bcb0991SDimitry Andric     // Break it apart. Components below the extension point are unmodified. The
11648bcb0991SDimitry Andric     // component containing the extension point becomes a narrower SEXT_INREG.
11658bcb0991SDimitry Andric     // Components above it are ashr'd from the component containing the
11668bcb0991SDimitry Andric     // extension point.
11678bcb0991SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
11688bcb0991SDimitry Andric       return UnableToLegalize;
11698bcb0991SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
11708bcb0991SDimitry Andric 
11718bcb0991SDimitry Andric     // List the registers where the destination will be scattered.
11728bcb0991SDimitry Andric     SmallVector<Register, 2> DstRegs;
11738bcb0991SDimitry Andric     // List the registers where the source will be split.
11748bcb0991SDimitry Andric     SmallVector<Register, 2> SrcRegs;
11758bcb0991SDimitry Andric 
11768bcb0991SDimitry Andric     // Create all the temporary registers.
11778bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
11788bcb0991SDimitry Andric       Register SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
11798bcb0991SDimitry Andric 
11808bcb0991SDimitry Andric       SrcRegs.push_back(SrcReg);
11818bcb0991SDimitry Andric     }
11828bcb0991SDimitry Andric 
11838bcb0991SDimitry Andric     // Explode the big arguments into smaller chunks.
11845ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge(SrcRegs, MI.getOperand(1));
11858bcb0991SDimitry Andric 
11868bcb0991SDimitry Andric     Register AshrCstReg =
11878bcb0991SDimitry Andric         MIRBuilder.buildConstant(NarrowTy, NarrowTy.getScalarSizeInBits() - 1)
11885ffd83dbSDimitry Andric             .getReg(0);
11898bcb0991SDimitry Andric     Register FullExtensionReg = 0;
11908bcb0991SDimitry Andric     Register PartialExtensionReg = 0;
11918bcb0991SDimitry Andric 
11928bcb0991SDimitry Andric     // Do the operation on each small part.
11938bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
11948bcb0991SDimitry Andric       if ((i + 1) * NarrowTy.getScalarSizeInBits() < SizeInBits)
11958bcb0991SDimitry Andric         DstRegs.push_back(SrcRegs[i]);
11968bcb0991SDimitry Andric       else if (i * NarrowTy.getScalarSizeInBits() > SizeInBits) {
11978bcb0991SDimitry Andric         assert(PartialExtensionReg &&
11988bcb0991SDimitry Andric                "Expected to visit partial extension before full");
11998bcb0991SDimitry Andric         if (FullExtensionReg) {
12008bcb0991SDimitry Andric           DstRegs.push_back(FullExtensionReg);
12018bcb0991SDimitry Andric           continue;
12028bcb0991SDimitry Andric         }
12035ffd83dbSDimitry Andric         DstRegs.push_back(
12045ffd83dbSDimitry Andric             MIRBuilder.buildAShr(NarrowTy, PartialExtensionReg, AshrCstReg)
12055ffd83dbSDimitry Andric                 .getReg(0));
12068bcb0991SDimitry Andric         FullExtensionReg = DstRegs.back();
12078bcb0991SDimitry Andric       } else {
12088bcb0991SDimitry Andric         DstRegs.push_back(
12098bcb0991SDimitry Andric             MIRBuilder
12108bcb0991SDimitry Andric                 .buildInstr(
12118bcb0991SDimitry Andric                     TargetOpcode::G_SEXT_INREG, {NarrowTy},
12128bcb0991SDimitry Andric                     {SrcRegs[i], SizeInBits % NarrowTy.getScalarSizeInBits()})
12135ffd83dbSDimitry Andric                 .getReg(0));
12148bcb0991SDimitry Andric         PartialExtensionReg = DstRegs.back();
12158bcb0991SDimitry Andric       }
12168bcb0991SDimitry Andric     }
12178bcb0991SDimitry Andric 
12188bcb0991SDimitry Andric     // Gather the destination registers into the final destination.
12198bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
12208bcb0991SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
12218bcb0991SDimitry Andric     MI.eraseFromParent();
12228bcb0991SDimitry Andric     return Legalized;
12238bcb0991SDimitry Andric   }
1224480093f4SDimitry Andric   case TargetOpcode::G_BSWAP:
1225480093f4SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
1226480093f4SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
1227480093f4SDimitry Andric       return UnableToLegalize;
1228480093f4SDimitry Andric 
1229480093f4SDimitry Andric     Observer.changingInstr(MI);
1230480093f4SDimitry Andric     SmallVector<Register, 2> SrcRegs, DstRegs;
1231480093f4SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
1232480093f4SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
1233480093f4SDimitry Andric 
1234480093f4SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
1235480093f4SDimitry Andric       auto DstPart = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
1236480093f4SDimitry Andric                                            {SrcRegs[NumParts - 1 - i]});
1237480093f4SDimitry Andric       DstRegs.push_back(DstPart.getReg(0));
1238480093f4SDimitry Andric     }
1239480093f4SDimitry Andric 
12405ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
1241480093f4SDimitry Andric 
1242480093f4SDimitry Andric     Observer.changedInstr(MI);
1243480093f4SDimitry Andric     MI.eraseFromParent();
1244480093f4SDimitry Andric     return Legalized;
1245480093f4SDimitry Andric   }
1246*e8d8bef9SDimitry Andric   case TargetOpcode::G_PTR_ADD:
12475ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
12485ffd83dbSDimitry Andric     if (TypeIdx != 1)
12495ffd83dbSDimitry Andric       return UnableToLegalize;
12505ffd83dbSDimitry Andric     Observer.changingInstr(MI);
12515ffd83dbSDimitry Andric     narrowScalarSrc(MI, NarrowTy, 2);
12525ffd83dbSDimitry Andric     Observer.changedInstr(MI);
12535ffd83dbSDimitry Andric     return Legalized;
12540b57cec5SDimitry Andric   }
1255*e8d8bef9SDimitry Andric   case TargetOpcode::G_FPTOUI: {
1256*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
1257*e8d8bef9SDimitry Andric       return UnableToLegalize;
1258*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
1259*e8d8bef9SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
1260*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
1261*e8d8bef9SDimitry Andric     return Legalized;
1262*e8d8bef9SDimitry Andric   }
1263*e8d8bef9SDimitry Andric   case TargetOpcode::G_FPTOSI: {
1264*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
1265*e8d8bef9SDimitry Andric       return UnableToLegalize;
1266*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
1267*e8d8bef9SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_SEXT);
1268*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
1269*e8d8bef9SDimitry Andric     return Legalized;
1270*e8d8bef9SDimitry Andric   }
1271*e8d8bef9SDimitry Andric   case TargetOpcode::G_FPEXT:
1272*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
1273*e8d8bef9SDimitry Andric       return UnableToLegalize;
1274*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
1275*e8d8bef9SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_FPEXT);
1276*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
1277*e8d8bef9SDimitry Andric     return Legalized;
12780b57cec5SDimitry Andric   }
12795ffd83dbSDimitry Andric }
12805ffd83dbSDimitry Andric 
12815ffd83dbSDimitry Andric Register LegalizerHelper::coerceToScalar(Register Val) {
12825ffd83dbSDimitry Andric   LLT Ty = MRI.getType(Val);
12835ffd83dbSDimitry Andric   if (Ty.isScalar())
12845ffd83dbSDimitry Andric     return Val;
12855ffd83dbSDimitry Andric 
12865ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
12875ffd83dbSDimitry Andric   LLT NewTy = LLT::scalar(Ty.getSizeInBits());
12885ffd83dbSDimitry Andric   if (Ty.isPointer()) {
12895ffd83dbSDimitry Andric     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
12905ffd83dbSDimitry Andric       return Register();
12915ffd83dbSDimitry Andric     return MIRBuilder.buildPtrToInt(NewTy, Val).getReg(0);
12925ffd83dbSDimitry Andric   }
12935ffd83dbSDimitry Andric 
12945ffd83dbSDimitry Andric   Register NewVal = Val;
12955ffd83dbSDimitry Andric 
12965ffd83dbSDimitry Andric   assert(Ty.isVector());
12975ffd83dbSDimitry Andric   LLT EltTy = Ty.getElementType();
12985ffd83dbSDimitry Andric   if (EltTy.isPointer())
12995ffd83dbSDimitry Andric     NewVal = MIRBuilder.buildPtrToInt(NewTy, NewVal).getReg(0);
13005ffd83dbSDimitry Andric   return MIRBuilder.buildBitcast(NewTy, NewVal).getReg(0);
13015ffd83dbSDimitry Andric }
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric void LegalizerHelper::widenScalarSrc(MachineInstr &MI, LLT WideTy,
13040b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned ExtOpcode) {
13050b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13065ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MO});
13075ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
13080b57cec5SDimitry Andric }
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric void LegalizerHelper::narrowScalarSrc(MachineInstr &MI, LLT NarrowTy,
13110b57cec5SDimitry Andric                                       unsigned OpIdx) {
13120b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13135ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildTrunc(NarrowTy, MO);
13145ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
13150b57cec5SDimitry Andric }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric void LegalizerHelper::widenScalarDst(MachineInstr &MI, LLT WideTy,
13180b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned TruncOpcode) {
13190b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13200b57cec5SDimitry Andric   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
13210b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13225ffd83dbSDimitry Andric   MIRBuilder.buildInstr(TruncOpcode, {MO}, {DstExt});
13230b57cec5SDimitry Andric   MO.setReg(DstExt);
13240b57cec5SDimitry Andric }
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric void LegalizerHelper::narrowScalarDst(MachineInstr &MI, LLT NarrowTy,
13270b57cec5SDimitry Andric                                       unsigned OpIdx, unsigned ExtOpcode) {
13280b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13290b57cec5SDimitry Andric   Register DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
13300b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13315ffd83dbSDimitry Andric   MIRBuilder.buildInstr(ExtOpcode, {MO}, {DstTrunc});
13320b57cec5SDimitry Andric   MO.setReg(DstTrunc);
13330b57cec5SDimitry Andric }
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorDst(MachineInstr &MI, LLT WideTy,
13360b57cec5SDimitry Andric                                             unsigned OpIdx) {
13370b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13380b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1339*e8d8bef9SDimitry Andric   MO.setReg(widenWithUnmerge(WideTy, MO.getReg()));
13400b57cec5SDimitry Andric }
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorSrc(MachineInstr &MI, LLT MoreTy,
13430b57cec5SDimitry Andric                                             unsigned OpIdx) {
13440b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric   LLT OldTy = MRI.getType(MO.getReg());
13470b57cec5SDimitry Andric   unsigned OldElts = OldTy.getNumElements();
13480b57cec5SDimitry Andric   unsigned NewElts = MoreTy.getNumElements();
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric   unsigned NumParts = NewElts / OldElts;
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   // Use concat_vectors if the result is a multiple of the number of elements.
13530b57cec5SDimitry Andric   if (NumParts * OldElts == NewElts) {
13540b57cec5SDimitry Andric     SmallVector<Register, 8> Parts;
13550b57cec5SDimitry Andric     Parts.push_back(MO.getReg());
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric     Register ImpDef = MIRBuilder.buildUndef(OldTy).getReg(0);
13580b57cec5SDimitry Andric     for (unsigned I = 1; I != NumParts; ++I)
13590b57cec5SDimitry Andric       Parts.push_back(ImpDef);
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric     auto Concat = MIRBuilder.buildConcatVectors(MoreTy, Parts);
13620b57cec5SDimitry Andric     MO.setReg(Concat.getReg(0));
13630b57cec5SDimitry Andric     return;
13640b57cec5SDimitry Andric   }
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   Register MoreReg = MRI.createGenericVirtualRegister(MoreTy);
13670b57cec5SDimitry Andric   Register ImpDef = MIRBuilder.buildUndef(MoreTy).getReg(0);
13680b57cec5SDimitry Andric   MIRBuilder.buildInsert(MoreReg, ImpDef, MO.getReg(), 0);
13690b57cec5SDimitry Andric   MO.setReg(MoreReg);
13700b57cec5SDimitry Andric }
13710b57cec5SDimitry Andric 
13725ffd83dbSDimitry Andric void LegalizerHelper::bitcastSrc(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
13735ffd83dbSDimitry Andric   MachineOperand &Op = MI.getOperand(OpIdx);
13745ffd83dbSDimitry Andric   Op.setReg(MIRBuilder.buildBitcast(CastTy, Op).getReg(0));
13755ffd83dbSDimitry Andric }
13765ffd83dbSDimitry Andric 
13775ffd83dbSDimitry Andric void LegalizerHelper::bitcastDst(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
13785ffd83dbSDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
13795ffd83dbSDimitry Andric   Register CastDst = MRI.createGenericVirtualRegister(CastTy);
13805ffd83dbSDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13815ffd83dbSDimitry Andric   MIRBuilder.buildBitcast(MO, CastDst);
13825ffd83dbSDimitry Andric   MO.setReg(CastDst);
13835ffd83dbSDimitry Andric }
13845ffd83dbSDimitry Andric 
13850b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
13860b57cec5SDimitry Andric LegalizerHelper::widenScalarMergeValues(MachineInstr &MI, unsigned TypeIdx,
13870b57cec5SDimitry Andric                                         LLT WideTy) {
13880b57cec5SDimitry Andric   if (TypeIdx != 1)
13890b57cec5SDimitry Andric     return UnableToLegalize;
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
13920b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
13930b57cec5SDimitry Andric   if (DstTy.isVector())
13940b57cec5SDimitry Andric     return UnableToLegalize;
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
13970b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src1);
13980b57cec5SDimitry Andric   const int DstSize = DstTy.getSizeInBits();
13990b57cec5SDimitry Andric   const int SrcSize = SrcTy.getSizeInBits();
14000b57cec5SDimitry Andric   const int WideSize = WideTy.getSizeInBits();
14010b57cec5SDimitry Andric   const int NumMerge = (DstSize + WideSize - 1) / WideSize;
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   unsigned NumOps = MI.getNumOperands();
14040b57cec5SDimitry Andric   unsigned NumSrc = MI.getNumOperands() - 1;
14050b57cec5SDimitry Andric   unsigned PartSize = DstTy.getSizeInBits() / NumSrc;
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric   if (WideSize >= DstSize) {
14080b57cec5SDimitry Andric     // Directly pack the bits in the target type.
14090b57cec5SDimitry Andric     Register ResultReg = MIRBuilder.buildZExt(WideTy, Src1).getReg(0);
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric     for (unsigned I = 2; I != NumOps; ++I) {
14120b57cec5SDimitry Andric       const unsigned Offset = (I - 1) * PartSize;
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric       Register SrcReg = MI.getOperand(I).getReg();
14150b57cec5SDimitry Andric       assert(MRI.getType(SrcReg) == LLT::scalar(PartSize));
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric       auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
14180b57cec5SDimitry Andric 
14198bcb0991SDimitry Andric       Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
14200b57cec5SDimitry Andric         MRI.createGenericVirtualRegister(WideTy);
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
14230b57cec5SDimitry Andric       auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
14240b57cec5SDimitry Andric       MIRBuilder.buildOr(NextResult, ResultReg, Shl);
14250b57cec5SDimitry Andric       ResultReg = NextResult;
14260b57cec5SDimitry Andric     }
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric     if (WideSize > DstSize)
14290b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg, ResultReg);
14308bcb0991SDimitry Andric     else if (DstTy.isPointer())
14318bcb0991SDimitry Andric       MIRBuilder.buildIntToPtr(DstReg, ResultReg);
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric     MI.eraseFromParent();
14340b57cec5SDimitry Andric     return Legalized;
14350b57cec5SDimitry Andric   }
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   // Unmerge the original values to the GCD type, and recombine to the next
14380b57cec5SDimitry Andric   // multiple greater than the original type.
14390b57cec5SDimitry Andric   //
14400b57cec5SDimitry Andric   // %3:_(s12) = G_MERGE_VALUES %0:_(s4), %1:_(s4), %2:_(s4) -> s6
14410b57cec5SDimitry Andric   // %4:_(s2), %5:_(s2) = G_UNMERGE_VALUES %0
14420b57cec5SDimitry Andric   // %6:_(s2), %7:_(s2) = G_UNMERGE_VALUES %1
14430b57cec5SDimitry Andric   // %8:_(s2), %9:_(s2) = G_UNMERGE_VALUES %2
14440b57cec5SDimitry Andric   // %10:_(s6) = G_MERGE_VALUES %4, %5, %6
14450b57cec5SDimitry Andric   // %11:_(s6) = G_MERGE_VALUES %7, %8, %9
14460b57cec5SDimitry Andric   // %12:_(s12) = G_MERGE_VALUES %10, %11
14470b57cec5SDimitry Andric   //
14480b57cec5SDimitry Andric   // Padding with undef if necessary:
14490b57cec5SDimitry Andric   //
14500b57cec5SDimitry Andric   // %2:_(s8) = G_MERGE_VALUES %0:_(s4), %1:_(s4) -> s6
14510b57cec5SDimitry Andric   // %3:_(s2), %4:_(s2) = G_UNMERGE_VALUES %0
14520b57cec5SDimitry Andric   // %5:_(s2), %6:_(s2) = G_UNMERGE_VALUES %1
14530b57cec5SDimitry Andric   // %7:_(s2) = G_IMPLICIT_DEF
14540b57cec5SDimitry Andric   // %8:_(s6) = G_MERGE_VALUES %3, %4, %5
14550b57cec5SDimitry Andric   // %9:_(s6) = G_MERGE_VALUES %6, %7, %7
14560b57cec5SDimitry Andric   // %10:_(s12) = G_MERGE_VALUES %8, %9
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   const int GCD = greatestCommonDivisor(SrcSize, WideSize);
14590b57cec5SDimitry Andric   LLT GCDTy = LLT::scalar(GCD);
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric   SmallVector<Register, 8> Parts;
14620b57cec5SDimitry Andric   SmallVector<Register, 8> NewMergeRegs;
14630b57cec5SDimitry Andric   SmallVector<Register, 8> Unmerges;
14640b57cec5SDimitry Andric   LLT WideDstTy = LLT::scalar(NumMerge * WideSize);
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   // Decompose the original operands if they don't evenly divide.
14670b57cec5SDimitry Andric   for (int I = 1, E = MI.getNumOperands(); I != E; ++I) {
14680b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
14690b57cec5SDimitry Andric     if (GCD == SrcSize) {
14700b57cec5SDimitry Andric       Unmerges.push_back(SrcReg);
14710b57cec5SDimitry Andric     } else {
14720b57cec5SDimitry Andric       auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
14730b57cec5SDimitry Andric       for (int J = 0, JE = Unmerge->getNumOperands() - 1; J != JE; ++J)
14740b57cec5SDimitry Andric         Unmerges.push_back(Unmerge.getReg(J));
14750b57cec5SDimitry Andric     }
14760b57cec5SDimitry Andric   }
14770b57cec5SDimitry Andric 
14780b57cec5SDimitry Andric   // Pad with undef to the next size that is a multiple of the requested size.
14790b57cec5SDimitry Andric   if (static_cast<int>(Unmerges.size()) != NumMerge * WideSize) {
14800b57cec5SDimitry Andric     Register UndefReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
14810b57cec5SDimitry Andric     for (int I = Unmerges.size(); I != NumMerge * WideSize; ++I)
14820b57cec5SDimitry Andric       Unmerges.push_back(UndefReg);
14830b57cec5SDimitry Andric   }
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric   const int PartsPerGCD = WideSize / GCD;
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   // Build merges of each piece.
14880b57cec5SDimitry Andric   ArrayRef<Register> Slicer(Unmerges);
14890b57cec5SDimitry Andric   for (int I = 0; I != NumMerge; ++I, Slicer = Slicer.drop_front(PartsPerGCD)) {
14900b57cec5SDimitry Andric     auto Merge = MIRBuilder.buildMerge(WideTy, Slicer.take_front(PartsPerGCD));
14910b57cec5SDimitry Andric     NewMergeRegs.push_back(Merge.getReg(0));
14920b57cec5SDimitry Andric   }
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric   // A truncate may be necessary if the requested type doesn't evenly divide the
14950b57cec5SDimitry Andric   // original result type.
14960b57cec5SDimitry Andric   if (DstTy.getSizeInBits() == WideDstTy.getSizeInBits()) {
14970b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, NewMergeRegs);
14980b57cec5SDimitry Andric   } else {
14990b57cec5SDimitry Andric     auto FinalMerge = MIRBuilder.buildMerge(WideDstTy, NewMergeRegs);
15000b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, FinalMerge.getReg(0));
15010b57cec5SDimitry Andric   }
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   MI.eraseFromParent();
15040b57cec5SDimitry Andric   return Legalized;
15050b57cec5SDimitry Andric }
15060b57cec5SDimitry Andric 
1507*e8d8bef9SDimitry Andric Register LegalizerHelper::widenWithUnmerge(LLT WideTy, Register OrigReg) {
1508*e8d8bef9SDimitry Andric   Register WideReg = MRI.createGenericVirtualRegister(WideTy);
1509*e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(OrigReg);
1510*e8d8bef9SDimitry Andric   LLT LCMTy = getLCMType(WideTy, OrigTy);
1511*e8d8bef9SDimitry Andric 
1512*e8d8bef9SDimitry Andric   const int NumMergeParts = LCMTy.getSizeInBits() / WideTy.getSizeInBits();
1513*e8d8bef9SDimitry Andric   const int NumUnmergeParts = LCMTy.getSizeInBits() / OrigTy.getSizeInBits();
1514*e8d8bef9SDimitry Andric 
1515*e8d8bef9SDimitry Andric   Register UnmergeSrc = WideReg;
1516*e8d8bef9SDimitry Andric 
1517*e8d8bef9SDimitry Andric   // Create a merge to the LCM type, padding with undef
1518*e8d8bef9SDimitry Andric   // %0:_(<3 x s32>) = G_FOO => <4 x s32>
1519*e8d8bef9SDimitry Andric   // =>
1520*e8d8bef9SDimitry Andric   // %1:_(<4 x s32>) = G_FOO
1521*e8d8bef9SDimitry Andric   // %2:_(<4 x s32>) = G_IMPLICIT_DEF
1522*e8d8bef9SDimitry Andric   // %3:_(<12 x s32>) = G_CONCAT_VECTORS %1, %2, %2
1523*e8d8bef9SDimitry Andric   // %0:_(<3 x s32>), %4:_, %5:_, %6:_ = G_UNMERGE_VALUES %3
1524*e8d8bef9SDimitry Andric   if (NumMergeParts > 1) {
1525*e8d8bef9SDimitry Andric     Register Undef = MIRBuilder.buildUndef(WideTy).getReg(0);
1526*e8d8bef9SDimitry Andric     SmallVector<Register, 8> MergeParts(NumMergeParts, Undef);
1527*e8d8bef9SDimitry Andric     MergeParts[0] = WideReg;
1528*e8d8bef9SDimitry Andric     UnmergeSrc = MIRBuilder.buildMerge(LCMTy, MergeParts).getReg(0);
1529*e8d8bef9SDimitry Andric   }
1530*e8d8bef9SDimitry Andric 
1531*e8d8bef9SDimitry Andric   // Unmerge to the original register and pad with dead defs.
1532*e8d8bef9SDimitry Andric   SmallVector<Register, 8> UnmergeResults(NumUnmergeParts);
1533*e8d8bef9SDimitry Andric   UnmergeResults[0] = OrigReg;
1534*e8d8bef9SDimitry Andric   for (int I = 1; I != NumUnmergeParts; ++I)
1535*e8d8bef9SDimitry Andric     UnmergeResults[I] = MRI.createGenericVirtualRegister(OrigTy);
1536*e8d8bef9SDimitry Andric 
1537*e8d8bef9SDimitry Andric   MIRBuilder.buildUnmerge(UnmergeResults, UnmergeSrc);
1538*e8d8bef9SDimitry Andric   return WideReg;
1539*e8d8bef9SDimitry Andric }
1540*e8d8bef9SDimitry Andric 
15410b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
15420b57cec5SDimitry Andric LegalizerHelper::widenScalarUnmergeValues(MachineInstr &MI, unsigned TypeIdx,
15430b57cec5SDimitry Andric                                           LLT WideTy) {
15440b57cec5SDimitry Andric   if (TypeIdx != 0)
15450b57cec5SDimitry Andric     return UnableToLegalize;
15460b57cec5SDimitry Andric 
15475ffd83dbSDimitry Andric   int NumDst = MI.getNumOperands() - 1;
15480b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
15490b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
15505ffd83dbSDimitry Andric   if (SrcTy.isVector())
15510b57cec5SDimitry Andric     return UnableToLegalize;
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
15540b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
15550b57cec5SDimitry Andric   if (!DstTy.isScalar())
15560b57cec5SDimitry Andric     return UnableToLegalize;
15570b57cec5SDimitry Andric 
15585ffd83dbSDimitry Andric   if (WideTy.getSizeInBits() >= SrcTy.getSizeInBits()) {
15595ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
15605ffd83dbSDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
15615ffd83dbSDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace())) {
15625ffd83dbSDimitry Andric         LLVM_DEBUG(
15635ffd83dbSDimitry Andric             dbgs() << "Not casting non-integral address space integer\n");
15645ffd83dbSDimitry Andric         return UnableToLegalize;
15650b57cec5SDimitry Andric       }
15660b57cec5SDimitry Andric 
15675ffd83dbSDimitry Andric       SrcTy = LLT::scalar(SrcTy.getSizeInBits());
15685ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildPtrToInt(SrcTy, SrcReg).getReg(0);
15695ffd83dbSDimitry Andric     }
15700b57cec5SDimitry Andric 
15715ffd83dbSDimitry Andric     // Widen SrcTy to WideTy. This does not affect the result, but since the
15725ffd83dbSDimitry Andric     // user requested this size, it is probably better handled than SrcTy and
15735ffd83dbSDimitry Andric     // should reduce the total number of legalization artifacts
15745ffd83dbSDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
15755ffd83dbSDimitry Andric       SrcTy = WideTy;
15765ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
15775ffd83dbSDimitry Andric     }
15780b57cec5SDimitry Andric 
15795ffd83dbSDimitry Andric     // Theres no unmerge type to target. Directly extract the bits from the
15805ffd83dbSDimitry Andric     // source type
15815ffd83dbSDimitry Andric     unsigned DstSize = DstTy.getSizeInBits();
15820b57cec5SDimitry Andric 
15835ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
15845ffd83dbSDimitry Andric     for (int I = 1; I != NumDst; ++I) {
15855ffd83dbSDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcTy, DstSize * I);
15865ffd83dbSDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcTy, SrcReg, ShiftAmt);
15875ffd83dbSDimitry Andric       MIRBuilder.buildTrunc(MI.getOperand(I), Shr);
15885ffd83dbSDimitry Andric     }
15895ffd83dbSDimitry Andric 
15905ffd83dbSDimitry Andric     MI.eraseFromParent();
15915ffd83dbSDimitry Andric     return Legalized;
15925ffd83dbSDimitry Andric   }
15935ffd83dbSDimitry Andric 
15945ffd83dbSDimitry Andric   // Extend the source to a wider type.
15955ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(SrcTy, WideTy);
15965ffd83dbSDimitry Andric 
15975ffd83dbSDimitry Andric   Register WideSrc = SrcReg;
15985ffd83dbSDimitry Andric   if (LCMTy.getSizeInBits() != SrcTy.getSizeInBits()) {
15995ffd83dbSDimitry Andric     // TODO: If this is an integral address space, cast to integer and anyext.
16005ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
16015ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Widening pointer source types not implemented\n");
16025ffd83dbSDimitry Andric       return UnableToLegalize;
16035ffd83dbSDimitry Andric     }
16045ffd83dbSDimitry Andric 
16055ffd83dbSDimitry Andric     WideSrc = MIRBuilder.buildAnyExt(LCMTy, WideSrc).getReg(0);
16065ffd83dbSDimitry Andric   }
16075ffd83dbSDimitry Andric 
16085ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(WideTy, WideSrc);
16095ffd83dbSDimitry Andric 
1610*e8d8bef9SDimitry Andric   // Create a sequence of unmerges and merges to the original results. Since we
1611*e8d8bef9SDimitry Andric   // may have widened the source, we will need to pad the results with dead defs
1612*e8d8bef9SDimitry Andric   // to cover the source register.
1613*e8d8bef9SDimitry Andric   // e.g. widen s48 to s64:
1614*e8d8bef9SDimitry Andric   // %1:_(s48), %2:_(s48) = G_UNMERGE_VALUES %0:_(s96)
16155ffd83dbSDimitry Andric   //
16165ffd83dbSDimitry Andric   // =>
1617*e8d8bef9SDimitry Andric   //  %4:_(s192) = G_ANYEXT %0:_(s96)
1618*e8d8bef9SDimitry Andric   //  %5:_(s64), %6, %7 = G_UNMERGE_VALUES %4 ; Requested unmerge
1619*e8d8bef9SDimitry Andric   //  ; unpack to GCD type, with extra dead defs
1620*e8d8bef9SDimitry Andric   //  %8:_(s16), %9, %10, %11 = G_UNMERGE_VALUES %5:_(s64)
1621*e8d8bef9SDimitry Andric   //  %12:_(s16), %13, dead %14, dead %15 = G_UNMERGE_VALUES %6:_(s64)
1622*e8d8bef9SDimitry Andric   //  dead %16:_(s16), dead %17, dead %18, dead %18 = G_UNMERGE_VALUES %7:_(s64)
1623*e8d8bef9SDimitry Andric   //  %1:_(s48) = G_MERGE_VALUES %8:_(s16), %9, %10   ; Remerge to destination
1624*e8d8bef9SDimitry Andric   //  %2:_(s48) = G_MERGE_VALUES %11:_(s16), %12, %13 ; Remerge to destination
1625*e8d8bef9SDimitry Andric   const LLT GCDTy = getGCDType(WideTy, DstTy);
16265ffd83dbSDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
1627*e8d8bef9SDimitry Andric   const int PartsPerRemerge = DstTy.getSizeInBits() / GCDTy.getSizeInBits();
1628*e8d8bef9SDimitry Andric 
1629*e8d8bef9SDimitry Andric   // Directly unmerge to the destination without going through a GCD type
1630*e8d8bef9SDimitry Andric   // if possible
1631*e8d8bef9SDimitry Andric   if (PartsPerRemerge == 1) {
16325ffd83dbSDimitry Andric     const int PartsPerUnmerge = WideTy.getSizeInBits() / DstTy.getSizeInBits();
16335ffd83dbSDimitry Andric 
16345ffd83dbSDimitry Andric     for (int I = 0; I != NumUnmerge; ++I) {
16355ffd83dbSDimitry Andric       auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
16365ffd83dbSDimitry Andric 
16375ffd83dbSDimitry Andric       for (int J = 0; J != PartsPerUnmerge; ++J) {
16385ffd83dbSDimitry Andric         int Idx = I * PartsPerUnmerge + J;
16395ffd83dbSDimitry Andric         if (Idx < NumDst)
16405ffd83dbSDimitry Andric           MIB.addDef(MI.getOperand(Idx).getReg());
16415ffd83dbSDimitry Andric         else {
16425ffd83dbSDimitry Andric           // Create dead def for excess components.
16435ffd83dbSDimitry Andric           MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
16445ffd83dbSDimitry Andric         }
16455ffd83dbSDimitry Andric       }
16465ffd83dbSDimitry Andric 
16475ffd83dbSDimitry Andric       MIB.addUse(Unmerge.getReg(I));
16485ffd83dbSDimitry Andric     }
1649*e8d8bef9SDimitry Andric   } else {
1650*e8d8bef9SDimitry Andric     SmallVector<Register, 16> Parts;
1651*e8d8bef9SDimitry Andric     for (int J = 0; J != NumUnmerge; ++J)
1652*e8d8bef9SDimitry Andric       extractGCDType(Parts, GCDTy, Unmerge.getReg(J));
1653*e8d8bef9SDimitry Andric 
1654*e8d8bef9SDimitry Andric     SmallVector<Register, 8> RemergeParts;
1655*e8d8bef9SDimitry Andric     for (int I = 0; I != NumDst; ++I) {
1656*e8d8bef9SDimitry Andric       for (int J = 0; J < PartsPerRemerge; ++J) {
1657*e8d8bef9SDimitry Andric         const int Idx = I * PartsPerRemerge + J;
1658*e8d8bef9SDimitry Andric         RemergeParts.emplace_back(Parts[Idx]);
1659*e8d8bef9SDimitry Andric       }
1660*e8d8bef9SDimitry Andric 
1661*e8d8bef9SDimitry Andric       MIRBuilder.buildMerge(MI.getOperand(I).getReg(), RemergeParts);
1662*e8d8bef9SDimitry Andric       RemergeParts.clear();
1663*e8d8bef9SDimitry Andric     }
1664*e8d8bef9SDimitry Andric   }
16655ffd83dbSDimitry Andric 
16665ffd83dbSDimitry Andric   MI.eraseFromParent();
16670b57cec5SDimitry Andric   return Legalized;
16680b57cec5SDimitry Andric }
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
16710b57cec5SDimitry Andric LegalizerHelper::widenScalarExtract(MachineInstr &MI, unsigned TypeIdx,
16720b57cec5SDimitry Andric                                     LLT WideTy) {
16730b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
16740b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
16750b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
16780b57cec5SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   if (TypeIdx == 0) {
16810b57cec5SDimitry Andric     if (SrcTy.isVector() || DstTy.isVector())
16820b57cec5SDimitry Andric       return UnableToLegalize;
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric     SrcOp Src(SrcReg);
16850b57cec5SDimitry Andric     if (SrcTy.isPointer()) {
16860b57cec5SDimitry Andric       // Extracts from pointers can be handled only if they are really just
16870b57cec5SDimitry Andric       // simple integers.
16880b57cec5SDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
16890b57cec5SDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace()))
16900b57cec5SDimitry Andric         return UnableToLegalize;
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric       LLT SrcAsIntTy = LLT::scalar(SrcTy.getSizeInBits());
16930b57cec5SDimitry Andric       Src = MIRBuilder.buildPtrToInt(SrcAsIntTy, Src);
16940b57cec5SDimitry Andric       SrcTy = SrcAsIntTy;
16950b57cec5SDimitry Andric     }
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric     if (DstTy.isPointer())
16980b57cec5SDimitry Andric       return UnableToLegalize;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric     if (Offset == 0) {
17010b57cec5SDimitry Andric       // Avoid a shift in the degenerate case.
17020b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg,
17030b57cec5SDimitry Andric                             MIRBuilder.buildAnyExtOrTrunc(WideTy, Src));
17040b57cec5SDimitry Andric       MI.eraseFromParent();
17050b57cec5SDimitry Andric       return Legalized;
17060b57cec5SDimitry Andric     }
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric     // Do a shift in the source type.
17090b57cec5SDimitry Andric     LLT ShiftTy = SrcTy;
17100b57cec5SDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
17110b57cec5SDimitry Andric       Src = MIRBuilder.buildAnyExt(WideTy, Src);
17120b57cec5SDimitry Andric       ShiftTy = WideTy;
1713*e8d8bef9SDimitry Andric     }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric     auto LShr = MIRBuilder.buildLShr(
17160b57cec5SDimitry Andric       ShiftTy, Src, MIRBuilder.buildConstant(ShiftTy, Offset));
17170b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, LShr);
17180b57cec5SDimitry Andric     MI.eraseFromParent();
17190b57cec5SDimitry Andric     return Legalized;
17200b57cec5SDimitry Andric   }
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric   if (SrcTy.isScalar()) {
17230b57cec5SDimitry Andric     Observer.changingInstr(MI);
17240b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17250b57cec5SDimitry Andric     Observer.changedInstr(MI);
17260b57cec5SDimitry Andric     return Legalized;
17270b57cec5SDimitry Andric   }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   if (!SrcTy.isVector())
17300b57cec5SDimitry Andric     return UnableToLegalize;
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   if (DstTy != SrcTy.getElementType())
17330b57cec5SDimitry Andric     return UnableToLegalize;
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   if (Offset % SrcTy.getScalarSizeInBits() != 0)
17360b57cec5SDimitry Andric     return UnableToLegalize;
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   Observer.changingInstr(MI);
17390b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17400b57cec5SDimitry Andric 
17410b57cec5SDimitry Andric   MI.getOperand(2).setImm((WideTy.getSizeInBits() / SrcTy.getSizeInBits()) *
17420b57cec5SDimitry Andric                           Offset);
17430b57cec5SDimitry Andric   widenScalarDst(MI, WideTy.getScalarType(), 0);
17440b57cec5SDimitry Andric   Observer.changedInstr(MI);
17450b57cec5SDimitry Andric   return Legalized;
17460b57cec5SDimitry Andric }
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
17490b57cec5SDimitry Andric LegalizerHelper::widenScalarInsert(MachineInstr &MI, unsigned TypeIdx,
17500b57cec5SDimitry Andric                                    LLT WideTy) {
1751*e8d8bef9SDimitry Andric   if (TypeIdx != 0 || WideTy.isVector())
17520b57cec5SDimitry Andric     return UnableToLegalize;
17530b57cec5SDimitry Andric   Observer.changingInstr(MI);
17540b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
17550b57cec5SDimitry Andric   widenScalarDst(MI, WideTy);
17560b57cec5SDimitry Andric   Observer.changedInstr(MI);
17570b57cec5SDimitry Andric   return Legalized;
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
1761*e8d8bef9SDimitry Andric LegalizerHelper::widenScalarAddoSubo(MachineInstr &MI, unsigned TypeIdx,
1762*e8d8bef9SDimitry Andric                                      LLT WideTy) {
1763*e8d8bef9SDimitry Andric   if (TypeIdx == 1)
1764*e8d8bef9SDimitry Andric     return UnableToLegalize; // TODO
1765*e8d8bef9SDimitry Andric   unsigned Op = MI.getOpcode();
1766*e8d8bef9SDimitry Andric   unsigned Opcode = Op == TargetOpcode::G_UADDO || Op == TargetOpcode::G_SADDO
1767*e8d8bef9SDimitry Andric                         ? TargetOpcode::G_ADD
1768*e8d8bef9SDimitry Andric                         : TargetOpcode::G_SUB;
1769*e8d8bef9SDimitry Andric   unsigned ExtOpcode =
1770*e8d8bef9SDimitry Andric       Op == TargetOpcode::G_UADDO || Op == TargetOpcode::G_USUBO
1771*e8d8bef9SDimitry Andric           ? TargetOpcode::G_ZEXT
1772*e8d8bef9SDimitry Andric           : TargetOpcode::G_SEXT;
1773*e8d8bef9SDimitry Andric   auto LHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(2)});
1774*e8d8bef9SDimitry Andric   auto RHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(3)});
1775*e8d8bef9SDimitry Andric   // Do the arithmetic in the larger type.
1776*e8d8bef9SDimitry Andric   auto NewOp = MIRBuilder.buildInstr(Opcode, {WideTy}, {LHSExt, RHSExt});
1777*e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(MI.getOperand(0).getReg());
1778*e8d8bef9SDimitry Andric   auto TruncOp = MIRBuilder.buildTrunc(OrigTy, NewOp);
1779*e8d8bef9SDimitry Andric   auto ExtOp = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {TruncOp});
1780*e8d8bef9SDimitry Andric   // There is no overflow if the ExtOp is the same as NewOp.
1781*e8d8bef9SDimitry Andric   MIRBuilder.buildICmp(CmpInst::ICMP_NE, MI.getOperand(1), NewOp, ExtOp);
1782*e8d8bef9SDimitry Andric   // Now trunc the NewOp to the original result.
1783*e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(MI.getOperand(0), NewOp);
1784*e8d8bef9SDimitry Andric   MI.eraseFromParent();
1785*e8d8bef9SDimitry Andric   return Legalized;
1786*e8d8bef9SDimitry Andric }
1787*e8d8bef9SDimitry Andric 
1788*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
1789*e8d8bef9SDimitry Andric LegalizerHelper::widenScalarAddSubShlSat(MachineInstr &MI, unsigned TypeIdx,
17905ffd83dbSDimitry Andric                                          LLT WideTy) {
17915ffd83dbSDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SADDSAT ||
1792*e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSUBSAT ||
1793*e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSHLSAT;
1794*e8d8bef9SDimitry Andric   bool IsShift = MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
1795*e8d8bef9SDimitry Andric                  MI.getOpcode() == TargetOpcode::G_USHLSAT;
17965ffd83dbSDimitry Andric   // We can convert this to:
17975ffd83dbSDimitry Andric   //   1. Any extend iN to iM
17985ffd83dbSDimitry Andric   //   2. SHL by M-N
1799*e8d8bef9SDimitry Andric   //   3. [US][ADD|SUB|SHL]SAT
18005ffd83dbSDimitry Andric   //   4. L/ASHR by M-N
18015ffd83dbSDimitry Andric   //
18025ffd83dbSDimitry Andric   // It may be more efficient to lower this to a min and a max operation in
18035ffd83dbSDimitry Andric   // the higher precision arithmetic if the promoted operation isn't legal,
18045ffd83dbSDimitry Andric   // but this decision is up to the target's lowering request.
18055ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
18060b57cec5SDimitry Andric 
18075ffd83dbSDimitry Andric   unsigned NewBits = WideTy.getScalarSizeInBits();
18085ffd83dbSDimitry Andric   unsigned SHLAmount = NewBits - MRI.getType(DstReg).getScalarSizeInBits();
18095ffd83dbSDimitry Andric 
1810*e8d8bef9SDimitry Andric   // Shifts must zero-extend the RHS to preserve the unsigned quantity, and
1811*e8d8bef9SDimitry Andric   // must not left shift the RHS to preserve the shift amount.
18125ffd83dbSDimitry Andric   auto LHS = MIRBuilder.buildAnyExt(WideTy, MI.getOperand(1));
1813*e8d8bef9SDimitry Andric   auto RHS = IsShift ? MIRBuilder.buildZExt(WideTy, MI.getOperand(2))
1814*e8d8bef9SDimitry Andric                      : MIRBuilder.buildAnyExt(WideTy, MI.getOperand(2));
18155ffd83dbSDimitry Andric   auto ShiftK = MIRBuilder.buildConstant(WideTy, SHLAmount);
18165ffd83dbSDimitry Andric   auto ShiftL = MIRBuilder.buildShl(WideTy, LHS, ShiftK);
1817*e8d8bef9SDimitry Andric   auto ShiftR = IsShift ? RHS : MIRBuilder.buildShl(WideTy, RHS, ShiftK);
18185ffd83dbSDimitry Andric 
18195ffd83dbSDimitry Andric   auto WideInst = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy},
18205ffd83dbSDimitry Andric                                         {ShiftL, ShiftR}, MI.getFlags());
18215ffd83dbSDimitry Andric 
18225ffd83dbSDimitry Andric   // Use a shift that will preserve the number of sign bits when the trunc is
18235ffd83dbSDimitry Andric   // folded away.
18245ffd83dbSDimitry Andric   auto Result = IsSigned ? MIRBuilder.buildAShr(WideTy, WideInst, ShiftK)
18255ffd83dbSDimitry Andric                          : MIRBuilder.buildLShr(WideTy, WideInst, ShiftK);
18265ffd83dbSDimitry Andric 
18275ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(DstReg, Result);
18285ffd83dbSDimitry Andric   MI.eraseFromParent();
18295ffd83dbSDimitry Andric   return Legalized;
18305ffd83dbSDimitry Andric }
18315ffd83dbSDimitry Andric 
18325ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
18335ffd83dbSDimitry Andric LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
18340b57cec5SDimitry Andric   switch (MI.getOpcode()) {
18350b57cec5SDimitry Andric   default:
18360b57cec5SDimitry Andric     return UnableToLegalize;
18370b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
18380b57cec5SDimitry Andric     return widenScalarExtract(MI, TypeIdx, WideTy);
18390b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
18400b57cec5SDimitry Andric     return widenScalarInsert(MI, TypeIdx, WideTy);
18410b57cec5SDimitry Andric   case TargetOpcode::G_MERGE_VALUES:
18420b57cec5SDimitry Andric     return widenScalarMergeValues(MI, TypeIdx, WideTy);
18430b57cec5SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES:
18440b57cec5SDimitry Andric     return widenScalarUnmergeValues(MI, TypeIdx, WideTy);
1845*e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
1846*e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
18470b57cec5SDimitry Andric   case TargetOpcode::G_UADDO:
1848*e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBO:
1849*e8d8bef9SDimitry Andric     return widenScalarAddoSubo(MI, TypeIdx, WideTy);
18505ffd83dbSDimitry Andric   case TargetOpcode::G_SADDSAT:
18515ffd83dbSDimitry Andric   case TargetOpcode::G_SSUBSAT:
1852*e8d8bef9SDimitry Andric   case TargetOpcode::G_SSHLSAT:
18535ffd83dbSDimitry Andric   case TargetOpcode::G_UADDSAT:
18545ffd83dbSDimitry Andric   case TargetOpcode::G_USUBSAT:
1855*e8d8bef9SDimitry Andric   case TargetOpcode::G_USHLSAT:
1856*e8d8bef9SDimitry Andric     return widenScalarAddSubShlSat(MI, TypeIdx, WideTy);
18570b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
18580b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
18590b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
18600b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
18610b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP: {
18620b57cec5SDimitry Andric     if (TypeIdx == 0) {
18630b57cec5SDimitry Andric       Observer.changingInstr(MI);
18640b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
18650b57cec5SDimitry Andric       Observer.changedInstr(MI);
18660b57cec5SDimitry Andric       return Legalized;
18670b57cec5SDimitry Andric     }
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric     // First ZEXT the input.
18720b57cec5SDimitry Andric     auto MIBSrc = MIRBuilder.buildZExt(WideTy, SrcReg);
18730b57cec5SDimitry Andric     LLT CurTy = MRI.getType(SrcReg);
18740b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTTZ) {
18750b57cec5SDimitry Andric       // The count is the same in the larger type except if the original
18760b57cec5SDimitry Andric       // value was zero.  This can be handled by setting the bit just off
18770b57cec5SDimitry Andric       // the top of the original type.
18780b57cec5SDimitry Andric       auto TopBit =
18790b57cec5SDimitry Andric           APInt::getOneBitSet(WideTy.getSizeInBits(), CurTy.getSizeInBits());
18800b57cec5SDimitry Andric       MIBSrc = MIRBuilder.buildOr(
18810b57cec5SDimitry Andric         WideTy, MIBSrc, MIRBuilder.buildConstant(WideTy, TopBit));
18820b57cec5SDimitry Andric     }
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric     // Perform the operation at the larger size.
18850b57cec5SDimitry Andric     auto MIBNewOp = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy}, {MIBSrc});
18860b57cec5SDimitry Andric     // This is already the correct result for CTPOP and CTTZs
18870b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTLZ ||
18880b57cec5SDimitry Andric         MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF) {
18890b57cec5SDimitry Andric       // The correct result is NewOp - (Difference in widety and current ty).
18900b57cec5SDimitry Andric       unsigned SizeDiff = WideTy.getSizeInBits() - CurTy.getSizeInBits();
18915ffd83dbSDimitry Andric       MIBNewOp = MIRBuilder.buildSub(
18925ffd83dbSDimitry Andric           WideTy, MIBNewOp, MIRBuilder.buildConstant(WideTy, SizeDiff));
18930b57cec5SDimitry Andric     }
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric     MIRBuilder.buildZExtOrTrunc(MI.getOperand(0), MIBNewOp);
18960b57cec5SDimitry Andric     MI.eraseFromParent();
18970b57cec5SDimitry Andric     return Legalized;
18980b57cec5SDimitry Andric   }
18990b57cec5SDimitry Andric   case TargetOpcode::G_BSWAP: {
19000b57cec5SDimitry Andric     Observer.changingInstr(MI);
19010b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric     Register ShrReg = MRI.createGenericVirtualRegister(WideTy);
19040b57cec5SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
19050b57cec5SDimitry Andric     Register ShiftAmtReg = MRI.createGenericVirtualRegister(WideTy);
19060b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric     MI.getOperand(0).setReg(DstExt);
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric     LLT Ty = MRI.getType(DstReg);
19130b57cec5SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
19140b57cec5SDimitry Andric     MIRBuilder.buildConstant(ShiftAmtReg, DiffBits);
19155ffd83dbSDimitry Andric     MIRBuilder.buildLShr(ShrReg, DstExt, ShiftAmtReg);
19160b57cec5SDimitry Andric 
19170b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, ShrReg);
19180b57cec5SDimitry Andric     Observer.changedInstr(MI);
19190b57cec5SDimitry Andric     return Legalized;
19200b57cec5SDimitry Andric   }
19218bcb0991SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
19228bcb0991SDimitry Andric     Observer.changingInstr(MI);
19238bcb0991SDimitry Andric 
19248bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
19258bcb0991SDimitry Andric     LLT Ty = MRI.getType(DstReg);
19268bcb0991SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
19278bcb0991SDimitry Andric 
19288bcb0991SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
19298bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19308bcb0991SDimitry Andric     MI.getOperand(0).setReg(DstExt);
19318bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
19328bcb0991SDimitry Andric 
19338bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, DiffBits);
19348bcb0991SDimitry Andric     auto Shift = MIRBuilder.buildLShr(WideTy, DstExt, ShiftAmt);
19358bcb0991SDimitry Andric     MIRBuilder.buildTrunc(DstReg, Shift);
19368bcb0991SDimitry Andric     Observer.changedInstr(MI);
19378bcb0991SDimitry Andric     return Legalized;
19388bcb0991SDimitry Andric   }
19395ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
19405ffd83dbSDimitry Andric     Observer.changingInstr(MI);
19415ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19425ffd83dbSDimitry Andric     widenScalarDst(MI, WideTy);
19435ffd83dbSDimitry Andric     Observer.changedInstr(MI);
19445ffd83dbSDimitry Andric     return Legalized;
19455ffd83dbSDimitry Andric 
19460b57cec5SDimitry Andric   case TargetOpcode::G_ADD:
19470b57cec5SDimitry Andric   case TargetOpcode::G_AND:
19480b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
19490b57cec5SDimitry Andric   case TargetOpcode::G_OR:
19500b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
19510b57cec5SDimitry Andric   case TargetOpcode::G_SUB:
19520b57cec5SDimitry Andric     // Perform operation at larger width (any extension is fines here, high bits
19530b57cec5SDimitry Andric     // don't affect the result) and then truncate the result back to the
19540b57cec5SDimitry Andric     // original type.
19550b57cec5SDimitry Andric     Observer.changingInstr(MI);
19560b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19570b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
19580b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
19590b57cec5SDimitry Andric     Observer.changedInstr(MI);
19600b57cec5SDimitry Andric     return Legalized;
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric   case TargetOpcode::G_SHL:
19630b57cec5SDimitry Andric     Observer.changingInstr(MI);
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric     if (TypeIdx == 0) {
19660b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
19670b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
19680b57cec5SDimitry Andric     } else {
19690b57cec5SDimitry Andric       assert(TypeIdx == 1);
19700b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
19710b57cec5SDimitry Andric       // unsigned integer:
19720b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
19730b57cec5SDimitry Andric     }
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric     Observer.changedInstr(MI);
19760b57cec5SDimitry Andric     return Legalized;
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
19790b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
19800b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
19810b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
19820b57cec5SDimitry Andric     Observer.changingInstr(MI);
19830b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
19840b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
19850b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
19860b57cec5SDimitry Andric     Observer.changedInstr(MI);
19870b57cec5SDimitry Andric     return Legalized;
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric   case TargetOpcode::G_ASHR:
19900b57cec5SDimitry Andric   case TargetOpcode::G_LSHR:
19910b57cec5SDimitry Andric     Observer.changingInstr(MI);
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric     if (TypeIdx == 0) {
19940b57cec5SDimitry Andric       unsigned CvtOp = MI.getOpcode() == TargetOpcode::G_ASHR ?
19950b57cec5SDimitry Andric         TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, CvtOp);
19980b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
19990b57cec5SDimitry Andric     } else {
20000b57cec5SDimitry Andric       assert(TypeIdx == 1);
20010b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
20020b57cec5SDimitry Andric       // unsigned integer:
20030b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
20040b57cec5SDimitry Andric     }
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric     Observer.changedInstr(MI);
20070b57cec5SDimitry Andric     return Legalized;
20080b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
20090b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
20100b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
20110b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
20120b57cec5SDimitry Andric     Observer.changingInstr(MI);
20130b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
20140b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
20150b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
20160b57cec5SDimitry Andric     Observer.changedInstr(MI);
20170b57cec5SDimitry Andric     return Legalized;
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
20200b57cec5SDimitry Andric     Observer.changingInstr(MI);
20210b57cec5SDimitry Andric     if (TypeIdx == 0) {
20220b57cec5SDimitry Andric       // Perform operation at larger width (any extension is fine here, high
20230b57cec5SDimitry Andric       // bits don't affect the result) and then truncate the result back to the
20240b57cec5SDimitry Andric       // original type.
20250b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
20260b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
20270b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
20280b57cec5SDimitry Andric     } else {
20290b57cec5SDimitry Andric       bool IsVec = MRI.getType(MI.getOperand(1).getReg()).isVector();
20300b57cec5SDimitry Andric       // Explicit extension is required here since high bits affect the result.
20310b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, MIRBuilder.getBoolExtOp(IsVec, false));
20320b57cec5SDimitry Andric     }
20330b57cec5SDimitry Andric     Observer.changedInstr(MI);
20340b57cec5SDimitry Andric     return Legalized;
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
20370b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
20380b57cec5SDimitry Andric     Observer.changingInstr(MI);
20398bcb0991SDimitry Andric 
20408bcb0991SDimitry Andric     if (TypeIdx == 0)
20410b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
20428bcb0991SDimitry Andric     else
20438bcb0991SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
20448bcb0991SDimitry Andric 
20450b57cec5SDimitry Andric     Observer.changedInstr(MI);
20460b57cec5SDimitry Andric     return Legalized;
20470b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
20480b57cec5SDimitry Andric     Observer.changingInstr(MI);
2049*e8d8bef9SDimitry Andric 
2050*e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2051*e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2052*e8d8bef9SDimitry Andric     else
20530b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
2054*e8d8bef9SDimitry Andric 
20550b57cec5SDimitry Andric     Observer.changedInstr(MI);
20560b57cec5SDimitry Andric     return Legalized;
20570b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
20580b57cec5SDimitry Andric     Observer.changingInstr(MI);
2059*e8d8bef9SDimitry Andric 
2060*e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2061*e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2062*e8d8bef9SDimitry Andric     else
20630b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
2064*e8d8bef9SDimitry Andric 
20650b57cec5SDimitry Andric     Observer.changedInstr(MI);
20660b57cec5SDimitry Andric     return Legalized;
20670b57cec5SDimitry Andric   case TargetOpcode::G_LOAD:
20680b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
20690b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
20700b57cec5SDimitry Andric     Observer.changingInstr(MI);
20710b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
20720b57cec5SDimitry Andric     Observer.changedInstr(MI);
20730b57cec5SDimitry Andric     return Legalized;
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
20760b57cec5SDimitry Andric     if (TypeIdx != 0)
20770b57cec5SDimitry Andric       return UnableToLegalize;
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2080*e8d8bef9SDimitry Andric     if (!Ty.isScalar())
20810b57cec5SDimitry Andric       return UnableToLegalize;
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric     Observer.changingInstr(MI);
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric     unsigned ExtType = Ty.getScalarSizeInBits() == 1 ?
20860b57cec5SDimitry Andric       TargetOpcode::G_ZEXT : TargetOpcode::G_ANYEXT;
20870b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, ExtType);
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric     Observer.changedInstr(MI);
20900b57cec5SDimitry Andric     return Legalized;
20910b57cec5SDimitry Andric   }
20920b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
20930b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
20940b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
2095480093f4SDimitry Andric     unsigned ExtOpc = LI.getExtOpcodeForWideningConstant(
2096480093f4SDimitry Andric         MRI.getType(MI.getOperand(0).getReg()));
2097480093f4SDimitry Andric     assert((ExtOpc == TargetOpcode::G_ZEXT || ExtOpc == TargetOpcode::G_SEXT ||
2098480093f4SDimitry Andric             ExtOpc == TargetOpcode::G_ANYEXT) &&
2099480093f4SDimitry Andric            "Illegal Extend");
2100480093f4SDimitry Andric     const APInt &SrcVal = SrcMO.getCImm()->getValue();
2101480093f4SDimitry Andric     const APInt &Val = (ExtOpc == TargetOpcode::G_SEXT)
2102480093f4SDimitry Andric                            ? SrcVal.sext(WideTy.getSizeInBits())
2103480093f4SDimitry Andric                            : SrcVal.zext(WideTy.getSizeInBits());
21040b57cec5SDimitry Andric     Observer.changingInstr(MI);
21050b57cec5SDimitry Andric     SrcMO.setCImm(ConstantInt::get(Ctx, Val));
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21080b57cec5SDimitry Andric     Observer.changedInstr(MI);
21090b57cec5SDimitry Andric     return Legalized;
21100b57cec5SDimitry Andric   }
21110b57cec5SDimitry Andric   case TargetOpcode::G_FCONSTANT: {
21120b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
21130b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
21140b57cec5SDimitry Andric     APFloat Val = SrcMO.getFPImm()->getValueAPF();
21150b57cec5SDimitry Andric     bool LosesInfo;
21160b57cec5SDimitry Andric     switch (WideTy.getSizeInBits()) {
21170b57cec5SDimitry Andric     case 32:
21180b57cec5SDimitry Andric       Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
21190b57cec5SDimitry Andric                   &LosesInfo);
21200b57cec5SDimitry Andric       break;
21210b57cec5SDimitry Andric     case 64:
21220b57cec5SDimitry Andric       Val.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
21230b57cec5SDimitry Andric                   &LosesInfo);
21240b57cec5SDimitry Andric       break;
21250b57cec5SDimitry Andric     default:
21260b57cec5SDimitry Andric       return UnableToLegalize;
21270b57cec5SDimitry Andric     }
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric     assert(!LosesInfo && "extend should always be lossless");
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric     Observer.changingInstr(MI);
21320b57cec5SDimitry Andric     SrcMO.setFPImm(ConstantFP::get(Ctx, Val));
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
21350b57cec5SDimitry Andric     Observer.changedInstr(MI);
21360b57cec5SDimitry Andric     return Legalized;
21370b57cec5SDimitry Andric   }
21380b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
21390b57cec5SDimitry Andric     Observer.changingInstr(MI);
21400b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21410b57cec5SDimitry Andric     Observer.changedInstr(MI);
21420b57cec5SDimitry Andric     return Legalized;
21430b57cec5SDimitry Andric   }
21440b57cec5SDimitry Andric   case TargetOpcode::G_BRCOND:
21450b57cec5SDimitry Andric     Observer.changingInstr(MI);
21460b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, MIRBuilder.getBoolExtOp(false, false));
21470b57cec5SDimitry Andric     Observer.changedInstr(MI);
21480b57cec5SDimitry Andric     return Legalized;
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   case TargetOpcode::G_FCMP:
21510b57cec5SDimitry Andric     Observer.changingInstr(MI);
21520b57cec5SDimitry Andric     if (TypeIdx == 0)
21530b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
21540b57cec5SDimitry Andric     else {
21550b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
21560b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_FPEXT);
21570b57cec5SDimitry Andric     }
21580b57cec5SDimitry Andric     Observer.changedInstr(MI);
21590b57cec5SDimitry Andric     return Legalized;
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric   case TargetOpcode::G_ICMP:
21620b57cec5SDimitry Andric     Observer.changingInstr(MI);
21630b57cec5SDimitry Andric     if (TypeIdx == 0)
21640b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
21650b57cec5SDimitry Andric     else {
21660b57cec5SDimitry Andric       unsigned ExtOpcode = CmpInst::isSigned(static_cast<CmpInst::Predicate>(
21670b57cec5SDimitry Andric                                MI.getOperand(1).getPredicate()))
21680b57cec5SDimitry Andric                                ? TargetOpcode::G_SEXT
21690b57cec5SDimitry Andric                                : TargetOpcode::G_ZEXT;
21700b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, ExtOpcode);
21710b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, ExtOpcode);
21720b57cec5SDimitry Andric     }
21730b57cec5SDimitry Andric     Observer.changedInstr(MI);
21740b57cec5SDimitry Andric     return Legalized;
21750b57cec5SDimitry Andric 
2176480093f4SDimitry Andric   case TargetOpcode::G_PTR_ADD:
2177480093f4SDimitry Andric     assert(TypeIdx == 1 && "unable to legalize pointer of G_PTR_ADD");
21780b57cec5SDimitry Andric     Observer.changingInstr(MI);
21790b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
21800b57cec5SDimitry Andric     Observer.changedInstr(MI);
21810b57cec5SDimitry Andric     return Legalized;
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   case TargetOpcode::G_PHI: {
21840b57cec5SDimitry Andric     assert(TypeIdx == 0 && "Expecting only Idx 0");
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric     Observer.changingInstr(MI);
21870b57cec5SDimitry Andric     for (unsigned I = 1; I < MI.getNumOperands(); I += 2) {
21880b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
21890b57cec5SDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
21900b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_ANYEXT);
21910b57cec5SDimitry Andric     }
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
21940b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
21950b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
21960b57cec5SDimitry Andric     Observer.changedInstr(MI);
21970b57cec5SDimitry Andric     return Legalized;
21980b57cec5SDimitry Andric   }
21990b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
22000b57cec5SDimitry Andric     if (TypeIdx == 0) {
22010b57cec5SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
22020b57cec5SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
22030b57cec5SDimitry Andric       Observer.changingInstr(MI);
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric       widenScalarSrc(MI, LLT::vector(VecTy.getNumElements(),
22060b57cec5SDimitry Andric                                      WideTy.getSizeInBits()),
22070b57cec5SDimitry Andric                      1, TargetOpcode::G_SEXT);
22080b57cec5SDimitry Andric 
22090b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
22100b57cec5SDimitry Andric       Observer.changedInstr(MI);
22110b57cec5SDimitry Andric       return Legalized;
22120b57cec5SDimitry Andric     }
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric     if (TypeIdx != 2)
22150b57cec5SDimitry Andric       return UnableToLegalize;
22160b57cec5SDimitry Andric     Observer.changingInstr(MI);
2217480093f4SDimitry Andric     // TODO: Probably should be zext
22180b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
22190b57cec5SDimitry Andric     Observer.changedInstr(MI);
22200b57cec5SDimitry Andric     return Legalized;
22210b57cec5SDimitry Andric   }
2222480093f4SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
2223480093f4SDimitry Andric     if (TypeIdx == 1) {
2224480093f4SDimitry Andric       Observer.changingInstr(MI);
2225480093f4SDimitry Andric 
2226480093f4SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
2227480093f4SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
2228480093f4SDimitry Andric       LLT WideVecTy = LLT::vector(VecTy.getNumElements(), WideTy);
2229480093f4SDimitry Andric 
2230480093f4SDimitry Andric       widenScalarSrc(MI, WideVecTy, 1, TargetOpcode::G_ANYEXT);
2231480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2232480093f4SDimitry Andric       widenScalarDst(MI, WideVecTy, 0);
2233480093f4SDimitry Andric       Observer.changedInstr(MI);
2234480093f4SDimitry Andric       return Legalized;
2235480093f4SDimitry Andric     }
2236480093f4SDimitry Andric 
2237480093f4SDimitry Andric     if (TypeIdx == 2) {
2238480093f4SDimitry Andric       Observer.changingInstr(MI);
2239480093f4SDimitry Andric       // TODO: Probably should be zext
2240480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2241480093f4SDimitry Andric       Observer.changedInstr(MI);
22425ffd83dbSDimitry Andric       return Legalized;
2243480093f4SDimitry Andric     }
2244480093f4SDimitry Andric 
22455ffd83dbSDimitry Andric     return UnableToLegalize;
2246480093f4SDimitry Andric   }
22470b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
22480b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
22490b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
22500b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
22518bcb0991SDimitry Andric   case TargetOpcode::G_FMAD:
22520b57cec5SDimitry Andric   case TargetOpcode::G_FNEG:
22530b57cec5SDimitry Andric   case TargetOpcode::G_FABS:
22540b57cec5SDimitry Andric   case TargetOpcode::G_FCANONICALIZE:
22550b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM:
22560b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM:
22570b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
22580b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
22590b57cec5SDimitry Andric   case TargetOpcode::G_FMINIMUM:
22600b57cec5SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
22610b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
22620b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
22630b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
22640b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
22650b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
22660b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
22670b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
22680b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
22690b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
22700b57cec5SDimitry Andric   case TargetOpcode::G_FRINT:
22710b57cec5SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
22720b57cec5SDimitry Andric   case TargetOpcode::G_FSQRT:
22730b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
22740b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
22750b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
22760b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_TRUNC:
22770b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
2278*e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
22790b57cec5SDimitry Andric     assert(TypeIdx == 0);
22800b57cec5SDimitry Andric     Observer.changingInstr(MI);
22810b57cec5SDimitry Andric 
22820b57cec5SDimitry Andric     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
22830b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_FPEXT);
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
22860b57cec5SDimitry Andric     Observer.changedInstr(MI);
22870b57cec5SDimitry Andric     return Legalized;
2288*e8d8bef9SDimitry Andric   case TargetOpcode::G_FPOWI: {
2289*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2290*e8d8bef9SDimitry Andric       return UnableToLegalize;
2291*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2292*e8d8bef9SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
2293*e8d8bef9SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2294*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2295*e8d8bef9SDimitry Andric     return Legalized;
2296*e8d8bef9SDimitry Andric   }
22970b57cec5SDimitry Andric   case TargetOpcode::G_INTTOPTR:
22980b57cec5SDimitry Andric     if (TypeIdx != 1)
22990b57cec5SDimitry Andric       return UnableToLegalize;
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric     Observer.changingInstr(MI);
23020b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
23030b57cec5SDimitry Andric     Observer.changedInstr(MI);
23040b57cec5SDimitry Andric     return Legalized;
23050b57cec5SDimitry Andric   case TargetOpcode::G_PTRTOINT:
23060b57cec5SDimitry Andric     if (TypeIdx != 0)
23070b57cec5SDimitry Andric       return UnableToLegalize;
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric     Observer.changingInstr(MI);
23100b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0);
23110b57cec5SDimitry Andric     Observer.changedInstr(MI);
23120b57cec5SDimitry Andric     return Legalized;
23130b57cec5SDimitry Andric   case TargetOpcode::G_BUILD_VECTOR: {
23140b57cec5SDimitry Andric     Observer.changingInstr(MI);
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric     const LLT WideEltTy = TypeIdx == 1 ? WideTy : WideTy.getElementType();
23170b57cec5SDimitry Andric     for (int I = 1, E = MI.getNumOperands(); I != E; ++I)
23180b57cec5SDimitry Andric       widenScalarSrc(MI, WideEltTy, I, TargetOpcode::G_ANYEXT);
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric     // Avoid changing the result vector type if the source element type was
23210b57cec5SDimitry Andric     // requested.
23220b57cec5SDimitry Andric     if (TypeIdx == 1) {
2323*e8d8bef9SDimitry Andric       MI.setDesc(MIRBuilder.getTII().get(TargetOpcode::G_BUILD_VECTOR_TRUNC));
23240b57cec5SDimitry Andric     } else {
23250b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
23260b57cec5SDimitry Andric     }
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric     Observer.changedInstr(MI);
23290b57cec5SDimitry Andric     return Legalized;
23300b57cec5SDimitry Andric   }
23318bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG:
23328bcb0991SDimitry Andric     if (TypeIdx != 0)
23338bcb0991SDimitry Andric       return UnableToLegalize;
23348bcb0991SDimitry Andric 
23358bcb0991SDimitry Andric     Observer.changingInstr(MI);
23368bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
23378bcb0991SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_TRUNC);
23388bcb0991SDimitry Andric     Observer.changedInstr(MI);
23398bcb0991SDimitry Andric     return Legalized;
23405ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
23415ffd83dbSDimitry Andric     if (TypeIdx != 1)
23425ffd83dbSDimitry Andric       return UnableToLegalize;
23435ffd83dbSDimitry Andric     Observer.changingInstr(MI);
23445ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
23455ffd83dbSDimitry Andric     Observer.changedInstr(MI);
23465ffd83dbSDimitry Andric     return Legalized;
23475ffd83dbSDimitry Andric   }
23485ffd83dbSDimitry Andric   }
23495ffd83dbSDimitry Andric }
23505ffd83dbSDimitry Andric 
23515ffd83dbSDimitry Andric static void getUnmergePieces(SmallVectorImpl<Register> &Pieces,
23525ffd83dbSDimitry Andric                              MachineIRBuilder &B, Register Src, LLT Ty) {
23535ffd83dbSDimitry Andric   auto Unmerge = B.buildUnmerge(Ty, Src);
23545ffd83dbSDimitry Andric   for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
23555ffd83dbSDimitry Andric     Pieces.push_back(Unmerge.getReg(I));
23565ffd83dbSDimitry Andric }
23575ffd83dbSDimitry Andric 
23585ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
23595ffd83dbSDimitry Andric LegalizerHelper::lowerBitcast(MachineInstr &MI) {
23605ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
23615ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
23625ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
23635ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
23645ffd83dbSDimitry Andric 
23655ffd83dbSDimitry Andric   if (SrcTy.isVector()) {
23665ffd83dbSDimitry Andric     LLT SrcEltTy = SrcTy.getElementType();
23675ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
23685ffd83dbSDimitry Andric 
23695ffd83dbSDimitry Andric     if (DstTy.isVector()) {
23705ffd83dbSDimitry Andric       int NumDstElt = DstTy.getNumElements();
23715ffd83dbSDimitry Andric       int NumSrcElt = SrcTy.getNumElements();
23725ffd83dbSDimitry Andric 
23735ffd83dbSDimitry Andric       LLT DstEltTy = DstTy.getElementType();
23745ffd83dbSDimitry Andric       LLT DstCastTy = DstEltTy; // Intermediate bitcast result type
23755ffd83dbSDimitry Andric       LLT SrcPartTy = SrcEltTy; // Original unmerge result type.
23765ffd83dbSDimitry Andric 
23775ffd83dbSDimitry Andric       // If there's an element size mismatch, insert intermediate casts to match
23785ffd83dbSDimitry Andric       // the result element type.
23795ffd83dbSDimitry Andric       if (NumSrcElt < NumDstElt) { // Source element type is larger.
23805ffd83dbSDimitry Andric         // %1:_(<4 x s8>) = G_BITCAST %0:_(<2 x s16>)
23815ffd83dbSDimitry Andric         //
23825ffd83dbSDimitry Andric         // =>
23835ffd83dbSDimitry Andric         //
23845ffd83dbSDimitry Andric         // %2:_(s16), %3:_(s16) = G_UNMERGE_VALUES %0
23855ffd83dbSDimitry Andric         // %3:_(<2 x s8>) = G_BITCAST %2
23865ffd83dbSDimitry Andric         // %4:_(<2 x s8>) = G_BITCAST %3
23875ffd83dbSDimitry Andric         // %1:_(<4 x s16>) = G_CONCAT_VECTORS %3, %4
23885ffd83dbSDimitry Andric         DstCastTy = LLT::vector(NumDstElt / NumSrcElt, DstEltTy);
23895ffd83dbSDimitry Andric         SrcPartTy = SrcEltTy;
23905ffd83dbSDimitry Andric       } else if (NumSrcElt > NumDstElt) { // Source element type is smaller.
23915ffd83dbSDimitry Andric         //
23925ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BITCAST %0:_(<4 x s8>)
23935ffd83dbSDimitry Andric         //
23945ffd83dbSDimitry Andric         // =>
23955ffd83dbSDimitry Andric         //
23965ffd83dbSDimitry Andric         // %2:_(<2 x s8>), %3:_(<2 x s8>) = G_UNMERGE_VALUES %0
23975ffd83dbSDimitry Andric         // %3:_(s16) = G_BITCAST %2
23985ffd83dbSDimitry Andric         // %4:_(s16) = G_BITCAST %3
23995ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BUILD_VECTOR %3, %4
24005ffd83dbSDimitry Andric         SrcPartTy = LLT::vector(NumSrcElt / NumDstElt, SrcEltTy);
24015ffd83dbSDimitry Andric         DstCastTy = DstEltTy;
24025ffd83dbSDimitry Andric       }
24035ffd83dbSDimitry Andric 
24045ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcPartTy);
24055ffd83dbSDimitry Andric       for (Register &SrcReg : SrcRegs)
24065ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(DstCastTy, SrcReg).getReg(0);
24075ffd83dbSDimitry Andric     } else
24085ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcEltTy);
24095ffd83dbSDimitry Andric 
24105ffd83dbSDimitry Andric     MIRBuilder.buildMerge(Dst, SrcRegs);
24115ffd83dbSDimitry Andric     MI.eraseFromParent();
24125ffd83dbSDimitry Andric     return Legalized;
24135ffd83dbSDimitry Andric   }
24145ffd83dbSDimitry Andric 
24155ffd83dbSDimitry Andric   if (DstTy.isVector()) {
24165ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
24175ffd83dbSDimitry Andric     getUnmergePieces(SrcRegs, MIRBuilder, Src, DstTy.getElementType());
24185ffd83dbSDimitry Andric     MIRBuilder.buildMerge(Dst, SrcRegs);
24195ffd83dbSDimitry Andric     MI.eraseFromParent();
24205ffd83dbSDimitry Andric     return Legalized;
24215ffd83dbSDimitry Andric   }
24225ffd83dbSDimitry Andric 
24235ffd83dbSDimitry Andric   return UnableToLegalize;
24245ffd83dbSDimitry Andric }
24255ffd83dbSDimitry Andric 
2426*e8d8bef9SDimitry Andric /// Figure out the bit offset into a register when coercing a vector index for
2427*e8d8bef9SDimitry Andric /// the wide element type. This is only for the case when promoting vector to
2428*e8d8bef9SDimitry Andric /// one with larger elements.
2429*e8d8bef9SDimitry Andric //
2430*e8d8bef9SDimitry Andric ///
2431*e8d8bef9SDimitry Andric /// %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2432*e8d8bef9SDimitry Andric /// %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2433*e8d8bef9SDimitry Andric static Register getBitcastWiderVectorElementOffset(MachineIRBuilder &B,
2434*e8d8bef9SDimitry Andric                                                    Register Idx,
2435*e8d8bef9SDimitry Andric                                                    unsigned NewEltSize,
2436*e8d8bef9SDimitry Andric                                                    unsigned OldEltSize) {
2437*e8d8bef9SDimitry Andric   const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2438*e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(Idx);
2439*e8d8bef9SDimitry Andric 
2440*e8d8bef9SDimitry Andric   // Now figure out the amount we need to shift to get the target bits.
2441*e8d8bef9SDimitry Andric   auto OffsetMask = B.buildConstant(
2442*e8d8bef9SDimitry Andric     IdxTy, ~(APInt::getAllOnesValue(IdxTy.getSizeInBits()) << Log2EltRatio));
2443*e8d8bef9SDimitry Andric   auto OffsetIdx = B.buildAnd(IdxTy, Idx, OffsetMask);
2444*e8d8bef9SDimitry Andric   return B.buildShl(IdxTy, OffsetIdx,
2445*e8d8bef9SDimitry Andric                     B.buildConstant(IdxTy, Log2_32(OldEltSize))).getReg(0);
2446*e8d8bef9SDimitry Andric }
2447*e8d8bef9SDimitry Andric 
2448*e8d8bef9SDimitry Andric /// Perform a G_EXTRACT_VECTOR_ELT in a different sized vector element. If this
2449*e8d8bef9SDimitry Andric /// is casting to a vector with a smaller element size, perform multiple element
2450*e8d8bef9SDimitry Andric /// extracts and merge the results. If this is coercing to a vector with larger
2451*e8d8bef9SDimitry Andric /// elements, index the bitcasted vector and extract the target element with bit
2452*e8d8bef9SDimitry Andric /// operations. This is intended to force the indexing in the native register
2453*e8d8bef9SDimitry Andric /// size for architectures that can dynamically index the register file.
24545ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
2455*e8d8bef9SDimitry Andric LegalizerHelper::bitcastExtractVectorElt(MachineInstr &MI, unsigned TypeIdx,
2456*e8d8bef9SDimitry Andric                                          LLT CastTy) {
2457*e8d8bef9SDimitry Andric   if (TypeIdx != 1)
2458*e8d8bef9SDimitry Andric     return UnableToLegalize;
2459*e8d8bef9SDimitry Andric 
2460*e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2461*e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
2462*e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(2).getReg();
2463*e8d8bef9SDimitry Andric   LLT SrcVecTy = MRI.getType(SrcVec);
2464*e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Idx);
2465*e8d8bef9SDimitry Andric 
2466*e8d8bef9SDimitry Andric   LLT SrcEltTy = SrcVecTy.getElementType();
2467*e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2468*e8d8bef9SDimitry Andric   unsigned OldNumElts = SrcVecTy.getNumElements();
2469*e8d8bef9SDimitry Andric 
2470*e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2471*e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2472*e8d8bef9SDimitry Andric 
2473*e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2474*e8d8bef9SDimitry Andric   const unsigned OldEltSize = SrcEltTy.getSizeInBits();
2475*e8d8bef9SDimitry Andric   if (NewNumElts > OldNumElts) {
2476*e8d8bef9SDimitry Andric     // Decreasing the vector element size
2477*e8d8bef9SDimitry Andric     //
2478*e8d8bef9SDimitry Andric     // e.g. i64 = extract_vector_elt x:v2i64, y:i32
2479*e8d8bef9SDimitry Andric     //  =>
2480*e8d8bef9SDimitry Andric     //  v4i32:castx = bitcast x:v2i64
2481*e8d8bef9SDimitry Andric     //
2482*e8d8bef9SDimitry Andric     // i64 = bitcast
2483*e8d8bef9SDimitry Andric     //   (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
2484*e8d8bef9SDimitry Andric     //                       (i32 (extract_vector_elt castx, (2 * y + 1)))
2485*e8d8bef9SDimitry Andric     //
2486*e8d8bef9SDimitry Andric     if (NewNumElts % OldNumElts != 0)
2487*e8d8bef9SDimitry Andric       return UnableToLegalize;
2488*e8d8bef9SDimitry Andric 
2489*e8d8bef9SDimitry Andric     // Type of the intermediate result vector.
2490*e8d8bef9SDimitry Andric     const unsigned NewEltsPerOldElt = NewNumElts / OldNumElts;
2491*e8d8bef9SDimitry Andric     LLT MidTy = LLT::scalarOrVector(NewEltsPerOldElt, NewEltTy);
2492*e8d8bef9SDimitry Andric 
2493*e8d8bef9SDimitry Andric     auto NewEltsPerOldEltK = MIRBuilder.buildConstant(IdxTy, NewEltsPerOldElt);
2494*e8d8bef9SDimitry Andric 
2495*e8d8bef9SDimitry Andric     SmallVector<Register, 8> NewOps(NewEltsPerOldElt);
2496*e8d8bef9SDimitry Andric     auto NewBaseIdx = MIRBuilder.buildMul(IdxTy, Idx, NewEltsPerOldEltK);
2497*e8d8bef9SDimitry Andric 
2498*e8d8bef9SDimitry Andric     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
2499*e8d8bef9SDimitry Andric       auto IdxOffset = MIRBuilder.buildConstant(IdxTy, I);
2500*e8d8bef9SDimitry Andric       auto TmpIdx = MIRBuilder.buildAdd(IdxTy, NewBaseIdx, IdxOffset);
2501*e8d8bef9SDimitry Andric       auto Elt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec, TmpIdx);
2502*e8d8bef9SDimitry Andric       NewOps[I] = Elt.getReg(0);
2503*e8d8bef9SDimitry Andric     }
2504*e8d8bef9SDimitry Andric 
2505*e8d8bef9SDimitry Andric     auto NewVec = MIRBuilder.buildBuildVector(MidTy, NewOps);
2506*e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, NewVec);
2507*e8d8bef9SDimitry Andric     MI.eraseFromParent();
2508*e8d8bef9SDimitry Andric     return Legalized;
2509*e8d8bef9SDimitry Andric   }
2510*e8d8bef9SDimitry Andric 
2511*e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2512*e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
2513*e8d8bef9SDimitry Andric       return UnableToLegalize;
2514*e8d8bef9SDimitry Andric 
2515*e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2516*e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2517*e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2518*e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
2519*e8d8bef9SDimitry Andric       return UnableToLegalize;
2520*e8d8bef9SDimitry Andric 
2521*e8d8bef9SDimitry Andric     // Increasing the vector element size.
2522*e8d8bef9SDimitry Andric     // %elt:_(small_elt) = G_EXTRACT_VECTOR_ELT %vec:_(<N x small_elt>), %idx
2523*e8d8bef9SDimitry Andric     //
2524*e8d8bef9SDimitry Andric     //   =>
2525*e8d8bef9SDimitry Andric     //
2526*e8d8bef9SDimitry Andric     // %cast = G_BITCAST %vec
2527*e8d8bef9SDimitry Andric     // %scaled_idx = G_LSHR %idx, Log2(DstEltSize / SrcEltSize)
2528*e8d8bef9SDimitry Andric     // %wide_elt  = G_EXTRACT_VECTOR_ELT %cast, %scaled_idx
2529*e8d8bef9SDimitry Andric     // %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2530*e8d8bef9SDimitry Andric     // %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2531*e8d8bef9SDimitry Andric     // %elt_bits = G_LSHR %wide_elt, %offset_bits
2532*e8d8bef9SDimitry Andric     // %elt = G_TRUNC %elt_bits
2533*e8d8bef9SDimitry Andric 
2534*e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2535*e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2536*e8d8bef9SDimitry Andric 
2537*e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2538*e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2539*e8d8bef9SDimitry Andric 
2540*e8d8bef9SDimitry Andric     Register WideElt = CastVec;
2541*e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2542*e8d8bef9SDimitry Andric       WideElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2543*e8d8bef9SDimitry Andric                                                      ScaledIdx).getReg(0);
2544*e8d8bef9SDimitry Andric     }
2545*e8d8bef9SDimitry Andric 
2546*e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2547*e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2548*e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2549*e8d8bef9SDimitry Andric 
2550*e8d8bef9SDimitry Andric     // Shift the wide element to get the target element.
2551*e8d8bef9SDimitry Andric     auto ExtractedBits = MIRBuilder.buildLShr(NewEltTy, WideElt, OffsetBits);
2552*e8d8bef9SDimitry Andric     MIRBuilder.buildTrunc(Dst, ExtractedBits);
2553*e8d8bef9SDimitry Andric     MI.eraseFromParent();
2554*e8d8bef9SDimitry Andric     return Legalized;
2555*e8d8bef9SDimitry Andric   }
2556*e8d8bef9SDimitry Andric 
2557*e8d8bef9SDimitry Andric   return UnableToLegalize;
2558*e8d8bef9SDimitry Andric }
2559*e8d8bef9SDimitry Andric 
2560*e8d8bef9SDimitry Andric /// Emit code to insert \p InsertReg into \p TargetRet at \p OffsetBits in \p
2561*e8d8bef9SDimitry Andric /// TargetReg, while preserving other bits in \p TargetReg.
2562*e8d8bef9SDimitry Andric ///
2563*e8d8bef9SDimitry Andric /// (InsertReg << Offset) | (TargetReg & ~(-1 >> InsertReg.size()) << Offset)
2564*e8d8bef9SDimitry Andric static Register buildBitFieldInsert(MachineIRBuilder &B,
2565*e8d8bef9SDimitry Andric                                     Register TargetReg, Register InsertReg,
2566*e8d8bef9SDimitry Andric                                     Register OffsetBits) {
2567*e8d8bef9SDimitry Andric   LLT TargetTy = B.getMRI()->getType(TargetReg);
2568*e8d8bef9SDimitry Andric   LLT InsertTy = B.getMRI()->getType(InsertReg);
2569*e8d8bef9SDimitry Andric   auto ZextVal = B.buildZExt(TargetTy, InsertReg);
2570*e8d8bef9SDimitry Andric   auto ShiftedInsertVal = B.buildShl(TargetTy, ZextVal, OffsetBits);
2571*e8d8bef9SDimitry Andric 
2572*e8d8bef9SDimitry Andric   // Produce a bitmask of the value to insert
2573*e8d8bef9SDimitry Andric   auto EltMask = B.buildConstant(
2574*e8d8bef9SDimitry Andric     TargetTy, APInt::getLowBitsSet(TargetTy.getSizeInBits(),
2575*e8d8bef9SDimitry Andric                                    InsertTy.getSizeInBits()));
2576*e8d8bef9SDimitry Andric   // Shift it into position
2577*e8d8bef9SDimitry Andric   auto ShiftedMask = B.buildShl(TargetTy, EltMask, OffsetBits);
2578*e8d8bef9SDimitry Andric   auto InvShiftedMask = B.buildNot(TargetTy, ShiftedMask);
2579*e8d8bef9SDimitry Andric 
2580*e8d8bef9SDimitry Andric   // Clear out the bits in the wide element
2581*e8d8bef9SDimitry Andric   auto MaskedOldElt = B.buildAnd(TargetTy, TargetReg, InvShiftedMask);
2582*e8d8bef9SDimitry Andric 
2583*e8d8bef9SDimitry Andric   // The value to insert has all zeros already, so stick it into the masked
2584*e8d8bef9SDimitry Andric   // wide element.
2585*e8d8bef9SDimitry Andric   return B.buildOr(TargetTy, MaskedOldElt, ShiftedInsertVal).getReg(0);
2586*e8d8bef9SDimitry Andric }
2587*e8d8bef9SDimitry Andric 
2588*e8d8bef9SDimitry Andric /// Perform a G_INSERT_VECTOR_ELT in a different sized vector element. If this
2589*e8d8bef9SDimitry Andric /// is increasing the element size, perform the indexing in the target element
2590*e8d8bef9SDimitry Andric /// type, and use bit operations to insert at the element position. This is
2591*e8d8bef9SDimitry Andric /// intended for architectures that can dynamically index the register file and
2592*e8d8bef9SDimitry Andric /// want to force indexing in the native register size.
2593*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2594*e8d8bef9SDimitry Andric LegalizerHelper::bitcastInsertVectorElt(MachineInstr &MI, unsigned TypeIdx,
2595*e8d8bef9SDimitry Andric                                         LLT CastTy) {
25965ffd83dbSDimitry Andric   if (TypeIdx != 0)
25975ffd83dbSDimitry Andric     return UnableToLegalize;
25985ffd83dbSDimitry Andric 
2599*e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2600*e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
2601*e8d8bef9SDimitry Andric   Register Val = MI.getOperand(2).getReg();
2602*e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(3).getReg();
2603*e8d8bef9SDimitry Andric 
2604*e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(Dst);
2605*e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Idx);
2606*e8d8bef9SDimitry Andric 
2607*e8d8bef9SDimitry Andric   LLT VecEltTy = VecTy.getElementType();
2608*e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2609*e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2610*e8d8bef9SDimitry Andric   const unsigned OldEltSize = VecEltTy.getSizeInBits();
2611*e8d8bef9SDimitry Andric 
2612*e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2613*e8d8bef9SDimitry Andric   unsigned OldNumElts = VecTy.getNumElements();
2614*e8d8bef9SDimitry Andric 
2615*e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2616*e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2617*e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
26185ffd83dbSDimitry Andric       return UnableToLegalize;
26195ffd83dbSDimitry Andric 
2620*e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2621*e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2622*e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2623*e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
26245ffd83dbSDimitry Andric       return UnableToLegalize;
26255ffd83dbSDimitry Andric 
2626*e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2627*e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2628*e8d8bef9SDimitry Andric 
2629*e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2630*e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2631*e8d8bef9SDimitry Andric 
2632*e8d8bef9SDimitry Andric     Register ExtractedElt = CastVec;
2633*e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2634*e8d8bef9SDimitry Andric       ExtractedElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2635*e8d8bef9SDimitry Andric                                                           ScaledIdx).getReg(0);
26365ffd83dbSDimitry Andric     }
26375ffd83dbSDimitry Andric 
2638*e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2639*e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2640*e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2641*e8d8bef9SDimitry Andric 
2642*e8d8bef9SDimitry Andric     Register InsertedElt = buildBitFieldInsert(MIRBuilder, ExtractedElt,
2643*e8d8bef9SDimitry Andric                                                Val, OffsetBits);
2644*e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2645*e8d8bef9SDimitry Andric       InsertedElt = MIRBuilder.buildInsertVectorElement(
2646*e8d8bef9SDimitry Andric         CastTy, CastVec, InsertedElt, ScaledIdx).getReg(0);
2647*e8d8bef9SDimitry Andric     }
2648*e8d8bef9SDimitry Andric 
2649*e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, InsertedElt);
2650*e8d8bef9SDimitry Andric     MI.eraseFromParent();
26515ffd83dbSDimitry Andric     return Legalized;
26525ffd83dbSDimitry Andric   }
2653*e8d8bef9SDimitry Andric 
26545ffd83dbSDimitry Andric   return UnableToLegalize;
26550b57cec5SDimitry Andric }
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
2658*e8d8bef9SDimitry Andric LegalizerHelper::lowerLoad(MachineInstr &MI) {
26590b57cec5SDimitry Andric   // Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
26600b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
26610b57cec5SDimitry Andric   Register PtrReg = MI.getOperand(1).getReg();
26620b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
26630b57cec5SDimitry Andric   auto &MMO = **MI.memoperands_begin();
26640b57cec5SDimitry Andric 
26658bcb0991SDimitry Andric   if (DstTy.getSizeInBits() == MMO.getSizeInBits()) {
26668bcb0991SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_LOAD) {
26678bcb0991SDimitry Andric       // This load needs splitting into power of 2 sized loads.
26688bcb0991SDimitry Andric       if (DstTy.isVector())
26690b57cec5SDimitry Andric         return UnableToLegalize;
26708bcb0991SDimitry Andric       if (isPowerOf2_32(DstTy.getSizeInBits()))
26718bcb0991SDimitry Andric         return UnableToLegalize; // Don't know what we're being asked to do.
26728bcb0991SDimitry Andric 
26738bcb0991SDimitry Andric       // Our strategy here is to generate anyextending loads for the smaller
26748bcb0991SDimitry Andric       // types up to next power-2 result type, and then combine the two larger
26758bcb0991SDimitry Andric       // result values together, before truncating back down to the non-pow-2
26768bcb0991SDimitry Andric       // type.
26778bcb0991SDimitry Andric       // E.g. v1 = i24 load =>
26785ffd83dbSDimitry Andric       // v2 = i32 zextload (2 byte)
26798bcb0991SDimitry Andric       // v3 = i32 load (1 byte)
26808bcb0991SDimitry Andric       // v4 = i32 shl v3, 16
26818bcb0991SDimitry Andric       // v5 = i32 or v4, v2
26828bcb0991SDimitry Andric       // v1 = i24 trunc v5
26838bcb0991SDimitry Andric       // By doing this we generate the correct truncate which should get
26848bcb0991SDimitry Andric       // combined away as an artifact with a matching extend.
26858bcb0991SDimitry Andric       uint64_t LargeSplitSize = PowerOf2Floor(DstTy.getSizeInBits());
26868bcb0991SDimitry Andric       uint64_t SmallSplitSize = DstTy.getSizeInBits() - LargeSplitSize;
26878bcb0991SDimitry Andric 
26888bcb0991SDimitry Andric       MachineFunction &MF = MIRBuilder.getMF();
26898bcb0991SDimitry Andric       MachineMemOperand *LargeMMO =
26908bcb0991SDimitry Andric         MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
26918bcb0991SDimitry Andric       MachineMemOperand *SmallMMO = MF.getMachineMemOperand(
26928bcb0991SDimitry Andric         &MMO, LargeSplitSize / 8, SmallSplitSize / 8);
26938bcb0991SDimitry Andric 
26948bcb0991SDimitry Andric       LLT PtrTy = MRI.getType(PtrReg);
26958bcb0991SDimitry Andric       unsigned AnyExtSize = NextPowerOf2(DstTy.getSizeInBits());
26968bcb0991SDimitry Andric       LLT AnyExtTy = LLT::scalar(AnyExtSize);
26978bcb0991SDimitry Andric       Register LargeLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
26988bcb0991SDimitry Andric       Register SmallLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
26995ffd83dbSDimitry Andric       auto LargeLoad = MIRBuilder.buildLoadInstr(
27005ffd83dbSDimitry Andric         TargetOpcode::G_ZEXTLOAD, LargeLdReg, PtrReg, *LargeMMO);
27018bcb0991SDimitry Andric 
27025ffd83dbSDimitry Andric       auto OffsetCst = MIRBuilder.buildConstant(
27035ffd83dbSDimitry Andric         LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2704480093f4SDimitry Andric       Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2705480093f4SDimitry Andric       auto SmallPtr =
2706480093f4SDimitry Andric         MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
27078bcb0991SDimitry Andric       auto SmallLoad = MIRBuilder.buildLoad(SmallLdReg, SmallPtr.getReg(0),
27088bcb0991SDimitry Andric                                             *SmallMMO);
27098bcb0991SDimitry Andric 
27108bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(AnyExtTy, LargeSplitSize);
27118bcb0991SDimitry Andric       auto Shift = MIRBuilder.buildShl(AnyExtTy, SmallLoad, ShiftAmt);
27128bcb0991SDimitry Andric       auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
27138bcb0991SDimitry Andric       MIRBuilder.buildTrunc(DstReg, {Or.getReg(0)});
27148bcb0991SDimitry Andric       MI.eraseFromParent();
27158bcb0991SDimitry Andric       return Legalized;
27168bcb0991SDimitry Andric     }
2717*e8d8bef9SDimitry Andric 
27180b57cec5SDimitry Andric     MIRBuilder.buildLoad(DstReg, PtrReg, MMO);
27190b57cec5SDimitry Andric     MI.eraseFromParent();
27200b57cec5SDimitry Andric     return Legalized;
27210b57cec5SDimitry Andric   }
27220b57cec5SDimitry Andric 
27230b57cec5SDimitry Andric   if (DstTy.isScalar()) {
27240b57cec5SDimitry Andric     Register TmpReg =
27250b57cec5SDimitry Andric       MRI.createGenericVirtualRegister(LLT::scalar(MMO.getSizeInBits()));
27260b57cec5SDimitry Andric     MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
27270b57cec5SDimitry Andric     switch (MI.getOpcode()) {
27280b57cec5SDimitry Andric     default:
27290b57cec5SDimitry Andric       llvm_unreachable("Unexpected opcode");
27300b57cec5SDimitry Andric     case TargetOpcode::G_LOAD:
2731*e8d8bef9SDimitry Andric       MIRBuilder.buildAnyExtOrTrunc(DstReg, TmpReg);
27320b57cec5SDimitry Andric       break;
27330b57cec5SDimitry Andric     case TargetOpcode::G_SEXTLOAD:
27340b57cec5SDimitry Andric       MIRBuilder.buildSExt(DstReg, TmpReg);
27350b57cec5SDimitry Andric       break;
27360b57cec5SDimitry Andric     case TargetOpcode::G_ZEXTLOAD:
27370b57cec5SDimitry Andric       MIRBuilder.buildZExt(DstReg, TmpReg);
27380b57cec5SDimitry Andric       break;
27390b57cec5SDimitry Andric     }
2740*e8d8bef9SDimitry Andric 
27410b57cec5SDimitry Andric     MI.eraseFromParent();
27420b57cec5SDimitry Andric     return Legalized;
27430b57cec5SDimitry Andric   }
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric   return UnableToLegalize;
27460b57cec5SDimitry Andric }
2747*e8d8bef9SDimitry Andric 
2748*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2749*e8d8bef9SDimitry Andric LegalizerHelper::lowerStore(MachineInstr &MI) {
27508bcb0991SDimitry Andric   // Lower a non-power of 2 store into multiple pow-2 stores.
27518bcb0991SDimitry Andric   // E.g. split an i24 store into an i16 store + i8 store.
27528bcb0991SDimitry Andric   // We do this by first extending the stored value to the next largest power
27538bcb0991SDimitry Andric   // of 2 type, and then using truncating stores to store the components.
27548bcb0991SDimitry Andric   // By doing this, likewise with G_LOAD, generate an extend that can be
27558bcb0991SDimitry Andric   // artifact-combined away instead of leaving behind extracts.
27568bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(0).getReg();
27578bcb0991SDimitry Andric   Register PtrReg = MI.getOperand(1).getReg();
27588bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
27598bcb0991SDimitry Andric   MachineMemOperand &MMO = **MI.memoperands_begin();
27608bcb0991SDimitry Andric   if (SrcTy.getSizeInBits() != MMO.getSizeInBits())
27618bcb0991SDimitry Andric     return UnableToLegalize;
27628bcb0991SDimitry Andric   if (SrcTy.isVector())
27638bcb0991SDimitry Andric     return UnableToLegalize;
27648bcb0991SDimitry Andric   if (isPowerOf2_32(SrcTy.getSizeInBits()))
27658bcb0991SDimitry Andric     return UnableToLegalize; // Don't know what we're being asked to do.
27668bcb0991SDimitry Andric 
27678bcb0991SDimitry Andric   // Extend to the next pow-2.
27688bcb0991SDimitry Andric   const LLT ExtendTy = LLT::scalar(NextPowerOf2(SrcTy.getSizeInBits()));
27698bcb0991SDimitry Andric   auto ExtVal = MIRBuilder.buildAnyExt(ExtendTy, SrcReg);
27708bcb0991SDimitry Andric 
27718bcb0991SDimitry Andric   // Obtain the smaller value by shifting away the larger value.
27728bcb0991SDimitry Andric   uint64_t LargeSplitSize = PowerOf2Floor(SrcTy.getSizeInBits());
27738bcb0991SDimitry Andric   uint64_t SmallSplitSize = SrcTy.getSizeInBits() - LargeSplitSize;
27748bcb0991SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(ExtendTy, LargeSplitSize);
27758bcb0991SDimitry Andric   auto SmallVal = MIRBuilder.buildLShr(ExtendTy, ExtVal, ShiftAmt);
27768bcb0991SDimitry Andric 
2777480093f4SDimitry Andric   // Generate the PtrAdd and truncating stores.
27788bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(PtrReg);
27795ffd83dbSDimitry Andric   auto OffsetCst = MIRBuilder.buildConstant(
27805ffd83dbSDimitry Andric     LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2781480093f4SDimitry Andric   Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2782480093f4SDimitry Andric   auto SmallPtr =
2783480093f4SDimitry Andric     MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
27848bcb0991SDimitry Andric 
27858bcb0991SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
27868bcb0991SDimitry Andric   MachineMemOperand *LargeMMO =
27878bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
27888bcb0991SDimitry Andric   MachineMemOperand *SmallMMO =
27898bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
27908bcb0991SDimitry Andric   MIRBuilder.buildStore(ExtVal.getReg(0), PtrReg, *LargeMMO);
27918bcb0991SDimitry Andric   MIRBuilder.buildStore(SmallVal.getReg(0), SmallPtr.getReg(0), *SmallMMO);
27928bcb0991SDimitry Andric   MI.eraseFromParent();
27938bcb0991SDimitry Andric   return Legalized;
27948bcb0991SDimitry Andric }
2795*e8d8bef9SDimitry Andric 
2796*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2797*e8d8bef9SDimitry Andric LegalizerHelper::bitcast(MachineInstr &MI, unsigned TypeIdx, LLT CastTy) {
2798*e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
2799*e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD: {
2800*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2801*e8d8bef9SDimitry Andric       return UnableToLegalize;
2802*e8d8bef9SDimitry Andric 
2803*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2804*e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
2805*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2806*e8d8bef9SDimitry Andric     return Legalized;
2807*e8d8bef9SDimitry Andric   }
2808*e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE: {
2809*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2810*e8d8bef9SDimitry Andric       return UnableToLegalize;
2811*e8d8bef9SDimitry Andric 
2812*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2813*e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 0);
2814*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2815*e8d8bef9SDimitry Andric     return Legalized;
2816*e8d8bef9SDimitry Andric   }
2817*e8d8bef9SDimitry Andric   case TargetOpcode::G_SELECT: {
2818*e8d8bef9SDimitry Andric     if (TypeIdx != 0)
2819*e8d8bef9SDimitry Andric       return UnableToLegalize;
2820*e8d8bef9SDimitry Andric 
2821*e8d8bef9SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector()) {
2822*e8d8bef9SDimitry Andric       LLVM_DEBUG(
2823*e8d8bef9SDimitry Andric           dbgs() << "bitcast action not implemented for vector select\n");
2824*e8d8bef9SDimitry Andric       return UnableToLegalize;
2825*e8d8bef9SDimitry Andric     }
2826*e8d8bef9SDimitry Andric 
2827*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2828*e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
2829*e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 3);
2830*e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
2831*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2832*e8d8bef9SDimitry Andric     return Legalized;
2833*e8d8bef9SDimitry Andric   }
2834*e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
2835*e8d8bef9SDimitry Andric   case TargetOpcode::G_OR:
2836*e8d8bef9SDimitry Andric   case TargetOpcode::G_XOR: {
2837*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2838*e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 1);
2839*e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
2840*e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
2841*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2842*e8d8bef9SDimitry Andric     return Legalized;
2843*e8d8bef9SDimitry Andric   }
2844*e8d8bef9SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
2845*e8d8bef9SDimitry Andric     return bitcastExtractVectorElt(MI, TypeIdx, CastTy);
2846*e8d8bef9SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT:
2847*e8d8bef9SDimitry Andric     return bitcastInsertVectorElt(MI, TypeIdx, CastTy);
2848*e8d8bef9SDimitry Andric   default:
2849*e8d8bef9SDimitry Andric     return UnableToLegalize;
2850*e8d8bef9SDimitry Andric   }
2851*e8d8bef9SDimitry Andric }
2852*e8d8bef9SDimitry Andric 
2853*e8d8bef9SDimitry Andric // Legalize an instruction by changing the opcode in place.
2854*e8d8bef9SDimitry Andric void LegalizerHelper::changeOpcode(MachineInstr &MI, unsigned NewOpcode) {
2855*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2856*e8d8bef9SDimitry Andric     MI.setDesc(MIRBuilder.getTII().get(NewOpcode));
2857*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2858*e8d8bef9SDimitry Andric }
2859*e8d8bef9SDimitry Andric 
2860*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2861*e8d8bef9SDimitry Andric LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT LowerHintTy) {
2862*e8d8bef9SDimitry Andric   using namespace TargetOpcode;
2863*e8d8bef9SDimitry Andric 
2864*e8d8bef9SDimitry Andric   switch(MI.getOpcode()) {
2865*e8d8bef9SDimitry Andric   default:
2866*e8d8bef9SDimitry Andric     return UnableToLegalize;
2867*e8d8bef9SDimitry Andric   case TargetOpcode::G_BITCAST:
2868*e8d8bef9SDimitry Andric     return lowerBitcast(MI);
2869*e8d8bef9SDimitry Andric   case TargetOpcode::G_SREM:
2870*e8d8bef9SDimitry Andric   case TargetOpcode::G_UREM: {
2871*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2872*e8d8bef9SDimitry Andric     auto Quot =
2873*e8d8bef9SDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV, {Ty},
2874*e8d8bef9SDimitry Andric                               {MI.getOperand(1), MI.getOperand(2)});
2875*e8d8bef9SDimitry Andric 
2876*e8d8bef9SDimitry Andric     auto Prod = MIRBuilder.buildMul(Ty, Quot, MI.getOperand(2));
2877*e8d8bef9SDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MI.getOperand(1), Prod);
2878*e8d8bef9SDimitry Andric     MI.eraseFromParent();
2879*e8d8bef9SDimitry Andric     return Legalized;
2880*e8d8bef9SDimitry Andric   }
2881*e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
2882*e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
2883*e8d8bef9SDimitry Andric     return lowerSADDO_SSUBO(MI);
2884*e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULH:
2885*e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULH:
2886*e8d8bef9SDimitry Andric     return lowerSMULH_UMULH(MI);
2887*e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULO:
2888*e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULO: {
2889*e8d8bef9SDimitry Andric     // Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
2890*e8d8bef9SDimitry Andric     // result.
2891*e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
2892*e8d8bef9SDimitry Andric     Register Overflow = MI.getOperand(1).getReg();
2893*e8d8bef9SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
2894*e8d8bef9SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
2895*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
2896*e8d8bef9SDimitry Andric 
2897*e8d8bef9SDimitry Andric     unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
2898*e8d8bef9SDimitry Andric                           ? TargetOpcode::G_SMULH
2899*e8d8bef9SDimitry Andric                           : TargetOpcode::G_UMULH;
2900*e8d8bef9SDimitry Andric 
2901*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2902*e8d8bef9SDimitry Andric     const auto &TII = MIRBuilder.getTII();
2903*e8d8bef9SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_MUL));
2904*e8d8bef9SDimitry Andric     MI.RemoveOperand(1);
2905*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2906*e8d8bef9SDimitry Andric 
2907*e8d8bef9SDimitry Andric     auto HiPart = MIRBuilder.buildInstr(Opcode, {Ty}, {LHS, RHS});
2908*e8d8bef9SDimitry Andric     auto Zero = MIRBuilder.buildConstant(Ty, 0);
2909*e8d8bef9SDimitry Andric 
2910*e8d8bef9SDimitry Andric     // Move insert point forward so we can use the Res register if needed.
2911*e8d8bef9SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
2912*e8d8bef9SDimitry Andric 
2913*e8d8bef9SDimitry Andric     // For *signed* multiply, overflow is detected by checking:
2914*e8d8bef9SDimitry Andric     // (hi != (lo >> bitwidth-1))
2915*e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SMULH) {
2916*e8d8bef9SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(Ty, Ty.getSizeInBits() - 1);
2917*e8d8bef9SDimitry Andric       auto Shifted = MIRBuilder.buildAShr(Ty, Res, ShiftAmt);
2918*e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
2919*e8d8bef9SDimitry Andric     } else {
2920*e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
2921*e8d8bef9SDimitry Andric     }
2922*e8d8bef9SDimitry Andric     return Legalized;
2923*e8d8bef9SDimitry Andric   }
2924*e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
2925*e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
2926*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
2927*e8d8bef9SDimitry Andric 
2928*e8d8bef9SDimitry Andric     // TODO: Handle vector types once we are able to
2929*e8d8bef9SDimitry Andric     // represent them.
2930*e8d8bef9SDimitry Andric     if (Ty.isVector())
2931*e8d8bef9SDimitry Andric       return UnableToLegalize;
2932*e8d8bef9SDimitry Andric     auto SignMask =
2933*e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignMask(Ty.getSizeInBits()));
2934*e8d8bef9SDimitry Andric     Register SubByReg = MI.getOperand(1).getReg();
2935*e8d8bef9SDimitry Andric     MIRBuilder.buildXor(Res, SubByReg, SignMask);
2936*e8d8bef9SDimitry Andric     MI.eraseFromParent();
2937*e8d8bef9SDimitry Andric     return Legalized;
2938*e8d8bef9SDimitry Andric   }
2939*e8d8bef9SDimitry Andric   case TargetOpcode::G_FSUB: {
2940*e8d8bef9SDimitry Andric     Register Res = MI.getOperand(0).getReg();
2941*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
2942*e8d8bef9SDimitry Andric 
2943*e8d8bef9SDimitry Andric     // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
2944*e8d8bef9SDimitry Andric     // First, check if G_FNEG is marked as Lower. If so, we may
2945*e8d8bef9SDimitry Andric     // end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
2946*e8d8bef9SDimitry Andric     if (LI.getAction({G_FNEG, {Ty}}).Action == Lower)
2947*e8d8bef9SDimitry Andric       return UnableToLegalize;
2948*e8d8bef9SDimitry Andric     Register LHS = MI.getOperand(1).getReg();
2949*e8d8bef9SDimitry Andric     Register RHS = MI.getOperand(2).getReg();
2950*e8d8bef9SDimitry Andric     Register Neg = MRI.createGenericVirtualRegister(Ty);
2951*e8d8bef9SDimitry Andric     MIRBuilder.buildFNeg(Neg, RHS);
2952*e8d8bef9SDimitry Andric     MIRBuilder.buildFAdd(Res, LHS, Neg, MI.getFlags());
2953*e8d8bef9SDimitry Andric     MI.eraseFromParent();
2954*e8d8bef9SDimitry Andric     return Legalized;
2955*e8d8bef9SDimitry Andric   }
2956*e8d8bef9SDimitry Andric   case TargetOpcode::G_FMAD:
2957*e8d8bef9SDimitry Andric     return lowerFMad(MI);
2958*e8d8bef9SDimitry Andric   case TargetOpcode::G_FFLOOR:
2959*e8d8bef9SDimitry Andric     return lowerFFloor(MI);
2960*e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
2961*e8d8bef9SDimitry Andric     return lowerIntrinsicRound(MI);
2962*e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
2963*e8d8bef9SDimitry Andric     // Since round even is the assumed rounding mode for unconstrained FP
2964*e8d8bef9SDimitry Andric     // operations, rint and roundeven are the same operation.
2965*e8d8bef9SDimitry Andric     changeOpcode(MI, TargetOpcode::G_FRINT);
2966*e8d8bef9SDimitry Andric     return Legalized;
2967*e8d8bef9SDimitry Andric   }
2968*e8d8bef9SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
2969*e8d8bef9SDimitry Andric     Register OldValRes = MI.getOperand(0).getReg();
2970*e8d8bef9SDimitry Andric     Register SuccessRes = MI.getOperand(1).getReg();
2971*e8d8bef9SDimitry Andric     Register Addr = MI.getOperand(2).getReg();
2972*e8d8bef9SDimitry Andric     Register CmpVal = MI.getOperand(3).getReg();
2973*e8d8bef9SDimitry Andric     Register NewVal = MI.getOperand(4).getReg();
2974*e8d8bef9SDimitry Andric     MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
2975*e8d8bef9SDimitry Andric                                   **MI.memoperands_begin());
2976*e8d8bef9SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
2977*e8d8bef9SDimitry Andric     MI.eraseFromParent();
2978*e8d8bef9SDimitry Andric     return Legalized;
2979*e8d8bef9SDimitry Andric   }
2980*e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD:
2981*e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
2982*e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
2983*e8d8bef9SDimitry Andric     return lowerLoad(MI);
2984*e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE:
2985*e8d8bef9SDimitry Andric     return lowerStore(MI);
29860b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
29870b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
29880b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
29890b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
29900b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP:
2991*e8d8bef9SDimitry Andric     return lowerBitCount(MI);
29920b57cec5SDimitry Andric   case G_UADDO: {
29930b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
29940b57cec5SDimitry Andric     Register CarryOut = MI.getOperand(1).getReg();
29950b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
29960b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
29970b57cec5SDimitry Andric 
29980b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, LHS, RHS);
29990b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, RHS);
30000b57cec5SDimitry Andric 
30010b57cec5SDimitry Andric     MI.eraseFromParent();
30020b57cec5SDimitry Andric     return Legalized;
30030b57cec5SDimitry Andric   }
30040b57cec5SDimitry Andric   case G_UADDE: {
30050b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
30060b57cec5SDimitry Andric     Register CarryOut = MI.getOperand(1).getReg();
30070b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
30080b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
30090b57cec5SDimitry Andric     Register CarryIn = MI.getOperand(4).getReg();
30105ffd83dbSDimitry Andric     LLT Ty = MRI.getType(Res);
30110b57cec5SDimitry Andric 
30125ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildAdd(Ty, LHS, RHS);
30135ffd83dbSDimitry Andric     auto ZExtCarryIn = MIRBuilder.buildZExt(Ty, CarryIn);
30140b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
30150b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric     MI.eraseFromParent();
30180b57cec5SDimitry Andric     return Legalized;
30190b57cec5SDimitry Andric   }
30200b57cec5SDimitry Andric   case G_USUBO: {
30210b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
30220b57cec5SDimitry Andric     Register BorrowOut = MI.getOperand(1).getReg();
30230b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
30240b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, LHS, RHS);
30270b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
30280b57cec5SDimitry Andric 
30290b57cec5SDimitry Andric     MI.eraseFromParent();
30300b57cec5SDimitry Andric     return Legalized;
30310b57cec5SDimitry Andric   }
30320b57cec5SDimitry Andric   case G_USUBE: {
30330b57cec5SDimitry Andric     Register Res = MI.getOperand(0).getReg();
30340b57cec5SDimitry Andric     Register BorrowOut = MI.getOperand(1).getReg();
30350b57cec5SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
30360b57cec5SDimitry Andric     Register RHS = MI.getOperand(3).getReg();
30370b57cec5SDimitry Andric     Register BorrowIn = MI.getOperand(4).getReg();
30385ffd83dbSDimitry Andric     const LLT CondTy = MRI.getType(BorrowOut);
30395ffd83dbSDimitry Andric     const LLT Ty = MRI.getType(Res);
30400b57cec5SDimitry Andric 
30415ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildSub(Ty, LHS, RHS);
30425ffd83dbSDimitry Andric     auto ZExtBorrowIn = MIRBuilder.buildZExt(Ty, BorrowIn);
30430b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
30445ffd83dbSDimitry Andric 
30455ffd83dbSDimitry Andric     auto LHS_EQ_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, CondTy, LHS, RHS);
30465ffd83dbSDimitry Andric     auto LHS_ULT_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CondTy, LHS, RHS);
30470b57cec5SDimitry Andric     MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
30480b57cec5SDimitry Andric 
30490b57cec5SDimitry Andric     MI.eraseFromParent();
30500b57cec5SDimitry Andric     return Legalized;
30510b57cec5SDimitry Andric   }
30520b57cec5SDimitry Andric   case G_UITOFP:
3053*e8d8bef9SDimitry Andric     return lowerUITOFP(MI);
30540b57cec5SDimitry Andric   case G_SITOFP:
3055*e8d8bef9SDimitry Andric     return lowerSITOFP(MI);
30568bcb0991SDimitry Andric   case G_FPTOUI:
3057*e8d8bef9SDimitry Andric     return lowerFPTOUI(MI);
30585ffd83dbSDimitry Andric   case G_FPTOSI:
30595ffd83dbSDimitry Andric     return lowerFPTOSI(MI);
30605ffd83dbSDimitry Andric   case G_FPTRUNC:
3061*e8d8bef9SDimitry Andric     return lowerFPTRUNC(MI);
3062*e8d8bef9SDimitry Andric   case G_FPOWI:
3063*e8d8bef9SDimitry Andric     return lowerFPOWI(MI);
30640b57cec5SDimitry Andric   case G_SMIN:
30650b57cec5SDimitry Andric   case G_SMAX:
30660b57cec5SDimitry Andric   case G_UMIN:
30670b57cec5SDimitry Andric   case G_UMAX:
3068*e8d8bef9SDimitry Andric     return lowerMinMax(MI);
30690b57cec5SDimitry Andric   case G_FCOPYSIGN:
3070*e8d8bef9SDimitry Andric     return lowerFCopySign(MI);
30710b57cec5SDimitry Andric   case G_FMINNUM:
30720b57cec5SDimitry Andric   case G_FMAXNUM:
30730b57cec5SDimitry Andric     return lowerFMinNumMaxNum(MI);
30745ffd83dbSDimitry Andric   case G_MERGE_VALUES:
30755ffd83dbSDimitry Andric     return lowerMergeValues(MI);
30768bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
30778bcb0991SDimitry Andric     return lowerUnmergeValues(MI);
30788bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
30798bcb0991SDimitry Andric     assert(MI.getOperand(2).isImm() && "Expected immediate");
30808bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
30818bcb0991SDimitry Andric 
30828bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
30838bcb0991SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
30848bcb0991SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
30858bcb0991SDimitry Andric     Register TmpRes = MRI.createGenericVirtualRegister(DstTy);
30868bcb0991SDimitry Andric 
30878bcb0991SDimitry Andric     auto MIBSz = MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - SizeInBits);
30885ffd83dbSDimitry Andric     MIRBuilder.buildShl(TmpRes, SrcReg, MIBSz->getOperand(0));
30895ffd83dbSDimitry Andric     MIRBuilder.buildAShr(DstReg, TmpRes, MIBSz->getOperand(0));
30908bcb0991SDimitry Andric     MI.eraseFromParent();
30918bcb0991SDimitry Andric     return Legalized;
30928bcb0991SDimitry Andric   }
3093*e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
3094*e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
3095*e8d8bef9SDimitry Andric     return lowerExtractInsertVectorElt(MI);
30968bcb0991SDimitry Andric   case G_SHUFFLE_VECTOR:
30978bcb0991SDimitry Andric     return lowerShuffleVector(MI);
30988bcb0991SDimitry Andric   case G_DYN_STACKALLOC:
30998bcb0991SDimitry Andric     return lowerDynStackAlloc(MI);
31008bcb0991SDimitry Andric   case G_EXTRACT:
31018bcb0991SDimitry Andric     return lowerExtract(MI);
31028bcb0991SDimitry Andric   case G_INSERT:
31038bcb0991SDimitry Andric     return lowerInsert(MI);
3104480093f4SDimitry Andric   case G_BSWAP:
3105480093f4SDimitry Andric     return lowerBswap(MI);
3106480093f4SDimitry Andric   case G_BITREVERSE:
3107480093f4SDimitry Andric     return lowerBitreverse(MI);
3108480093f4SDimitry Andric   case G_READ_REGISTER:
31095ffd83dbSDimitry Andric   case G_WRITE_REGISTER:
31105ffd83dbSDimitry Andric     return lowerReadWriteRegister(MI);
3111*e8d8bef9SDimitry Andric   case G_UADDSAT:
3112*e8d8bef9SDimitry Andric   case G_USUBSAT: {
3113*e8d8bef9SDimitry Andric     // Try to make a reasonable guess about which lowering strategy to use. The
3114*e8d8bef9SDimitry Andric     // target can override this with custom lowering and calling the
3115*e8d8bef9SDimitry Andric     // implementation functions.
3116*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3117*e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_UMIN, Ty}))
3118*e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3119*e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
31200b57cec5SDimitry Andric   }
3121*e8d8bef9SDimitry Andric   case G_SADDSAT:
3122*e8d8bef9SDimitry Andric   case G_SSUBSAT: {
3123*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3124*e8d8bef9SDimitry Andric 
3125*e8d8bef9SDimitry Andric     // FIXME: It would probably make more sense to see if G_SADDO is preferred,
3126*e8d8bef9SDimitry Andric     // since it's a shorter expansion. However, we would need to figure out the
3127*e8d8bef9SDimitry Andric     // preferred boolean type for the carry out for the query.
3128*e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_SMIN, Ty}) && LI.isLegalOrCustom({G_SMAX, Ty}))
3129*e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3130*e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
3131*e8d8bef9SDimitry Andric   }
3132*e8d8bef9SDimitry Andric   case G_SSHLSAT:
3133*e8d8bef9SDimitry Andric   case G_USHLSAT:
3134*e8d8bef9SDimitry Andric     return lowerShlSat(MI);
3135*e8d8bef9SDimitry Andric   case G_ABS: {
3136*e8d8bef9SDimitry Andric     // Expand %res = G_ABS %a into:
3137*e8d8bef9SDimitry Andric     // %v1 = G_ASHR %a, scalar_size-1
3138*e8d8bef9SDimitry Andric     // %v2 = G_ADD %a, %v1
3139*e8d8bef9SDimitry Andric     // %res = G_XOR %v2, %v1
3140*e8d8bef9SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3141*e8d8bef9SDimitry Andric     Register OpReg = MI.getOperand(1).getReg();
3142*e8d8bef9SDimitry Andric     auto ShiftAmt =
3143*e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - 1);
3144*e8d8bef9SDimitry Andric     auto Shift =
3145*e8d8bef9SDimitry Andric         MIRBuilder.buildAShr(DstTy, OpReg, ShiftAmt);
3146*e8d8bef9SDimitry Andric     auto Add = MIRBuilder.buildAdd(DstTy, OpReg, Shift);
3147*e8d8bef9SDimitry Andric     MIRBuilder.buildXor(MI.getOperand(0).getReg(), Add, Shift);
3148*e8d8bef9SDimitry Andric     MI.eraseFromParent();
3149*e8d8bef9SDimitry Andric     return Legalized;
3150*e8d8bef9SDimitry Andric   }
3151*e8d8bef9SDimitry Andric   case G_SELECT:
3152*e8d8bef9SDimitry Andric     return lowerSelect(MI);
3153*e8d8bef9SDimitry Andric   }
3154*e8d8bef9SDimitry Andric }
3155*e8d8bef9SDimitry Andric 
3156*e8d8bef9SDimitry Andric Align LegalizerHelper::getStackTemporaryAlignment(LLT Ty,
3157*e8d8bef9SDimitry Andric                                                   Align MinAlign) const {
3158*e8d8bef9SDimitry Andric   // FIXME: We're missing a way to go back from LLT to llvm::Type to query the
3159*e8d8bef9SDimitry Andric   // datalayout for the preferred alignment. Also there should be a target hook
3160*e8d8bef9SDimitry Andric   // for this to allow targets to reduce the alignment and ignore the
3161*e8d8bef9SDimitry Andric   // datalayout. e.g. AMDGPU should always use a 4-byte alignment, regardless of
3162*e8d8bef9SDimitry Andric   // the type.
3163*e8d8bef9SDimitry Andric   return std::max(Align(PowerOf2Ceil(Ty.getSizeInBytes())), MinAlign);
3164*e8d8bef9SDimitry Andric }
3165*e8d8bef9SDimitry Andric 
3166*e8d8bef9SDimitry Andric MachineInstrBuilder
3167*e8d8bef9SDimitry Andric LegalizerHelper::createStackTemporary(TypeSize Bytes, Align Alignment,
3168*e8d8bef9SDimitry Andric                                       MachinePointerInfo &PtrInfo) {
3169*e8d8bef9SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
3170*e8d8bef9SDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
3171*e8d8bef9SDimitry Andric   int FrameIdx = MF.getFrameInfo().CreateStackObject(Bytes, Alignment, false);
3172*e8d8bef9SDimitry Andric 
3173*e8d8bef9SDimitry Andric   unsigned AddrSpace = DL.getAllocaAddrSpace();
3174*e8d8bef9SDimitry Andric   LLT FramePtrTy = LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace));
3175*e8d8bef9SDimitry Andric 
3176*e8d8bef9SDimitry Andric   PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIdx);
3177*e8d8bef9SDimitry Andric   return MIRBuilder.buildFrameIndex(FramePtrTy, FrameIdx);
3178*e8d8bef9SDimitry Andric }
3179*e8d8bef9SDimitry Andric 
3180*e8d8bef9SDimitry Andric static Register clampDynamicVectorIndex(MachineIRBuilder &B, Register IdxReg,
3181*e8d8bef9SDimitry Andric                                         LLT VecTy) {
3182*e8d8bef9SDimitry Andric   int64_t IdxVal;
3183*e8d8bef9SDimitry Andric   if (mi_match(IdxReg, *B.getMRI(), m_ICst(IdxVal)))
3184*e8d8bef9SDimitry Andric     return IdxReg;
3185*e8d8bef9SDimitry Andric 
3186*e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(IdxReg);
3187*e8d8bef9SDimitry Andric   unsigned NElts = VecTy.getNumElements();
3188*e8d8bef9SDimitry Andric   if (isPowerOf2_32(NElts)) {
3189*e8d8bef9SDimitry Andric     APInt Imm = APInt::getLowBitsSet(IdxTy.getSizeInBits(), Log2_32(NElts));
3190*e8d8bef9SDimitry Andric     return B.buildAnd(IdxTy, IdxReg, B.buildConstant(IdxTy, Imm)).getReg(0);
3191*e8d8bef9SDimitry Andric   }
3192*e8d8bef9SDimitry Andric 
3193*e8d8bef9SDimitry Andric   return B.buildUMin(IdxTy, IdxReg, B.buildConstant(IdxTy, NElts - 1))
3194*e8d8bef9SDimitry Andric       .getReg(0);
3195*e8d8bef9SDimitry Andric }
3196*e8d8bef9SDimitry Andric 
3197*e8d8bef9SDimitry Andric Register LegalizerHelper::getVectorElementPointer(Register VecPtr, LLT VecTy,
3198*e8d8bef9SDimitry Andric                                                   Register Index) {
3199*e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
3200*e8d8bef9SDimitry Andric 
3201*e8d8bef9SDimitry Andric   // Calculate the element offset and add it to the pointer.
3202*e8d8bef9SDimitry Andric   unsigned EltSize = EltTy.getSizeInBits() / 8; // FIXME: should be ABI size.
3203*e8d8bef9SDimitry Andric   assert(EltSize * 8 == EltTy.getSizeInBits() &&
3204*e8d8bef9SDimitry Andric          "Converting bits to bytes lost precision");
3205*e8d8bef9SDimitry Andric 
3206*e8d8bef9SDimitry Andric   Index = clampDynamicVectorIndex(MIRBuilder, Index, VecTy);
3207*e8d8bef9SDimitry Andric 
3208*e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Index);
3209*e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(IdxTy, Index,
3210*e8d8bef9SDimitry Andric                                  MIRBuilder.buildConstant(IdxTy, EltSize));
3211*e8d8bef9SDimitry Andric 
3212*e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(VecPtr);
3213*e8d8bef9SDimitry Andric   return MIRBuilder.buildPtrAdd(PtrTy, VecPtr, Mul).getReg(0);
32140b57cec5SDimitry Andric }
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorImplicitDef(
32170b57cec5SDimitry Andric     MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy) {
32180b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3219*e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3220*e8d8bef9SDimitry Andric   LLT LCMTy = getLCMType(DstTy, NarrowTy);
32210b57cec5SDimitry Andric 
3222*e8d8bef9SDimitry Andric   unsigned NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
32230b57cec5SDimitry Andric 
3224*e8d8bef9SDimitry Andric   auto NewUndef = MIRBuilder.buildUndef(NarrowTy);
3225*e8d8bef9SDimitry Andric   SmallVector<Register, 8> Parts(NumParts, NewUndef.getReg(0));
32260b57cec5SDimitry Andric 
3227*e8d8bef9SDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
32280b57cec5SDimitry Andric   MI.eraseFromParent();
32290b57cec5SDimitry Andric   return Legalized;
32300b57cec5SDimitry Andric }
32310b57cec5SDimitry Andric 
32320b57cec5SDimitry Andric // Handle splitting vector operations which need to have the same number of
32330b57cec5SDimitry Andric // elements in each type index, but each type index may have a different element
32340b57cec5SDimitry Andric // type.
32350b57cec5SDimitry Andric //
32360b57cec5SDimitry Andric // e.g.  <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
32370b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
32380b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
32390b57cec5SDimitry Andric //
32400b57cec5SDimitry Andric // Also handles some irregular breakdown cases, e.g.
32410b57cec5SDimitry Andric // e.g.  <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
32420b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
32430b57cec5SDimitry Andric //             s64 = G_SHL s64, s32
32440b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
32450b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorMultiEltType(
32460b57cec5SDimitry Andric   MachineInstr &MI, unsigned TypeIdx, LLT NarrowTyArg) {
32470b57cec5SDimitry Andric   if (TypeIdx != 0)
32480b57cec5SDimitry Andric     return UnableToLegalize;
32490b57cec5SDimitry Andric 
32500b57cec5SDimitry Andric   const LLT NarrowTy0 = NarrowTyArg;
32510b57cec5SDimitry Andric   const unsigned NewNumElts =
32520b57cec5SDimitry Andric       NarrowTy0.isVector() ? NarrowTy0.getNumElements() : 1;
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
32550b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
32560b57cec5SDimitry Andric   LLT LeftoverTy0;
32570b57cec5SDimitry Andric 
32580b57cec5SDimitry Andric   // All of the operands need to have the same number of elements, so if we can
32590b57cec5SDimitry Andric   // determine a type breakdown for the result type, we can for all of the
32600b57cec5SDimitry Andric   // source types.
32610b57cec5SDimitry Andric   int NumParts = getNarrowTypeBreakDown(DstTy, NarrowTy0, LeftoverTy0).first;
32620b57cec5SDimitry Andric   if (NumParts < 0)
32630b57cec5SDimitry Andric     return UnableToLegalize;
32640b57cec5SDimitry Andric 
32650b57cec5SDimitry Andric   SmallVector<MachineInstrBuilder, 4> NewInsts;
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
32680b57cec5SDimitry Andric   SmallVector<Register, 4> PartRegs, LeftoverRegs;
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
32710b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
32720b57cec5SDimitry Andric     LLT SrcTyI = MRI.getType(SrcReg);
32730b57cec5SDimitry Andric     LLT NarrowTyI = LLT::scalarOrVector(NewNumElts, SrcTyI.getScalarType());
32740b57cec5SDimitry Andric     LLT LeftoverTyI;
32750b57cec5SDimitry Andric 
32760b57cec5SDimitry Andric     // Split this operand into the requested typed registers, and any leftover
32770b57cec5SDimitry Andric     // required to reproduce the original type.
32780b57cec5SDimitry Andric     if (!extractParts(SrcReg, SrcTyI, NarrowTyI, LeftoverTyI, PartRegs,
32790b57cec5SDimitry Andric                       LeftoverRegs))
32800b57cec5SDimitry Andric       return UnableToLegalize;
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric     if (I == 1) {
32830b57cec5SDimitry Andric       // For the first operand, create an instruction for each part and setup
32840b57cec5SDimitry Andric       // the result.
32850b57cec5SDimitry Andric       for (Register PartReg : PartRegs) {
32860b57cec5SDimitry Andric         Register PartDstReg = MRI.createGenericVirtualRegister(NarrowTy0);
32870b57cec5SDimitry Andric         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
32880b57cec5SDimitry Andric                                .addDef(PartDstReg)
32890b57cec5SDimitry Andric                                .addUse(PartReg));
32900b57cec5SDimitry Andric         DstRegs.push_back(PartDstReg);
32910b57cec5SDimitry Andric       }
32920b57cec5SDimitry Andric 
32930b57cec5SDimitry Andric       for (Register LeftoverReg : LeftoverRegs) {
32940b57cec5SDimitry Andric         Register PartDstReg = MRI.createGenericVirtualRegister(LeftoverTy0);
32950b57cec5SDimitry Andric         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
32960b57cec5SDimitry Andric                                .addDef(PartDstReg)
32970b57cec5SDimitry Andric                                .addUse(LeftoverReg));
32980b57cec5SDimitry Andric         LeftoverDstRegs.push_back(PartDstReg);
32990b57cec5SDimitry Andric       }
33000b57cec5SDimitry Andric     } else {
33010b57cec5SDimitry Andric       assert(NewInsts.size() == PartRegs.size() + LeftoverRegs.size());
33020b57cec5SDimitry Andric 
33030b57cec5SDimitry Andric       // Add the newly created operand splits to the existing instructions. The
33040b57cec5SDimitry Andric       // odd-sized pieces are ordered after the requested NarrowTyArg sized
33050b57cec5SDimitry Andric       // pieces.
33060b57cec5SDimitry Andric       unsigned InstCount = 0;
33070b57cec5SDimitry Andric       for (unsigned J = 0, JE = PartRegs.size(); J != JE; ++J)
33080b57cec5SDimitry Andric         NewInsts[InstCount++].addUse(PartRegs[J]);
33090b57cec5SDimitry Andric       for (unsigned J = 0, JE = LeftoverRegs.size(); J != JE; ++J)
33100b57cec5SDimitry Andric         NewInsts[InstCount++].addUse(LeftoverRegs[J]);
33110b57cec5SDimitry Andric     }
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric     PartRegs.clear();
33140b57cec5SDimitry Andric     LeftoverRegs.clear();
33150b57cec5SDimitry Andric   }
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric   // Insert the newly built operations and rebuild the result register.
33180b57cec5SDimitry Andric   for (auto &MIB : NewInsts)
33190b57cec5SDimitry Andric     MIRBuilder.insertInstr(MIB);
33200b57cec5SDimitry Andric 
33210b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy0, DstRegs, LeftoverTy0, LeftoverDstRegs);
33220b57cec5SDimitry Andric 
33230b57cec5SDimitry Andric   MI.eraseFromParent();
33240b57cec5SDimitry Andric   return Legalized;
33250b57cec5SDimitry Andric }
33260b57cec5SDimitry Andric 
33270b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
33280b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorCasts(MachineInstr &MI, unsigned TypeIdx,
33290b57cec5SDimitry Andric                                           LLT NarrowTy) {
33300b57cec5SDimitry Andric   if (TypeIdx != 0)
33310b57cec5SDimitry Andric     return UnableToLegalize;
33320b57cec5SDimitry Andric 
33330b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
33340b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
33350b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
33360b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric   LLT NarrowTy0 = NarrowTy;
33390b57cec5SDimitry Andric   LLT NarrowTy1;
33400b57cec5SDimitry Andric   unsigned NumParts;
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   if (NarrowTy.isVector()) {
33430b57cec5SDimitry Andric     // Uneven breakdown not handled.
33440b57cec5SDimitry Andric     NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
33450b57cec5SDimitry Andric     if (NumParts * NarrowTy.getNumElements() != DstTy.getNumElements())
33460b57cec5SDimitry Andric       return UnableToLegalize;
33470b57cec5SDimitry Andric 
3348*e8d8bef9SDimitry Andric     NarrowTy1 = LLT::vector(NarrowTy.getNumElements(), SrcTy.getElementType());
33490b57cec5SDimitry Andric   } else {
33500b57cec5SDimitry Andric     NumParts = DstTy.getNumElements();
33510b57cec5SDimitry Andric     NarrowTy1 = SrcTy.getElementType();
33520b57cec5SDimitry Andric   }
33530b57cec5SDimitry Andric 
33540b57cec5SDimitry Andric   SmallVector<Register, 4> SrcRegs, DstRegs;
33550b57cec5SDimitry Andric   extractParts(SrcReg, NarrowTy1, NumParts, SrcRegs);
33560b57cec5SDimitry Andric 
33570b57cec5SDimitry Andric   for (unsigned I = 0; I < NumParts; ++I) {
33580b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
33595ffd83dbSDimitry Andric     MachineInstr *NewInst =
33605ffd83dbSDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode(), {DstReg}, {SrcRegs[I]});
33610b57cec5SDimitry Andric 
33620b57cec5SDimitry Andric     NewInst->setFlags(MI.getFlags());
33630b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
33640b57cec5SDimitry Andric   }
33650b57cec5SDimitry Andric 
33660b57cec5SDimitry Andric   if (NarrowTy.isVector())
33670b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
33680b57cec5SDimitry Andric   else
33690b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
33700b57cec5SDimitry Andric 
33710b57cec5SDimitry Andric   MI.eraseFromParent();
33720b57cec5SDimitry Andric   return Legalized;
33730b57cec5SDimitry Andric }
33740b57cec5SDimitry Andric 
33750b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
33760b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorCmp(MachineInstr &MI, unsigned TypeIdx,
33770b57cec5SDimitry Andric                                         LLT NarrowTy) {
33780b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
33790b57cec5SDimitry Andric   Register Src0Reg = MI.getOperand(2).getReg();
33800b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
33810b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src0Reg);
33820b57cec5SDimitry Andric 
33830b57cec5SDimitry Andric   unsigned NumParts;
33840b57cec5SDimitry Andric   LLT NarrowTy0, NarrowTy1;
33850b57cec5SDimitry Andric 
33860b57cec5SDimitry Andric   if (TypeIdx == 0) {
33870b57cec5SDimitry Andric     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
33880b57cec5SDimitry Andric     unsigned OldElts = DstTy.getNumElements();
33890b57cec5SDimitry Andric 
33900b57cec5SDimitry Andric     NarrowTy0 = NarrowTy;
33910b57cec5SDimitry Andric     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) : DstTy.getNumElements();
33920b57cec5SDimitry Andric     NarrowTy1 = NarrowTy.isVector() ?
33930b57cec5SDimitry Andric       LLT::vector(NarrowTy.getNumElements(), SrcTy.getScalarSizeInBits()) :
33940b57cec5SDimitry Andric       SrcTy.getElementType();
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric   } else {
33970b57cec5SDimitry Andric     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
33980b57cec5SDimitry Andric     unsigned OldElts = SrcTy.getNumElements();
33990b57cec5SDimitry Andric 
34000b57cec5SDimitry Andric     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) :
34010b57cec5SDimitry Andric       NarrowTy.getNumElements();
34020b57cec5SDimitry Andric     NarrowTy0 = LLT::vector(NarrowTy.getNumElements(),
34030b57cec5SDimitry Andric                             DstTy.getScalarSizeInBits());
34040b57cec5SDimitry Andric     NarrowTy1 = NarrowTy;
34050b57cec5SDimitry Andric   }
34060b57cec5SDimitry Andric 
34070b57cec5SDimitry Andric   // FIXME: Don't know how to handle the situation where the small vectors
34080b57cec5SDimitry Andric   // aren't all the same size yet.
34090b57cec5SDimitry Andric   if (NarrowTy1.isVector() &&
34100b57cec5SDimitry Andric       NarrowTy1.getNumElements() * NumParts != DstTy.getNumElements())
34110b57cec5SDimitry Andric     return UnableToLegalize;
34120b57cec5SDimitry Andric 
34130b57cec5SDimitry Andric   CmpInst::Predicate Pred
34140b57cec5SDimitry Andric     = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric   SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
34170b57cec5SDimitry Andric   extractParts(MI.getOperand(2).getReg(), NarrowTy1, NumParts, Src1Regs);
34180b57cec5SDimitry Andric   extractParts(MI.getOperand(3).getReg(), NarrowTy1, NumParts, Src2Regs);
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric   for (unsigned I = 0; I < NumParts; ++I) {
34210b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
34220b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
34230b57cec5SDimitry Andric 
34240b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_ICMP)
34250b57cec5SDimitry Andric       MIRBuilder.buildICmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
34260b57cec5SDimitry Andric     else {
34270b57cec5SDimitry Andric       MachineInstr *NewCmp
34280b57cec5SDimitry Andric         = MIRBuilder.buildFCmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
34290b57cec5SDimitry Andric       NewCmp->setFlags(MI.getFlags());
34300b57cec5SDimitry Andric     }
34310b57cec5SDimitry Andric   }
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric   if (NarrowTy1.isVector())
34340b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
34350b57cec5SDimitry Andric   else
34360b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
34370b57cec5SDimitry Andric 
34380b57cec5SDimitry Andric   MI.eraseFromParent();
34390b57cec5SDimitry Andric   return Legalized;
34400b57cec5SDimitry Andric }
34410b57cec5SDimitry Andric 
34420b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
34430b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorSelect(MachineInstr &MI, unsigned TypeIdx,
34440b57cec5SDimitry Andric                                            LLT NarrowTy) {
34450b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
34460b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
34470b57cec5SDimitry Andric 
34480b57cec5SDimitry Andric   unsigned NumParts = 0;
34490b57cec5SDimitry Andric   LLT NarrowTy0, NarrowTy1;
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
34520b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
34530b57cec5SDimitry Andric   unsigned Size = DstTy.getSizeInBits();
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric   assert(TypeIdx == 0 || CondTy.isVector());
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric   if (TypeIdx == 0) {
34580b57cec5SDimitry Andric     NarrowTy0 = NarrowTy;
34590b57cec5SDimitry Andric     NarrowTy1 = CondTy;
34600b57cec5SDimitry Andric 
34610b57cec5SDimitry Andric     unsigned NarrowSize = NarrowTy0.getSizeInBits();
34620b57cec5SDimitry Andric     // FIXME: Don't know how to handle the situation where the small vectors
34630b57cec5SDimitry Andric     // aren't all the same size yet.
34640b57cec5SDimitry Andric     if (Size % NarrowSize != 0)
34650b57cec5SDimitry Andric       return UnableToLegalize;
34660b57cec5SDimitry Andric 
34670b57cec5SDimitry Andric     NumParts = Size / NarrowSize;
34680b57cec5SDimitry Andric 
34690b57cec5SDimitry Andric     // Need to break down the condition type
34700b57cec5SDimitry Andric     if (CondTy.isVector()) {
34710b57cec5SDimitry Andric       if (CondTy.getNumElements() == NumParts)
34720b57cec5SDimitry Andric         NarrowTy1 = CondTy.getElementType();
34730b57cec5SDimitry Andric       else
34740b57cec5SDimitry Andric         NarrowTy1 = LLT::vector(CondTy.getNumElements() / NumParts,
34750b57cec5SDimitry Andric                                 CondTy.getScalarSizeInBits());
34760b57cec5SDimitry Andric     }
34770b57cec5SDimitry Andric   } else {
34780b57cec5SDimitry Andric     NumParts = CondTy.getNumElements();
34790b57cec5SDimitry Andric     if (NarrowTy.isVector()) {
34800b57cec5SDimitry Andric       // TODO: Handle uneven breakdown.
34810b57cec5SDimitry Andric       if (NumParts * NarrowTy.getNumElements() != CondTy.getNumElements())
34820b57cec5SDimitry Andric         return UnableToLegalize;
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric       return UnableToLegalize;
34850b57cec5SDimitry Andric     } else {
34860b57cec5SDimitry Andric       NarrowTy0 = DstTy.getElementType();
34870b57cec5SDimitry Andric       NarrowTy1 = NarrowTy;
34880b57cec5SDimitry Andric     }
34890b57cec5SDimitry Andric   }
34900b57cec5SDimitry Andric 
34910b57cec5SDimitry Andric   SmallVector<Register, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
34920b57cec5SDimitry Andric   if (CondTy.isVector())
34930b57cec5SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy1, NumParts, Src0Regs);
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric   extractParts(MI.getOperand(2).getReg(), NarrowTy0, NumParts, Src1Regs);
34960b57cec5SDimitry Andric   extractParts(MI.getOperand(3).getReg(), NarrowTy0, NumParts, Src2Regs);
34970b57cec5SDimitry Andric 
34980b57cec5SDimitry Andric   for (unsigned i = 0; i < NumParts; ++i) {
34990b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
35000b57cec5SDimitry Andric     MIRBuilder.buildSelect(DstReg, CondTy.isVector() ? Src0Regs[i] : CondReg,
35010b57cec5SDimitry Andric                            Src1Regs[i], Src2Regs[i]);
35020b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
35030b57cec5SDimitry Andric   }
35040b57cec5SDimitry Andric 
35050b57cec5SDimitry Andric   if (NarrowTy0.isVector())
35060b57cec5SDimitry Andric     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
35070b57cec5SDimitry Andric   else
35080b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
35090b57cec5SDimitry Andric 
35100b57cec5SDimitry Andric   MI.eraseFromParent();
35110b57cec5SDimitry Andric   return Legalized;
35120b57cec5SDimitry Andric }
35130b57cec5SDimitry Andric 
35140b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
35150b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
35160b57cec5SDimitry Andric                                         LLT NarrowTy) {
35170b57cec5SDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
35180b57cec5SDimitry Andric   LLT PhiTy = MRI.getType(DstReg);
35190b57cec5SDimitry Andric   LLT LeftoverTy;
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   // All of the operands need to have the same number of elements, so if we can
35220b57cec5SDimitry Andric   // determine a type breakdown for the result type, we can for all of the
35230b57cec5SDimitry Andric   // source types.
35240b57cec5SDimitry Andric   int NumParts, NumLeftover;
35250b57cec5SDimitry Andric   std::tie(NumParts, NumLeftover)
35260b57cec5SDimitry Andric     = getNarrowTypeBreakDown(PhiTy, NarrowTy, LeftoverTy);
35270b57cec5SDimitry Andric   if (NumParts < 0)
35280b57cec5SDimitry Andric     return UnableToLegalize;
35290b57cec5SDimitry Andric 
35300b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
35310b57cec5SDimitry Andric   SmallVector<MachineInstrBuilder, 4> NewInsts;
35320b57cec5SDimitry Andric 
35330b57cec5SDimitry Andric   const int TotalNumParts = NumParts + NumLeftover;
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   // Insert the new phis in the result block first.
35360b57cec5SDimitry Andric   for (int I = 0; I != TotalNumParts; ++I) {
35370b57cec5SDimitry Andric     LLT Ty = I < NumParts ? NarrowTy : LeftoverTy;
35380b57cec5SDimitry Andric     Register PartDstReg = MRI.createGenericVirtualRegister(Ty);
35390b57cec5SDimitry Andric     NewInsts.push_back(MIRBuilder.buildInstr(TargetOpcode::G_PHI)
35400b57cec5SDimitry Andric                        .addDef(PartDstReg));
35410b57cec5SDimitry Andric     if (I < NumParts)
35420b57cec5SDimitry Andric       DstRegs.push_back(PartDstReg);
35430b57cec5SDimitry Andric     else
35440b57cec5SDimitry Andric       LeftoverDstRegs.push_back(PartDstReg);
35450b57cec5SDimitry Andric   }
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
35480b57cec5SDimitry Andric   MIRBuilder.setInsertPt(*MBB, MBB->getFirstNonPHI());
35490b57cec5SDimitry Andric   insertParts(DstReg, PhiTy, NarrowTy, DstRegs, LeftoverTy, LeftoverDstRegs);
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric   SmallVector<Register, 4> PartRegs, LeftoverRegs;
35520b57cec5SDimitry Andric 
35530b57cec5SDimitry Andric   // Insert code to extract the incoming values in each predecessor block.
35540b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
35550b57cec5SDimitry Andric     PartRegs.clear();
35560b57cec5SDimitry Andric     LeftoverRegs.clear();
35570b57cec5SDimitry Andric 
35580b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
35590b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
35600b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
35610b57cec5SDimitry Andric 
35620b57cec5SDimitry Andric     LLT Unused;
35630b57cec5SDimitry Andric     if (!extractParts(SrcReg, PhiTy, NarrowTy, Unused, PartRegs,
35640b57cec5SDimitry Andric                       LeftoverRegs))
35650b57cec5SDimitry Andric       return UnableToLegalize;
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric     // Add the newly created operand splits to the existing instructions. The
35680b57cec5SDimitry Andric     // odd-sized pieces are ordered after the requested NarrowTyArg sized
35690b57cec5SDimitry Andric     // pieces.
35700b57cec5SDimitry Andric     for (int J = 0; J != TotalNumParts; ++J) {
35710b57cec5SDimitry Andric       MachineInstrBuilder MIB = NewInsts[J];
35720b57cec5SDimitry Andric       MIB.addUse(J < NumParts ? PartRegs[J] : LeftoverRegs[J - NumParts]);
35730b57cec5SDimitry Andric       MIB.addMBB(&OpMBB);
35740b57cec5SDimitry Andric     }
35750b57cec5SDimitry Andric   }
35760b57cec5SDimitry Andric 
35770b57cec5SDimitry Andric   MI.eraseFromParent();
35780b57cec5SDimitry Andric   return Legalized;
35790b57cec5SDimitry Andric }
35800b57cec5SDimitry Andric 
35810b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
35828bcb0991SDimitry Andric LegalizerHelper::fewerElementsVectorUnmergeValues(MachineInstr &MI,
35838bcb0991SDimitry Andric                                                   unsigned TypeIdx,
35848bcb0991SDimitry Andric                                                   LLT NarrowTy) {
35858bcb0991SDimitry Andric   if (TypeIdx != 1)
35868bcb0991SDimitry Andric     return UnableToLegalize;
35878bcb0991SDimitry Andric 
35888bcb0991SDimitry Andric   const int NumDst = MI.getNumOperands() - 1;
35898bcb0991SDimitry Andric   const Register SrcReg = MI.getOperand(NumDst).getReg();
35908bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
35918bcb0991SDimitry Andric 
35928bcb0991SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
35938bcb0991SDimitry Andric 
35948bcb0991SDimitry Andric   // TODO: Create sequence of extracts.
35958bcb0991SDimitry Andric   if (DstTy == NarrowTy)
35968bcb0991SDimitry Andric     return UnableToLegalize;
35978bcb0991SDimitry Andric 
35988bcb0991SDimitry Andric   LLT GCDTy = getGCDType(SrcTy, NarrowTy);
35998bcb0991SDimitry Andric   if (DstTy == GCDTy) {
36008bcb0991SDimitry Andric     // This would just be a copy of the same unmerge.
36018bcb0991SDimitry Andric     // TODO: Create extracts, pad with undef and create intermediate merges.
36028bcb0991SDimitry Andric     return UnableToLegalize;
36038bcb0991SDimitry Andric   }
36048bcb0991SDimitry Andric 
36058bcb0991SDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
36068bcb0991SDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
36078bcb0991SDimitry Andric   const int PartsPerUnmerge = NumDst / NumUnmerge;
36088bcb0991SDimitry Andric 
36098bcb0991SDimitry Andric   for (int I = 0; I != NumUnmerge; ++I) {
36108bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
36118bcb0991SDimitry Andric 
36128bcb0991SDimitry Andric     for (int J = 0; J != PartsPerUnmerge; ++J)
36138bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I * PartsPerUnmerge + J).getReg());
36148bcb0991SDimitry Andric     MIB.addUse(Unmerge.getReg(I));
36158bcb0991SDimitry Andric   }
36168bcb0991SDimitry Andric 
36178bcb0991SDimitry Andric   MI.eraseFromParent();
36188bcb0991SDimitry Andric   return Legalized;
36198bcb0991SDimitry Andric }
36208bcb0991SDimitry Andric 
3621*e8d8bef9SDimitry Andric // Handle FewerElementsVector a G_BUILD_VECTOR or G_CONCAT_VECTORS that produces
3622*e8d8bef9SDimitry Andric // a vector
3623*e8d8bef9SDimitry Andric //
3624*e8d8bef9SDimitry Andric // Create a G_BUILD_VECTOR or G_CONCAT_VECTORS of NarrowTy pieces, padding with
3625*e8d8bef9SDimitry Andric // undef as necessary.
36268bcb0991SDimitry Andric //
36278bcb0991SDimitry Andric // %3:_(<3 x s16>) = G_BUILD_VECTOR %0, %1, %2
36288bcb0991SDimitry Andric //   -> <2 x s16>
36298bcb0991SDimitry Andric //
36308bcb0991SDimitry Andric // %4:_(s16) = G_IMPLICIT_DEF
36318bcb0991SDimitry Andric // %5:_(<2 x s16>) = G_BUILD_VECTOR %0, %1
36328bcb0991SDimitry Andric // %6:_(<2 x s16>) = G_BUILD_VECTOR %2, %4
3633*e8d8bef9SDimitry Andric // %7:_(<2 x s16>) = G_IMPLICIT_DEF
3634*e8d8bef9SDimitry Andric // %8:_(<6 x s16>) = G_CONCAT_VECTORS %5, %6, %7
3635*e8d8bef9SDimitry Andric // %3:_(<3 x s16>), %8:_(<3 x s16>) = G_UNMERGE_VALUES %8
3636*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3637*e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorMerge(MachineInstr &MI, unsigned TypeIdx,
3638*e8d8bef9SDimitry Andric                                           LLT NarrowTy) {
3639*e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3640*e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3641*e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
3642*e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
36438bcb0991SDimitry Andric 
3644*e8d8bef9SDimitry Andric   // Break into a common type
3645*e8d8bef9SDimitry Andric   SmallVector<Register, 16> Parts;
3646*e8d8bef9SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3647*e8d8bef9SDimitry Andric     extractGCDType(Parts, GCDTy, MI.getOperand(I).getReg());
3648*e8d8bef9SDimitry Andric 
3649*e8d8bef9SDimitry Andric   // Build the requested new merge, padding with undef.
3650*e8d8bef9SDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts,
3651*e8d8bef9SDimitry Andric                                   TargetOpcode::G_ANYEXT);
3652*e8d8bef9SDimitry Andric 
3653*e8d8bef9SDimitry Andric   // Pack into the original result register.
3654*e8d8bef9SDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
3655*e8d8bef9SDimitry Andric 
3656*e8d8bef9SDimitry Andric   MI.eraseFromParent();
3657*e8d8bef9SDimitry Andric   return Legalized;
36588bcb0991SDimitry Andric }
36598bcb0991SDimitry Andric 
3660*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3661*e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorExtractInsertVectorElt(MachineInstr &MI,
3662*e8d8bef9SDimitry Andric                                                            unsigned TypeIdx,
3663*e8d8bef9SDimitry Andric                                                            LLT NarrowVecTy) {
3664*e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3665*e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
3666*e8d8bef9SDimitry Andric   Register InsertVal;
3667*e8d8bef9SDimitry Andric   bool IsInsert = MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT;
3668*e8d8bef9SDimitry Andric 
3669*e8d8bef9SDimitry Andric   assert((IsInsert ? TypeIdx == 0 : TypeIdx == 1) && "not a vector type index");
3670*e8d8bef9SDimitry Andric   if (IsInsert)
3671*e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
3672*e8d8bef9SDimitry Andric 
3673*e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
3674*e8d8bef9SDimitry Andric 
3675*e8d8bef9SDimitry Andric   // TODO: Handle total scalarization case.
3676*e8d8bef9SDimitry Andric   if (!NarrowVecTy.isVector())
3677*e8d8bef9SDimitry Andric     return UnableToLegalize;
3678*e8d8bef9SDimitry Andric 
3679*e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
3680*e8d8bef9SDimitry Andric 
3681*e8d8bef9SDimitry Andric   // If the index is a constant, we can really break this down as you would
3682*e8d8bef9SDimitry Andric   // expect, and index into the target size pieces.
3683*e8d8bef9SDimitry Andric   int64_t IdxVal;
3684*e8d8bef9SDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal))) {
3685*e8d8bef9SDimitry Andric     // Avoid out of bounds indexing the pieces.
3686*e8d8bef9SDimitry Andric     if (IdxVal >= VecTy.getNumElements()) {
3687*e8d8bef9SDimitry Andric       MIRBuilder.buildUndef(DstReg);
3688*e8d8bef9SDimitry Andric       MI.eraseFromParent();
3689*e8d8bef9SDimitry Andric       return Legalized;
36908bcb0991SDimitry Andric     }
36918bcb0991SDimitry Andric 
3692*e8d8bef9SDimitry Andric     SmallVector<Register, 8> VecParts;
3693*e8d8bef9SDimitry Andric     LLT GCDTy = extractGCDType(VecParts, VecTy, NarrowVecTy, SrcVec);
3694*e8d8bef9SDimitry Andric 
3695*e8d8bef9SDimitry Andric     // Build a sequence of NarrowTy pieces in VecParts for this operand.
3696*e8d8bef9SDimitry Andric     LLT LCMTy = buildLCMMergePieces(VecTy, NarrowVecTy, GCDTy, VecParts,
3697*e8d8bef9SDimitry Andric                                     TargetOpcode::G_ANYEXT);
3698*e8d8bef9SDimitry Andric 
3699*e8d8bef9SDimitry Andric     unsigned NewNumElts = NarrowVecTy.getNumElements();
3700*e8d8bef9SDimitry Andric 
3701*e8d8bef9SDimitry Andric     LLT IdxTy = MRI.getType(Idx);
3702*e8d8bef9SDimitry Andric     int64_t PartIdx = IdxVal / NewNumElts;
3703*e8d8bef9SDimitry Andric     auto NewIdx =
3704*e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(IdxTy, IdxVal - NewNumElts * PartIdx);
3705*e8d8bef9SDimitry Andric 
3706*e8d8bef9SDimitry Andric     if (IsInsert) {
3707*e8d8bef9SDimitry Andric       LLT PartTy = MRI.getType(VecParts[PartIdx]);
3708*e8d8bef9SDimitry Andric 
3709*e8d8bef9SDimitry Andric       // Use the adjusted index to insert into one of the subvectors.
3710*e8d8bef9SDimitry Andric       auto InsertPart = MIRBuilder.buildInsertVectorElement(
3711*e8d8bef9SDimitry Andric           PartTy, VecParts[PartIdx], InsertVal, NewIdx);
3712*e8d8bef9SDimitry Andric       VecParts[PartIdx] = InsertPart.getReg(0);
3713*e8d8bef9SDimitry Andric 
3714*e8d8bef9SDimitry Andric       // Recombine the inserted subvector with the others to reform the result
3715*e8d8bef9SDimitry Andric       // vector.
3716*e8d8bef9SDimitry Andric       buildWidenedRemergeToDst(DstReg, LCMTy, VecParts);
3717*e8d8bef9SDimitry Andric     } else {
3718*e8d8bef9SDimitry Andric       MIRBuilder.buildExtractVectorElement(DstReg, VecParts[PartIdx], NewIdx);
37198bcb0991SDimitry Andric     }
37208bcb0991SDimitry Andric 
37218bcb0991SDimitry Andric     MI.eraseFromParent();
37228bcb0991SDimitry Andric     return Legalized;
37238bcb0991SDimitry Andric   }
37248bcb0991SDimitry Andric 
3725*e8d8bef9SDimitry Andric   // With a variable index, we can't perform the operation in a smaller type, so
3726*e8d8bef9SDimitry Andric   // we're forced to expand this.
3727*e8d8bef9SDimitry Andric   //
3728*e8d8bef9SDimitry Andric   // TODO: We could emit a chain of compare/select to figure out which piece to
3729*e8d8bef9SDimitry Andric   // index.
3730*e8d8bef9SDimitry Andric   return lowerExtractInsertVectorElt(MI);
3731*e8d8bef9SDimitry Andric }
3732*e8d8bef9SDimitry Andric 
37338bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
37340b57cec5SDimitry Andric LegalizerHelper::reduceLoadStoreWidth(MachineInstr &MI, unsigned TypeIdx,
37350b57cec5SDimitry Andric                                       LLT NarrowTy) {
37360b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
37370b57cec5SDimitry Andric   if (TypeIdx != 0)
37380b57cec5SDimitry Andric     return UnableToLegalize;
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric   MachineMemOperand *MMO = *MI.memoperands_begin();
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric   // This implementation doesn't work for atomics. Give up instead of doing
37430b57cec5SDimitry Andric   // something invalid.
37440b57cec5SDimitry Andric   if (MMO->getOrdering() != AtomicOrdering::NotAtomic ||
37450b57cec5SDimitry Andric       MMO->getFailureOrdering() != AtomicOrdering::NotAtomic)
37460b57cec5SDimitry Andric     return UnableToLegalize;
37470b57cec5SDimitry Andric 
37480b57cec5SDimitry Andric   bool IsLoad = MI.getOpcode() == TargetOpcode::G_LOAD;
37490b57cec5SDimitry Andric   Register ValReg = MI.getOperand(0).getReg();
37500b57cec5SDimitry Andric   Register AddrReg = MI.getOperand(1).getReg();
37510b57cec5SDimitry Andric   LLT ValTy = MRI.getType(ValReg);
37520b57cec5SDimitry Andric 
37535ffd83dbSDimitry Andric   // FIXME: Do we need a distinct NarrowMemory legalize action?
37545ffd83dbSDimitry Andric   if (ValTy.getSizeInBits() != 8 * MMO->getSize()) {
37555ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Can't narrow extload/truncstore\n");
37565ffd83dbSDimitry Andric     return UnableToLegalize;
37575ffd83dbSDimitry Andric   }
37585ffd83dbSDimitry Andric 
37590b57cec5SDimitry Andric   int NumParts = -1;
37600b57cec5SDimitry Andric   int NumLeftover = -1;
37610b57cec5SDimitry Andric   LLT LeftoverTy;
37620b57cec5SDimitry Andric   SmallVector<Register, 8> NarrowRegs, NarrowLeftoverRegs;
37630b57cec5SDimitry Andric   if (IsLoad) {
37640b57cec5SDimitry Andric     std::tie(NumParts, NumLeftover) = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
37650b57cec5SDimitry Andric   } else {
37660b57cec5SDimitry Andric     if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
37670b57cec5SDimitry Andric                      NarrowLeftoverRegs)) {
37680b57cec5SDimitry Andric       NumParts = NarrowRegs.size();
37690b57cec5SDimitry Andric       NumLeftover = NarrowLeftoverRegs.size();
37700b57cec5SDimitry Andric     }
37710b57cec5SDimitry Andric   }
37720b57cec5SDimitry Andric 
37730b57cec5SDimitry Andric   if (NumParts == -1)
37740b57cec5SDimitry Andric     return UnableToLegalize;
37750b57cec5SDimitry Andric 
3776*e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(AddrReg);
3777*e8d8bef9SDimitry Andric   const LLT OffsetTy = LLT::scalar(PtrTy.getSizeInBits());
37780b57cec5SDimitry Andric 
37790b57cec5SDimitry Andric   unsigned TotalSize = ValTy.getSizeInBits();
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric   // Split the load/store into PartTy sized pieces starting at Offset. If this
37820b57cec5SDimitry Andric   // is a load, return the new registers in ValRegs. For a store, each elements
37830b57cec5SDimitry Andric   // of ValRegs should be PartTy. Returns the next offset that needs to be
37840b57cec5SDimitry Andric   // handled.
37850b57cec5SDimitry Andric   auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<Register> &ValRegs,
37860b57cec5SDimitry Andric                              unsigned Offset) -> unsigned {
37870b57cec5SDimitry Andric     MachineFunction &MF = MIRBuilder.getMF();
37880b57cec5SDimitry Andric     unsigned PartSize = PartTy.getSizeInBits();
37890b57cec5SDimitry Andric     for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
37900b57cec5SDimitry Andric          Offset += PartSize, ++Idx) {
37910b57cec5SDimitry Andric       unsigned ByteSize = PartSize / 8;
37920b57cec5SDimitry Andric       unsigned ByteOffset = Offset / 8;
37930b57cec5SDimitry Andric       Register NewAddrReg;
37940b57cec5SDimitry Andric 
3795480093f4SDimitry Andric       MIRBuilder.materializePtrAdd(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric       MachineMemOperand *NewMMO =
37980b57cec5SDimitry Andric         MF.getMachineMemOperand(MMO, ByteOffset, ByteSize);
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric       if (IsLoad) {
38010b57cec5SDimitry Andric         Register Dst = MRI.createGenericVirtualRegister(PartTy);
38020b57cec5SDimitry Andric         ValRegs.push_back(Dst);
38030b57cec5SDimitry Andric         MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
38040b57cec5SDimitry Andric       } else {
38050b57cec5SDimitry Andric         MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
38060b57cec5SDimitry Andric       }
38070b57cec5SDimitry Andric     }
38080b57cec5SDimitry Andric 
38090b57cec5SDimitry Andric     return Offset;
38100b57cec5SDimitry Andric   };
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric   unsigned HandledOffset = splitTypePieces(NarrowTy, NarrowRegs, 0);
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric   // Handle the rest of the register if this isn't an even type breakdown.
38150b57cec5SDimitry Andric   if (LeftoverTy.isValid())
38160b57cec5SDimitry Andric     splitTypePieces(LeftoverTy, NarrowLeftoverRegs, HandledOffset);
38170b57cec5SDimitry Andric 
38180b57cec5SDimitry Andric   if (IsLoad) {
38190b57cec5SDimitry Andric     insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
38200b57cec5SDimitry Andric                 LeftoverTy, NarrowLeftoverRegs);
38210b57cec5SDimitry Andric   }
38220b57cec5SDimitry Andric 
38230b57cec5SDimitry Andric   MI.eraseFromParent();
38240b57cec5SDimitry Andric   return Legalized;
38250b57cec5SDimitry Andric }
38260b57cec5SDimitry Andric 
38270b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
38285ffd83dbSDimitry Andric LegalizerHelper::reduceOperationWidth(MachineInstr &MI, unsigned int TypeIdx,
38295ffd83dbSDimitry Andric                                       LLT NarrowTy) {
38305ffd83dbSDimitry Andric   assert(TypeIdx == 0 && "only one type index expected");
38315ffd83dbSDimitry Andric 
38325ffd83dbSDimitry Andric   const unsigned Opc = MI.getOpcode();
38335ffd83dbSDimitry Andric   const int NumOps = MI.getNumOperands() - 1;
38345ffd83dbSDimitry Andric   const Register DstReg = MI.getOperand(0).getReg();
38355ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
38365ffd83dbSDimitry Andric   const unsigned NarrowSize = NarrowTy.getSizeInBits();
38375ffd83dbSDimitry Andric   const LLT NarrowScalarTy = LLT::scalar(NarrowSize);
38385ffd83dbSDimitry Andric 
38395ffd83dbSDimitry Andric   assert(NumOps <= 3 && "expected instruction with 1 result and 1-3 sources");
38405ffd83dbSDimitry Andric 
38415ffd83dbSDimitry Andric   // First of all check whether we are narrowing (changing the element type)
38425ffd83dbSDimitry Andric   // or reducing the vector elements
38435ffd83dbSDimitry Andric   const LLT DstTy = MRI.getType(DstReg);
38445ffd83dbSDimitry Andric   const bool IsNarrow = NarrowTy.getScalarType() != DstTy.getScalarType();
38455ffd83dbSDimitry Andric 
38465ffd83dbSDimitry Andric   SmallVector<Register, 8> ExtractedRegs[3];
38475ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
38485ffd83dbSDimitry Andric 
38495ffd83dbSDimitry Andric   unsigned NarrowElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
38505ffd83dbSDimitry Andric 
38515ffd83dbSDimitry Andric   // Break down all the sources into NarrowTy pieces we can operate on. This may
38525ffd83dbSDimitry Andric   // involve creating merges to a wider type, padded with undef.
38535ffd83dbSDimitry Andric   for (int I = 0; I != NumOps; ++I) {
38545ffd83dbSDimitry Andric     Register SrcReg = MI.getOperand(I + 1).getReg();
38555ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
38565ffd83dbSDimitry Andric 
38575ffd83dbSDimitry Andric     // The type to narrow SrcReg to. For narrowing, this is a smaller scalar.
38585ffd83dbSDimitry Andric     // For fewerElements, this is a smaller vector with the same element type.
38595ffd83dbSDimitry Andric     LLT OpNarrowTy;
38605ffd83dbSDimitry Andric     if (IsNarrow) {
38615ffd83dbSDimitry Andric       OpNarrowTy = NarrowScalarTy;
38625ffd83dbSDimitry Andric 
38635ffd83dbSDimitry Andric       // In case of narrowing, we need to cast vectors to scalars for this to
38645ffd83dbSDimitry Andric       // work properly
38655ffd83dbSDimitry Andric       // FIXME: Can we do without the bitcast here if we're narrowing?
38665ffd83dbSDimitry Andric       if (SrcTy.isVector()) {
38675ffd83dbSDimitry Andric         SrcTy = LLT::scalar(SrcTy.getSizeInBits());
38685ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(SrcTy, SrcReg).getReg(0);
38695ffd83dbSDimitry Andric       }
38705ffd83dbSDimitry Andric     } else {
38715ffd83dbSDimitry Andric       OpNarrowTy = LLT::scalarOrVector(NarrowElts, SrcTy.getScalarType());
38725ffd83dbSDimitry Andric     }
38735ffd83dbSDimitry Andric 
38745ffd83dbSDimitry Andric     LLT GCDTy = extractGCDType(ExtractedRegs[I], SrcTy, OpNarrowTy, SrcReg);
38755ffd83dbSDimitry Andric 
38765ffd83dbSDimitry Andric     // Build a sequence of NarrowTy pieces in ExtractedRegs for this operand.
38775ffd83dbSDimitry Andric     buildLCMMergePieces(SrcTy, OpNarrowTy, GCDTy, ExtractedRegs[I],
38785ffd83dbSDimitry Andric                         TargetOpcode::G_ANYEXT);
38795ffd83dbSDimitry Andric   }
38805ffd83dbSDimitry Andric 
38815ffd83dbSDimitry Andric   SmallVector<Register, 8> ResultRegs;
38825ffd83dbSDimitry Andric 
38835ffd83dbSDimitry Andric   // Input operands for each sub-instruction.
38845ffd83dbSDimitry Andric   SmallVector<SrcOp, 4> InputRegs(NumOps, Register());
38855ffd83dbSDimitry Andric 
38865ffd83dbSDimitry Andric   int NumParts = ExtractedRegs[0].size();
38875ffd83dbSDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
38885ffd83dbSDimitry Andric   const LLT DstScalarTy = LLT::scalar(DstSize);
38895ffd83dbSDimitry Andric 
38905ffd83dbSDimitry Andric   // Narrowing needs to use scalar types
38915ffd83dbSDimitry Andric   LLT DstLCMTy, NarrowDstTy;
38925ffd83dbSDimitry Andric   if (IsNarrow) {
38935ffd83dbSDimitry Andric     DstLCMTy = getLCMType(DstScalarTy, NarrowScalarTy);
38945ffd83dbSDimitry Andric     NarrowDstTy = NarrowScalarTy;
38955ffd83dbSDimitry Andric   } else {
38965ffd83dbSDimitry Andric     DstLCMTy = getLCMType(DstTy, NarrowTy);
38975ffd83dbSDimitry Andric     NarrowDstTy = NarrowTy;
38985ffd83dbSDimitry Andric   }
38995ffd83dbSDimitry Andric 
39005ffd83dbSDimitry Andric   // We widened the source registers to satisfy merge/unmerge size
39015ffd83dbSDimitry Andric   // constraints. We'll have some extra fully undef parts.
39025ffd83dbSDimitry Andric   const int NumRealParts = (DstSize + NarrowSize - 1) / NarrowSize;
39035ffd83dbSDimitry Andric 
39045ffd83dbSDimitry Andric   for (int I = 0; I != NumRealParts; ++I) {
39055ffd83dbSDimitry Andric     // Emit this instruction on each of the split pieces.
39065ffd83dbSDimitry Andric     for (int J = 0; J != NumOps; ++J)
39075ffd83dbSDimitry Andric       InputRegs[J] = ExtractedRegs[J][I];
39085ffd83dbSDimitry Andric 
39095ffd83dbSDimitry Andric     auto Inst = MIRBuilder.buildInstr(Opc, {NarrowDstTy}, InputRegs, Flags);
39105ffd83dbSDimitry Andric     ResultRegs.push_back(Inst.getReg(0));
39115ffd83dbSDimitry Andric   }
39125ffd83dbSDimitry Andric 
39135ffd83dbSDimitry Andric   // Fill out the widened result with undef instead of creating instructions
39145ffd83dbSDimitry Andric   // with undef inputs.
39155ffd83dbSDimitry Andric   int NumUndefParts = NumParts - NumRealParts;
39165ffd83dbSDimitry Andric   if (NumUndefParts != 0)
39175ffd83dbSDimitry Andric     ResultRegs.append(NumUndefParts,
39185ffd83dbSDimitry Andric                       MIRBuilder.buildUndef(NarrowDstTy).getReg(0));
39195ffd83dbSDimitry Andric 
39205ffd83dbSDimitry Andric   // Extract the possibly padded result. Use a scratch register if we need to do
39215ffd83dbSDimitry Andric   // a final bitcast, otherwise use the original result register.
39225ffd83dbSDimitry Andric   Register MergeDstReg;
39235ffd83dbSDimitry Andric   if (IsNarrow && DstTy.isVector())
39245ffd83dbSDimitry Andric     MergeDstReg = MRI.createGenericVirtualRegister(DstScalarTy);
39255ffd83dbSDimitry Andric   else
39265ffd83dbSDimitry Andric     MergeDstReg = DstReg;
39275ffd83dbSDimitry Andric 
39285ffd83dbSDimitry Andric   buildWidenedRemergeToDst(MergeDstReg, DstLCMTy, ResultRegs);
39295ffd83dbSDimitry Andric 
39305ffd83dbSDimitry Andric   // Recast to vector if we narrowed a vector
39315ffd83dbSDimitry Andric   if (IsNarrow && DstTy.isVector())
39325ffd83dbSDimitry Andric     MIRBuilder.buildBitcast(DstReg, MergeDstReg);
39335ffd83dbSDimitry Andric 
39345ffd83dbSDimitry Andric   MI.eraseFromParent();
39355ffd83dbSDimitry Andric   return Legalized;
39365ffd83dbSDimitry Andric }
39375ffd83dbSDimitry Andric 
39385ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
39395ffd83dbSDimitry Andric LegalizerHelper::fewerElementsVectorSextInReg(MachineInstr &MI, unsigned TypeIdx,
39405ffd83dbSDimitry Andric                                               LLT NarrowTy) {
39415ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
39425ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
39435ffd83dbSDimitry Andric   int64_t Imm = MI.getOperand(2).getImm();
39445ffd83dbSDimitry Andric 
39455ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
39465ffd83dbSDimitry Andric 
39475ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
39485ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
39495ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts);
39505ffd83dbSDimitry Andric 
39515ffd83dbSDimitry Andric   for (Register &R : Parts)
39525ffd83dbSDimitry Andric     R = MIRBuilder.buildSExtInReg(NarrowTy, R, Imm).getReg(0);
39535ffd83dbSDimitry Andric 
39545ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
39555ffd83dbSDimitry Andric 
39565ffd83dbSDimitry Andric   MI.eraseFromParent();
39575ffd83dbSDimitry Andric   return Legalized;
39585ffd83dbSDimitry Andric }
39595ffd83dbSDimitry Andric 
39605ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
39610b57cec5SDimitry Andric LegalizerHelper::fewerElementsVector(MachineInstr &MI, unsigned TypeIdx,
39620b57cec5SDimitry Andric                                      LLT NarrowTy) {
39630b57cec5SDimitry Andric   using namespace TargetOpcode;
39640b57cec5SDimitry Andric 
39650b57cec5SDimitry Andric   switch (MI.getOpcode()) {
39660b57cec5SDimitry Andric   case G_IMPLICIT_DEF:
39670b57cec5SDimitry Andric     return fewerElementsVectorImplicitDef(MI, TypeIdx, NarrowTy);
39685ffd83dbSDimitry Andric   case G_TRUNC:
39690b57cec5SDimitry Andric   case G_AND:
39700b57cec5SDimitry Andric   case G_OR:
39710b57cec5SDimitry Andric   case G_XOR:
39720b57cec5SDimitry Andric   case G_ADD:
39730b57cec5SDimitry Andric   case G_SUB:
39740b57cec5SDimitry Andric   case G_MUL:
3975*e8d8bef9SDimitry Andric   case G_PTR_ADD:
39760b57cec5SDimitry Andric   case G_SMULH:
39770b57cec5SDimitry Andric   case G_UMULH:
39780b57cec5SDimitry Andric   case G_FADD:
39790b57cec5SDimitry Andric   case G_FMUL:
39800b57cec5SDimitry Andric   case G_FSUB:
39810b57cec5SDimitry Andric   case G_FNEG:
39820b57cec5SDimitry Andric   case G_FABS:
39830b57cec5SDimitry Andric   case G_FCANONICALIZE:
39840b57cec5SDimitry Andric   case G_FDIV:
39850b57cec5SDimitry Andric   case G_FREM:
39860b57cec5SDimitry Andric   case G_FMA:
39878bcb0991SDimitry Andric   case G_FMAD:
39880b57cec5SDimitry Andric   case G_FPOW:
39890b57cec5SDimitry Andric   case G_FEXP:
39900b57cec5SDimitry Andric   case G_FEXP2:
39910b57cec5SDimitry Andric   case G_FLOG:
39920b57cec5SDimitry Andric   case G_FLOG2:
39930b57cec5SDimitry Andric   case G_FLOG10:
39940b57cec5SDimitry Andric   case G_FNEARBYINT:
39950b57cec5SDimitry Andric   case G_FCEIL:
39960b57cec5SDimitry Andric   case G_FFLOOR:
39970b57cec5SDimitry Andric   case G_FRINT:
39980b57cec5SDimitry Andric   case G_INTRINSIC_ROUND:
3999*e8d8bef9SDimitry Andric   case G_INTRINSIC_ROUNDEVEN:
40000b57cec5SDimitry Andric   case G_INTRINSIC_TRUNC:
40010b57cec5SDimitry Andric   case G_FCOS:
40020b57cec5SDimitry Andric   case G_FSIN:
40030b57cec5SDimitry Andric   case G_FSQRT:
40040b57cec5SDimitry Andric   case G_BSWAP:
40058bcb0991SDimitry Andric   case G_BITREVERSE:
40060b57cec5SDimitry Andric   case G_SDIV:
4007480093f4SDimitry Andric   case G_UDIV:
4008480093f4SDimitry Andric   case G_SREM:
4009480093f4SDimitry Andric   case G_UREM:
40100b57cec5SDimitry Andric   case G_SMIN:
40110b57cec5SDimitry Andric   case G_SMAX:
40120b57cec5SDimitry Andric   case G_UMIN:
40130b57cec5SDimitry Andric   case G_UMAX:
40140b57cec5SDimitry Andric   case G_FMINNUM:
40150b57cec5SDimitry Andric   case G_FMAXNUM:
40160b57cec5SDimitry Andric   case G_FMINNUM_IEEE:
40170b57cec5SDimitry Andric   case G_FMAXNUM_IEEE:
40180b57cec5SDimitry Andric   case G_FMINIMUM:
40190b57cec5SDimitry Andric   case G_FMAXIMUM:
40205ffd83dbSDimitry Andric   case G_FSHL:
40215ffd83dbSDimitry Andric   case G_FSHR:
40225ffd83dbSDimitry Andric   case G_FREEZE:
40235ffd83dbSDimitry Andric   case G_SADDSAT:
40245ffd83dbSDimitry Andric   case G_SSUBSAT:
40255ffd83dbSDimitry Andric   case G_UADDSAT:
40265ffd83dbSDimitry Andric   case G_USUBSAT:
40275ffd83dbSDimitry Andric     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
40280b57cec5SDimitry Andric   case G_SHL:
40290b57cec5SDimitry Andric   case G_LSHR:
40300b57cec5SDimitry Andric   case G_ASHR:
4031*e8d8bef9SDimitry Andric   case G_SSHLSAT:
4032*e8d8bef9SDimitry Andric   case G_USHLSAT:
40330b57cec5SDimitry Andric   case G_CTLZ:
40340b57cec5SDimitry Andric   case G_CTLZ_ZERO_UNDEF:
40350b57cec5SDimitry Andric   case G_CTTZ:
40360b57cec5SDimitry Andric   case G_CTTZ_ZERO_UNDEF:
40370b57cec5SDimitry Andric   case G_CTPOP:
40380b57cec5SDimitry Andric   case G_FCOPYSIGN:
40390b57cec5SDimitry Andric     return fewerElementsVectorMultiEltType(MI, TypeIdx, NarrowTy);
40400b57cec5SDimitry Andric   case G_ZEXT:
40410b57cec5SDimitry Andric   case G_SEXT:
40420b57cec5SDimitry Andric   case G_ANYEXT:
40430b57cec5SDimitry Andric   case G_FPEXT:
40440b57cec5SDimitry Andric   case G_FPTRUNC:
40450b57cec5SDimitry Andric   case G_SITOFP:
40460b57cec5SDimitry Andric   case G_UITOFP:
40470b57cec5SDimitry Andric   case G_FPTOSI:
40480b57cec5SDimitry Andric   case G_FPTOUI:
40490b57cec5SDimitry Andric   case G_INTTOPTR:
40500b57cec5SDimitry Andric   case G_PTRTOINT:
40510b57cec5SDimitry Andric   case G_ADDRSPACE_CAST:
40520b57cec5SDimitry Andric     return fewerElementsVectorCasts(MI, TypeIdx, NarrowTy);
40530b57cec5SDimitry Andric   case G_ICMP:
40540b57cec5SDimitry Andric   case G_FCMP:
40550b57cec5SDimitry Andric     return fewerElementsVectorCmp(MI, TypeIdx, NarrowTy);
40560b57cec5SDimitry Andric   case G_SELECT:
40570b57cec5SDimitry Andric     return fewerElementsVectorSelect(MI, TypeIdx, NarrowTy);
40580b57cec5SDimitry Andric   case G_PHI:
40590b57cec5SDimitry Andric     return fewerElementsVectorPhi(MI, TypeIdx, NarrowTy);
40608bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
40618bcb0991SDimitry Andric     return fewerElementsVectorUnmergeValues(MI, TypeIdx, NarrowTy);
40628bcb0991SDimitry Andric   case G_BUILD_VECTOR:
4063*e8d8bef9SDimitry Andric     assert(TypeIdx == 0 && "not a vector type index");
4064*e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4065*e8d8bef9SDimitry Andric   case G_CONCAT_VECTORS:
4066*e8d8bef9SDimitry Andric     if (TypeIdx != 1) // TODO: This probably does work as expected already.
4067*e8d8bef9SDimitry Andric       return UnableToLegalize;
4068*e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4069*e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
4070*e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
4071*e8d8bef9SDimitry Andric     return fewerElementsVectorExtractInsertVectorElt(MI, TypeIdx, NarrowTy);
40720b57cec5SDimitry Andric   case G_LOAD:
40730b57cec5SDimitry Andric   case G_STORE:
40740b57cec5SDimitry Andric     return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
40755ffd83dbSDimitry Andric   case G_SEXT_INREG:
40765ffd83dbSDimitry Andric     return fewerElementsVectorSextInReg(MI, TypeIdx, NarrowTy);
40770b57cec5SDimitry Andric   default:
40780b57cec5SDimitry Andric     return UnableToLegalize;
40790b57cec5SDimitry Andric   }
40800b57cec5SDimitry Andric }
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
40830b57cec5SDimitry Andric LegalizerHelper::narrowScalarShiftByConstant(MachineInstr &MI, const APInt &Amt,
40840b57cec5SDimitry Andric                                              const LLT HalfTy, const LLT AmtTy) {
40850b57cec5SDimitry Andric 
40860b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
40870b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
40885ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric   if (Amt.isNullValue()) {
40915ffd83dbSDimitry Andric     MIRBuilder.buildMerge(MI.getOperand(0), {InL, InH});
40920b57cec5SDimitry Andric     MI.eraseFromParent();
40930b57cec5SDimitry Andric     return Legalized;
40940b57cec5SDimitry Andric   }
40950b57cec5SDimitry Andric 
40960b57cec5SDimitry Andric   LLT NVT = HalfTy;
40970b57cec5SDimitry Andric   unsigned NVTBits = HalfTy.getSizeInBits();
40980b57cec5SDimitry Andric   unsigned VTBits = 2 * NVTBits;
40990b57cec5SDimitry Andric 
41000b57cec5SDimitry Andric   SrcOp Lo(Register(0)), Hi(Register(0));
41010b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_SHL) {
41020b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
41030b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
41040b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
41050b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
41060b57cec5SDimitry Andric       Hi = MIRBuilder.buildShl(NVT, InL,
41070b57cec5SDimitry Andric                                MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
41080b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
41090b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
41100b57cec5SDimitry Andric       Hi = InL;
41110b57cec5SDimitry Andric     } else {
41120b57cec5SDimitry Andric       Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
41130b57cec5SDimitry Andric       auto OrLHS =
41140b57cec5SDimitry Andric           MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
41150b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildLShr(
41160b57cec5SDimitry Andric           NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
41170b57cec5SDimitry Andric       Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
41180b57cec5SDimitry Andric     }
41190b57cec5SDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
41200b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
41210b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
41220b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
41230b57cec5SDimitry Andric       Lo = MIRBuilder.buildLShr(NVT, InH,
41240b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
41250b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
41260b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
41270b57cec5SDimitry Andric       Lo = InH;
41280b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
41290b57cec5SDimitry Andric     } else {
41300b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
41310b57cec5SDimitry Andric 
41320b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
41330b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
41340b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
41370b57cec5SDimitry Andric       Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
41380b57cec5SDimitry Andric     }
41390b57cec5SDimitry Andric   } else {
41400b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
41410b57cec5SDimitry Andric       Hi = Lo = MIRBuilder.buildAShr(
41420b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
41430b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
41440b57cec5SDimitry Andric       Lo = MIRBuilder.buildAShr(NVT, InH,
41450b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
41460b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
41470b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
41480b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
41490b57cec5SDimitry Andric       Lo = InH;
41500b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
41510b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
41520b57cec5SDimitry Andric     } else {
41530b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
41560b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
41570b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
41600b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
41610b57cec5SDimitry Andric     }
41620b57cec5SDimitry Andric   }
41630b57cec5SDimitry Andric 
41645ffd83dbSDimitry Andric   MIRBuilder.buildMerge(MI.getOperand(0), {Lo, Hi});
41650b57cec5SDimitry Andric   MI.eraseFromParent();
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric   return Legalized;
41680b57cec5SDimitry Andric }
41690b57cec5SDimitry Andric 
41700b57cec5SDimitry Andric // TODO: Optimize if constant shift amount.
41710b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
41720b57cec5SDimitry Andric LegalizerHelper::narrowScalarShift(MachineInstr &MI, unsigned TypeIdx,
41730b57cec5SDimitry Andric                                    LLT RequestedTy) {
41740b57cec5SDimitry Andric   if (TypeIdx == 1) {
41750b57cec5SDimitry Andric     Observer.changingInstr(MI);
41760b57cec5SDimitry Andric     narrowScalarSrc(MI, RequestedTy, 2);
41770b57cec5SDimitry Andric     Observer.changedInstr(MI);
41780b57cec5SDimitry Andric     return Legalized;
41790b57cec5SDimitry Andric   }
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
41820b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
41830b57cec5SDimitry Andric   if (DstTy.isVector())
41840b57cec5SDimitry Andric     return UnableToLegalize;
41850b57cec5SDimitry Andric 
41860b57cec5SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
41870b57cec5SDimitry Andric   LLT ShiftAmtTy = MRI.getType(Amt);
41880b57cec5SDimitry Andric   const unsigned DstEltSize = DstTy.getScalarSizeInBits();
41890b57cec5SDimitry Andric   if (DstEltSize % 2 != 0)
41900b57cec5SDimitry Andric     return UnableToLegalize;
41910b57cec5SDimitry Andric 
41920b57cec5SDimitry Andric   // Ignore the input type. We can only go to exactly half the size of the
41930b57cec5SDimitry Andric   // input. If that isn't small enough, the resulting pieces will be further
41940b57cec5SDimitry Andric   // legalized.
41950b57cec5SDimitry Andric   const unsigned NewBitSize = DstEltSize / 2;
41960b57cec5SDimitry Andric   const LLT HalfTy = LLT::scalar(NewBitSize);
41970b57cec5SDimitry Andric   const LLT CondTy = LLT::scalar(1);
41980b57cec5SDimitry Andric 
41990b57cec5SDimitry Andric   if (const MachineInstr *KShiftAmt =
42000b57cec5SDimitry Andric           getOpcodeDef(TargetOpcode::G_CONSTANT, Amt, MRI)) {
42010b57cec5SDimitry Andric     return narrowScalarShiftByConstant(
42020b57cec5SDimitry Andric         MI, KShiftAmt->getOperand(1).getCImm()->getValue(), HalfTy, ShiftAmtTy);
42030b57cec5SDimitry Andric   }
42040b57cec5SDimitry Andric 
42050b57cec5SDimitry Andric   // TODO: Expand with known bits.
42060b57cec5SDimitry Andric 
42070b57cec5SDimitry Andric   // Handle the fully general expansion by an unknown amount.
42080b57cec5SDimitry Andric   auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
42090b57cec5SDimitry Andric 
42100b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
42110b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
42125ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
42130b57cec5SDimitry Andric 
42140b57cec5SDimitry Andric   auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
42150b57cec5SDimitry Andric   auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
42160b57cec5SDimitry Andric 
42170b57cec5SDimitry Andric   auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
42180b57cec5SDimitry Andric   auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
42190b57cec5SDimitry Andric   auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   Register ResultRegs[2];
42220b57cec5SDimitry Andric   switch (MI.getOpcode()) {
42230b57cec5SDimitry Andric   case TargetOpcode::G_SHL: {
42240b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
42258bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildShl(HalfTy, InL, Amt);
42260b57cec5SDimitry Andric 
42278bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
42288bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, Amt);
42298bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
42320b57cec5SDimitry Andric     auto LoL = MIRBuilder.buildConstant(HalfTy, 0);         // Lo part is zero.
42330b57cec5SDimitry Andric     auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
42340b57cec5SDimitry Andric 
42350b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
42360b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(
42370b57cec5SDimitry Andric         HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
42400b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
42410b57cec5SDimitry Andric     break;
42420b57cec5SDimitry Andric   }
42438bcb0991SDimitry Andric   case TargetOpcode::G_LSHR:
42440b57cec5SDimitry Andric   case TargetOpcode::G_ASHR: {
42450b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
42468bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy}, {InH, Amt});
42470b57cec5SDimitry Andric 
42488bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, Amt);
42498bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
42508bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
42510b57cec5SDimitry Andric 
42520b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
42538bcb0991SDimitry Andric     MachineInstrBuilder HiL;
42548bcb0991SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_LSHR) {
42558bcb0991SDimitry Andric       HiL = MIRBuilder.buildConstant(HalfTy, 0);            // Hi part is zero.
42568bcb0991SDimitry Andric     } else {
42578bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1);
42588bcb0991SDimitry Andric       HiL = MIRBuilder.buildAShr(HalfTy, InH, ShiftAmt);    // Sign of Hi part.
42598bcb0991SDimitry Andric     }
42608bcb0991SDimitry Andric     auto LoL = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy},
42618bcb0991SDimitry Andric                                      {InH, AmtExcess});     // Lo from Hi part.
42620b57cec5SDimitry Andric 
42630b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(
42640b57cec5SDimitry Andric         HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
42670b57cec5SDimitry Andric 
42680b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
42690b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
42700b57cec5SDimitry Andric     break;
42710b57cec5SDimitry Andric   }
42720b57cec5SDimitry Andric   default:
42730b57cec5SDimitry Andric     llvm_unreachable("not a shift");
42740b57cec5SDimitry Andric   }
42750b57cec5SDimitry Andric 
42760b57cec5SDimitry Andric   MIRBuilder.buildMerge(DstReg, ResultRegs);
42770b57cec5SDimitry Andric   MI.eraseFromParent();
42780b57cec5SDimitry Andric   return Legalized;
42790b57cec5SDimitry Andric }
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
42820b57cec5SDimitry Andric LegalizerHelper::moreElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
42830b57cec5SDimitry Andric                                        LLT MoreTy) {
42840b57cec5SDimitry Andric   assert(TypeIdx == 0 && "Expecting only Idx 0");
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric   Observer.changingInstr(MI);
42870b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
42880b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
42890b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
42900b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, I);
42910b57cec5SDimitry Andric   }
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
42940b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
42950b57cec5SDimitry Andric   moreElementsVectorDst(MI, MoreTy, 0);
42960b57cec5SDimitry Andric   Observer.changedInstr(MI);
42970b57cec5SDimitry Andric   return Legalized;
42980b57cec5SDimitry Andric }
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
43010b57cec5SDimitry Andric LegalizerHelper::moreElementsVector(MachineInstr &MI, unsigned TypeIdx,
43020b57cec5SDimitry Andric                                     LLT MoreTy) {
43030b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
43040b57cec5SDimitry Andric   switch (Opc) {
43058bcb0991SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF:
43068bcb0991SDimitry Andric   case TargetOpcode::G_LOAD: {
43078bcb0991SDimitry Andric     if (TypeIdx != 0)
43088bcb0991SDimitry Andric       return UnableToLegalize;
43090b57cec5SDimitry Andric     Observer.changingInstr(MI);
43100b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43110b57cec5SDimitry Andric     Observer.changedInstr(MI);
43120b57cec5SDimitry Andric     return Legalized;
43130b57cec5SDimitry Andric   }
43148bcb0991SDimitry Andric   case TargetOpcode::G_STORE:
43158bcb0991SDimitry Andric     if (TypeIdx != 0)
43168bcb0991SDimitry Andric       return UnableToLegalize;
43178bcb0991SDimitry Andric     Observer.changingInstr(MI);
43188bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 0);
43198bcb0991SDimitry Andric     Observer.changedInstr(MI);
43208bcb0991SDimitry Andric     return Legalized;
43210b57cec5SDimitry Andric   case TargetOpcode::G_AND:
43220b57cec5SDimitry Andric   case TargetOpcode::G_OR:
43230b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
43240b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
43250b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
43260b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
4327480093f4SDimitry Andric   case TargetOpcode::G_UMAX:
4328480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM:
4329480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM:
4330480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
4331480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
4332480093f4SDimitry Andric   case TargetOpcode::G_FMINIMUM:
4333480093f4SDimitry Andric   case TargetOpcode::G_FMAXIMUM: {
43340b57cec5SDimitry Andric     Observer.changingInstr(MI);
43350b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
43360b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
43370b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43380b57cec5SDimitry Andric     Observer.changedInstr(MI);
43390b57cec5SDimitry Andric     return Legalized;
43400b57cec5SDimitry Andric   }
43410b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
43420b57cec5SDimitry Andric     if (TypeIdx != 1)
43430b57cec5SDimitry Andric       return UnableToLegalize;
43440b57cec5SDimitry Andric     Observer.changingInstr(MI);
43450b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
43460b57cec5SDimitry Andric     Observer.changedInstr(MI);
43470b57cec5SDimitry Andric     return Legalized;
43480b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
43495ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
43500b57cec5SDimitry Andric     if (TypeIdx != 0)
43510b57cec5SDimitry Andric       return UnableToLegalize;
43520b57cec5SDimitry Andric     Observer.changingInstr(MI);
43530b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
43540b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43550b57cec5SDimitry Andric     Observer.changedInstr(MI);
43560b57cec5SDimitry Andric     return Legalized;
43570b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
43580b57cec5SDimitry Andric     if (TypeIdx != 0)
43590b57cec5SDimitry Andric       return UnableToLegalize;
43600b57cec5SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector())
43610b57cec5SDimitry Andric       return UnableToLegalize;
43620b57cec5SDimitry Andric 
43630b57cec5SDimitry Andric     Observer.changingInstr(MI);
43640b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
43650b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 3);
43660b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
43670b57cec5SDimitry Andric     Observer.changedInstr(MI);
43680b57cec5SDimitry Andric     return Legalized;
43698bcb0991SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES: {
43708bcb0991SDimitry Andric     if (TypeIdx != 1)
43718bcb0991SDimitry Andric       return UnableToLegalize;
43728bcb0991SDimitry Andric 
43738bcb0991SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
43748bcb0991SDimitry Andric     int NumDst = MI.getNumOperands() - 1;
43758bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, NumDst);
43768bcb0991SDimitry Andric 
43778bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
43788bcb0991SDimitry Andric     for (int I = 0; I != NumDst; ++I)
43798bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I).getReg());
43808bcb0991SDimitry Andric 
43818bcb0991SDimitry Andric     int NewNumDst = MoreTy.getSizeInBits() / DstTy.getSizeInBits();
43828bcb0991SDimitry Andric     for (int I = NumDst; I != NewNumDst; ++I)
43838bcb0991SDimitry Andric       MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
43848bcb0991SDimitry Andric 
43858bcb0991SDimitry Andric     MIB.addUse(MI.getOperand(NumDst).getReg());
43868bcb0991SDimitry Andric     MI.eraseFromParent();
43878bcb0991SDimitry Andric     return Legalized;
43888bcb0991SDimitry Andric   }
43890b57cec5SDimitry Andric   case TargetOpcode::G_PHI:
43900b57cec5SDimitry Andric     return moreElementsVectorPhi(MI, TypeIdx, MoreTy);
43910b57cec5SDimitry Andric   default:
43920b57cec5SDimitry Andric     return UnableToLegalize;
43930b57cec5SDimitry Andric   }
43940b57cec5SDimitry Andric }
43950b57cec5SDimitry Andric 
43960b57cec5SDimitry Andric void LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
43970b57cec5SDimitry Andric                                         ArrayRef<Register> Src1Regs,
43980b57cec5SDimitry Andric                                         ArrayRef<Register> Src2Regs,
43990b57cec5SDimitry Andric                                         LLT NarrowTy) {
44000b57cec5SDimitry Andric   MachineIRBuilder &B = MIRBuilder;
44010b57cec5SDimitry Andric   unsigned SrcParts = Src1Regs.size();
44020b57cec5SDimitry Andric   unsigned DstParts = DstRegs.size();
44030b57cec5SDimitry Andric 
44040b57cec5SDimitry Andric   unsigned DstIdx = 0; // Low bits of the result.
44050b57cec5SDimitry Andric   Register FactorSum =
44060b57cec5SDimitry Andric       B.buildMul(NarrowTy, Src1Regs[DstIdx], Src2Regs[DstIdx]).getReg(0);
44070b57cec5SDimitry Andric   DstRegs[DstIdx] = FactorSum;
44080b57cec5SDimitry Andric 
44090b57cec5SDimitry Andric   unsigned CarrySumPrevDstIdx;
44100b57cec5SDimitry Andric   SmallVector<Register, 4> Factors;
44110b57cec5SDimitry Andric 
44120b57cec5SDimitry Andric   for (DstIdx = 1; DstIdx < DstParts; DstIdx++) {
44130b57cec5SDimitry Andric     // Collect low parts of muls for DstIdx.
44140b57cec5SDimitry Andric     for (unsigned i = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
44150b57cec5SDimitry Andric          i <= std::min(DstIdx, SrcParts - 1); ++i) {
44160b57cec5SDimitry Andric       MachineInstrBuilder Mul =
44170b57cec5SDimitry Andric           B.buildMul(NarrowTy, Src1Regs[DstIdx - i], Src2Regs[i]);
44180b57cec5SDimitry Andric       Factors.push_back(Mul.getReg(0));
44190b57cec5SDimitry Andric     }
44200b57cec5SDimitry Andric     // Collect high parts of muls from previous DstIdx.
44210b57cec5SDimitry Andric     for (unsigned i = DstIdx < SrcParts ? 0 : DstIdx - SrcParts;
44220b57cec5SDimitry Andric          i <= std::min(DstIdx - 1, SrcParts - 1); ++i) {
44230b57cec5SDimitry Andric       MachineInstrBuilder Umulh =
44240b57cec5SDimitry Andric           B.buildUMulH(NarrowTy, Src1Regs[DstIdx - 1 - i], Src2Regs[i]);
44250b57cec5SDimitry Andric       Factors.push_back(Umulh.getReg(0));
44260b57cec5SDimitry Andric     }
4427480093f4SDimitry Andric     // Add CarrySum from additions calculated for previous DstIdx.
44280b57cec5SDimitry Andric     if (DstIdx != 1) {
44290b57cec5SDimitry Andric       Factors.push_back(CarrySumPrevDstIdx);
44300b57cec5SDimitry Andric     }
44310b57cec5SDimitry Andric 
44320b57cec5SDimitry Andric     Register CarrySum;
44330b57cec5SDimitry Andric     // Add all factors and accumulate all carries into CarrySum.
44340b57cec5SDimitry Andric     if (DstIdx != DstParts - 1) {
44350b57cec5SDimitry Andric       MachineInstrBuilder Uaddo =
44360b57cec5SDimitry Andric           B.buildUAddo(NarrowTy, LLT::scalar(1), Factors[0], Factors[1]);
44370b57cec5SDimitry Andric       FactorSum = Uaddo.getReg(0);
44380b57cec5SDimitry Andric       CarrySum = B.buildZExt(NarrowTy, Uaddo.getReg(1)).getReg(0);
44390b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i) {
44400b57cec5SDimitry Andric         MachineInstrBuilder Uaddo =
44410b57cec5SDimitry Andric             B.buildUAddo(NarrowTy, LLT::scalar(1), FactorSum, Factors[i]);
44420b57cec5SDimitry Andric         FactorSum = Uaddo.getReg(0);
44430b57cec5SDimitry Andric         MachineInstrBuilder Carry = B.buildZExt(NarrowTy, Uaddo.getReg(1));
44440b57cec5SDimitry Andric         CarrySum = B.buildAdd(NarrowTy, CarrySum, Carry).getReg(0);
44450b57cec5SDimitry Andric       }
44460b57cec5SDimitry Andric     } else {
44470b57cec5SDimitry Andric       // Since value for the next index is not calculated, neither is CarrySum.
44480b57cec5SDimitry Andric       FactorSum = B.buildAdd(NarrowTy, Factors[0], Factors[1]).getReg(0);
44490b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i)
44500b57cec5SDimitry Andric         FactorSum = B.buildAdd(NarrowTy, FactorSum, Factors[i]).getReg(0);
44510b57cec5SDimitry Andric     }
44520b57cec5SDimitry Andric 
44530b57cec5SDimitry Andric     CarrySumPrevDstIdx = CarrySum;
44540b57cec5SDimitry Andric     DstRegs[DstIdx] = FactorSum;
44550b57cec5SDimitry Andric     Factors.clear();
44560b57cec5SDimitry Andric   }
44570b57cec5SDimitry Andric }
44580b57cec5SDimitry Andric 
44590b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
44600b57cec5SDimitry Andric LegalizerHelper::narrowScalarMul(MachineInstr &MI, LLT NarrowTy) {
44610b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
44620b57cec5SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
44630b57cec5SDimitry Andric   Register Src2 = MI.getOperand(2).getReg();
44640b57cec5SDimitry Andric 
44650b57cec5SDimitry Andric   LLT Ty = MRI.getType(DstReg);
44660b57cec5SDimitry Andric   if (Ty.isVector())
44670b57cec5SDimitry Andric     return UnableToLegalize;
44680b57cec5SDimitry Andric 
44690b57cec5SDimitry Andric   unsigned SrcSize = MRI.getType(Src1).getSizeInBits();
44700b57cec5SDimitry Andric   unsigned DstSize = Ty.getSizeInBits();
44710b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
44720b57cec5SDimitry Andric   if (DstSize % NarrowSize != 0 || SrcSize % NarrowSize != 0)
44730b57cec5SDimitry Andric     return UnableToLegalize;
44740b57cec5SDimitry Andric 
44750b57cec5SDimitry Andric   unsigned NumDstParts = DstSize / NarrowSize;
44760b57cec5SDimitry Andric   unsigned NumSrcParts = SrcSize / NarrowSize;
44770b57cec5SDimitry Andric   bool IsMulHigh = MI.getOpcode() == TargetOpcode::G_UMULH;
44780b57cec5SDimitry Andric   unsigned DstTmpParts = NumDstParts * (IsMulHigh ? 2 : 1);
44790b57cec5SDimitry Andric 
44805ffd83dbSDimitry Andric   SmallVector<Register, 2> Src1Parts, Src2Parts;
44815ffd83dbSDimitry Andric   SmallVector<Register, 2> DstTmpRegs(DstTmpParts);
44820b57cec5SDimitry Andric   extractParts(Src1, NarrowTy, NumSrcParts, Src1Parts);
44830b57cec5SDimitry Andric   extractParts(Src2, NarrowTy, NumSrcParts, Src2Parts);
44840b57cec5SDimitry Andric   multiplyRegisters(DstTmpRegs, Src1Parts, Src2Parts, NarrowTy);
44850b57cec5SDimitry Andric 
44860b57cec5SDimitry Andric   // Take only high half of registers if this is high mul.
44870b57cec5SDimitry Andric   ArrayRef<Register> DstRegs(
44880b57cec5SDimitry Andric       IsMulHigh ? &DstTmpRegs[DstTmpParts / 2] : &DstTmpRegs[0], NumDstParts);
44890b57cec5SDimitry Andric   MIRBuilder.buildMerge(DstReg, DstRegs);
44900b57cec5SDimitry Andric   MI.eraseFromParent();
44910b57cec5SDimitry Andric   return Legalized;
44920b57cec5SDimitry Andric }
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
44950b57cec5SDimitry Andric LegalizerHelper::narrowScalarExtract(MachineInstr &MI, unsigned TypeIdx,
44960b57cec5SDimitry Andric                                      LLT NarrowTy) {
44970b57cec5SDimitry Andric   if (TypeIdx != 1)
44980b57cec5SDimitry Andric     return UnableToLegalize;
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric   int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
45030b57cec5SDimitry Andric   // FIXME: add support for when SizeOp1 isn't an exact multiple of
45040b57cec5SDimitry Andric   // NarrowSize.
45050b57cec5SDimitry Andric   if (SizeOp1 % NarrowSize != 0)
45060b57cec5SDimitry Andric     return UnableToLegalize;
45070b57cec5SDimitry Andric   int NumParts = SizeOp1 / NarrowSize;
45080b57cec5SDimitry Andric 
45090b57cec5SDimitry Andric   SmallVector<Register, 2> SrcRegs, DstRegs;
45100b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
45110b57cec5SDimitry Andric   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
45120b57cec5SDimitry Andric 
45130b57cec5SDimitry Andric   Register OpReg = MI.getOperand(0).getReg();
45140b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(2).getImm();
45150b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
45160b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i) {
45170b57cec5SDimitry Andric     unsigned SrcStart = i * NarrowSize;
45180b57cec5SDimitry Andric 
45190b57cec5SDimitry Andric     if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
45200b57cec5SDimitry Andric       // No part of the extract uses this subregister, ignore it.
45210b57cec5SDimitry Andric       continue;
45220b57cec5SDimitry Andric     } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
45230b57cec5SDimitry Andric       // The entire subregister is extracted, forward the value.
45240b57cec5SDimitry Andric       DstRegs.push_back(SrcRegs[i]);
45250b57cec5SDimitry Andric       continue;
45260b57cec5SDimitry Andric     }
45270b57cec5SDimitry Andric 
45280b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
45290b57cec5SDimitry Andric     // extended infinitely in both directions.
45300b57cec5SDimitry Andric     int64_t ExtractOffset;
45310b57cec5SDimitry Andric     uint64_t SegSize;
45320b57cec5SDimitry Andric     if (OpStart < SrcStart) {
45330b57cec5SDimitry Andric       ExtractOffset = 0;
45340b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
45350b57cec5SDimitry Andric     } else {
45360b57cec5SDimitry Andric       ExtractOffset = OpStart - SrcStart;
45370b57cec5SDimitry Andric       SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
45380b57cec5SDimitry Andric     }
45390b57cec5SDimitry Andric 
45400b57cec5SDimitry Andric     Register SegReg = SrcRegs[i];
45410b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != NarrowSize) {
45420b57cec5SDimitry Andric       // A genuine extract is needed.
45430b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
45440b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
45450b57cec5SDimitry Andric     }
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric     DstRegs.push_back(SegReg);
45480b57cec5SDimitry Andric   }
45490b57cec5SDimitry Andric 
45500b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
45510b57cec5SDimitry Andric   if (MRI.getType(DstReg).isVector())
45520b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
45535ffd83dbSDimitry Andric   else if (DstRegs.size() > 1)
45540b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
45555ffd83dbSDimitry Andric   else
45565ffd83dbSDimitry Andric     MIRBuilder.buildCopy(DstReg, DstRegs[0]);
45570b57cec5SDimitry Andric   MI.eraseFromParent();
45580b57cec5SDimitry Andric   return Legalized;
45590b57cec5SDimitry Andric }
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
45620b57cec5SDimitry Andric LegalizerHelper::narrowScalarInsert(MachineInstr &MI, unsigned TypeIdx,
45630b57cec5SDimitry Andric                                     LLT NarrowTy) {
45640b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
45650b57cec5SDimitry Andric   if (TypeIdx != 0)
45660b57cec5SDimitry Andric     return UnableToLegalize;
45670b57cec5SDimitry Andric 
45680b57cec5SDimitry Andric   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
45690b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
45700b57cec5SDimitry Andric 
45710b57cec5SDimitry Andric   // FIXME: add support for when SizeOp0 isn't an exact multiple of
45720b57cec5SDimitry Andric   // NarrowSize.
45730b57cec5SDimitry Andric   if (SizeOp0 % NarrowSize != 0)
45740b57cec5SDimitry Andric     return UnableToLegalize;
45750b57cec5SDimitry Andric 
45760b57cec5SDimitry Andric   int NumParts = SizeOp0 / NarrowSize;
45770b57cec5SDimitry Andric 
45780b57cec5SDimitry Andric   SmallVector<Register, 2> SrcRegs, DstRegs;
45790b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
45800b57cec5SDimitry Andric   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
45810b57cec5SDimitry Andric 
45820b57cec5SDimitry Andric   Register OpReg = MI.getOperand(2).getReg();
45830b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(3).getImm();
45840b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
45850b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i) {
45860b57cec5SDimitry Andric     unsigned DstStart = i * NarrowSize;
45870b57cec5SDimitry Andric 
45880b57cec5SDimitry Andric     if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
45890b57cec5SDimitry Andric       // No part of the insert affects this subregister, forward the original.
45900b57cec5SDimitry Andric       DstRegs.push_back(SrcRegs[i]);
45910b57cec5SDimitry Andric       continue;
45920b57cec5SDimitry Andric     } else if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
45930b57cec5SDimitry Andric       // The entire subregister is defined by this insert, forward the new
45940b57cec5SDimitry Andric       // value.
45950b57cec5SDimitry Andric       DstRegs.push_back(OpReg);
45960b57cec5SDimitry Andric       continue;
45970b57cec5SDimitry Andric     }
45980b57cec5SDimitry Andric 
45990b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
46000b57cec5SDimitry Andric     // extended infinitely in both directions.
46010b57cec5SDimitry Andric     int64_t ExtractOffset, InsertOffset;
46020b57cec5SDimitry Andric     uint64_t SegSize;
46030b57cec5SDimitry Andric     if (OpStart < DstStart) {
46040b57cec5SDimitry Andric       InsertOffset = 0;
46050b57cec5SDimitry Andric       ExtractOffset = DstStart - OpStart;
46060b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
46070b57cec5SDimitry Andric     } else {
46080b57cec5SDimitry Andric       InsertOffset = OpStart - DstStart;
46090b57cec5SDimitry Andric       ExtractOffset = 0;
46100b57cec5SDimitry Andric       SegSize =
46110b57cec5SDimitry Andric         std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
46120b57cec5SDimitry Andric     }
46130b57cec5SDimitry Andric 
46140b57cec5SDimitry Andric     Register SegReg = OpReg;
46150b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != OpSize) {
46160b57cec5SDimitry Andric       // A genuine extract is needed.
46170b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
46180b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
46190b57cec5SDimitry Andric     }
46200b57cec5SDimitry Andric 
46210b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
46220b57cec5SDimitry Andric     MIRBuilder.buildInsert(DstReg, SrcRegs[i], SegReg, InsertOffset);
46230b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
46240b57cec5SDimitry Andric   }
46250b57cec5SDimitry Andric 
46260b57cec5SDimitry Andric   assert(DstRegs.size() == (unsigned)NumParts && "not all parts covered");
46270b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
46280b57cec5SDimitry Andric   if(MRI.getType(DstReg).isVector())
46290b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
46300b57cec5SDimitry Andric   else
46310b57cec5SDimitry Andric     MIRBuilder.buildMerge(DstReg, DstRegs);
46320b57cec5SDimitry Andric   MI.eraseFromParent();
46330b57cec5SDimitry Andric   return Legalized;
46340b57cec5SDimitry Andric }
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
46370b57cec5SDimitry Andric LegalizerHelper::narrowScalarBasic(MachineInstr &MI, unsigned TypeIdx,
46380b57cec5SDimitry Andric                                    LLT NarrowTy) {
46390b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
46400b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
46410b57cec5SDimitry Andric 
46420b57cec5SDimitry Andric   assert(MI.getNumOperands() == 3 && TypeIdx == 0);
46430b57cec5SDimitry Andric 
46440b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
46450b57cec5SDimitry Andric   SmallVector<Register, 4> Src0Regs, Src0LeftoverRegs;
46460b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
46470b57cec5SDimitry Andric   LLT LeftoverTy;
46480b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(1).getReg(), DstTy, NarrowTy, LeftoverTy,
46490b57cec5SDimitry Andric                     Src0Regs, Src0LeftoverRegs))
46500b57cec5SDimitry Andric     return UnableToLegalize;
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric   LLT Unused;
46530b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, Unused,
46540b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
46550b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
46560b57cec5SDimitry Andric 
46570b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
46580b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
46590b57cec5SDimitry Andric                                         {Src0Regs[I], Src1Regs[I]});
46605ffd83dbSDimitry Andric     DstRegs.push_back(Inst.getReg(0));
46610b57cec5SDimitry Andric   }
46620b57cec5SDimitry Andric 
46630b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
46640b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(
46650b57cec5SDimitry Andric       MI.getOpcode(),
46660b57cec5SDimitry Andric       {LeftoverTy}, {Src0LeftoverRegs[I], Src1LeftoverRegs[I]});
46675ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Inst.getReg(0));
46680b57cec5SDimitry Andric   }
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
46710b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
46720b57cec5SDimitry Andric 
46730b57cec5SDimitry Andric   MI.eraseFromParent();
46740b57cec5SDimitry Andric   return Legalized;
46750b57cec5SDimitry Andric }
46760b57cec5SDimitry Andric 
46770b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
46785ffd83dbSDimitry Andric LegalizerHelper::narrowScalarExt(MachineInstr &MI, unsigned TypeIdx,
46795ffd83dbSDimitry Andric                                  LLT NarrowTy) {
46805ffd83dbSDimitry Andric   if (TypeIdx != 0)
46815ffd83dbSDimitry Andric     return UnableToLegalize;
46825ffd83dbSDimitry Andric 
46835ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
46845ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
46855ffd83dbSDimitry Andric 
46865ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
46875ffd83dbSDimitry Andric   if (DstTy.isVector())
46885ffd83dbSDimitry Andric     return UnableToLegalize;
46895ffd83dbSDimitry Andric 
46905ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
46915ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
46925ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts, MI.getOpcode());
46935ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
46945ffd83dbSDimitry Andric 
46955ffd83dbSDimitry Andric   MI.eraseFromParent();
46965ffd83dbSDimitry Andric   return Legalized;
46975ffd83dbSDimitry Andric }
46985ffd83dbSDimitry Andric 
46995ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
47000b57cec5SDimitry Andric LegalizerHelper::narrowScalarSelect(MachineInstr &MI, unsigned TypeIdx,
47010b57cec5SDimitry Andric                                     LLT NarrowTy) {
47020b57cec5SDimitry Andric   if (TypeIdx != 0)
47030b57cec5SDimitry Andric     return UnableToLegalize;
47040b57cec5SDimitry Andric 
47050b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
47060b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
47070b57cec5SDimitry Andric   if (CondTy.isVector()) // TODO: Handle vselect
47080b57cec5SDimitry Andric     return UnableToLegalize;
47090b57cec5SDimitry Andric 
47100b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
47110b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
47120b57cec5SDimitry Andric 
47130b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
47140b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
47150b57cec5SDimitry Andric   SmallVector<Register, 4> Src2Regs, Src2LeftoverRegs;
47160b57cec5SDimitry Andric   LLT LeftoverTy;
47170b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
47180b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
47190b57cec5SDimitry Andric     return UnableToLegalize;
47200b57cec5SDimitry Andric 
47210b57cec5SDimitry Andric   LLT Unused;
47220b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
47230b57cec5SDimitry Andric                     Src2Regs, Src2LeftoverRegs))
47240b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
47250b57cec5SDimitry Andric 
47260b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
47270b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(NarrowTy,
47280b57cec5SDimitry Andric                                          CondReg, Src1Regs[I], Src2Regs[I]);
47295ffd83dbSDimitry Andric     DstRegs.push_back(Select.getReg(0));
47300b57cec5SDimitry Andric   }
47310b57cec5SDimitry Andric 
47320b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
47330b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(
47340b57cec5SDimitry Andric       LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
47355ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Select.getReg(0));
47360b57cec5SDimitry Andric   }
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
47390b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
47400b57cec5SDimitry Andric 
47410b57cec5SDimitry Andric   MI.eraseFromParent();
47420b57cec5SDimitry Andric   return Legalized;
47430b57cec5SDimitry Andric }
47440b57cec5SDimitry Andric 
47450b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
47465ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTLZ(MachineInstr &MI, unsigned TypeIdx,
47475ffd83dbSDimitry Andric                                   LLT NarrowTy) {
47485ffd83dbSDimitry Andric   if (TypeIdx != 1)
47495ffd83dbSDimitry Andric     return UnableToLegalize;
47505ffd83dbSDimitry Andric 
47515ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
47525ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
47535ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
47545ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
47555ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
47565ffd83dbSDimitry Andric 
47575ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
47585ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF;
47595ffd83dbSDimitry Andric 
47605ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
47615ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
47625ffd83dbSDimitry Andric     // ctlz(Hi:Lo) -> Hi == 0 ? (NarrowSize + ctlz(Lo)) : ctlz(Hi)
47635ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
47645ffd83dbSDimitry Andric     auto HiIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
47655ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(1), C_0);
47665ffd83dbSDimitry Andric     auto LoCTLZ = IsUndef ?
47675ffd83dbSDimitry Andric       B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0)) :
47685ffd83dbSDimitry Andric       B.buildCTLZ(DstTy, UnmergeSrc.getReg(0));
47695ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
47705ffd83dbSDimitry Andric     auto HiIsZeroCTLZ = B.buildAdd(DstTy, LoCTLZ, C_NarrowSize);
47715ffd83dbSDimitry Andric     auto HiCTLZ = B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1));
47725ffd83dbSDimitry Andric     B.buildSelect(DstReg, HiIsZero, HiIsZeroCTLZ, HiCTLZ);
47735ffd83dbSDimitry Andric 
47745ffd83dbSDimitry Andric     MI.eraseFromParent();
47755ffd83dbSDimitry Andric     return Legalized;
47765ffd83dbSDimitry Andric   }
47775ffd83dbSDimitry Andric 
47785ffd83dbSDimitry Andric   return UnableToLegalize;
47795ffd83dbSDimitry Andric }
47805ffd83dbSDimitry Andric 
47815ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
47825ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTTZ(MachineInstr &MI, unsigned TypeIdx,
47835ffd83dbSDimitry Andric                                   LLT NarrowTy) {
47845ffd83dbSDimitry Andric   if (TypeIdx != 1)
47855ffd83dbSDimitry Andric     return UnableToLegalize;
47865ffd83dbSDimitry Andric 
47875ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
47885ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
47895ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
47905ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
47915ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
47925ffd83dbSDimitry Andric 
47935ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
47945ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF;
47955ffd83dbSDimitry Andric 
47965ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
47975ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
47985ffd83dbSDimitry Andric     // cttz(Hi:Lo) -> Lo == 0 ? (cttz(Hi) + NarrowSize) : cttz(Lo)
47995ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
48005ffd83dbSDimitry Andric     auto LoIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
48015ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(0), C_0);
48025ffd83dbSDimitry Andric     auto HiCTTZ = IsUndef ?
48035ffd83dbSDimitry Andric       B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1)) :
48045ffd83dbSDimitry Andric       B.buildCTTZ(DstTy, UnmergeSrc.getReg(1));
48055ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
48065ffd83dbSDimitry Andric     auto LoIsZeroCTTZ = B.buildAdd(DstTy, HiCTTZ, C_NarrowSize);
48075ffd83dbSDimitry Andric     auto LoCTTZ = B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0));
48085ffd83dbSDimitry Andric     B.buildSelect(DstReg, LoIsZero, LoIsZeroCTTZ, LoCTTZ);
48095ffd83dbSDimitry Andric 
48105ffd83dbSDimitry Andric     MI.eraseFromParent();
48115ffd83dbSDimitry Andric     return Legalized;
48125ffd83dbSDimitry Andric   }
48135ffd83dbSDimitry Andric 
48145ffd83dbSDimitry Andric   return UnableToLegalize;
48155ffd83dbSDimitry Andric }
48165ffd83dbSDimitry Andric 
48175ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
48185ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTPOP(MachineInstr &MI, unsigned TypeIdx,
48195ffd83dbSDimitry Andric                                    LLT NarrowTy) {
48205ffd83dbSDimitry Andric   if (TypeIdx != 1)
48215ffd83dbSDimitry Andric     return UnableToLegalize;
48225ffd83dbSDimitry Andric 
48235ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
48245ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
48255ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
48265ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
48275ffd83dbSDimitry Andric 
48285ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
48295ffd83dbSDimitry Andric     auto UnmergeSrc = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
48305ffd83dbSDimitry Andric 
48315ffd83dbSDimitry Andric     auto LoCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(0));
48325ffd83dbSDimitry Andric     auto HiCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(1));
48335ffd83dbSDimitry Andric     MIRBuilder.buildAdd(DstReg, HiCTPOP, LoCTPOP);
48345ffd83dbSDimitry Andric 
48355ffd83dbSDimitry Andric     MI.eraseFromParent();
48365ffd83dbSDimitry Andric     return Legalized;
48375ffd83dbSDimitry Andric   }
48385ffd83dbSDimitry Andric 
48395ffd83dbSDimitry Andric   return UnableToLegalize;
48405ffd83dbSDimitry Andric }
48415ffd83dbSDimitry Andric 
48425ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
4843*e8d8bef9SDimitry Andric LegalizerHelper::lowerBitCount(MachineInstr &MI) {
48440b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
4845*e8d8bef9SDimitry Andric   const auto &TII = MIRBuilder.getTII();
48460b57cec5SDimitry Andric   auto isSupported = [this](const LegalityQuery &Q) {
48470b57cec5SDimitry Andric     auto QAction = LI.getAction(Q).Action;
48480b57cec5SDimitry Andric     return QAction == Legal || QAction == Libcall || QAction == Custom;
48490b57cec5SDimitry Andric   };
48500b57cec5SDimitry Andric   switch (Opc) {
48510b57cec5SDimitry Andric   default:
48520b57cec5SDimitry Andric     return UnableToLegalize;
48530b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
48540b57cec5SDimitry Andric     // This trivially expands to CTLZ.
48550b57cec5SDimitry Andric     Observer.changingInstr(MI);
48560b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
48570b57cec5SDimitry Andric     Observer.changedInstr(MI);
48580b57cec5SDimitry Andric     return Legalized;
48590b57cec5SDimitry Andric   }
48600b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ: {
48615ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
48620b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
48635ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
48645ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
48655ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
48665ffd83dbSDimitry Andric 
48675ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
48680b57cec5SDimitry Andric       // If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
48695ffd83dbSDimitry Andric       auto CtlzZU = MIRBuilder.buildCTLZ_ZERO_UNDEF(DstTy, SrcReg);
48705ffd83dbSDimitry Andric       auto ZeroSrc = MIRBuilder.buildConstant(SrcTy, 0);
48715ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
48725ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, SrcTy.changeElementSize(1), SrcReg, ZeroSrc);
48735ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
48745ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CtlzZU);
48750b57cec5SDimitry Andric       MI.eraseFromParent();
48760b57cec5SDimitry Andric       return Legalized;
48770b57cec5SDimitry Andric     }
48780b57cec5SDimitry Andric     // for now, we do this:
48790b57cec5SDimitry Andric     // NewLen = NextPowerOf2(Len);
48800b57cec5SDimitry Andric     // x = x | (x >> 1);
48810b57cec5SDimitry Andric     // x = x | (x >> 2);
48820b57cec5SDimitry Andric     // ...
48830b57cec5SDimitry Andric     // x = x | (x >>16);
48840b57cec5SDimitry Andric     // x = x | (x >>32); // for 64-bit input
48850b57cec5SDimitry Andric     // Upto NewLen/2
48860b57cec5SDimitry Andric     // return Len - popcount(x);
48870b57cec5SDimitry Andric     //
48880b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
48890b57cec5SDimitry Andric     Register Op = SrcReg;
48900b57cec5SDimitry Andric     unsigned NewLen = PowerOf2Ceil(Len);
48910b57cec5SDimitry Andric     for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
48925ffd83dbSDimitry Andric       auto MIBShiftAmt = MIRBuilder.buildConstant(SrcTy, 1ULL << i);
48935ffd83dbSDimitry Andric       auto MIBOp = MIRBuilder.buildOr(
48945ffd83dbSDimitry Andric           SrcTy, Op, MIRBuilder.buildLShr(SrcTy, Op, MIBShiftAmt));
48955ffd83dbSDimitry Andric       Op = MIBOp.getReg(0);
48960b57cec5SDimitry Andric     }
48975ffd83dbSDimitry Andric     auto MIBPop = MIRBuilder.buildCTPOP(DstTy, Op);
48985ffd83dbSDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MIRBuilder.buildConstant(DstTy, Len),
48995ffd83dbSDimitry Andric                         MIBPop);
49000b57cec5SDimitry Andric     MI.eraseFromParent();
49010b57cec5SDimitry Andric     return Legalized;
49020b57cec5SDimitry Andric   }
49030b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
49040b57cec5SDimitry Andric     // This trivially expands to CTTZ.
49050b57cec5SDimitry Andric     Observer.changingInstr(MI);
49060b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
49070b57cec5SDimitry Andric     Observer.changedInstr(MI);
49080b57cec5SDimitry Andric     return Legalized;
49090b57cec5SDimitry Andric   }
49100b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ: {
49115ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
49120b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
49135ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
49145ffd83dbSDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
49155ffd83dbSDimitry Andric 
49165ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
49175ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
49180b57cec5SDimitry Andric       // If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
49190b57cec5SDimitry Andric       // zero.
49205ffd83dbSDimitry Andric       auto CttzZU = MIRBuilder.buildCTTZ_ZERO_UNDEF(DstTy, SrcReg);
49215ffd83dbSDimitry Andric       auto Zero = MIRBuilder.buildConstant(SrcTy, 0);
49225ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
49235ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, DstTy.changeElementSize(1), SrcReg, Zero);
49245ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
49255ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CttzZU);
49260b57cec5SDimitry Andric       MI.eraseFromParent();
49270b57cec5SDimitry Andric       return Legalized;
49280b57cec5SDimitry Andric     }
49290b57cec5SDimitry Andric     // for now, we use: { return popcount(~x & (x - 1)); }
49300b57cec5SDimitry Andric     // unless the target has ctlz but not ctpop, in which case we use:
49310b57cec5SDimitry Andric     // { return 32 - nlz(~x & (x-1)); }
49320b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
4933*e8d8bef9SDimitry Andric     auto MIBCstNeg1 = MIRBuilder.buildConstant(SrcTy, -1);
4934*e8d8bef9SDimitry Andric     auto MIBNot = MIRBuilder.buildXor(SrcTy, SrcReg, MIBCstNeg1);
49355ffd83dbSDimitry Andric     auto MIBTmp = MIRBuilder.buildAnd(
4936*e8d8bef9SDimitry Andric         SrcTy, MIBNot, MIRBuilder.buildAdd(SrcTy, SrcReg, MIBCstNeg1));
4937*e8d8bef9SDimitry Andric     if (!isSupported({TargetOpcode::G_CTPOP, {SrcTy, SrcTy}}) &&
4938*e8d8bef9SDimitry Andric         isSupported({TargetOpcode::G_CTLZ, {SrcTy, SrcTy}})) {
4939*e8d8bef9SDimitry Andric       auto MIBCstLen = MIRBuilder.buildConstant(SrcTy, Len);
49405ffd83dbSDimitry Andric       MIRBuilder.buildSub(MI.getOperand(0), MIBCstLen,
4941*e8d8bef9SDimitry Andric                           MIRBuilder.buildCTLZ(SrcTy, MIBTmp));
49420b57cec5SDimitry Andric       MI.eraseFromParent();
49430b57cec5SDimitry Andric       return Legalized;
49440b57cec5SDimitry Andric     }
49450b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
49465ffd83dbSDimitry Andric     MI.getOperand(1).setReg(MIBTmp.getReg(0));
49475ffd83dbSDimitry Andric     return Legalized;
49485ffd83dbSDimitry Andric   }
49495ffd83dbSDimitry Andric   case TargetOpcode::G_CTPOP: {
4950*e8d8bef9SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
4951*e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(SrcReg);
49525ffd83dbSDimitry Andric     unsigned Size = Ty.getSizeInBits();
49535ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
49545ffd83dbSDimitry Andric 
49555ffd83dbSDimitry Andric     // Count set bits in blocks of 2 bits. Default approach would be
49565ffd83dbSDimitry Andric     // B2Count = { val & 0x55555555 } + { (val >> 1) & 0x55555555 }
49575ffd83dbSDimitry Andric     // We use following formula instead:
49585ffd83dbSDimitry Andric     // B2Count = val - { (val >> 1) & 0x55555555 }
49595ffd83dbSDimitry Andric     // since it gives same result in blocks of 2 with one instruction less.
49605ffd83dbSDimitry Andric     auto C_1 = B.buildConstant(Ty, 1);
4961*e8d8bef9SDimitry Andric     auto B2Set1LoTo1Hi = B.buildLShr(Ty, SrcReg, C_1);
49625ffd83dbSDimitry Andric     APInt B2Mask1HiTo0 = APInt::getSplat(Size, APInt(8, 0x55));
49635ffd83dbSDimitry Andric     auto C_B2Mask1HiTo0 = B.buildConstant(Ty, B2Mask1HiTo0);
49645ffd83dbSDimitry Andric     auto B2Count1Hi = B.buildAnd(Ty, B2Set1LoTo1Hi, C_B2Mask1HiTo0);
4965*e8d8bef9SDimitry Andric     auto B2Count = B.buildSub(Ty, SrcReg, B2Count1Hi);
49665ffd83dbSDimitry Andric 
49675ffd83dbSDimitry Andric     // In order to get count in blocks of 4 add values from adjacent block of 2.
49685ffd83dbSDimitry Andric     // B4Count = { B2Count & 0x33333333 } + { (B2Count >> 2) & 0x33333333 }
49695ffd83dbSDimitry Andric     auto C_2 = B.buildConstant(Ty, 2);
49705ffd83dbSDimitry Andric     auto B4Set2LoTo2Hi = B.buildLShr(Ty, B2Count, C_2);
49715ffd83dbSDimitry Andric     APInt B4Mask2HiTo0 = APInt::getSplat(Size, APInt(8, 0x33));
49725ffd83dbSDimitry Andric     auto C_B4Mask2HiTo0 = B.buildConstant(Ty, B4Mask2HiTo0);
49735ffd83dbSDimitry Andric     auto B4HiB2Count = B.buildAnd(Ty, B4Set2LoTo2Hi, C_B4Mask2HiTo0);
49745ffd83dbSDimitry Andric     auto B4LoB2Count = B.buildAnd(Ty, B2Count, C_B4Mask2HiTo0);
49755ffd83dbSDimitry Andric     auto B4Count = B.buildAdd(Ty, B4HiB2Count, B4LoB2Count);
49765ffd83dbSDimitry Andric 
49775ffd83dbSDimitry Andric     // For count in blocks of 8 bits we don't have to mask high 4 bits before
49785ffd83dbSDimitry Andric     // addition since count value sits in range {0,...,8} and 4 bits are enough
49795ffd83dbSDimitry Andric     // to hold such binary values. After addition high 4 bits still hold count
49805ffd83dbSDimitry Andric     // of set bits in high 4 bit block, set them to zero and get 8 bit result.
49815ffd83dbSDimitry Andric     // B8Count = { B4Count + (B4Count >> 4) } & 0x0F0F0F0F
49825ffd83dbSDimitry Andric     auto C_4 = B.buildConstant(Ty, 4);
49835ffd83dbSDimitry Andric     auto B8HiB4Count = B.buildLShr(Ty, B4Count, C_4);
49845ffd83dbSDimitry Andric     auto B8CountDirty4Hi = B.buildAdd(Ty, B8HiB4Count, B4Count);
49855ffd83dbSDimitry Andric     APInt B8Mask4HiTo0 = APInt::getSplat(Size, APInt(8, 0x0F));
49865ffd83dbSDimitry Andric     auto C_B8Mask4HiTo0 = B.buildConstant(Ty, B8Mask4HiTo0);
49875ffd83dbSDimitry Andric     auto B8Count = B.buildAnd(Ty, B8CountDirty4Hi, C_B8Mask4HiTo0);
49885ffd83dbSDimitry Andric 
49895ffd83dbSDimitry Andric     assert(Size<=128 && "Scalar size is too large for CTPOP lower algorithm");
49905ffd83dbSDimitry Andric     // 8 bits can hold CTPOP result of 128 bit int or smaller. Mul with this
49915ffd83dbSDimitry Andric     // bitmask will set 8 msb in ResTmp to sum of all B8Counts in 8 bit blocks.
49925ffd83dbSDimitry Andric     auto MulMask = B.buildConstant(Ty, APInt::getSplat(Size, APInt(8, 0x01)));
49935ffd83dbSDimitry Andric     auto ResTmp = B.buildMul(Ty, B8Count, MulMask);
49945ffd83dbSDimitry Andric 
49955ffd83dbSDimitry Andric     // Shift count result from 8 high bits to low bits.
49965ffd83dbSDimitry Andric     auto C_SizeM8 = B.buildConstant(Ty, Size - 8);
49975ffd83dbSDimitry Andric     B.buildLShr(MI.getOperand(0).getReg(), ResTmp, C_SizeM8);
49985ffd83dbSDimitry Andric 
49995ffd83dbSDimitry Andric     MI.eraseFromParent();
50000b57cec5SDimitry Andric     return Legalized;
50010b57cec5SDimitry Andric   }
50020b57cec5SDimitry Andric   }
50030b57cec5SDimitry Andric }
50040b57cec5SDimitry Andric 
50050b57cec5SDimitry Andric // Expand s32 = G_UITOFP s64 using bit operations to an IEEE float
50060b57cec5SDimitry Andric // representation.
50070b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
50080b57cec5SDimitry Andric LegalizerHelper::lowerU64ToF32BitOps(MachineInstr &MI) {
50090b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
50100b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
50110b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
50120b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
50130b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
50140b57cec5SDimitry Andric 
50150b57cec5SDimitry Andric   assert(MRI.getType(Src) == S64 && MRI.getType(Dst) == S32);
50160b57cec5SDimitry Andric 
50170b57cec5SDimitry Andric   // unsigned cul2f(ulong u) {
50180b57cec5SDimitry Andric   //   uint lz = clz(u);
50190b57cec5SDimitry Andric   //   uint e = (u != 0) ? 127U + 63U - lz : 0;
50200b57cec5SDimitry Andric   //   u = (u << lz) & 0x7fffffffffffffffUL;
50210b57cec5SDimitry Andric   //   ulong t = u & 0xffffffffffUL;
50220b57cec5SDimitry Andric   //   uint v = (e << 23) | (uint)(u >> 40);
50230b57cec5SDimitry Andric   //   uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
50240b57cec5SDimitry Andric   //   return as_float(v + r);
50250b57cec5SDimitry Andric   // }
50260b57cec5SDimitry Andric 
50270b57cec5SDimitry Andric   auto Zero32 = MIRBuilder.buildConstant(S32, 0);
50280b57cec5SDimitry Andric   auto Zero64 = MIRBuilder.buildConstant(S64, 0);
50290b57cec5SDimitry Andric 
50300b57cec5SDimitry Andric   auto LZ = MIRBuilder.buildCTLZ_ZERO_UNDEF(S32, Src);
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric   auto K = MIRBuilder.buildConstant(S32, 127U + 63U);
50330b57cec5SDimitry Andric   auto Sub = MIRBuilder.buildSub(S32, K, LZ);
50340b57cec5SDimitry Andric 
50350b57cec5SDimitry Andric   auto NotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, Src, Zero64);
50360b57cec5SDimitry Andric   auto E = MIRBuilder.buildSelect(S32, NotZero, Sub, Zero32);
50370b57cec5SDimitry Andric 
50380b57cec5SDimitry Andric   auto Mask0 = MIRBuilder.buildConstant(S64, (-1ULL) >> 1);
50390b57cec5SDimitry Andric   auto ShlLZ = MIRBuilder.buildShl(S64, Src, LZ);
50400b57cec5SDimitry Andric 
50410b57cec5SDimitry Andric   auto U = MIRBuilder.buildAnd(S64, ShlLZ, Mask0);
50420b57cec5SDimitry Andric 
50430b57cec5SDimitry Andric   auto Mask1 = MIRBuilder.buildConstant(S64, 0xffffffffffULL);
50440b57cec5SDimitry Andric   auto T = MIRBuilder.buildAnd(S64, U, Mask1);
50450b57cec5SDimitry Andric 
50460b57cec5SDimitry Andric   auto UShl = MIRBuilder.buildLShr(S64, U, MIRBuilder.buildConstant(S64, 40));
50470b57cec5SDimitry Andric   auto ShlE = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 23));
50480b57cec5SDimitry Andric   auto V = MIRBuilder.buildOr(S32, ShlE, MIRBuilder.buildTrunc(S32, UShl));
50490b57cec5SDimitry Andric 
50500b57cec5SDimitry Andric   auto C = MIRBuilder.buildConstant(S64, 0x8000000000ULL);
50510b57cec5SDimitry Andric   auto RCmp = MIRBuilder.buildICmp(CmpInst::ICMP_UGT, S1, T, C);
50520b57cec5SDimitry Andric   auto TCmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, T, C);
50530b57cec5SDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
50540b57cec5SDimitry Andric 
50550b57cec5SDimitry Andric   auto VTrunc1 = MIRBuilder.buildAnd(S32, V, One);
50560b57cec5SDimitry Andric   auto Select0 = MIRBuilder.buildSelect(S32, TCmp, VTrunc1, Zero32);
50570b57cec5SDimitry Andric   auto R = MIRBuilder.buildSelect(S32, RCmp, One, Select0);
50580b57cec5SDimitry Andric   MIRBuilder.buildAdd(Dst, V, R);
50590b57cec5SDimitry Andric 
50605ffd83dbSDimitry Andric   MI.eraseFromParent();
50610b57cec5SDimitry Andric   return Legalized;
50620b57cec5SDimitry Andric }
50630b57cec5SDimitry Andric 
5064*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerUITOFP(MachineInstr &MI) {
50650b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
50660b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
50670b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst);
50680b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src);
50690b57cec5SDimitry Andric 
5070480093f4SDimitry Andric   if (SrcTy == LLT::scalar(1)) {
5071480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, 1.0);
5072480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
5073480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
5074480093f4SDimitry Andric     MI.eraseFromParent();
5075480093f4SDimitry Andric     return Legalized;
5076480093f4SDimitry Andric   }
5077480093f4SDimitry Andric 
50780b57cec5SDimitry Andric   if (SrcTy != LLT::scalar(64))
50790b57cec5SDimitry Andric     return UnableToLegalize;
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric   if (DstTy == LLT::scalar(32)) {
50820b57cec5SDimitry Andric     // TODO: SelectionDAG has several alternative expansions to port which may
50830b57cec5SDimitry Andric     // be more reasonble depending on the available instructions. If a target
50840b57cec5SDimitry Andric     // has sitofp, does not have CTLZ, or can efficiently use f64 as an
50850b57cec5SDimitry Andric     // intermediate type, this is probably worse.
50860b57cec5SDimitry Andric     return lowerU64ToF32BitOps(MI);
50870b57cec5SDimitry Andric   }
50880b57cec5SDimitry Andric 
50890b57cec5SDimitry Andric   return UnableToLegalize;
50900b57cec5SDimitry Andric }
50910b57cec5SDimitry Andric 
5092*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSITOFP(MachineInstr &MI) {
50930b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
50940b57cec5SDimitry Andric   Register Src = MI.getOperand(1).getReg();
50950b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst);
50960b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(Src);
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
50990b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
51000b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
51010b57cec5SDimitry Andric 
5102480093f4SDimitry Andric   if (SrcTy == S1) {
5103480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, -1.0);
5104480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
5105480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
5106480093f4SDimitry Andric     MI.eraseFromParent();
5107480093f4SDimitry Andric     return Legalized;
5108480093f4SDimitry Andric   }
5109480093f4SDimitry Andric 
51100b57cec5SDimitry Andric   if (SrcTy != S64)
51110b57cec5SDimitry Andric     return UnableToLegalize;
51120b57cec5SDimitry Andric 
51130b57cec5SDimitry Andric   if (DstTy == S32) {
51140b57cec5SDimitry Andric     // signed cl2f(long l) {
51150b57cec5SDimitry Andric     //   long s = l >> 63;
51160b57cec5SDimitry Andric     //   float r = cul2f((l + s) ^ s);
51170b57cec5SDimitry Andric     //   return s ? -r : r;
51180b57cec5SDimitry Andric     // }
51190b57cec5SDimitry Andric     Register L = Src;
51200b57cec5SDimitry Andric     auto SignBit = MIRBuilder.buildConstant(S64, 63);
51210b57cec5SDimitry Andric     auto S = MIRBuilder.buildAShr(S64, L, SignBit);
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric     auto LPlusS = MIRBuilder.buildAdd(S64, L, S);
51240b57cec5SDimitry Andric     auto Xor = MIRBuilder.buildXor(S64, LPlusS, S);
51250b57cec5SDimitry Andric     auto R = MIRBuilder.buildUITOFP(S32, Xor);
51260b57cec5SDimitry Andric 
51270b57cec5SDimitry Andric     auto RNeg = MIRBuilder.buildFNeg(S32, R);
51280b57cec5SDimitry Andric     auto SignNotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, S,
51290b57cec5SDimitry Andric                                             MIRBuilder.buildConstant(S64, 0));
51300b57cec5SDimitry Andric     MIRBuilder.buildSelect(Dst, SignNotZero, RNeg, R);
51315ffd83dbSDimitry Andric     MI.eraseFromParent();
51320b57cec5SDimitry Andric     return Legalized;
51330b57cec5SDimitry Andric   }
51340b57cec5SDimitry Andric 
51350b57cec5SDimitry Andric   return UnableToLegalize;
51360b57cec5SDimitry Andric }
51370b57cec5SDimitry Andric 
5138*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOUI(MachineInstr &MI) {
51398bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
51408bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
51418bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst);
51428bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(Src);
51438bcb0991SDimitry Andric   const LLT S64 = LLT::scalar(64);
51448bcb0991SDimitry Andric   const LLT S32 = LLT::scalar(32);
51458bcb0991SDimitry Andric 
51468bcb0991SDimitry Andric   if (SrcTy != S64 && SrcTy != S32)
51478bcb0991SDimitry Andric     return UnableToLegalize;
51488bcb0991SDimitry Andric   if (DstTy != S32 && DstTy != S64)
51498bcb0991SDimitry Andric     return UnableToLegalize;
51508bcb0991SDimitry Andric 
51518bcb0991SDimitry Andric   // FPTOSI gives same result as FPTOUI for positive signed integers.
51528bcb0991SDimitry Andric   // FPTOUI needs to deal with fp values that convert to unsigned integers
51538bcb0991SDimitry Andric   // greater or equal to 2^31 for float or 2^63 for double. For brevity 2^Exp.
51548bcb0991SDimitry Andric 
51558bcb0991SDimitry Andric   APInt TwoPExpInt = APInt::getSignMask(DstTy.getSizeInBits());
51568bcb0991SDimitry Andric   APFloat TwoPExpFP(SrcTy.getSizeInBits() == 32 ? APFloat::IEEEsingle()
51578bcb0991SDimitry Andric                                                 : APFloat::IEEEdouble(),
51588bcb0991SDimitry Andric                     APInt::getNullValue(SrcTy.getSizeInBits()));
51598bcb0991SDimitry Andric   TwoPExpFP.convertFromAPInt(TwoPExpInt, false, APFloat::rmNearestTiesToEven);
51608bcb0991SDimitry Andric 
51618bcb0991SDimitry Andric   MachineInstrBuilder FPTOSI = MIRBuilder.buildFPTOSI(DstTy, Src);
51628bcb0991SDimitry Andric 
51638bcb0991SDimitry Andric   MachineInstrBuilder Threshold = MIRBuilder.buildFConstant(SrcTy, TwoPExpFP);
51648bcb0991SDimitry Andric   // For fp Value greater or equal to Threshold(2^Exp), we use FPTOSI on
51658bcb0991SDimitry Andric   // (Value - 2^Exp) and add 2^Exp by setting highest bit in result to 1.
51668bcb0991SDimitry Andric   MachineInstrBuilder FSub = MIRBuilder.buildFSub(SrcTy, Src, Threshold);
51678bcb0991SDimitry Andric   MachineInstrBuilder ResLowBits = MIRBuilder.buildFPTOSI(DstTy, FSub);
51688bcb0991SDimitry Andric   MachineInstrBuilder ResHighBit = MIRBuilder.buildConstant(DstTy, TwoPExpInt);
51698bcb0991SDimitry Andric   MachineInstrBuilder Res = MIRBuilder.buildXor(DstTy, ResLowBits, ResHighBit);
51708bcb0991SDimitry Andric 
5171480093f4SDimitry Andric   const LLT S1 = LLT::scalar(1);
5172480093f4SDimitry Andric 
51738bcb0991SDimitry Andric   MachineInstrBuilder FCMP =
5174480093f4SDimitry Andric       MIRBuilder.buildFCmp(CmpInst::FCMP_ULT, S1, Src, Threshold);
51758bcb0991SDimitry Andric   MIRBuilder.buildSelect(Dst, FCMP, FPTOSI, Res);
51768bcb0991SDimitry Andric 
51778bcb0991SDimitry Andric   MI.eraseFromParent();
51788bcb0991SDimitry Andric   return Legalized;
51798bcb0991SDimitry Andric }
51808bcb0991SDimitry Andric 
51815ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOSI(MachineInstr &MI) {
51825ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
51835ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
51845ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
51855ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
51865ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
51875ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
51885ffd83dbSDimitry Andric 
51895ffd83dbSDimitry Andric   // FIXME: Only f32 to i64 conversions are supported.
51905ffd83dbSDimitry Andric   if (SrcTy.getScalarType() != S32 || DstTy.getScalarType() != S64)
51915ffd83dbSDimitry Andric     return UnableToLegalize;
51925ffd83dbSDimitry Andric 
51935ffd83dbSDimitry Andric   // Expand f32 -> i64 conversion
51945ffd83dbSDimitry Andric   // This algorithm comes from compiler-rt's implementation of fixsfdi:
51955ffd83dbSDimitry Andric   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
51965ffd83dbSDimitry Andric 
51975ffd83dbSDimitry Andric   unsigned SrcEltBits = SrcTy.getScalarSizeInBits();
51985ffd83dbSDimitry Andric 
51995ffd83dbSDimitry Andric   auto ExponentMask = MIRBuilder.buildConstant(SrcTy, 0x7F800000);
52005ffd83dbSDimitry Andric   auto ExponentLoBit = MIRBuilder.buildConstant(SrcTy, 23);
52015ffd83dbSDimitry Andric 
52025ffd83dbSDimitry Andric   auto AndExpMask = MIRBuilder.buildAnd(SrcTy, Src, ExponentMask);
52035ffd83dbSDimitry Andric   auto ExponentBits = MIRBuilder.buildLShr(SrcTy, AndExpMask, ExponentLoBit);
52045ffd83dbSDimitry Andric 
52055ffd83dbSDimitry Andric   auto SignMask = MIRBuilder.buildConstant(SrcTy,
52065ffd83dbSDimitry Andric                                            APInt::getSignMask(SrcEltBits));
52075ffd83dbSDimitry Andric   auto AndSignMask = MIRBuilder.buildAnd(SrcTy, Src, SignMask);
52085ffd83dbSDimitry Andric   auto SignLowBit = MIRBuilder.buildConstant(SrcTy, SrcEltBits - 1);
52095ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildAShr(SrcTy, AndSignMask, SignLowBit);
52105ffd83dbSDimitry Andric   Sign = MIRBuilder.buildSExt(DstTy, Sign);
52115ffd83dbSDimitry Andric 
52125ffd83dbSDimitry Andric   auto MantissaMask = MIRBuilder.buildConstant(SrcTy, 0x007FFFFF);
52135ffd83dbSDimitry Andric   auto AndMantissaMask = MIRBuilder.buildAnd(SrcTy, Src, MantissaMask);
52145ffd83dbSDimitry Andric   auto K = MIRBuilder.buildConstant(SrcTy, 0x00800000);
52155ffd83dbSDimitry Andric 
52165ffd83dbSDimitry Andric   auto R = MIRBuilder.buildOr(SrcTy, AndMantissaMask, K);
52175ffd83dbSDimitry Andric   R = MIRBuilder.buildZExt(DstTy, R);
52185ffd83dbSDimitry Andric 
52195ffd83dbSDimitry Andric   auto Bias = MIRBuilder.buildConstant(SrcTy, 127);
52205ffd83dbSDimitry Andric   auto Exponent = MIRBuilder.buildSub(SrcTy, ExponentBits, Bias);
52215ffd83dbSDimitry Andric   auto SubExponent = MIRBuilder.buildSub(SrcTy, Exponent, ExponentLoBit);
52225ffd83dbSDimitry Andric   auto ExponentSub = MIRBuilder.buildSub(SrcTy, ExponentLoBit, Exponent);
52235ffd83dbSDimitry Andric 
52245ffd83dbSDimitry Andric   auto Shl = MIRBuilder.buildShl(DstTy, R, SubExponent);
52255ffd83dbSDimitry Andric   auto Srl = MIRBuilder.buildLShr(DstTy, R, ExponentSub);
52265ffd83dbSDimitry Andric 
52275ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
52285ffd83dbSDimitry Andric   auto CmpGt = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,
52295ffd83dbSDimitry Andric                                     S1, Exponent, ExponentLoBit);
52305ffd83dbSDimitry Andric 
52315ffd83dbSDimitry Andric   R = MIRBuilder.buildSelect(DstTy, CmpGt, Shl, Srl);
52325ffd83dbSDimitry Andric 
52335ffd83dbSDimitry Andric   auto XorSign = MIRBuilder.buildXor(DstTy, R, Sign);
52345ffd83dbSDimitry Andric   auto Ret = MIRBuilder.buildSub(DstTy, XorSign, Sign);
52355ffd83dbSDimitry Andric 
52365ffd83dbSDimitry Andric   auto ZeroSrcTy = MIRBuilder.buildConstant(SrcTy, 0);
52375ffd83dbSDimitry Andric 
52385ffd83dbSDimitry Andric   auto ExponentLt0 = MIRBuilder.buildICmp(CmpInst::ICMP_SLT,
52395ffd83dbSDimitry Andric                                           S1, Exponent, ZeroSrcTy);
52405ffd83dbSDimitry Andric 
52415ffd83dbSDimitry Andric   auto ZeroDstTy = MIRBuilder.buildConstant(DstTy, 0);
52425ffd83dbSDimitry Andric   MIRBuilder.buildSelect(Dst, ExponentLt0, ZeroDstTy, Ret);
52435ffd83dbSDimitry Andric 
52445ffd83dbSDimitry Andric   MI.eraseFromParent();
52455ffd83dbSDimitry Andric   return Legalized;
52465ffd83dbSDimitry Andric }
52475ffd83dbSDimitry Andric 
52485ffd83dbSDimitry Andric // f64 -> f16 conversion using round-to-nearest-even rounding mode.
52495ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
52505ffd83dbSDimitry Andric LegalizerHelper::lowerFPTRUNC_F64_TO_F16(MachineInstr &MI) {
52515ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
52525ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
52535ffd83dbSDimitry Andric 
52545ffd83dbSDimitry Andric   if (MRI.getType(Src).isVector()) // TODO: Handle vectors directly.
52555ffd83dbSDimitry Andric     return UnableToLegalize;
52565ffd83dbSDimitry Andric 
52575ffd83dbSDimitry Andric   const unsigned ExpMask = 0x7ff;
52585ffd83dbSDimitry Andric   const unsigned ExpBiasf64 = 1023;
52595ffd83dbSDimitry Andric   const unsigned ExpBiasf16 = 15;
52605ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
52615ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
52625ffd83dbSDimitry Andric 
52635ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(S32, Src);
52645ffd83dbSDimitry Andric   Register U = Unmerge.getReg(0);
52655ffd83dbSDimitry Andric   Register UH = Unmerge.getReg(1);
52665ffd83dbSDimitry Andric 
52675ffd83dbSDimitry Andric   auto E = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 20));
52685ffd83dbSDimitry Andric   E = MIRBuilder.buildAnd(S32, E, MIRBuilder.buildConstant(S32, ExpMask));
52695ffd83dbSDimitry Andric 
52705ffd83dbSDimitry Andric   // Subtract the fp64 exponent bias (1023) to get the real exponent and
52715ffd83dbSDimitry Andric   // add the f16 bias (15) to get the biased exponent for the f16 format.
52725ffd83dbSDimitry Andric   E = MIRBuilder.buildAdd(
52735ffd83dbSDimitry Andric     S32, E, MIRBuilder.buildConstant(S32, -ExpBiasf64 + ExpBiasf16));
52745ffd83dbSDimitry Andric 
52755ffd83dbSDimitry Andric   auto M = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 8));
52765ffd83dbSDimitry Andric   M = MIRBuilder.buildAnd(S32, M, MIRBuilder.buildConstant(S32, 0xffe));
52775ffd83dbSDimitry Andric 
52785ffd83dbSDimitry Andric   auto MaskedSig = MIRBuilder.buildAnd(S32, UH,
52795ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1ff));
52805ffd83dbSDimitry Andric   MaskedSig = MIRBuilder.buildOr(S32, MaskedSig, U);
52815ffd83dbSDimitry Andric 
52825ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildConstant(S32, 0);
52835ffd83dbSDimitry Andric   auto SigCmpNE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, MaskedSig, Zero);
52845ffd83dbSDimitry Andric   auto Lo40Set = MIRBuilder.buildZExt(S32, SigCmpNE0);
52855ffd83dbSDimitry Andric   M = MIRBuilder.buildOr(S32, M, Lo40Set);
52865ffd83dbSDimitry Andric 
52875ffd83dbSDimitry Andric   // (M != 0 ? 0x0200 : 0) | 0x7c00;
52885ffd83dbSDimitry Andric   auto Bits0x200 = MIRBuilder.buildConstant(S32, 0x0200);
52895ffd83dbSDimitry Andric   auto CmpM_NE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, M, Zero);
52905ffd83dbSDimitry Andric   auto SelectCC = MIRBuilder.buildSelect(S32, CmpM_NE0, Bits0x200, Zero);
52915ffd83dbSDimitry Andric 
52925ffd83dbSDimitry Andric   auto Bits0x7c00 = MIRBuilder.buildConstant(S32, 0x7c00);
52935ffd83dbSDimitry Andric   auto I = MIRBuilder.buildOr(S32, SelectCC, Bits0x7c00);
52945ffd83dbSDimitry Andric 
52955ffd83dbSDimitry Andric   // N = M | (E << 12);
52965ffd83dbSDimitry Andric   auto EShl12 = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 12));
52975ffd83dbSDimitry Andric   auto N = MIRBuilder.buildOr(S32, M, EShl12);
52985ffd83dbSDimitry Andric 
52995ffd83dbSDimitry Andric   // B = clamp(1-E, 0, 13);
53005ffd83dbSDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
53015ffd83dbSDimitry Andric   auto OneSubExp = MIRBuilder.buildSub(S32, One, E);
53025ffd83dbSDimitry Andric   auto B = MIRBuilder.buildSMax(S32, OneSubExp, Zero);
53035ffd83dbSDimitry Andric   B = MIRBuilder.buildSMin(S32, B, MIRBuilder.buildConstant(S32, 13));
53045ffd83dbSDimitry Andric 
53055ffd83dbSDimitry Andric   auto SigSetHigh = MIRBuilder.buildOr(S32, M,
53065ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1000));
53075ffd83dbSDimitry Andric 
53085ffd83dbSDimitry Andric   auto D = MIRBuilder.buildLShr(S32, SigSetHigh, B);
53095ffd83dbSDimitry Andric   auto D0 = MIRBuilder.buildShl(S32, D, B);
53105ffd83dbSDimitry Andric 
53115ffd83dbSDimitry Andric   auto D0_NE_SigSetHigh = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1,
53125ffd83dbSDimitry Andric                                              D0, SigSetHigh);
53135ffd83dbSDimitry Andric   auto D1 = MIRBuilder.buildZExt(S32, D0_NE_SigSetHigh);
53145ffd83dbSDimitry Andric   D = MIRBuilder.buildOr(S32, D, D1);
53155ffd83dbSDimitry Andric 
53165ffd83dbSDimitry Andric   auto CmpELtOne = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, S1, E, One);
53175ffd83dbSDimitry Andric   auto V = MIRBuilder.buildSelect(S32, CmpELtOne, D, N);
53185ffd83dbSDimitry Andric 
53195ffd83dbSDimitry Andric   auto VLow3 = MIRBuilder.buildAnd(S32, V, MIRBuilder.buildConstant(S32, 7));
53205ffd83dbSDimitry Andric   V = MIRBuilder.buildLShr(S32, V, MIRBuilder.buildConstant(S32, 2));
53215ffd83dbSDimitry Andric 
53225ffd83dbSDimitry Andric   auto VLow3Eq3 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, VLow3,
53235ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 3));
53245ffd83dbSDimitry Andric   auto V0 = MIRBuilder.buildZExt(S32, VLow3Eq3);
53255ffd83dbSDimitry Andric 
53265ffd83dbSDimitry Andric   auto VLow3Gt5 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT, S1, VLow3,
53275ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 5));
53285ffd83dbSDimitry Andric   auto V1 = MIRBuilder.buildZExt(S32, VLow3Gt5);
53295ffd83dbSDimitry Andric 
53305ffd83dbSDimitry Andric   V1 = MIRBuilder.buildOr(S32, V0, V1);
53315ffd83dbSDimitry Andric   V = MIRBuilder.buildAdd(S32, V, V1);
53325ffd83dbSDimitry Andric 
53335ffd83dbSDimitry Andric   auto CmpEGt30 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,  S1,
53345ffd83dbSDimitry Andric                                        E, MIRBuilder.buildConstant(S32, 30));
53355ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt30,
53365ffd83dbSDimitry Andric                              MIRBuilder.buildConstant(S32, 0x7c00), V);
53375ffd83dbSDimitry Andric 
53385ffd83dbSDimitry Andric   auto CmpEGt1039 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1,
53395ffd83dbSDimitry Andric                                          E, MIRBuilder.buildConstant(S32, 1039));
53405ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt1039, I, V);
53415ffd83dbSDimitry Andric 
53425ffd83dbSDimitry Andric   // Extract the sign bit.
53435ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 16));
53445ffd83dbSDimitry Andric   Sign = MIRBuilder.buildAnd(S32, Sign, MIRBuilder.buildConstant(S32, 0x8000));
53455ffd83dbSDimitry Andric 
53465ffd83dbSDimitry Andric   // Insert the sign bit
53475ffd83dbSDimitry Andric   V = MIRBuilder.buildOr(S32, Sign, V);
53485ffd83dbSDimitry Andric 
53495ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst, V);
53505ffd83dbSDimitry Andric   MI.eraseFromParent();
53515ffd83dbSDimitry Andric   return Legalized;
53525ffd83dbSDimitry Andric }
53535ffd83dbSDimitry Andric 
53545ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
5355*e8d8bef9SDimitry Andric LegalizerHelper::lowerFPTRUNC(MachineInstr &MI) {
53565ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
53575ffd83dbSDimitry Andric   Register Src = MI.getOperand(1).getReg();
53585ffd83dbSDimitry Andric 
53595ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(Dst);
53605ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src);
53615ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
53625ffd83dbSDimitry Andric   const LLT S16 = LLT::scalar(16);
53635ffd83dbSDimitry Andric 
53645ffd83dbSDimitry Andric   if (DstTy.getScalarType() == S16 && SrcTy.getScalarType() == S64)
53655ffd83dbSDimitry Andric     return lowerFPTRUNC_F64_TO_F16(MI);
53665ffd83dbSDimitry Andric 
53675ffd83dbSDimitry Andric   return UnableToLegalize;
53685ffd83dbSDimitry Andric }
53695ffd83dbSDimitry Andric 
5370*e8d8bef9SDimitry Andric // TODO: If RHS is a constant SelectionDAGBuilder expands this into a
5371*e8d8bef9SDimitry Andric // multiplication tree.
5372*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPOWI(MachineInstr &MI) {
5373*e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5374*e8d8bef9SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
5375*e8d8bef9SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
5376*e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
5377*e8d8bef9SDimitry Andric 
5378*e8d8bef9SDimitry Andric   auto CvtSrc1 = MIRBuilder.buildSITOFP(Ty, Src1);
5379*e8d8bef9SDimitry Andric   MIRBuilder.buildFPow(Dst, Src0, CvtSrc1, MI.getFlags());
5380*e8d8bef9SDimitry Andric   MI.eraseFromParent();
5381*e8d8bef9SDimitry Andric   return Legalized;
5382*e8d8bef9SDimitry Andric }
5383*e8d8bef9SDimitry Andric 
53840b57cec5SDimitry Andric static CmpInst::Predicate minMaxToCompare(unsigned Opc) {
53850b57cec5SDimitry Andric   switch (Opc) {
53860b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
53870b57cec5SDimitry Andric     return CmpInst::ICMP_SLT;
53880b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
53890b57cec5SDimitry Andric     return CmpInst::ICMP_SGT;
53900b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
53910b57cec5SDimitry Andric     return CmpInst::ICMP_ULT;
53920b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
53930b57cec5SDimitry Andric     return CmpInst::ICMP_UGT;
53940b57cec5SDimitry Andric   default:
53950b57cec5SDimitry Andric     llvm_unreachable("not in integer min/max");
53960b57cec5SDimitry Andric   }
53970b57cec5SDimitry Andric }
53980b57cec5SDimitry Andric 
5399*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerMinMax(MachineInstr &MI) {
54000b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
54010b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
54020b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
54030b57cec5SDimitry Andric 
54040b57cec5SDimitry Andric   const CmpInst::Predicate Pred = minMaxToCompare(MI.getOpcode());
54050b57cec5SDimitry Andric   LLT CmpType = MRI.getType(Dst).changeElementSize(1);
54060b57cec5SDimitry Andric 
54070b57cec5SDimitry Andric   auto Cmp = MIRBuilder.buildICmp(Pred, CmpType, Src0, Src1);
54080b57cec5SDimitry Andric   MIRBuilder.buildSelect(Dst, Cmp, Src0, Src1);
54090b57cec5SDimitry Andric 
54100b57cec5SDimitry Andric   MI.eraseFromParent();
54110b57cec5SDimitry Andric   return Legalized;
54120b57cec5SDimitry Andric }
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
5415*e8d8bef9SDimitry Andric LegalizerHelper::lowerFCopySign(MachineInstr &MI) {
54160b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
54170b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
54180b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric   const LLT Src0Ty = MRI.getType(Src0);
54210b57cec5SDimitry Andric   const LLT Src1Ty = MRI.getType(Src1);
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric   const int Src0Size = Src0Ty.getScalarSizeInBits();
54240b57cec5SDimitry Andric   const int Src1Size = Src1Ty.getScalarSizeInBits();
54250b57cec5SDimitry Andric 
54260b57cec5SDimitry Andric   auto SignBitMask = MIRBuilder.buildConstant(
54270b57cec5SDimitry Andric     Src0Ty, APInt::getSignMask(Src0Size));
54280b57cec5SDimitry Andric 
54290b57cec5SDimitry Andric   auto NotSignBitMask = MIRBuilder.buildConstant(
54300b57cec5SDimitry Andric     Src0Ty, APInt::getLowBitsSet(Src0Size, Src0Size - 1));
54310b57cec5SDimitry Andric 
54320b57cec5SDimitry Andric   auto And0 = MIRBuilder.buildAnd(Src0Ty, Src0, NotSignBitMask);
54330b57cec5SDimitry Andric   MachineInstr *Or;
54340b57cec5SDimitry Andric 
54350b57cec5SDimitry Andric   if (Src0Ty == Src1Ty) {
54365ffd83dbSDimitry Andric     auto And1 = MIRBuilder.buildAnd(Src1Ty, Src1, SignBitMask);
54370b57cec5SDimitry Andric     Or = MIRBuilder.buildOr(Dst, And0, And1);
54380b57cec5SDimitry Andric   } else if (Src0Size > Src1Size) {
54390b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src0Ty, Src0Size - Src1Size);
54400b57cec5SDimitry Andric     auto Zext = MIRBuilder.buildZExt(Src0Ty, Src1);
54410b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildShl(Src0Ty, Zext, ShiftAmt);
54420b57cec5SDimitry Andric     auto And1 = MIRBuilder.buildAnd(Src0Ty, Shift, SignBitMask);
54430b57cec5SDimitry Andric     Or = MIRBuilder.buildOr(Dst, And0, And1);
54440b57cec5SDimitry Andric   } else {
54450b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src1Ty, Src1Size - Src0Size);
54460b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildLShr(Src1Ty, Src1, ShiftAmt);
54470b57cec5SDimitry Andric     auto Trunc = MIRBuilder.buildTrunc(Src0Ty, Shift);
54480b57cec5SDimitry Andric     auto And1 = MIRBuilder.buildAnd(Src0Ty, Trunc, SignBitMask);
54490b57cec5SDimitry Andric     Or = MIRBuilder.buildOr(Dst, And0, And1);
54500b57cec5SDimitry Andric   }
54510b57cec5SDimitry Andric 
54520b57cec5SDimitry Andric   // Be careful about setting nsz/nnan/ninf on every instruction, since the
54530b57cec5SDimitry Andric   // constants are a nan and -0.0, but the final result should preserve
54540b57cec5SDimitry Andric   // everything.
54550b57cec5SDimitry Andric   if (unsigned Flags = MI.getFlags())
54560b57cec5SDimitry Andric     Or->setFlags(Flags);
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric   MI.eraseFromParent();
54590b57cec5SDimitry Andric   return Legalized;
54600b57cec5SDimitry Andric }
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
54630b57cec5SDimitry Andric LegalizerHelper::lowerFMinNumMaxNum(MachineInstr &MI) {
54640b57cec5SDimitry Andric   unsigned NewOp = MI.getOpcode() == TargetOpcode::G_FMINNUM ?
54650b57cec5SDimitry Andric     TargetOpcode::G_FMINNUM_IEEE : TargetOpcode::G_FMAXNUM_IEEE;
54660b57cec5SDimitry Andric 
54670b57cec5SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
54680b57cec5SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
54690b57cec5SDimitry Andric   Register Src1 = MI.getOperand(2).getReg();
54700b57cec5SDimitry Andric   LLT Ty = MRI.getType(Dst);
54710b57cec5SDimitry Andric 
54720b57cec5SDimitry Andric   if (!MI.getFlag(MachineInstr::FmNoNans)) {
54730b57cec5SDimitry Andric     // Insert canonicalizes if it's possible we need to quiet to get correct
54740b57cec5SDimitry Andric     // sNaN behavior.
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric     // Note this must be done here, and not as an optimization combine in the
54770b57cec5SDimitry Andric     // absence of a dedicate quiet-snan instruction as we're using an
54780b57cec5SDimitry Andric     // omni-purpose G_FCANONICALIZE.
54790b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src0, MRI))
54800b57cec5SDimitry Andric       Src0 = MIRBuilder.buildFCanonicalize(Ty, Src0, MI.getFlags()).getReg(0);
54810b57cec5SDimitry Andric 
54820b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src1, MRI))
54830b57cec5SDimitry Andric       Src1 = MIRBuilder.buildFCanonicalize(Ty, Src1, MI.getFlags()).getReg(0);
54840b57cec5SDimitry Andric   }
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric   // If there are no nans, it's safe to simply replace this with the non-IEEE
54870b57cec5SDimitry Andric   // version.
54880b57cec5SDimitry Andric   MIRBuilder.buildInstr(NewOp, {Dst}, {Src0, Src1}, MI.getFlags());
54890b57cec5SDimitry Andric   MI.eraseFromParent();
54900b57cec5SDimitry Andric   return Legalized;
54910b57cec5SDimitry Andric }
54928bcb0991SDimitry Andric 
54938bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFMad(MachineInstr &MI) {
54948bcb0991SDimitry Andric   // Expand G_FMAD a, b, c -> G_FADD (G_FMUL a, b), c
54958bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
54968bcb0991SDimitry Andric   LLT Ty = MRI.getType(DstReg);
54978bcb0991SDimitry Andric   unsigned Flags = MI.getFlags();
54988bcb0991SDimitry Andric 
54998bcb0991SDimitry Andric   auto Mul = MIRBuilder.buildFMul(Ty, MI.getOperand(1), MI.getOperand(2),
55008bcb0991SDimitry Andric                                   Flags);
55018bcb0991SDimitry Andric   MIRBuilder.buildFAdd(DstReg, Mul, MI.getOperand(3), Flags);
55028bcb0991SDimitry Andric   MI.eraseFromParent();
55038bcb0991SDimitry Andric   return Legalized;
55048bcb0991SDimitry Andric }
55058bcb0991SDimitry Andric 
55068bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
5507480093f4SDimitry Andric LegalizerHelper::lowerIntrinsicRound(MachineInstr &MI) {
5508480093f4SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55095ffd83dbSDimitry Andric   Register X = MI.getOperand(1).getReg();
55105ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
55115ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(DstReg);
55125ffd83dbSDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
55135ffd83dbSDimitry Andric 
55145ffd83dbSDimitry Andric   // round(x) =>
55155ffd83dbSDimitry Andric   //  t = trunc(x);
55165ffd83dbSDimitry Andric   //  d = fabs(x - t);
55175ffd83dbSDimitry Andric   //  o = copysign(1.0f, x);
55185ffd83dbSDimitry Andric   //  return t + (d >= 0.5 ? o : 0.0);
55195ffd83dbSDimitry Andric 
55205ffd83dbSDimitry Andric   auto T = MIRBuilder.buildIntrinsicTrunc(Ty, X, Flags);
55215ffd83dbSDimitry Andric 
55225ffd83dbSDimitry Andric   auto Diff = MIRBuilder.buildFSub(Ty, X, T, Flags);
55235ffd83dbSDimitry Andric   auto AbsDiff = MIRBuilder.buildFAbs(Ty, Diff, Flags);
55245ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
55255ffd83dbSDimitry Andric   auto One = MIRBuilder.buildFConstant(Ty, 1.0);
55265ffd83dbSDimitry Andric   auto Half = MIRBuilder.buildFConstant(Ty, 0.5);
55275ffd83dbSDimitry Andric   auto SignOne = MIRBuilder.buildFCopysign(Ty, One, X);
55285ffd83dbSDimitry Andric 
55295ffd83dbSDimitry Andric   auto Cmp = MIRBuilder.buildFCmp(CmpInst::FCMP_OGE, CondTy, AbsDiff, Half,
55305ffd83dbSDimitry Andric                                   Flags);
55315ffd83dbSDimitry Andric   auto Sel = MIRBuilder.buildSelect(Ty, Cmp, SignOne, Zero, Flags);
55325ffd83dbSDimitry Andric 
55335ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, T, Sel, Flags);
55345ffd83dbSDimitry Andric 
55355ffd83dbSDimitry Andric   MI.eraseFromParent();
55365ffd83dbSDimitry Andric   return Legalized;
55375ffd83dbSDimitry Andric }
55385ffd83dbSDimitry Andric 
55395ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55405ffd83dbSDimitry Andric LegalizerHelper::lowerFFloor(MachineInstr &MI) {
55415ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5542480093f4SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
5543480093f4SDimitry Andric   unsigned Flags = MI.getFlags();
5544480093f4SDimitry Andric   LLT Ty = MRI.getType(DstReg);
5545480093f4SDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
5546480093f4SDimitry Andric 
5547480093f4SDimitry Andric   // result = trunc(src);
5548480093f4SDimitry Andric   // if (src < 0.0 && src != result)
5549480093f4SDimitry Andric   //   result += -1.0.
5550480093f4SDimitry Andric 
5551480093f4SDimitry Andric   auto Trunc = MIRBuilder.buildIntrinsicTrunc(Ty, SrcReg, Flags);
55525ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
5553480093f4SDimitry Andric 
5554480093f4SDimitry Andric   auto Lt0 = MIRBuilder.buildFCmp(CmpInst::FCMP_OLT, CondTy,
5555480093f4SDimitry Andric                                   SrcReg, Zero, Flags);
5556480093f4SDimitry Andric   auto NeTrunc = MIRBuilder.buildFCmp(CmpInst::FCMP_ONE, CondTy,
5557480093f4SDimitry Andric                                       SrcReg, Trunc, Flags);
5558480093f4SDimitry Andric   auto And = MIRBuilder.buildAnd(CondTy, Lt0, NeTrunc);
5559480093f4SDimitry Andric   auto AddVal = MIRBuilder.buildSITOFP(Ty, And);
5560480093f4SDimitry Andric 
55615ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, Trunc, AddVal, Flags);
55625ffd83dbSDimitry Andric   MI.eraseFromParent();
55635ffd83dbSDimitry Andric   return Legalized;
55645ffd83dbSDimitry Andric }
55655ffd83dbSDimitry Andric 
55665ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55675ffd83dbSDimitry Andric LegalizerHelper::lowerMergeValues(MachineInstr &MI) {
55685ffd83dbSDimitry Andric   const unsigned NumOps = MI.getNumOperands();
55695ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55705ffd83dbSDimitry Andric   Register Src0Reg = MI.getOperand(1).getReg();
55715ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
55725ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(Src0Reg);
55735ffd83dbSDimitry Andric   unsigned PartSize = SrcTy.getSizeInBits();
55745ffd83dbSDimitry Andric 
55755ffd83dbSDimitry Andric   LLT WideTy = LLT::scalar(DstTy.getSizeInBits());
55765ffd83dbSDimitry Andric   Register ResultReg = MIRBuilder.buildZExt(WideTy, Src0Reg).getReg(0);
55775ffd83dbSDimitry Andric 
55785ffd83dbSDimitry Andric   for (unsigned I = 2; I != NumOps; ++I) {
55795ffd83dbSDimitry Andric     const unsigned Offset = (I - 1) * PartSize;
55805ffd83dbSDimitry Andric 
55815ffd83dbSDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
55825ffd83dbSDimitry Andric     auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
55835ffd83dbSDimitry Andric 
55845ffd83dbSDimitry Andric     Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
55855ffd83dbSDimitry Andric       MRI.createGenericVirtualRegister(WideTy);
55865ffd83dbSDimitry Andric 
55875ffd83dbSDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
55885ffd83dbSDimitry Andric     auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
55895ffd83dbSDimitry Andric     MIRBuilder.buildOr(NextResult, ResultReg, Shl);
55905ffd83dbSDimitry Andric     ResultReg = NextResult;
55915ffd83dbSDimitry Andric   }
55925ffd83dbSDimitry Andric 
55935ffd83dbSDimitry Andric   if (DstTy.isPointer()) {
55945ffd83dbSDimitry Andric     if (MIRBuilder.getDataLayout().isNonIntegralAddressSpace(
55955ffd83dbSDimitry Andric           DstTy.getAddressSpace())) {
55965ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Not casting nonintegral address space\n");
55975ffd83dbSDimitry Andric       return UnableToLegalize;
55985ffd83dbSDimitry Andric     }
55995ffd83dbSDimitry Andric 
56005ffd83dbSDimitry Andric     MIRBuilder.buildIntToPtr(DstReg, ResultReg);
56015ffd83dbSDimitry Andric   }
56025ffd83dbSDimitry Andric 
5603480093f4SDimitry Andric   MI.eraseFromParent();
5604480093f4SDimitry Andric   return Legalized;
5605480093f4SDimitry Andric }
5606480093f4SDimitry Andric 
5607480093f4SDimitry Andric LegalizerHelper::LegalizeResult
56088bcb0991SDimitry Andric LegalizerHelper::lowerUnmergeValues(MachineInstr &MI) {
56098bcb0991SDimitry Andric   const unsigned NumDst = MI.getNumOperands() - 1;
56105ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
56118bcb0991SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
56128bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
56135ffd83dbSDimitry Andric   if (DstTy.isPointer())
56145ffd83dbSDimitry Andric     return UnableToLegalize; // TODO
56158bcb0991SDimitry Andric 
56165ffd83dbSDimitry Andric   SrcReg = coerceToScalar(SrcReg);
56175ffd83dbSDimitry Andric   if (!SrcReg)
56185ffd83dbSDimitry Andric     return UnableToLegalize;
56198bcb0991SDimitry Andric 
56208bcb0991SDimitry Andric   // Expand scalarizing unmerge as bitcast to integer and shift.
56215ffd83dbSDimitry Andric   LLT IntTy = MRI.getType(SrcReg);
56228bcb0991SDimitry Andric 
56235ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
56248bcb0991SDimitry Andric 
56258bcb0991SDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
56268bcb0991SDimitry Andric   unsigned Offset = DstSize;
56278bcb0991SDimitry Andric   for (unsigned I = 1; I != NumDst; ++I, Offset += DstSize) {
56288bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntTy, Offset);
56295ffd83dbSDimitry Andric     auto Shift = MIRBuilder.buildLShr(IntTy, SrcReg, ShiftAmt);
56308bcb0991SDimitry Andric     MIRBuilder.buildTrunc(MI.getOperand(I), Shift);
56318bcb0991SDimitry Andric   }
56328bcb0991SDimitry Andric 
56338bcb0991SDimitry Andric   MI.eraseFromParent();
56348bcb0991SDimitry Andric   return Legalized;
56358bcb0991SDimitry Andric }
56368bcb0991SDimitry Andric 
5637*e8d8bef9SDimitry Andric /// Lower a vector extract or insert by writing the vector to a stack temporary
5638*e8d8bef9SDimitry Andric /// and reloading the element or vector.
5639*e8d8bef9SDimitry Andric ///
5640*e8d8bef9SDimitry Andric /// %dst = G_EXTRACT_VECTOR_ELT %vec, %idx
5641*e8d8bef9SDimitry Andric ///  =>
5642*e8d8bef9SDimitry Andric ///  %stack_temp = G_FRAME_INDEX
5643*e8d8bef9SDimitry Andric ///  G_STORE %vec, %stack_temp
5644*e8d8bef9SDimitry Andric ///  %idx = clamp(%idx, %vec.getNumElements())
5645*e8d8bef9SDimitry Andric ///  %element_ptr = G_PTR_ADD %stack_temp, %idx
5646*e8d8bef9SDimitry Andric ///  %dst = G_LOAD %element_ptr
5647*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
5648*e8d8bef9SDimitry Andric LegalizerHelper::lowerExtractInsertVectorElt(MachineInstr &MI) {
5649*e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5650*e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
5651*e8d8bef9SDimitry Andric   Register InsertVal;
5652*e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
5653*e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
5654*e8d8bef9SDimitry Andric 
5655*e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
5656*e8d8bef9SDimitry Andric 
5657*e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
5658*e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
5659*e8d8bef9SDimitry Andric   if (!EltTy.isByteSized()) { // Not implemented.
5660*e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-byte element vectors yet\n");
5661*e8d8bef9SDimitry Andric     return UnableToLegalize;
5662*e8d8bef9SDimitry Andric   }
5663*e8d8bef9SDimitry Andric 
5664*e8d8bef9SDimitry Andric   unsigned EltBytes = EltTy.getSizeInBytes();
5665*e8d8bef9SDimitry Andric   Align VecAlign = getStackTemporaryAlignment(VecTy);
5666*e8d8bef9SDimitry Andric   Align EltAlign;
5667*e8d8bef9SDimitry Andric 
5668*e8d8bef9SDimitry Andric   MachinePointerInfo PtrInfo;
5669*e8d8bef9SDimitry Andric   auto StackTemp = createStackTemporary(TypeSize::Fixed(VecTy.getSizeInBytes()),
5670*e8d8bef9SDimitry Andric                                         VecAlign, PtrInfo);
5671*e8d8bef9SDimitry Andric   MIRBuilder.buildStore(SrcVec, StackTemp, PtrInfo, VecAlign);
5672*e8d8bef9SDimitry Andric 
5673*e8d8bef9SDimitry Andric   // Get the pointer to the element, and be sure not to hit undefined behavior
5674*e8d8bef9SDimitry Andric   // if the index is out of bounds.
5675*e8d8bef9SDimitry Andric   Register EltPtr = getVectorElementPointer(StackTemp.getReg(0), VecTy, Idx);
5676*e8d8bef9SDimitry Andric 
5677*e8d8bef9SDimitry Andric   int64_t IdxVal;
5678*e8d8bef9SDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal))) {
5679*e8d8bef9SDimitry Andric     int64_t Offset = IdxVal * EltBytes;
5680*e8d8bef9SDimitry Andric     PtrInfo = PtrInfo.getWithOffset(Offset);
5681*e8d8bef9SDimitry Andric     EltAlign = commonAlignment(VecAlign, Offset);
5682*e8d8bef9SDimitry Andric   } else {
5683*e8d8bef9SDimitry Andric     // We lose information with a variable offset.
5684*e8d8bef9SDimitry Andric     EltAlign = getStackTemporaryAlignment(EltTy);
5685*e8d8bef9SDimitry Andric     PtrInfo = MachinePointerInfo(MRI.getType(EltPtr).getAddressSpace());
5686*e8d8bef9SDimitry Andric   }
5687*e8d8bef9SDimitry Andric 
5688*e8d8bef9SDimitry Andric   if (InsertVal) {
5689*e8d8bef9SDimitry Andric     // Write the inserted element
5690*e8d8bef9SDimitry Andric     MIRBuilder.buildStore(InsertVal, EltPtr, PtrInfo, EltAlign);
5691*e8d8bef9SDimitry Andric 
5692*e8d8bef9SDimitry Andric     // Reload the whole vector.
5693*e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, StackTemp, PtrInfo, VecAlign);
5694*e8d8bef9SDimitry Andric   } else {
5695*e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, EltPtr, PtrInfo, EltAlign);
5696*e8d8bef9SDimitry Andric   }
5697*e8d8bef9SDimitry Andric 
5698*e8d8bef9SDimitry Andric   MI.eraseFromParent();
5699*e8d8bef9SDimitry Andric   return Legalized;
5700*e8d8bef9SDimitry Andric }
5701*e8d8bef9SDimitry Andric 
57028bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
57038bcb0991SDimitry Andric LegalizerHelper::lowerShuffleVector(MachineInstr &MI) {
57048bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
57058bcb0991SDimitry Andric   Register Src0Reg = MI.getOperand(1).getReg();
57068bcb0991SDimitry Andric   Register Src1Reg = MI.getOperand(2).getReg();
57078bcb0991SDimitry Andric   LLT Src0Ty = MRI.getType(Src0Reg);
57088bcb0991SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
57098bcb0991SDimitry Andric   LLT IdxTy = LLT::scalar(32);
57108bcb0991SDimitry Andric 
5711480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
57128bcb0991SDimitry Andric 
57138bcb0991SDimitry Andric   if (DstTy.isScalar()) {
57148bcb0991SDimitry Andric     if (Src0Ty.isVector())
57158bcb0991SDimitry Andric       return UnableToLegalize;
57168bcb0991SDimitry Andric 
57178bcb0991SDimitry Andric     // This is just a SELECT.
57188bcb0991SDimitry Andric     assert(Mask.size() == 1 && "Expected a single mask element");
57198bcb0991SDimitry Andric     Register Val;
57208bcb0991SDimitry Andric     if (Mask[0] < 0 || Mask[0] > 1)
57218bcb0991SDimitry Andric       Val = MIRBuilder.buildUndef(DstTy).getReg(0);
57228bcb0991SDimitry Andric     else
57238bcb0991SDimitry Andric       Val = Mask[0] == 0 ? Src0Reg : Src1Reg;
57248bcb0991SDimitry Andric     MIRBuilder.buildCopy(DstReg, Val);
57258bcb0991SDimitry Andric     MI.eraseFromParent();
57268bcb0991SDimitry Andric     return Legalized;
57278bcb0991SDimitry Andric   }
57288bcb0991SDimitry Andric 
57298bcb0991SDimitry Andric   Register Undef;
57308bcb0991SDimitry Andric   SmallVector<Register, 32> BuildVec;
57318bcb0991SDimitry Andric   LLT EltTy = DstTy.getElementType();
57328bcb0991SDimitry Andric 
57338bcb0991SDimitry Andric   for (int Idx : Mask) {
57348bcb0991SDimitry Andric     if (Idx < 0) {
57358bcb0991SDimitry Andric       if (!Undef.isValid())
57368bcb0991SDimitry Andric         Undef = MIRBuilder.buildUndef(EltTy).getReg(0);
57378bcb0991SDimitry Andric       BuildVec.push_back(Undef);
57388bcb0991SDimitry Andric       continue;
57398bcb0991SDimitry Andric     }
57408bcb0991SDimitry Andric 
57418bcb0991SDimitry Andric     if (Src0Ty.isScalar()) {
57428bcb0991SDimitry Andric       BuildVec.push_back(Idx == 0 ? Src0Reg : Src1Reg);
57438bcb0991SDimitry Andric     } else {
57448bcb0991SDimitry Andric       int NumElts = Src0Ty.getNumElements();
57458bcb0991SDimitry Andric       Register SrcVec = Idx < NumElts ? Src0Reg : Src1Reg;
57468bcb0991SDimitry Andric       int ExtractIdx = Idx < NumElts ? Idx : Idx - NumElts;
57478bcb0991SDimitry Andric       auto IdxK = MIRBuilder.buildConstant(IdxTy, ExtractIdx);
57488bcb0991SDimitry Andric       auto Extract = MIRBuilder.buildExtractVectorElement(EltTy, SrcVec, IdxK);
57498bcb0991SDimitry Andric       BuildVec.push_back(Extract.getReg(0));
57508bcb0991SDimitry Andric     }
57518bcb0991SDimitry Andric   }
57528bcb0991SDimitry Andric 
57538bcb0991SDimitry Andric   MIRBuilder.buildBuildVector(DstReg, BuildVec);
57548bcb0991SDimitry Andric   MI.eraseFromParent();
57558bcb0991SDimitry Andric   return Legalized;
57568bcb0991SDimitry Andric }
57578bcb0991SDimitry Andric 
57588bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
57598bcb0991SDimitry Andric LegalizerHelper::lowerDynStackAlloc(MachineInstr &MI) {
57605ffd83dbSDimitry Andric   const auto &MF = *MI.getMF();
57615ffd83dbSDimitry Andric   const auto &TFI = *MF.getSubtarget().getFrameLowering();
57625ffd83dbSDimitry Andric   if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
57635ffd83dbSDimitry Andric     return UnableToLegalize;
57645ffd83dbSDimitry Andric 
57658bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
57668bcb0991SDimitry Andric   Register AllocSize = MI.getOperand(1).getReg();
57675ffd83dbSDimitry Andric   Align Alignment = assumeAligned(MI.getOperand(2).getImm());
57688bcb0991SDimitry Andric 
57698bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(Dst);
57708bcb0991SDimitry Andric   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
57718bcb0991SDimitry Andric 
57728bcb0991SDimitry Andric   Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
57738bcb0991SDimitry Andric   auto SPTmp = MIRBuilder.buildCopy(PtrTy, SPReg);
57748bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(IntPtrTy, SPTmp);
57758bcb0991SDimitry Andric 
57768bcb0991SDimitry Andric   // Subtract the final alloc from the SP. We use G_PTRTOINT here so we don't
57778bcb0991SDimitry Andric   // have to generate an extra instruction to negate the alloc and then use
5778480093f4SDimitry Andric   // G_PTR_ADD to add the negative offset.
57798bcb0991SDimitry Andric   auto Alloc = MIRBuilder.buildSub(IntPtrTy, SPTmp, AllocSize);
57805ffd83dbSDimitry Andric   if (Alignment > Align(1)) {
57815ffd83dbSDimitry Andric     APInt AlignMask(IntPtrTy.getSizeInBits(), Alignment.value(), true);
57828bcb0991SDimitry Andric     AlignMask.negate();
57838bcb0991SDimitry Andric     auto AlignCst = MIRBuilder.buildConstant(IntPtrTy, AlignMask);
57848bcb0991SDimitry Andric     Alloc = MIRBuilder.buildAnd(IntPtrTy, Alloc, AlignCst);
57858bcb0991SDimitry Andric   }
57868bcb0991SDimitry Andric 
57878bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(PtrTy, Alloc);
57888bcb0991SDimitry Andric   MIRBuilder.buildCopy(SPReg, SPTmp);
57898bcb0991SDimitry Andric   MIRBuilder.buildCopy(Dst, SPTmp);
57908bcb0991SDimitry Andric 
57918bcb0991SDimitry Andric   MI.eraseFromParent();
57928bcb0991SDimitry Andric   return Legalized;
57938bcb0991SDimitry Andric }
57948bcb0991SDimitry Andric 
57958bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
57968bcb0991SDimitry Andric LegalizerHelper::lowerExtract(MachineInstr &MI) {
57978bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
57988bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
57998bcb0991SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
58008bcb0991SDimitry Andric 
58018bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst);
58028bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(Src);
58038bcb0991SDimitry Andric 
58048bcb0991SDimitry Andric   if (DstTy.isScalar() &&
58058bcb0991SDimitry Andric       (SrcTy.isScalar() ||
58068bcb0991SDimitry Andric        (SrcTy.isVector() && DstTy == SrcTy.getElementType()))) {
58078bcb0991SDimitry Andric     LLT SrcIntTy = SrcTy;
58088bcb0991SDimitry Andric     if (!SrcTy.isScalar()) {
58098bcb0991SDimitry Andric       SrcIntTy = LLT::scalar(SrcTy.getSizeInBits());
58108bcb0991SDimitry Andric       Src = MIRBuilder.buildBitcast(SrcIntTy, Src).getReg(0);
58118bcb0991SDimitry Andric     }
58128bcb0991SDimitry Andric 
58138bcb0991SDimitry Andric     if (Offset == 0)
58148bcb0991SDimitry Andric       MIRBuilder.buildTrunc(Dst, Src);
58158bcb0991SDimitry Andric     else {
58168bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcIntTy, Offset);
58178bcb0991SDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcIntTy, Src, ShiftAmt);
58188bcb0991SDimitry Andric       MIRBuilder.buildTrunc(Dst, Shr);
58198bcb0991SDimitry Andric     }
58208bcb0991SDimitry Andric 
58218bcb0991SDimitry Andric     MI.eraseFromParent();
58228bcb0991SDimitry Andric     return Legalized;
58238bcb0991SDimitry Andric   }
58248bcb0991SDimitry Andric 
58258bcb0991SDimitry Andric   return UnableToLegalize;
58268bcb0991SDimitry Andric }
58278bcb0991SDimitry Andric 
58288bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerInsert(MachineInstr &MI) {
58298bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
58308bcb0991SDimitry Andric   Register Src = MI.getOperand(1).getReg();
58318bcb0991SDimitry Andric   Register InsertSrc = MI.getOperand(2).getReg();
58328bcb0991SDimitry Andric   uint64_t Offset = MI.getOperand(3).getImm();
58338bcb0991SDimitry Andric 
58348bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Src);
58358bcb0991SDimitry Andric   LLT InsertTy = MRI.getType(InsertSrc);
58368bcb0991SDimitry Andric 
58375ffd83dbSDimitry Andric   if (InsertTy.isVector() ||
58385ffd83dbSDimitry Andric       (DstTy.isVector() && DstTy.getElementType() != InsertTy))
58395ffd83dbSDimitry Andric     return UnableToLegalize;
58405ffd83dbSDimitry Andric 
58415ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
58425ffd83dbSDimitry Andric   if ((DstTy.isPointer() &&
58435ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(DstTy.getAddressSpace())) ||
58445ffd83dbSDimitry Andric       (InsertTy.isPointer() &&
58455ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(InsertTy.getAddressSpace()))) {
58465ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Not casting non-integral address space integer\n");
58475ffd83dbSDimitry Andric     return UnableToLegalize;
58485ffd83dbSDimitry Andric   }
58495ffd83dbSDimitry Andric 
58508bcb0991SDimitry Andric   LLT IntDstTy = DstTy;
58515ffd83dbSDimitry Andric 
58528bcb0991SDimitry Andric   if (!DstTy.isScalar()) {
58538bcb0991SDimitry Andric     IntDstTy = LLT::scalar(DstTy.getSizeInBits());
58545ffd83dbSDimitry Andric     Src = MIRBuilder.buildCast(IntDstTy, Src).getReg(0);
58555ffd83dbSDimitry Andric   }
58565ffd83dbSDimitry Andric 
58575ffd83dbSDimitry Andric   if (!InsertTy.isScalar()) {
58585ffd83dbSDimitry Andric     const LLT IntInsertTy = LLT::scalar(InsertTy.getSizeInBits());
58595ffd83dbSDimitry Andric     InsertSrc = MIRBuilder.buildPtrToInt(IntInsertTy, InsertSrc).getReg(0);
58608bcb0991SDimitry Andric   }
58618bcb0991SDimitry Andric 
58628bcb0991SDimitry Andric   Register ExtInsSrc = MIRBuilder.buildZExt(IntDstTy, InsertSrc).getReg(0);
58638bcb0991SDimitry Andric   if (Offset != 0) {
58648bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntDstTy, Offset);
58658bcb0991SDimitry Andric     ExtInsSrc = MIRBuilder.buildShl(IntDstTy, ExtInsSrc, ShiftAmt).getReg(0);
58668bcb0991SDimitry Andric   }
58678bcb0991SDimitry Andric 
58685ffd83dbSDimitry Andric   APInt MaskVal = APInt::getBitsSetWithWrap(
58695ffd83dbSDimitry Andric       DstTy.getSizeInBits(), Offset + InsertTy.getSizeInBits(), Offset);
58708bcb0991SDimitry Andric 
58718bcb0991SDimitry Andric   auto Mask = MIRBuilder.buildConstant(IntDstTy, MaskVal);
58728bcb0991SDimitry Andric   auto MaskedSrc = MIRBuilder.buildAnd(IntDstTy, Src, Mask);
58738bcb0991SDimitry Andric   auto Or = MIRBuilder.buildOr(IntDstTy, MaskedSrc, ExtInsSrc);
58748bcb0991SDimitry Andric 
58755ffd83dbSDimitry Andric   MIRBuilder.buildCast(Dst, Or);
58768bcb0991SDimitry Andric   MI.eraseFromParent();
58778bcb0991SDimitry Andric   return Legalized;
58788bcb0991SDimitry Andric }
58798bcb0991SDimitry Andric 
58808bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
58818bcb0991SDimitry Andric LegalizerHelper::lowerSADDO_SSUBO(MachineInstr &MI) {
58828bcb0991SDimitry Andric   Register Dst0 = MI.getOperand(0).getReg();
58838bcb0991SDimitry Andric   Register Dst1 = MI.getOperand(1).getReg();
58848bcb0991SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
58858bcb0991SDimitry Andric   Register RHS = MI.getOperand(3).getReg();
58868bcb0991SDimitry Andric   const bool IsAdd = MI.getOpcode() == TargetOpcode::G_SADDO;
58878bcb0991SDimitry Andric 
58888bcb0991SDimitry Andric   LLT Ty = MRI.getType(Dst0);
58898bcb0991SDimitry Andric   LLT BoolTy = MRI.getType(Dst1);
58908bcb0991SDimitry Andric 
58918bcb0991SDimitry Andric   if (IsAdd)
58928bcb0991SDimitry Andric     MIRBuilder.buildAdd(Dst0, LHS, RHS);
58938bcb0991SDimitry Andric   else
58948bcb0991SDimitry Andric     MIRBuilder.buildSub(Dst0, LHS, RHS);
58958bcb0991SDimitry Andric 
58968bcb0991SDimitry Andric   // TODO: If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
58978bcb0991SDimitry Andric 
58988bcb0991SDimitry Andric   auto Zero = MIRBuilder.buildConstant(Ty, 0);
58998bcb0991SDimitry Andric 
59008bcb0991SDimitry Andric   // For an addition, the result should be less than one of the operands (LHS)
59018bcb0991SDimitry Andric   // if and only if the other operand (RHS) is negative, otherwise there will
59028bcb0991SDimitry Andric   // be overflow.
59038bcb0991SDimitry Andric   // For a subtraction, the result should be less than one of the operands
59048bcb0991SDimitry Andric   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
59058bcb0991SDimitry Andric   // otherwise there will be overflow.
59068bcb0991SDimitry Andric   auto ResultLowerThanLHS =
59078bcb0991SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, Dst0, LHS);
59088bcb0991SDimitry Andric   auto ConditionRHS = MIRBuilder.buildICmp(
59098bcb0991SDimitry Andric       IsAdd ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGT, BoolTy, RHS, Zero);
59108bcb0991SDimitry Andric 
59118bcb0991SDimitry Andric   MIRBuilder.buildXor(Dst1, ConditionRHS, ResultLowerThanLHS);
59128bcb0991SDimitry Andric   MI.eraseFromParent();
59138bcb0991SDimitry Andric   return Legalized;
59148bcb0991SDimitry Andric }
5915480093f4SDimitry Andric 
5916480093f4SDimitry Andric LegalizerHelper::LegalizeResult
5917*e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToMinMax(MachineInstr &MI) {
5918*e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
5919*e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5920*e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5921*e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
5922*e8d8bef9SDimitry Andric   bool IsSigned;
5923*e8d8bef9SDimitry Andric   bool IsAdd;
5924*e8d8bef9SDimitry Andric   unsigned BaseOp;
5925*e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
5926*e8d8bef9SDimitry Andric   default:
5927*e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
5928*e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
5929*e8d8bef9SDimitry Andric     IsSigned = false;
5930*e8d8bef9SDimitry Andric     IsAdd = true;
5931*e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
5932*e8d8bef9SDimitry Andric     break;
5933*e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
5934*e8d8bef9SDimitry Andric     IsSigned = true;
5935*e8d8bef9SDimitry Andric     IsAdd = true;
5936*e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
5937*e8d8bef9SDimitry Andric     break;
5938*e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
5939*e8d8bef9SDimitry Andric     IsSigned = false;
5940*e8d8bef9SDimitry Andric     IsAdd = false;
5941*e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
5942*e8d8bef9SDimitry Andric     break;
5943*e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
5944*e8d8bef9SDimitry Andric     IsSigned = true;
5945*e8d8bef9SDimitry Andric     IsAdd = false;
5946*e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
5947*e8d8bef9SDimitry Andric     break;
5948*e8d8bef9SDimitry Andric   }
5949*e8d8bef9SDimitry Andric 
5950*e8d8bef9SDimitry Andric   if (IsSigned) {
5951*e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
5952*e8d8bef9SDimitry Andric     //   hi = 0x7fffffff - smax(a, 0)
5953*e8d8bef9SDimitry Andric     //   lo = 0x80000000 - smin(a, 0)
5954*e8d8bef9SDimitry Andric     //   a + smin(smax(lo, b), hi)
5955*e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
5956*e8d8bef9SDimitry Andric     //   lo = smax(a, -1) - 0x7fffffff
5957*e8d8bef9SDimitry Andric     //   hi = smin(a, -1) - 0x80000000
5958*e8d8bef9SDimitry Andric     //   a - smin(smax(lo, b), hi)
5959*e8d8bef9SDimitry Andric     // TODO: AMDGPU can use a "median of 3" instruction here:
5960*e8d8bef9SDimitry Andric     //   a +/- med3(lo, b, hi)
5961*e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
5962*e8d8bef9SDimitry Andric     auto MaxVal =
5963*e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(NumBits));
5964*e8d8bef9SDimitry Andric     auto MinVal =
5965*e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
5966*e8d8bef9SDimitry Andric     MachineInstrBuilder Hi, Lo;
5967*e8d8bef9SDimitry Andric     if (IsAdd) {
5968*e8d8bef9SDimitry Andric       auto Zero = MIRBuilder.buildConstant(Ty, 0);
5969*e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MaxVal, MIRBuilder.buildSMax(Ty, LHS, Zero));
5970*e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MinVal, MIRBuilder.buildSMin(Ty, LHS, Zero));
5971*e8d8bef9SDimitry Andric     } else {
5972*e8d8bef9SDimitry Andric       auto NegOne = MIRBuilder.buildConstant(Ty, -1);
5973*e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMax(Ty, LHS, NegOne),
5974*e8d8bef9SDimitry Andric                                MaxVal);
5975*e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMin(Ty, LHS, NegOne),
5976*e8d8bef9SDimitry Andric                                MinVal);
5977*e8d8bef9SDimitry Andric     }
5978*e8d8bef9SDimitry Andric     auto RHSClamped =
5979*e8d8bef9SDimitry Andric         MIRBuilder.buildSMin(Ty, MIRBuilder.buildSMax(Ty, Lo, RHS), Hi);
5980*e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, RHSClamped});
5981*e8d8bef9SDimitry Andric   } else {
5982*e8d8bef9SDimitry Andric     // uadd.sat(a, b) -> a + umin(~a, b)
5983*e8d8bef9SDimitry Andric     // usub.sat(a, b) -> a - umin(a, b)
5984*e8d8bef9SDimitry Andric     Register Not = IsAdd ? MIRBuilder.buildNot(Ty, LHS).getReg(0) : LHS;
5985*e8d8bef9SDimitry Andric     auto Min = MIRBuilder.buildUMin(Ty, Not, RHS);
5986*e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, Min});
5987*e8d8bef9SDimitry Andric   }
5988*e8d8bef9SDimitry Andric 
5989*e8d8bef9SDimitry Andric   MI.eraseFromParent();
5990*e8d8bef9SDimitry Andric   return Legalized;
5991*e8d8bef9SDimitry Andric }
5992*e8d8bef9SDimitry Andric 
5993*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
5994*e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToAddoSubo(MachineInstr &MI) {
5995*e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
5996*e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5997*e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5998*e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
5999*e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
6000*e8d8bef9SDimitry Andric   bool IsSigned;
6001*e8d8bef9SDimitry Andric   bool IsAdd;
6002*e8d8bef9SDimitry Andric   unsigned OverflowOp;
6003*e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
6004*e8d8bef9SDimitry Andric   default:
6005*e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
6006*e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
6007*e8d8bef9SDimitry Andric     IsSigned = false;
6008*e8d8bef9SDimitry Andric     IsAdd = true;
6009*e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_UADDO;
6010*e8d8bef9SDimitry Andric     break;
6011*e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
6012*e8d8bef9SDimitry Andric     IsSigned = true;
6013*e8d8bef9SDimitry Andric     IsAdd = true;
6014*e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SADDO;
6015*e8d8bef9SDimitry Andric     break;
6016*e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
6017*e8d8bef9SDimitry Andric     IsSigned = false;
6018*e8d8bef9SDimitry Andric     IsAdd = false;
6019*e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_USUBO;
6020*e8d8bef9SDimitry Andric     break;
6021*e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
6022*e8d8bef9SDimitry Andric     IsSigned = true;
6023*e8d8bef9SDimitry Andric     IsAdd = false;
6024*e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SSUBO;
6025*e8d8bef9SDimitry Andric     break;
6026*e8d8bef9SDimitry Andric   }
6027*e8d8bef9SDimitry Andric 
6028*e8d8bef9SDimitry Andric   auto OverflowRes =
6029*e8d8bef9SDimitry Andric       MIRBuilder.buildInstr(OverflowOp, {Ty, BoolTy}, {LHS, RHS});
6030*e8d8bef9SDimitry Andric   Register Tmp = OverflowRes.getReg(0);
6031*e8d8bef9SDimitry Andric   Register Ov = OverflowRes.getReg(1);
6032*e8d8bef9SDimitry Andric   MachineInstrBuilder Clamp;
6033*e8d8bef9SDimitry Andric   if (IsSigned) {
6034*e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
6035*e8d8bef9SDimitry Andric     //   {tmp, ov} = saddo(a, b)
6036*e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
6037*e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
6038*e8d8bef9SDimitry Andric     //   {tmp, ov} = ssubo(a, b)
6039*e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
6040*e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
6041*e8d8bef9SDimitry Andric     auto ShiftAmount = MIRBuilder.buildConstant(Ty, NumBits - 1);
6042*e8d8bef9SDimitry Andric     auto Sign = MIRBuilder.buildAShr(Ty, Tmp, ShiftAmount);
6043*e8d8bef9SDimitry Andric     auto MinVal =
6044*e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
6045*e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildAdd(Ty, Sign, MinVal);
6046*e8d8bef9SDimitry Andric   } else {
6047*e8d8bef9SDimitry Andric     // uadd.sat(a, b) ->
6048*e8d8bef9SDimitry Andric     //   {tmp, ov} = uaddo(a, b)
6049*e8d8bef9SDimitry Andric     //   ov ? 0xffffffff : tmp
6050*e8d8bef9SDimitry Andric     // usub.sat(a, b) ->
6051*e8d8bef9SDimitry Andric     //   {tmp, ov} = usubo(a, b)
6052*e8d8bef9SDimitry Andric     //   ov ? 0 : tmp
6053*e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildConstant(Ty, IsAdd ? -1 : 0);
6054*e8d8bef9SDimitry Andric   }
6055*e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, Clamp, Tmp);
6056*e8d8bef9SDimitry Andric 
6057*e8d8bef9SDimitry Andric   MI.eraseFromParent();
6058*e8d8bef9SDimitry Andric   return Legalized;
6059*e8d8bef9SDimitry Andric }
6060*e8d8bef9SDimitry Andric 
6061*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6062*e8d8bef9SDimitry Andric LegalizerHelper::lowerShlSat(MachineInstr &MI) {
6063*e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
6064*e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_USHLSAT) &&
6065*e8d8bef9SDimitry Andric          "Expected shlsat opcode!");
6066*e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SSHLSAT;
6067*e8d8bef9SDimitry Andric   Register Res = MI.getOperand(0).getReg();
6068*e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
6069*e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
6070*e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
6071*e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
6072*e8d8bef9SDimitry Andric 
6073*e8d8bef9SDimitry Andric   unsigned BW = Ty.getScalarSizeInBits();
6074*e8d8bef9SDimitry Andric   auto Result = MIRBuilder.buildShl(Ty, LHS, RHS);
6075*e8d8bef9SDimitry Andric   auto Orig = IsSigned ? MIRBuilder.buildAShr(Ty, Result, RHS)
6076*e8d8bef9SDimitry Andric                        : MIRBuilder.buildLShr(Ty, Result, RHS);
6077*e8d8bef9SDimitry Andric 
6078*e8d8bef9SDimitry Andric   MachineInstrBuilder SatVal;
6079*e8d8bef9SDimitry Andric   if (IsSigned) {
6080*e8d8bef9SDimitry Andric     auto SatMin = MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(BW));
6081*e8d8bef9SDimitry Andric     auto SatMax = MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(BW));
6082*e8d8bef9SDimitry Andric     auto Cmp = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, LHS,
6083*e8d8bef9SDimitry Andric                                     MIRBuilder.buildConstant(Ty, 0));
6084*e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildSelect(Ty, Cmp, SatMin, SatMax);
6085*e8d8bef9SDimitry Andric   } else {
6086*e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildConstant(Ty, APInt::getMaxValue(BW));
6087*e8d8bef9SDimitry Andric   }
6088*e8d8bef9SDimitry Andric   auto Ov = MIRBuilder.buildICmp(CmpInst::ICMP_NE, BoolTy, LHS, Orig);
6089*e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, SatVal, Result);
6090*e8d8bef9SDimitry Andric 
6091*e8d8bef9SDimitry Andric   MI.eraseFromParent();
6092*e8d8bef9SDimitry Andric   return Legalized;
6093*e8d8bef9SDimitry Andric }
6094*e8d8bef9SDimitry Andric 
6095*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6096480093f4SDimitry Andric LegalizerHelper::lowerBswap(MachineInstr &MI) {
6097480093f4SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6098480093f4SDimitry Andric   Register Src = MI.getOperand(1).getReg();
6099480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
61005ffd83dbSDimitry Andric   unsigned SizeInBytes = (Ty.getScalarSizeInBits() + 7) / 8;
6101480093f4SDimitry Andric   unsigned BaseShiftAmt = (SizeInBytes - 1) * 8;
6102480093f4SDimitry Andric 
6103480093f4SDimitry Andric   // Swap most and least significant byte, set remaining bytes in Res to zero.
6104480093f4SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt);
6105480093f4SDimitry Andric   auto LSByteShiftedLeft = MIRBuilder.buildShl(Ty, Src, ShiftAmt);
6106480093f4SDimitry Andric   auto MSByteShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
6107480093f4SDimitry Andric   auto Res = MIRBuilder.buildOr(Ty, MSByteShiftedRight, LSByteShiftedLeft);
6108480093f4SDimitry Andric 
6109480093f4SDimitry Andric   // Set i-th high/low byte in Res to i-th low/high byte from Src.
6110480093f4SDimitry Andric   for (unsigned i = 1; i < SizeInBytes / 2; ++i) {
6111480093f4SDimitry Andric     // AND with Mask leaves byte i unchanged and sets remaining bytes to 0.
6112480093f4SDimitry Andric     APInt APMask(SizeInBytes * 8, 0xFF << (i * 8));
6113480093f4SDimitry Andric     auto Mask = MIRBuilder.buildConstant(Ty, APMask);
6114480093f4SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt - 16 * i);
6115480093f4SDimitry Andric     // Low byte shifted left to place of high byte: (Src & Mask) << ShiftAmt.
6116480093f4SDimitry Andric     auto LoByte = MIRBuilder.buildAnd(Ty, Src, Mask);
6117480093f4SDimitry Andric     auto LoShiftedLeft = MIRBuilder.buildShl(Ty, LoByte, ShiftAmt);
6118480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, LoShiftedLeft);
6119480093f4SDimitry Andric     // High byte shifted right to place of low byte: (Src >> ShiftAmt) & Mask.
6120480093f4SDimitry Andric     auto SrcShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
6121480093f4SDimitry Andric     auto HiShiftedRight = MIRBuilder.buildAnd(Ty, SrcShiftedRight, Mask);
6122480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, HiShiftedRight);
6123480093f4SDimitry Andric   }
6124480093f4SDimitry Andric   Res.getInstr()->getOperand(0).setReg(Dst);
6125480093f4SDimitry Andric 
6126480093f4SDimitry Andric   MI.eraseFromParent();
6127480093f4SDimitry Andric   return Legalized;
6128480093f4SDimitry Andric }
6129480093f4SDimitry Andric 
6130480093f4SDimitry Andric //{ (Src & Mask) >> N } | { (Src << N) & Mask }
6131480093f4SDimitry Andric static MachineInstrBuilder SwapN(unsigned N, DstOp Dst, MachineIRBuilder &B,
6132480093f4SDimitry Andric                                  MachineInstrBuilder Src, APInt Mask) {
6133480093f4SDimitry Andric   const LLT Ty = Dst.getLLTTy(*B.getMRI());
6134480093f4SDimitry Andric   MachineInstrBuilder C_N = B.buildConstant(Ty, N);
6135480093f4SDimitry Andric   MachineInstrBuilder MaskLoNTo0 = B.buildConstant(Ty, Mask);
6136480093f4SDimitry Andric   auto LHS = B.buildLShr(Ty, B.buildAnd(Ty, Src, MaskLoNTo0), C_N);
6137480093f4SDimitry Andric   auto RHS = B.buildAnd(Ty, B.buildShl(Ty, Src, C_N), MaskLoNTo0);
6138480093f4SDimitry Andric   return B.buildOr(Dst, LHS, RHS);
6139480093f4SDimitry Andric }
6140480093f4SDimitry Andric 
6141480093f4SDimitry Andric LegalizerHelper::LegalizeResult
6142480093f4SDimitry Andric LegalizerHelper::lowerBitreverse(MachineInstr &MI) {
6143480093f4SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6144480093f4SDimitry Andric   Register Src = MI.getOperand(1).getReg();
6145480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
6146480093f4SDimitry Andric   unsigned Size = Ty.getSizeInBits();
6147480093f4SDimitry Andric 
6148480093f4SDimitry Andric   MachineInstrBuilder BSWAP =
6149480093f4SDimitry Andric       MIRBuilder.buildInstr(TargetOpcode::G_BSWAP, {Ty}, {Src});
6150480093f4SDimitry Andric 
6151480093f4SDimitry Andric   // swap high and low 4 bits in 8 bit blocks 7654|3210 -> 3210|7654
6152480093f4SDimitry Andric   //    [(val & 0xF0F0F0F0) >> 4] | [(val & 0x0F0F0F0F) << 4]
6153480093f4SDimitry Andric   // -> [(val & 0xF0F0F0F0) >> 4] | [(val << 4) & 0xF0F0F0F0]
6154480093f4SDimitry Andric   MachineInstrBuilder Swap4 =
6155480093f4SDimitry Andric       SwapN(4, Ty, MIRBuilder, BSWAP, APInt::getSplat(Size, APInt(8, 0xF0)));
6156480093f4SDimitry Andric 
6157480093f4SDimitry Andric   // swap high and low 2 bits in 4 bit blocks 32|10 76|54 -> 10|32 54|76
6158480093f4SDimitry Andric   //    [(val & 0xCCCCCCCC) >> 2] & [(val & 0x33333333) << 2]
6159480093f4SDimitry Andric   // -> [(val & 0xCCCCCCCC) >> 2] & [(val << 2) & 0xCCCCCCCC]
6160480093f4SDimitry Andric   MachineInstrBuilder Swap2 =
6161480093f4SDimitry Andric       SwapN(2, Ty, MIRBuilder, Swap4, APInt::getSplat(Size, APInt(8, 0xCC)));
6162480093f4SDimitry Andric 
6163480093f4SDimitry 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
6164480093f4SDimitry Andric   //    [(val & 0xAAAAAAAA) >> 1] & [(val & 0x55555555) << 1]
6165480093f4SDimitry Andric   // -> [(val & 0xAAAAAAAA) >> 1] & [(val << 1) & 0xAAAAAAAA]
6166480093f4SDimitry Andric   SwapN(1, Dst, MIRBuilder, Swap2, APInt::getSplat(Size, APInt(8, 0xAA)));
6167480093f4SDimitry Andric 
6168480093f4SDimitry Andric   MI.eraseFromParent();
6169480093f4SDimitry Andric   return Legalized;
6170480093f4SDimitry Andric }
6171480093f4SDimitry Andric 
6172480093f4SDimitry Andric LegalizerHelper::LegalizeResult
61735ffd83dbSDimitry Andric LegalizerHelper::lowerReadWriteRegister(MachineInstr &MI) {
6174480093f4SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
61755ffd83dbSDimitry Andric 
61765ffd83dbSDimitry Andric   bool IsRead = MI.getOpcode() == TargetOpcode::G_READ_REGISTER;
61775ffd83dbSDimitry Andric   int NameOpIdx = IsRead ? 1 : 0;
61785ffd83dbSDimitry Andric   int ValRegIndex = IsRead ? 0 : 1;
61795ffd83dbSDimitry Andric 
61805ffd83dbSDimitry Andric   Register ValReg = MI.getOperand(ValRegIndex).getReg();
61815ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(ValReg);
61825ffd83dbSDimitry Andric   const MDString *RegStr = cast<MDString>(
61835ffd83dbSDimitry Andric     cast<MDNode>(MI.getOperand(NameOpIdx).getMetadata())->getOperand(0));
61845ffd83dbSDimitry Andric 
6185*e8d8bef9SDimitry Andric   Register PhysReg = TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
61865ffd83dbSDimitry Andric   if (!PhysReg.isValid())
6187480093f4SDimitry Andric     return UnableToLegalize;
6188480093f4SDimitry Andric 
61895ffd83dbSDimitry Andric   if (IsRead)
61905ffd83dbSDimitry Andric     MIRBuilder.buildCopy(ValReg, PhysReg);
61915ffd83dbSDimitry Andric   else
61925ffd83dbSDimitry Andric     MIRBuilder.buildCopy(PhysReg, ValReg);
61935ffd83dbSDimitry Andric 
6194480093f4SDimitry Andric   MI.eraseFromParent();
6195480093f4SDimitry Andric   return Legalized;
6196480093f4SDimitry Andric }
6197*e8d8bef9SDimitry Andric 
6198*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6199*e8d8bef9SDimitry Andric LegalizerHelper::lowerSMULH_UMULH(MachineInstr &MI) {
6200*e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SMULH;
6201*e8d8bef9SDimitry Andric   unsigned ExtOp = IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
6202*e8d8bef9SDimitry Andric   Register Result = MI.getOperand(0).getReg();
6203*e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(Result);
6204*e8d8bef9SDimitry Andric   auto SizeInBits = OrigTy.getScalarSizeInBits();
6205*e8d8bef9SDimitry Andric   LLT WideTy = OrigTy.changeElementSize(SizeInBits * 2);
6206*e8d8bef9SDimitry Andric 
6207*e8d8bef9SDimitry Andric   auto LHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(1)});
6208*e8d8bef9SDimitry Andric   auto RHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(2)});
6209*e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(WideTy, LHS, RHS);
6210*e8d8bef9SDimitry Andric   unsigned ShiftOp = IsSigned ? TargetOpcode::G_ASHR : TargetOpcode::G_LSHR;
6211*e8d8bef9SDimitry Andric 
6212*e8d8bef9SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(WideTy, SizeInBits);
6213*e8d8bef9SDimitry Andric   auto Shifted = MIRBuilder.buildInstr(ShiftOp, {WideTy}, {Mul, ShiftAmt});
6214*e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(Result, Shifted);
6215*e8d8bef9SDimitry Andric 
6216*e8d8bef9SDimitry Andric   MI.eraseFromParent();
6217*e8d8bef9SDimitry Andric   return Legalized;
6218*e8d8bef9SDimitry Andric }
6219*e8d8bef9SDimitry Andric 
6220*e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSelect(MachineInstr &MI) {
6221*e8d8bef9SDimitry Andric   // Implement vector G_SELECT in terms of XOR, AND, OR.
6222*e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
6223*e8d8bef9SDimitry Andric   Register MaskReg = MI.getOperand(1).getReg();
6224*e8d8bef9SDimitry Andric   Register Op1Reg = MI.getOperand(2).getReg();
6225*e8d8bef9SDimitry Andric   Register Op2Reg = MI.getOperand(3).getReg();
6226*e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
6227*e8d8bef9SDimitry Andric   LLT MaskTy = MRI.getType(MaskReg);
6228*e8d8bef9SDimitry Andric   LLT Op1Ty = MRI.getType(Op1Reg);
6229*e8d8bef9SDimitry Andric   if (!DstTy.isVector())
6230*e8d8bef9SDimitry Andric     return UnableToLegalize;
6231*e8d8bef9SDimitry Andric 
6232*e8d8bef9SDimitry Andric   // Vector selects can have a scalar predicate. If so, splat into a vector and
6233*e8d8bef9SDimitry Andric   // finish for later legalization attempts to try again.
6234*e8d8bef9SDimitry Andric   if (MaskTy.isScalar()) {
6235*e8d8bef9SDimitry Andric     Register MaskElt = MaskReg;
6236*e8d8bef9SDimitry Andric     if (MaskTy.getSizeInBits() < DstTy.getScalarSizeInBits())
6237*e8d8bef9SDimitry Andric       MaskElt = MIRBuilder.buildSExt(DstTy.getElementType(), MaskElt).getReg(0);
6238*e8d8bef9SDimitry Andric     // Generate a vector splat idiom to be pattern matched later.
6239*e8d8bef9SDimitry Andric     auto ShufSplat = MIRBuilder.buildShuffleSplat(DstTy, MaskElt);
6240*e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
6241*e8d8bef9SDimitry Andric     MI.getOperand(1).setReg(ShufSplat.getReg(0));
6242*e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
6243*e8d8bef9SDimitry Andric     return Legalized;
6244*e8d8bef9SDimitry Andric   }
6245*e8d8bef9SDimitry Andric 
6246*e8d8bef9SDimitry Andric   if (MaskTy.getSizeInBits() != Op1Ty.getSizeInBits()) {
6247*e8d8bef9SDimitry Andric     return UnableToLegalize;
6248*e8d8bef9SDimitry Andric   }
6249*e8d8bef9SDimitry Andric 
6250*e8d8bef9SDimitry Andric   auto NotMask = MIRBuilder.buildNot(MaskTy, MaskReg);
6251*e8d8bef9SDimitry Andric   auto NewOp1 = MIRBuilder.buildAnd(MaskTy, Op1Reg, MaskReg);
6252*e8d8bef9SDimitry Andric   auto NewOp2 = MIRBuilder.buildAnd(MaskTy, Op2Reg, NotMask);
6253*e8d8bef9SDimitry Andric   MIRBuilder.buildOr(DstReg, NewOp1, NewOp2);
6254*e8d8bef9SDimitry Andric   MI.eraseFromParent();
6255*e8d8bef9SDimitry Andric   return Legalized;
6256*e8d8bef9SDimitry Andric }
6257