xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
18*06c3fb27SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
1981ad6265SDimitry Andric #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
21fe6060f1SDimitry Andric #include "llvm/CodeGen/GlobalISel/LostDebugLocObserver.h"
22e8d8bef9SDimitry Andric #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
2381ad6265SDimitry Andric #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
24fe6060f1SDimitry Andric #include "llvm/CodeGen/GlobalISel/Utils.h"
25*06c3fb27SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
2681ad6265SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
288bcb0991SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
31fe6060f1SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
33fe6060f1SDimitry Andric #include "llvm/IR/Instructions.h"
340b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
350b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
37349cc55cSDimitry Andric #include "llvm/Target/TargetMachine.h"
38bdd1243dSDimitry Andric #include <numeric>
39bdd1243dSDimitry Andric #include <optional>
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric #define DEBUG_TYPE "legalizer"
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric using namespace llvm;
440b57cec5SDimitry Andric using namespace LegalizeActions;
45e8d8bef9SDimitry Andric using namespace MIPatternMatch;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric /// Try to break down \p OrigTy into \p NarrowTy sized pieces.
480b57cec5SDimitry Andric ///
490b57cec5SDimitry Andric /// Returns the number of \p NarrowTy elements needed to reconstruct \p OrigTy,
500b57cec5SDimitry Andric /// with any leftover piece as type \p LeftoverTy
510b57cec5SDimitry Andric ///
520b57cec5SDimitry Andric /// Returns -1 in the first element of the pair if the breakdown is not
530b57cec5SDimitry Andric /// satisfiable.
540b57cec5SDimitry Andric static std::pair<int, int>
550b57cec5SDimitry Andric getNarrowTypeBreakDown(LLT OrigTy, LLT NarrowTy, LLT &LeftoverTy) {
560b57cec5SDimitry Andric   assert(!LeftoverTy.isValid() && "this is an out argument");
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   unsigned Size = OrigTy.getSizeInBits();
590b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
600b57cec5SDimitry Andric   unsigned NumParts = Size / NarrowSize;
610b57cec5SDimitry Andric   unsigned LeftoverSize = Size - NumParts * NarrowSize;
620b57cec5SDimitry Andric   assert(Size > NarrowSize);
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric   if (LeftoverSize == 0)
650b57cec5SDimitry Andric     return {NumParts, 0};
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric   if (NarrowTy.isVector()) {
680b57cec5SDimitry Andric     unsigned EltSize = OrigTy.getScalarSizeInBits();
690b57cec5SDimitry Andric     if (LeftoverSize % EltSize != 0)
700b57cec5SDimitry Andric       return {-1, -1};
71fe6060f1SDimitry Andric     LeftoverTy = LLT::scalarOrVector(
72fe6060f1SDimitry Andric         ElementCount::getFixed(LeftoverSize / EltSize), EltSize);
730b57cec5SDimitry Andric   } else {
740b57cec5SDimitry Andric     LeftoverTy = LLT::scalar(LeftoverSize);
750b57cec5SDimitry Andric   }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric   int NumLeftover = LeftoverSize / LeftoverTy.getSizeInBits();
780b57cec5SDimitry Andric   return std::make_pair(NumParts, NumLeftover);
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
815ffd83dbSDimitry Andric static Type *getFloatTypeForLLT(LLVMContext &Ctx, LLT Ty) {
825ffd83dbSDimitry Andric 
835ffd83dbSDimitry Andric   if (!Ty.isScalar())
845ffd83dbSDimitry Andric     return nullptr;
855ffd83dbSDimitry Andric 
865ffd83dbSDimitry Andric   switch (Ty.getSizeInBits()) {
875ffd83dbSDimitry Andric   case 16:
885ffd83dbSDimitry Andric     return Type::getHalfTy(Ctx);
895ffd83dbSDimitry Andric   case 32:
905ffd83dbSDimitry Andric     return Type::getFloatTy(Ctx);
915ffd83dbSDimitry Andric   case 64:
925ffd83dbSDimitry Andric     return Type::getDoubleTy(Ctx);
93e8d8bef9SDimitry Andric   case 80:
94e8d8bef9SDimitry Andric     return Type::getX86_FP80Ty(Ctx);
955ffd83dbSDimitry Andric   case 128:
965ffd83dbSDimitry Andric     return Type::getFP128Ty(Ctx);
975ffd83dbSDimitry Andric   default:
985ffd83dbSDimitry Andric     return nullptr;
995ffd83dbSDimitry Andric   }
1005ffd83dbSDimitry Andric }
1015ffd83dbSDimitry Andric 
1020b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF,
1030b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
1040b57cec5SDimitry Andric                                  MachineIRBuilder &Builder)
1055ffd83dbSDimitry Andric     : MIRBuilder(Builder), Observer(Observer), MRI(MF.getRegInfo()),
106e8d8bef9SDimitry Andric       LI(*MF.getSubtarget().getLegalizerInfo()),
107*06c3fb27SDimitry Andric       TLI(*MF.getSubtarget().getTargetLowering()), KB(nullptr) {}
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric LegalizerHelper::LegalizerHelper(MachineFunction &MF, const LegalizerInfo &LI,
1100b57cec5SDimitry Andric                                  GISelChangeObserver &Observer,
111*06c3fb27SDimitry Andric                                  MachineIRBuilder &B, GISelKnownBits *KB)
112e8d8bef9SDimitry Andric     : MIRBuilder(B), Observer(Observer), MRI(MF.getRegInfo()), LI(LI),
113*06c3fb27SDimitry Andric       TLI(*MF.getSubtarget().getTargetLowering()), KB(KB) {}
114e8d8bef9SDimitry Andric 
1150b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
116fe6060f1SDimitry Andric LegalizerHelper::legalizeInstrStep(MachineInstr &MI,
117fe6060f1SDimitry Andric                                    LostDebugLocObserver &LocObserver) {
1185ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "Legalizing: " << MI);
1195ffd83dbSDimitry Andric 
1205ffd83dbSDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INTRINSIC ||
1230b57cec5SDimitry Andric       MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS)
1245ffd83dbSDimitry Andric     return LI.legalizeIntrinsic(*this, MI) ? Legalized : UnableToLegalize;
1250b57cec5SDimitry Andric   auto Step = LI.getAction(MI, MRI);
1260b57cec5SDimitry Andric   switch (Step.Action) {
1270b57cec5SDimitry Andric   case Legal:
1280b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Already legal\n");
1290b57cec5SDimitry Andric     return AlreadyLegal;
1300b57cec5SDimitry Andric   case Libcall:
1310b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Convert to libcall\n");
132fe6060f1SDimitry Andric     return libcall(MI, LocObserver);
1330b57cec5SDimitry Andric   case NarrowScalar:
1340b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Narrow scalar\n");
1350b57cec5SDimitry Andric     return narrowScalar(MI, Step.TypeIdx, Step.NewType);
1360b57cec5SDimitry Andric   case WidenScalar:
1370b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Widen scalar\n");
1380b57cec5SDimitry Andric     return widenScalar(MI, Step.TypeIdx, Step.NewType);
1395ffd83dbSDimitry Andric   case Bitcast:
1405ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << ".. Bitcast type\n");
1415ffd83dbSDimitry Andric     return bitcast(MI, Step.TypeIdx, Step.NewType);
1420b57cec5SDimitry Andric   case Lower:
1430b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Lower\n");
1440b57cec5SDimitry Andric     return lower(MI, Step.TypeIdx, Step.NewType);
1450b57cec5SDimitry Andric   case FewerElements:
1460b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Reduce number of elements\n");
1470b57cec5SDimitry Andric     return fewerElementsVector(MI, Step.TypeIdx, Step.NewType);
1480b57cec5SDimitry Andric   case MoreElements:
1490b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Increase number of elements\n");
1500b57cec5SDimitry Andric     return moreElementsVector(MI, Step.TypeIdx, Step.NewType);
1510b57cec5SDimitry Andric   case Custom:
1520b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Custom legalization\n");
1535ffd83dbSDimitry Andric     return LI.legalizeCustom(*this, MI) ? Legalized : UnableToLegalize;
1540b57cec5SDimitry Andric   default:
1550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. Unable to legalize\n");
1560b57cec5SDimitry Andric     return UnableToLegalize;
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric void LegalizerHelper::extractParts(Register Reg, LLT Ty, int NumParts,
1610b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &VRegs) {
1620b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i)
1630b57cec5SDimitry Andric     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
1640b57cec5SDimitry Andric   MIRBuilder.buildUnmerge(VRegs, Reg);
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric bool LegalizerHelper::extractParts(Register Reg, LLT RegTy,
1680b57cec5SDimitry Andric                                    LLT MainTy, LLT &LeftoverTy,
1690b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &VRegs,
1700b57cec5SDimitry Andric                                    SmallVectorImpl<Register> &LeftoverRegs) {
1710b57cec5SDimitry Andric   assert(!LeftoverTy.isValid() && "this is an out argument");
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   unsigned RegSize = RegTy.getSizeInBits();
1740b57cec5SDimitry Andric   unsigned MainSize = MainTy.getSizeInBits();
1750b57cec5SDimitry Andric   unsigned NumParts = RegSize / MainSize;
1760b57cec5SDimitry Andric   unsigned LeftoverSize = RegSize - NumParts * MainSize;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   // Use an unmerge when possible.
1790b57cec5SDimitry Andric   if (LeftoverSize == 0) {
1800b57cec5SDimitry Andric     for (unsigned I = 0; I < NumParts; ++I)
1810b57cec5SDimitry Andric       VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
1820b57cec5SDimitry Andric     MIRBuilder.buildUnmerge(VRegs, Reg);
1830b57cec5SDimitry Andric     return true;
1840b57cec5SDimitry Andric   }
1850b57cec5SDimitry Andric 
1860eae32dcSDimitry Andric   // Perform irregular split. Leftover is last element of RegPieces.
1870b57cec5SDimitry Andric   if (MainTy.isVector()) {
1880eae32dcSDimitry Andric     SmallVector<Register, 8> RegPieces;
1890eae32dcSDimitry Andric     extractVectorParts(Reg, MainTy.getNumElements(), RegPieces);
1900eae32dcSDimitry Andric     for (unsigned i = 0; i < RegPieces.size() - 1; ++i)
1910eae32dcSDimitry Andric       VRegs.push_back(RegPieces[i]);
1920eae32dcSDimitry Andric     LeftoverRegs.push_back(RegPieces[RegPieces.size() - 1]);
1930eae32dcSDimitry Andric     LeftoverTy = MRI.getType(LeftoverRegs[0]);
1940eae32dcSDimitry Andric     return true;
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
1970eae32dcSDimitry Andric   LeftoverTy = LLT::scalar(LeftoverSize);
1980b57cec5SDimitry Andric   // For irregular sizes, extract the individual parts.
1990b57cec5SDimitry Andric   for (unsigned I = 0; I != NumParts; ++I) {
2000b57cec5SDimitry Andric     Register NewReg = MRI.createGenericVirtualRegister(MainTy);
2010b57cec5SDimitry Andric     VRegs.push_back(NewReg);
2020b57cec5SDimitry Andric     MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
2060b57cec5SDimitry Andric        Offset += LeftoverSize) {
2070b57cec5SDimitry Andric     Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
2080b57cec5SDimitry Andric     LeftoverRegs.push_back(NewReg);
2090b57cec5SDimitry Andric     MIRBuilder.buildExtract(NewReg, Reg, Offset);
2100b57cec5SDimitry Andric   }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   return true;
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150eae32dcSDimitry Andric void LegalizerHelper::extractVectorParts(Register Reg, unsigned NumElts,
2160eae32dcSDimitry Andric                                          SmallVectorImpl<Register> &VRegs) {
2170eae32dcSDimitry Andric   LLT RegTy = MRI.getType(Reg);
2180eae32dcSDimitry Andric   assert(RegTy.isVector() && "Expected a vector type");
2190eae32dcSDimitry Andric 
2200eae32dcSDimitry Andric   LLT EltTy = RegTy.getElementType();
2210eae32dcSDimitry Andric   LLT NarrowTy = (NumElts == 1) ? EltTy : LLT::fixed_vector(NumElts, EltTy);
2220eae32dcSDimitry Andric   unsigned RegNumElts = RegTy.getNumElements();
2230eae32dcSDimitry Andric   unsigned LeftoverNumElts = RegNumElts % NumElts;
2240eae32dcSDimitry Andric   unsigned NumNarrowTyPieces = RegNumElts / NumElts;
2250eae32dcSDimitry Andric 
2260eae32dcSDimitry Andric   // Perfect split without leftover
2270eae32dcSDimitry Andric   if (LeftoverNumElts == 0)
2280eae32dcSDimitry Andric     return extractParts(Reg, NarrowTy, NumNarrowTyPieces, VRegs);
2290eae32dcSDimitry Andric 
2300eae32dcSDimitry Andric   // Irregular split. Provide direct access to all elements for artifact
2310eae32dcSDimitry Andric   // combiner using unmerge to elements. Then build vectors with NumElts
2320eae32dcSDimitry Andric   // elements. Remaining element(s) will be (used to build vector) Leftover.
2330eae32dcSDimitry Andric   SmallVector<Register, 8> Elts;
2340eae32dcSDimitry Andric   extractParts(Reg, EltTy, RegNumElts, Elts);
2350eae32dcSDimitry Andric 
2360eae32dcSDimitry Andric   unsigned Offset = 0;
2370eae32dcSDimitry Andric   // Requested sub-vectors of NarrowTy.
2380eae32dcSDimitry Andric   for (unsigned i = 0; i < NumNarrowTyPieces; ++i, Offset += NumElts) {
2390eae32dcSDimitry Andric     ArrayRef<Register> Pieces(&Elts[Offset], NumElts);
240bdd1243dSDimitry Andric     VRegs.push_back(MIRBuilder.buildMergeLikeInstr(NarrowTy, Pieces).getReg(0));
2410eae32dcSDimitry Andric   }
2420eae32dcSDimitry Andric 
2430eae32dcSDimitry Andric   // Leftover element(s).
2440eae32dcSDimitry Andric   if (LeftoverNumElts == 1) {
2450eae32dcSDimitry Andric     VRegs.push_back(Elts[Offset]);
2460eae32dcSDimitry Andric   } else {
2470eae32dcSDimitry Andric     LLT LeftoverTy = LLT::fixed_vector(LeftoverNumElts, EltTy);
2480eae32dcSDimitry Andric     ArrayRef<Register> Pieces(&Elts[Offset], LeftoverNumElts);
249bdd1243dSDimitry Andric     VRegs.push_back(
250bdd1243dSDimitry Andric         MIRBuilder.buildMergeLikeInstr(LeftoverTy, Pieces).getReg(0));
2510eae32dcSDimitry Andric   }
2520eae32dcSDimitry Andric }
2530eae32dcSDimitry Andric 
2540b57cec5SDimitry Andric void LegalizerHelper::insertParts(Register DstReg,
2550b57cec5SDimitry Andric                                   LLT ResultTy, LLT PartTy,
2560b57cec5SDimitry Andric                                   ArrayRef<Register> PartRegs,
2570b57cec5SDimitry Andric                                   LLT LeftoverTy,
2580b57cec5SDimitry Andric                                   ArrayRef<Register> LeftoverRegs) {
2590b57cec5SDimitry Andric   if (!LeftoverTy.isValid()) {
2600b57cec5SDimitry Andric     assert(LeftoverRegs.empty());
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     if (!ResultTy.isVector()) {
263bdd1243dSDimitry Andric       MIRBuilder.buildMergeLikeInstr(DstReg, PartRegs);
2640b57cec5SDimitry Andric       return;
2650b57cec5SDimitry Andric     }
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric     if (PartTy.isVector())
2680b57cec5SDimitry Andric       MIRBuilder.buildConcatVectors(DstReg, PartRegs);
2690b57cec5SDimitry Andric     else
2700b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, PartRegs);
2710b57cec5SDimitry Andric     return;
2720b57cec5SDimitry Andric   }
2730b57cec5SDimitry Andric 
2740eae32dcSDimitry Andric   // Merge sub-vectors with different number of elements and insert into DstReg.
2750eae32dcSDimitry Andric   if (ResultTy.isVector()) {
2760eae32dcSDimitry Andric     assert(LeftoverRegs.size() == 1 && "Expected one leftover register");
2770eae32dcSDimitry Andric     SmallVector<Register, 8> AllRegs;
2780eae32dcSDimitry Andric     for (auto Reg : concat<const Register>(PartRegs, LeftoverRegs))
2790eae32dcSDimitry Andric       AllRegs.push_back(Reg);
2800eae32dcSDimitry Andric     return mergeMixedSubvectors(DstReg, AllRegs);
2810eae32dcSDimitry Andric   }
2820eae32dcSDimitry Andric 
283fe6060f1SDimitry Andric   SmallVector<Register> GCDRegs;
284fe6060f1SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(ResultTy, LeftoverTy), PartTy);
285fe6060f1SDimitry Andric   for (auto PartReg : concat<const Register>(PartRegs, LeftoverRegs))
286fe6060f1SDimitry Andric     extractGCDType(GCDRegs, GCDTy, PartReg);
287fe6060f1SDimitry Andric   LLT ResultLCMTy = buildLCMMergePieces(ResultTy, LeftoverTy, GCDTy, GCDRegs);
288fe6060f1SDimitry Andric   buildWidenedRemergeToDst(DstReg, ResultLCMTy, GCDRegs);
2890b57cec5SDimitry Andric }
2900b57cec5SDimitry Andric 
2910eae32dcSDimitry Andric void LegalizerHelper::appendVectorElts(SmallVectorImpl<Register> &Elts,
2920eae32dcSDimitry Andric                                        Register Reg) {
2930eae32dcSDimitry Andric   LLT Ty = MRI.getType(Reg);
2940eae32dcSDimitry Andric   SmallVector<Register, 8> RegElts;
2950eae32dcSDimitry Andric   extractParts(Reg, Ty.getScalarType(), Ty.getNumElements(), RegElts);
2960eae32dcSDimitry Andric   Elts.append(RegElts);
2970eae32dcSDimitry Andric }
2980eae32dcSDimitry Andric 
2990eae32dcSDimitry Andric /// Merge \p PartRegs with different types into \p DstReg.
3000eae32dcSDimitry Andric void LegalizerHelper::mergeMixedSubvectors(Register DstReg,
3010eae32dcSDimitry Andric                                            ArrayRef<Register> PartRegs) {
3020eae32dcSDimitry Andric   SmallVector<Register, 8> AllElts;
3030eae32dcSDimitry Andric   for (unsigned i = 0; i < PartRegs.size() - 1; ++i)
3040eae32dcSDimitry Andric     appendVectorElts(AllElts, PartRegs[i]);
3050eae32dcSDimitry Andric 
3060eae32dcSDimitry Andric   Register Leftover = PartRegs[PartRegs.size() - 1];
3070eae32dcSDimitry Andric   if (MRI.getType(Leftover).isScalar())
3080eae32dcSDimitry Andric     AllElts.push_back(Leftover);
3090eae32dcSDimitry Andric   else
3100eae32dcSDimitry Andric     appendVectorElts(AllElts, Leftover);
3110eae32dcSDimitry Andric 
312bdd1243dSDimitry Andric   MIRBuilder.buildMergeLikeInstr(DstReg, AllElts);
3130eae32dcSDimitry Andric }
3140eae32dcSDimitry Andric 
315e8d8bef9SDimitry Andric /// Append the result registers of G_UNMERGE_VALUES \p MI to \p Regs.
3165ffd83dbSDimitry Andric static void getUnmergeResults(SmallVectorImpl<Register> &Regs,
3175ffd83dbSDimitry Andric                               const MachineInstr &MI) {
3185ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES);
3195ffd83dbSDimitry Andric 
320e8d8bef9SDimitry Andric   const int StartIdx = Regs.size();
3215ffd83dbSDimitry Andric   const int NumResults = MI.getNumOperands() - 1;
322e8d8bef9SDimitry Andric   Regs.resize(Regs.size() + NumResults);
3235ffd83dbSDimitry Andric   for (int I = 0; I != NumResults; ++I)
324e8d8bef9SDimitry Andric     Regs[StartIdx + I] = MI.getOperand(I).getReg();
3255ffd83dbSDimitry Andric }
3265ffd83dbSDimitry Andric 
327e8d8bef9SDimitry Andric void LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts,
328e8d8bef9SDimitry Andric                                      LLT GCDTy, Register SrcReg) {
3295ffd83dbSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
3305ffd83dbSDimitry Andric   if (SrcTy == GCDTy) {
3315ffd83dbSDimitry Andric     // If the source already evenly divides the result type, we don't need to do
3325ffd83dbSDimitry Andric     // anything.
3335ffd83dbSDimitry Andric     Parts.push_back(SrcReg);
3345ffd83dbSDimitry Andric   } else {
3355ffd83dbSDimitry Andric     // Need to split into common type sized pieces.
3365ffd83dbSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
3375ffd83dbSDimitry Andric     getUnmergeResults(Parts, *Unmerge);
3385ffd83dbSDimitry Andric   }
339e8d8bef9SDimitry Andric }
3405ffd83dbSDimitry Andric 
341e8d8bef9SDimitry Andric LLT LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts, LLT DstTy,
342e8d8bef9SDimitry Andric                                     LLT NarrowTy, Register SrcReg) {
343e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
344e8d8bef9SDimitry Andric   LLT GCDTy = getGCDType(getGCDType(SrcTy, NarrowTy), DstTy);
345e8d8bef9SDimitry Andric   extractGCDType(Parts, GCDTy, SrcReg);
3465ffd83dbSDimitry Andric   return GCDTy;
3475ffd83dbSDimitry Andric }
3485ffd83dbSDimitry Andric 
3495ffd83dbSDimitry Andric LLT LegalizerHelper::buildLCMMergePieces(LLT DstTy, LLT NarrowTy, LLT GCDTy,
3505ffd83dbSDimitry Andric                                          SmallVectorImpl<Register> &VRegs,
3515ffd83dbSDimitry Andric                                          unsigned PadStrategy) {
3525ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(DstTy, NarrowTy);
3535ffd83dbSDimitry Andric 
3545ffd83dbSDimitry Andric   int NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
3555ffd83dbSDimitry Andric   int NumSubParts = NarrowTy.getSizeInBits() / GCDTy.getSizeInBits();
3565ffd83dbSDimitry Andric   int NumOrigSrc = VRegs.size();
3575ffd83dbSDimitry Andric 
3585ffd83dbSDimitry Andric   Register PadReg;
3595ffd83dbSDimitry Andric 
3605ffd83dbSDimitry Andric   // Get a value we can use to pad the source value if the sources won't evenly
3615ffd83dbSDimitry Andric   // cover the result type.
3625ffd83dbSDimitry Andric   if (NumOrigSrc < NumParts * NumSubParts) {
3635ffd83dbSDimitry Andric     if (PadStrategy == TargetOpcode::G_ZEXT)
3645ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildConstant(GCDTy, 0).getReg(0);
3655ffd83dbSDimitry Andric     else if (PadStrategy == TargetOpcode::G_ANYEXT)
3665ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
3675ffd83dbSDimitry Andric     else {
3685ffd83dbSDimitry Andric       assert(PadStrategy == TargetOpcode::G_SEXT);
3695ffd83dbSDimitry Andric 
3705ffd83dbSDimitry Andric       // Shift the sign bit of the low register through the high register.
3715ffd83dbSDimitry Andric       auto ShiftAmt =
3725ffd83dbSDimitry Andric         MIRBuilder.buildConstant(LLT::scalar(64), GCDTy.getSizeInBits() - 1);
3735ffd83dbSDimitry Andric       PadReg = MIRBuilder.buildAShr(GCDTy, VRegs.back(), ShiftAmt).getReg(0);
3745ffd83dbSDimitry Andric     }
3755ffd83dbSDimitry Andric   }
3765ffd83dbSDimitry Andric 
3775ffd83dbSDimitry Andric   // Registers for the final merge to be produced.
3785ffd83dbSDimitry Andric   SmallVector<Register, 4> Remerge(NumParts);
3795ffd83dbSDimitry Andric 
3805ffd83dbSDimitry Andric   // Registers needed for intermediate merges, which will be merged into a
3815ffd83dbSDimitry Andric   // source for Remerge.
3825ffd83dbSDimitry Andric   SmallVector<Register, 4> SubMerge(NumSubParts);
3835ffd83dbSDimitry Andric 
3845ffd83dbSDimitry Andric   // Once we've fully read off the end of the original source bits, we can reuse
3855ffd83dbSDimitry Andric   // the same high bits for remaining padding elements.
3865ffd83dbSDimitry Andric   Register AllPadReg;
3875ffd83dbSDimitry Andric 
3885ffd83dbSDimitry Andric   // Build merges to the LCM type to cover the original result type.
3895ffd83dbSDimitry Andric   for (int I = 0; I != NumParts; ++I) {
3905ffd83dbSDimitry Andric     bool AllMergePartsArePadding = true;
3915ffd83dbSDimitry Andric 
3925ffd83dbSDimitry Andric     // Build the requested merges to the requested type.
3935ffd83dbSDimitry Andric     for (int J = 0; J != NumSubParts; ++J) {
3945ffd83dbSDimitry Andric       int Idx = I * NumSubParts + J;
3955ffd83dbSDimitry Andric       if (Idx >= NumOrigSrc) {
3965ffd83dbSDimitry Andric         SubMerge[J] = PadReg;
3975ffd83dbSDimitry Andric         continue;
3985ffd83dbSDimitry Andric       }
3995ffd83dbSDimitry Andric 
4005ffd83dbSDimitry Andric       SubMerge[J] = VRegs[Idx];
4015ffd83dbSDimitry Andric 
4025ffd83dbSDimitry Andric       // There are meaningful bits here we can't reuse later.
4035ffd83dbSDimitry Andric       AllMergePartsArePadding = false;
4045ffd83dbSDimitry Andric     }
4055ffd83dbSDimitry Andric 
4065ffd83dbSDimitry Andric     // If we've filled up a complete piece with padding bits, we can directly
4075ffd83dbSDimitry Andric     // emit the natural sized constant if applicable, rather than a merge of
4085ffd83dbSDimitry Andric     // smaller constants.
4095ffd83dbSDimitry Andric     if (AllMergePartsArePadding && !AllPadReg) {
4105ffd83dbSDimitry Andric       if (PadStrategy == TargetOpcode::G_ANYEXT)
4115ffd83dbSDimitry Andric         AllPadReg = MIRBuilder.buildUndef(NarrowTy).getReg(0);
4125ffd83dbSDimitry Andric       else if (PadStrategy == TargetOpcode::G_ZEXT)
4135ffd83dbSDimitry Andric         AllPadReg = MIRBuilder.buildConstant(NarrowTy, 0).getReg(0);
4145ffd83dbSDimitry Andric 
4155ffd83dbSDimitry Andric       // If this is a sign extension, we can't materialize a trivial constant
4165ffd83dbSDimitry Andric       // with the right type and have to produce a merge.
4175ffd83dbSDimitry Andric     }
4185ffd83dbSDimitry Andric 
4195ffd83dbSDimitry Andric     if (AllPadReg) {
4205ffd83dbSDimitry Andric       // Avoid creating additional instructions if we're just adding additional
4215ffd83dbSDimitry Andric       // copies of padding bits.
4225ffd83dbSDimitry Andric       Remerge[I] = AllPadReg;
4235ffd83dbSDimitry Andric       continue;
4245ffd83dbSDimitry Andric     }
4255ffd83dbSDimitry Andric 
4265ffd83dbSDimitry Andric     if (NumSubParts == 1)
4275ffd83dbSDimitry Andric       Remerge[I] = SubMerge[0];
4285ffd83dbSDimitry Andric     else
429bdd1243dSDimitry Andric       Remerge[I] = MIRBuilder.buildMergeLikeInstr(NarrowTy, SubMerge).getReg(0);
4305ffd83dbSDimitry Andric 
4315ffd83dbSDimitry Andric     // In the sign extend padding case, re-use the first all-signbit merge.
4325ffd83dbSDimitry Andric     if (AllMergePartsArePadding && !AllPadReg)
4335ffd83dbSDimitry Andric       AllPadReg = Remerge[I];
4345ffd83dbSDimitry Andric   }
4355ffd83dbSDimitry Andric 
4365ffd83dbSDimitry Andric   VRegs = std::move(Remerge);
4375ffd83dbSDimitry Andric   return LCMTy;
4385ffd83dbSDimitry Andric }
4395ffd83dbSDimitry Andric 
4405ffd83dbSDimitry Andric void LegalizerHelper::buildWidenedRemergeToDst(Register DstReg, LLT LCMTy,
4415ffd83dbSDimitry Andric                                                ArrayRef<Register> RemergeRegs) {
4425ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
4435ffd83dbSDimitry Andric 
4445ffd83dbSDimitry Andric   // Create the merge to the widened source, and extract the relevant bits into
4455ffd83dbSDimitry Andric   // the result.
4465ffd83dbSDimitry Andric 
4475ffd83dbSDimitry Andric   if (DstTy == LCMTy) {
448bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(DstReg, RemergeRegs);
4495ffd83dbSDimitry Andric     return;
4505ffd83dbSDimitry Andric   }
4515ffd83dbSDimitry Andric 
452bdd1243dSDimitry Andric   auto Remerge = MIRBuilder.buildMergeLikeInstr(LCMTy, RemergeRegs);
4535ffd83dbSDimitry Andric   if (DstTy.isScalar() && LCMTy.isScalar()) {
4545ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(DstReg, Remerge);
4555ffd83dbSDimitry Andric     return;
4565ffd83dbSDimitry Andric   }
4575ffd83dbSDimitry Andric 
4585ffd83dbSDimitry Andric   if (LCMTy.isVector()) {
459e8d8bef9SDimitry Andric     unsigned NumDefs = LCMTy.getSizeInBits() / DstTy.getSizeInBits();
460e8d8bef9SDimitry Andric     SmallVector<Register, 8> UnmergeDefs(NumDefs);
461e8d8bef9SDimitry Andric     UnmergeDefs[0] = DstReg;
462e8d8bef9SDimitry Andric     for (unsigned I = 1; I != NumDefs; ++I)
463e8d8bef9SDimitry Andric       UnmergeDefs[I] = MRI.createGenericVirtualRegister(DstTy);
464e8d8bef9SDimitry Andric 
465e8d8bef9SDimitry Andric     MIRBuilder.buildUnmerge(UnmergeDefs,
466bdd1243dSDimitry Andric                             MIRBuilder.buildMergeLikeInstr(LCMTy, RemergeRegs));
4675ffd83dbSDimitry Andric     return;
4685ffd83dbSDimitry Andric   }
4695ffd83dbSDimitry Andric 
4705ffd83dbSDimitry Andric   llvm_unreachable("unhandled case");
4715ffd83dbSDimitry Andric }
4725ffd83dbSDimitry Andric 
4730b57cec5SDimitry Andric static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size) {
474e8d8bef9SDimitry Andric #define RTLIBCASE_INT(LibcallPrefix)                                           \
4755ffd83dbSDimitry Andric   do {                                                                         \
4765ffd83dbSDimitry Andric     switch (Size) {                                                            \
4775ffd83dbSDimitry Andric     case 32:                                                                   \
4785ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
4795ffd83dbSDimitry Andric     case 64:                                                                   \
4805ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
4815ffd83dbSDimitry Andric     case 128:                                                                  \
4825ffd83dbSDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
4835ffd83dbSDimitry Andric     default:                                                                   \
4845ffd83dbSDimitry Andric       llvm_unreachable("unexpected size");                                     \
4855ffd83dbSDimitry Andric     }                                                                          \
4865ffd83dbSDimitry Andric   } while (0)
4875ffd83dbSDimitry Andric 
488e8d8bef9SDimitry Andric #define RTLIBCASE(LibcallPrefix)                                               \
489e8d8bef9SDimitry Andric   do {                                                                         \
490e8d8bef9SDimitry Andric     switch (Size) {                                                            \
491e8d8bef9SDimitry Andric     case 32:                                                                   \
492e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##32;                                         \
493e8d8bef9SDimitry Andric     case 64:                                                                   \
494e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##64;                                         \
495e8d8bef9SDimitry Andric     case 80:                                                                   \
496e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##80;                                         \
497e8d8bef9SDimitry Andric     case 128:                                                                  \
498e8d8bef9SDimitry Andric       return RTLIB::LibcallPrefix##128;                                        \
499e8d8bef9SDimitry Andric     default:                                                                   \
500e8d8bef9SDimitry Andric       llvm_unreachable("unexpected size");                                     \
501e8d8bef9SDimitry Andric     }                                                                          \
502e8d8bef9SDimitry Andric   } while (0)
5035ffd83dbSDimitry Andric 
5040b57cec5SDimitry Andric   switch (Opcode) {
505bdd1243dSDimitry Andric   case TargetOpcode::G_MUL:
506bdd1243dSDimitry Andric     RTLIBCASE_INT(MUL_I);
5070b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
508e8d8bef9SDimitry Andric     RTLIBCASE_INT(SDIV_I);
5090b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
510e8d8bef9SDimitry Andric     RTLIBCASE_INT(UDIV_I);
5110b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
512e8d8bef9SDimitry Andric     RTLIBCASE_INT(SREM_I);
5130b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
514e8d8bef9SDimitry Andric     RTLIBCASE_INT(UREM_I);
5150b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
516e8d8bef9SDimitry Andric     RTLIBCASE_INT(CTLZ_I);
5170b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
5185ffd83dbSDimitry Andric     RTLIBCASE(ADD_F);
5190b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
5205ffd83dbSDimitry Andric     RTLIBCASE(SUB_F);
5210b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
5225ffd83dbSDimitry Andric     RTLIBCASE(MUL_F);
5230b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
5245ffd83dbSDimitry Andric     RTLIBCASE(DIV_F);
5250b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
5265ffd83dbSDimitry Andric     RTLIBCASE(EXP_F);
5270b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
5285ffd83dbSDimitry Andric     RTLIBCASE(EXP2_F);
5290b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
5305ffd83dbSDimitry Andric     RTLIBCASE(REM_F);
5310b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
5325ffd83dbSDimitry Andric     RTLIBCASE(POW_F);
5330b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
5345ffd83dbSDimitry Andric     RTLIBCASE(FMA_F);
5350b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
5365ffd83dbSDimitry Andric     RTLIBCASE(SIN_F);
5370b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
5385ffd83dbSDimitry Andric     RTLIBCASE(COS_F);
5390b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
5405ffd83dbSDimitry Andric     RTLIBCASE(LOG10_F);
5410b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
5425ffd83dbSDimitry Andric     RTLIBCASE(LOG_F);
5430b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
5445ffd83dbSDimitry Andric     RTLIBCASE(LOG2_F);
545*06c3fb27SDimitry Andric   case TargetOpcode::G_FLDEXP:
546*06c3fb27SDimitry Andric     RTLIBCASE(LDEXP_F);
5470b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
5485ffd83dbSDimitry Andric     RTLIBCASE(CEIL_F);
5490b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
5505ffd83dbSDimitry Andric     RTLIBCASE(FLOOR_F);
5515ffd83dbSDimitry Andric   case TargetOpcode::G_FMINNUM:
5525ffd83dbSDimitry Andric     RTLIBCASE(FMIN_F);
5535ffd83dbSDimitry Andric   case TargetOpcode::G_FMAXNUM:
5545ffd83dbSDimitry Andric     RTLIBCASE(FMAX_F);
5555ffd83dbSDimitry Andric   case TargetOpcode::G_FSQRT:
5565ffd83dbSDimitry Andric     RTLIBCASE(SQRT_F);
5575ffd83dbSDimitry Andric   case TargetOpcode::G_FRINT:
5585ffd83dbSDimitry Andric     RTLIBCASE(RINT_F);
5595ffd83dbSDimitry Andric   case TargetOpcode::G_FNEARBYINT:
5605ffd83dbSDimitry Andric     RTLIBCASE(NEARBYINT_F);
561e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
562e8d8bef9SDimitry Andric     RTLIBCASE(ROUNDEVEN_F);
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric   llvm_unreachable("Unknown libcall function");
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric 
5678bcb0991SDimitry Andric /// True if an instruction is in tail position in its caller. Intended for
5688bcb0991SDimitry Andric /// legalizing libcalls as tail calls when possible.
569fe6060f1SDimitry Andric static bool isLibCallInTailPosition(MachineInstr &MI,
570fe6060f1SDimitry Andric                                     const TargetInstrInfo &TII,
571fe6060f1SDimitry Andric                                     MachineRegisterInfo &MRI) {
5725ffd83dbSDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
5735ffd83dbSDimitry Andric   const Function &F = MBB.getParent()->getFunction();
5748bcb0991SDimitry Andric 
5758bcb0991SDimitry Andric   // Conservatively require the attributes of the call to match those of
5768bcb0991SDimitry Andric   // the return. Ignore NoAlias and NonNull because they don't affect the
5778bcb0991SDimitry Andric   // call sequence.
5788bcb0991SDimitry Andric   AttributeList CallerAttrs = F.getAttributes();
57904eeddc0SDimitry Andric   if (AttrBuilder(F.getContext(), CallerAttrs.getRetAttrs())
5808bcb0991SDimitry Andric           .removeAttribute(Attribute::NoAlias)
5818bcb0991SDimitry Andric           .removeAttribute(Attribute::NonNull)
5828bcb0991SDimitry Andric           .hasAttributes())
5838bcb0991SDimitry Andric     return false;
5848bcb0991SDimitry Andric 
5858bcb0991SDimitry Andric   // It's not safe to eliminate the sign / zero extension of the return value.
586349cc55cSDimitry Andric   if (CallerAttrs.hasRetAttr(Attribute::ZExt) ||
587349cc55cSDimitry Andric       CallerAttrs.hasRetAttr(Attribute::SExt))
5888bcb0991SDimitry Andric     return false;
5898bcb0991SDimitry Andric 
590fe6060f1SDimitry Andric   // Only tail call if the following instruction is a standard return or if we
591fe6060f1SDimitry Andric   // have a `thisreturn` callee, and a sequence like:
592fe6060f1SDimitry Andric   //
593fe6060f1SDimitry Andric   //   G_MEMCPY %0, %1, %2
594fe6060f1SDimitry Andric   //   $x0 = COPY %0
595fe6060f1SDimitry Andric   //   RET_ReallyLR implicit $x0
5965ffd83dbSDimitry Andric   auto Next = next_nodbg(MI.getIterator(), MBB.instr_end());
597fe6060f1SDimitry Andric   if (Next != MBB.instr_end() && Next->isCopy()) {
598fe6060f1SDimitry Andric     switch (MI.getOpcode()) {
599fe6060f1SDimitry Andric     default:
600fe6060f1SDimitry Andric       llvm_unreachable("unsupported opcode");
601fe6060f1SDimitry Andric     case TargetOpcode::G_BZERO:
602fe6060f1SDimitry Andric       return false;
603fe6060f1SDimitry Andric     case TargetOpcode::G_MEMCPY:
604fe6060f1SDimitry Andric     case TargetOpcode::G_MEMMOVE:
605fe6060f1SDimitry Andric     case TargetOpcode::G_MEMSET:
606fe6060f1SDimitry Andric       break;
607fe6060f1SDimitry Andric     }
608fe6060f1SDimitry Andric 
609fe6060f1SDimitry Andric     Register VReg = MI.getOperand(0).getReg();
610fe6060f1SDimitry Andric     if (!VReg.isVirtual() || VReg != Next->getOperand(1).getReg())
611fe6060f1SDimitry Andric       return false;
612fe6060f1SDimitry Andric 
613fe6060f1SDimitry Andric     Register PReg = Next->getOperand(0).getReg();
614fe6060f1SDimitry Andric     if (!PReg.isPhysical())
615fe6060f1SDimitry Andric       return false;
616fe6060f1SDimitry Andric 
617fe6060f1SDimitry Andric     auto Ret = next_nodbg(Next, MBB.instr_end());
618fe6060f1SDimitry Andric     if (Ret == MBB.instr_end() || !Ret->isReturn())
619fe6060f1SDimitry Andric       return false;
620fe6060f1SDimitry Andric 
621fe6060f1SDimitry Andric     if (Ret->getNumImplicitOperands() != 1)
622fe6060f1SDimitry Andric       return false;
623fe6060f1SDimitry Andric 
624fe6060f1SDimitry Andric     if (PReg != Ret->getOperand(0).getReg())
625fe6060f1SDimitry Andric       return false;
626fe6060f1SDimitry Andric 
627fe6060f1SDimitry Andric     // Skip over the COPY that we just validated.
628fe6060f1SDimitry Andric     Next = Ret;
629fe6060f1SDimitry Andric   }
630fe6060f1SDimitry Andric 
6315ffd83dbSDimitry Andric   if (Next == MBB.instr_end() || TII.isTailCall(*Next) || !Next->isReturn())
6328bcb0991SDimitry Andric     return false;
6338bcb0991SDimitry Andric 
6348bcb0991SDimitry Andric   return true;
6358bcb0991SDimitry Andric }
6368bcb0991SDimitry Andric 
6370b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
6385ffd83dbSDimitry Andric llvm::createLibcall(MachineIRBuilder &MIRBuilder, const char *Name,
6390b57cec5SDimitry Andric                     const CallLowering::ArgInfo &Result,
6405ffd83dbSDimitry Andric                     ArrayRef<CallLowering::ArgInfo> Args,
6415ffd83dbSDimitry Andric                     const CallingConv::ID CC) {
6420b57cec5SDimitry Andric   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
6430b57cec5SDimitry Andric 
6448bcb0991SDimitry Andric   CallLowering::CallLoweringInfo Info;
6455ffd83dbSDimitry Andric   Info.CallConv = CC;
6468bcb0991SDimitry Andric   Info.Callee = MachineOperand::CreateES(Name);
6478bcb0991SDimitry Andric   Info.OrigRet = Result;
6488bcb0991SDimitry Andric   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
6498bcb0991SDimitry Andric   if (!CLI.lowerCall(MIRBuilder, Info))
6500b57cec5SDimitry Andric     return LegalizerHelper::UnableToLegalize;
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   return LegalizerHelper::Legalized;
6530b57cec5SDimitry Andric }
6540b57cec5SDimitry Andric 
6555ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
6565ffd83dbSDimitry Andric llvm::createLibcall(MachineIRBuilder &MIRBuilder, RTLIB::Libcall Libcall,
6575ffd83dbSDimitry Andric                     const CallLowering::ArgInfo &Result,
6585ffd83dbSDimitry Andric                     ArrayRef<CallLowering::ArgInfo> Args) {
6595ffd83dbSDimitry Andric   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
6605ffd83dbSDimitry Andric   const char *Name = TLI.getLibcallName(Libcall);
6615ffd83dbSDimitry Andric   const CallingConv::ID CC = TLI.getLibcallCallingConv(Libcall);
6625ffd83dbSDimitry Andric   return createLibcall(MIRBuilder, Name, Result, Args, CC);
6635ffd83dbSDimitry Andric }
6645ffd83dbSDimitry Andric 
6650b57cec5SDimitry Andric // Useful for libcalls where all operands have the same type.
6660b57cec5SDimitry Andric static LegalizerHelper::LegalizeResult
6670b57cec5SDimitry Andric simpleLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, unsigned Size,
6680b57cec5SDimitry Andric               Type *OpType) {
6690b57cec5SDimitry Andric   auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
6700b57cec5SDimitry Andric 
671fe6060f1SDimitry Andric   // FIXME: What does the original arg index mean here?
6720b57cec5SDimitry Andric   SmallVector<CallLowering::ArgInfo, 3> Args;
6734824e7fdSDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
6744824e7fdSDimitry Andric     Args.push_back({MO.getReg(), OpType, 0});
675fe6060f1SDimitry Andric   return createLibcall(MIRBuilder, Libcall,
676fe6060f1SDimitry Andric                        {MI.getOperand(0).getReg(), OpType, 0}, Args);
6770b57cec5SDimitry Andric }
6780b57cec5SDimitry Andric 
6798bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
6808bcb0991SDimitry Andric llvm::createMemLibcall(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
681fe6060f1SDimitry Andric                        MachineInstr &MI, LostDebugLocObserver &LocObserver) {
6828bcb0991SDimitry Andric   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
6838bcb0991SDimitry Andric 
6848bcb0991SDimitry Andric   SmallVector<CallLowering::ArgInfo, 3> Args;
6858bcb0991SDimitry Andric   // Add all the args, except for the last which is an imm denoting 'tail'.
686e8d8bef9SDimitry Andric   for (unsigned i = 0; i < MI.getNumOperands() - 1; ++i) {
6878bcb0991SDimitry Andric     Register Reg = MI.getOperand(i).getReg();
6888bcb0991SDimitry Andric 
6898bcb0991SDimitry Andric     // Need derive an IR type for call lowering.
6908bcb0991SDimitry Andric     LLT OpLLT = MRI.getType(Reg);
6918bcb0991SDimitry Andric     Type *OpTy = nullptr;
6928bcb0991SDimitry Andric     if (OpLLT.isPointer())
6938bcb0991SDimitry Andric       OpTy = Type::getInt8PtrTy(Ctx, OpLLT.getAddressSpace());
6948bcb0991SDimitry Andric     else
6958bcb0991SDimitry Andric       OpTy = IntegerType::get(Ctx, OpLLT.getSizeInBits());
696fe6060f1SDimitry Andric     Args.push_back({Reg, OpTy, 0});
6978bcb0991SDimitry Andric   }
6988bcb0991SDimitry Andric 
6998bcb0991SDimitry Andric   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
7008bcb0991SDimitry Andric   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
7018bcb0991SDimitry Andric   RTLIB::Libcall RTLibcall;
702fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
703fe6060f1SDimitry Andric   switch (Opc) {
704fe6060f1SDimitry Andric   case TargetOpcode::G_BZERO:
705fe6060f1SDimitry Andric     RTLibcall = RTLIB::BZERO;
706fe6060f1SDimitry Andric     break;
707e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
7088bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMCPY;
709fe6060f1SDimitry Andric     Args[0].Flags[0].setReturned();
7108bcb0991SDimitry Andric     break;
711e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
7128bcb0991SDimitry Andric     RTLibcall = RTLIB::MEMMOVE;
713fe6060f1SDimitry Andric     Args[0].Flags[0].setReturned();
7148bcb0991SDimitry Andric     break;
715e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET:
716e8d8bef9SDimitry Andric     RTLibcall = RTLIB::MEMSET;
717fe6060f1SDimitry Andric     Args[0].Flags[0].setReturned();
718e8d8bef9SDimitry Andric     break;
7198bcb0991SDimitry Andric   default:
720fe6060f1SDimitry Andric     llvm_unreachable("unsupported opcode");
7218bcb0991SDimitry Andric   }
7228bcb0991SDimitry Andric   const char *Name = TLI.getLibcallName(RTLibcall);
7238bcb0991SDimitry Andric 
724fe6060f1SDimitry Andric   // Unsupported libcall on the target.
725fe6060f1SDimitry Andric   if (!Name) {
726fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << ".. .. Could not find libcall name for "
727fe6060f1SDimitry Andric                       << MIRBuilder.getTII().getName(Opc) << "\n");
728fe6060f1SDimitry Andric     return LegalizerHelper::UnableToLegalize;
729fe6060f1SDimitry Andric   }
730fe6060f1SDimitry Andric 
7318bcb0991SDimitry Andric   CallLowering::CallLoweringInfo Info;
7328bcb0991SDimitry Andric   Info.CallConv = TLI.getLibcallCallingConv(RTLibcall);
7338bcb0991SDimitry Andric   Info.Callee = MachineOperand::CreateES(Name);
734fe6060f1SDimitry Andric   Info.OrigRet = CallLowering::ArgInfo({0}, Type::getVoidTy(Ctx), 0);
735e8d8bef9SDimitry Andric   Info.IsTailCall = MI.getOperand(MI.getNumOperands() - 1).getImm() &&
736fe6060f1SDimitry Andric                     isLibCallInTailPosition(MI, MIRBuilder.getTII(), MRI);
7378bcb0991SDimitry Andric 
7388bcb0991SDimitry Andric   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
7398bcb0991SDimitry Andric   if (!CLI.lowerCall(MIRBuilder, Info))
7408bcb0991SDimitry Andric     return LegalizerHelper::UnableToLegalize;
7418bcb0991SDimitry Andric 
7428bcb0991SDimitry Andric   if (Info.LoweredTailCall) {
7438bcb0991SDimitry Andric     assert(Info.IsTailCall && "Lowered tail call when it wasn't a tail call?");
744fe6060f1SDimitry Andric 
745fe6060f1SDimitry Andric     // Check debug locations before removing the return.
746fe6060f1SDimitry Andric     LocObserver.checkpoint(true);
747fe6060f1SDimitry Andric 
7485ffd83dbSDimitry Andric     // We must have a return following the call (or debug insts) to get past
7498bcb0991SDimitry Andric     // isLibCallInTailPosition.
7505ffd83dbSDimitry Andric     do {
7515ffd83dbSDimitry Andric       MachineInstr *Next = MI.getNextNode();
752fe6060f1SDimitry Andric       assert(Next &&
753fe6060f1SDimitry Andric              (Next->isCopy() || Next->isReturn() || Next->isDebugInstr()) &&
7545ffd83dbSDimitry Andric              "Expected instr following MI to be return or debug inst?");
7558bcb0991SDimitry Andric       // We lowered a tail call, so the call is now the return from the block.
7568bcb0991SDimitry Andric       // Delete the old return.
7575ffd83dbSDimitry Andric       Next->eraseFromParent();
7585ffd83dbSDimitry Andric     } while (MI.getNextNode());
759fe6060f1SDimitry Andric 
760fe6060f1SDimitry Andric     // We expect to lose the debug location from the return.
761fe6060f1SDimitry Andric     LocObserver.checkpoint(false);
7628bcb0991SDimitry Andric   }
7638bcb0991SDimitry Andric 
7648bcb0991SDimitry Andric   return LegalizerHelper::Legalized;
7658bcb0991SDimitry Andric }
7668bcb0991SDimitry Andric 
7670b57cec5SDimitry Andric static RTLIB::Libcall getConvRTLibDesc(unsigned Opcode, Type *ToType,
7680b57cec5SDimitry Andric                                        Type *FromType) {
7690b57cec5SDimitry Andric   auto ToMVT = MVT::getVT(ToType);
7700b57cec5SDimitry Andric   auto FromMVT = MVT::getVT(FromType);
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   switch (Opcode) {
7730b57cec5SDimitry Andric   case TargetOpcode::G_FPEXT:
7740b57cec5SDimitry Andric     return RTLIB::getFPEXT(FromMVT, ToMVT);
7750b57cec5SDimitry Andric   case TargetOpcode::G_FPTRUNC:
7760b57cec5SDimitry Andric     return RTLIB::getFPROUND(FromMVT, ToMVT);
7770b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
7780b57cec5SDimitry Andric     return RTLIB::getFPTOSINT(FromMVT, ToMVT);
7790b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
7800b57cec5SDimitry Andric     return RTLIB::getFPTOUINT(FromMVT, ToMVT);
7810b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
7820b57cec5SDimitry Andric     return RTLIB::getSINTTOFP(FromMVT, ToMVT);
7830b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
7840b57cec5SDimitry Andric     return RTLIB::getUINTTOFP(FromMVT, ToMVT);
7850b57cec5SDimitry Andric   }
7860b57cec5SDimitry Andric   llvm_unreachable("Unsupported libcall function");
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric static LegalizerHelper::LegalizeResult
7900b57cec5SDimitry Andric conversionLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, Type *ToType,
7910b57cec5SDimitry Andric                   Type *FromType) {
7920b57cec5SDimitry Andric   RTLIB::Libcall Libcall = getConvRTLibDesc(MI.getOpcode(), ToType, FromType);
793fe6060f1SDimitry Andric   return createLibcall(MIRBuilder, Libcall,
794fe6060f1SDimitry Andric                        {MI.getOperand(0).getReg(), ToType, 0},
795fe6060f1SDimitry Andric                        {{MI.getOperand(1).getReg(), FromType, 0}});
7960b57cec5SDimitry Andric }
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
799fe6060f1SDimitry Andric LegalizerHelper::libcall(MachineInstr &MI, LostDebugLocObserver &LocObserver) {
8000b57cec5SDimitry Andric   LLT LLTy = MRI.getType(MI.getOperand(0).getReg());
8010b57cec5SDimitry Andric   unsigned Size = LLTy.getSizeInBits();
8020b57cec5SDimitry Andric   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   switch (MI.getOpcode()) {
8050b57cec5SDimitry Andric   default:
8060b57cec5SDimitry Andric     return UnableToLegalize;
807bdd1243dSDimitry Andric   case TargetOpcode::G_MUL:
8080b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
8090b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
8100b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
8110b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
8120b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
8130b57cec5SDimitry Andric     Type *HLTy = IntegerType::get(Ctx, Size);
8140b57cec5SDimitry Andric     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
8150b57cec5SDimitry Andric     if (Status != Legalized)
8160b57cec5SDimitry Andric       return Status;
8170b57cec5SDimitry Andric     break;
8180b57cec5SDimitry Andric   }
8190b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
8200b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
8210b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
8220b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
8230b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
8240b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
8250b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
8260b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
8270b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
8280b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
8290b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
8300b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
831*06c3fb27SDimitry Andric   case TargetOpcode::G_FLDEXP:
8320b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
8330b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
8340b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
8355ffd83dbSDimitry Andric   case TargetOpcode::G_FFLOOR:
8365ffd83dbSDimitry Andric   case TargetOpcode::G_FMINNUM:
8375ffd83dbSDimitry Andric   case TargetOpcode::G_FMAXNUM:
8385ffd83dbSDimitry Andric   case TargetOpcode::G_FSQRT:
8395ffd83dbSDimitry Andric   case TargetOpcode::G_FRINT:
840e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
841e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
8425ffd83dbSDimitry Andric     Type *HLTy = getFloatTypeForLLT(Ctx, LLTy);
843e8d8bef9SDimitry Andric     if (!HLTy || (Size != 32 && Size != 64 && Size != 80 && Size != 128)) {
844e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "No libcall available for type " << LLTy << ".\n");
8450b57cec5SDimitry Andric       return UnableToLegalize;
8460b57cec5SDimitry Andric     }
8470b57cec5SDimitry Andric     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
8480b57cec5SDimitry Andric     if (Status != Legalized)
8490b57cec5SDimitry Andric       return Status;
8500b57cec5SDimitry Andric     break;
8510b57cec5SDimitry Andric   }
8525ffd83dbSDimitry Andric   case TargetOpcode::G_FPEXT:
8530b57cec5SDimitry Andric   case TargetOpcode::G_FPTRUNC: {
8545ffd83dbSDimitry Andric     Type *FromTy = getFloatTypeForLLT(Ctx,  MRI.getType(MI.getOperand(1).getReg()));
8555ffd83dbSDimitry Andric     Type *ToTy = getFloatTypeForLLT(Ctx, MRI.getType(MI.getOperand(0).getReg()));
8565ffd83dbSDimitry Andric     if (!FromTy || !ToTy)
8570b57cec5SDimitry Andric       return UnableToLegalize;
8585ffd83dbSDimitry Andric     LegalizeResult Status = conversionLibcall(MI, MIRBuilder, ToTy, FromTy );
8590b57cec5SDimitry Andric     if (Status != Legalized)
8600b57cec5SDimitry Andric       return Status;
8610b57cec5SDimitry Andric     break;
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
8640b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI: {
8650b57cec5SDimitry Andric     // FIXME: Support other types
8660b57cec5SDimitry Andric     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
8670b57cec5SDimitry Andric     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
8680b57cec5SDimitry Andric     if ((ToSize != 32 && ToSize != 64) || (FromSize != 32 && FromSize != 64))
8690b57cec5SDimitry Andric       return UnableToLegalize;
8700b57cec5SDimitry Andric     LegalizeResult Status = conversionLibcall(
8710b57cec5SDimitry Andric         MI, MIRBuilder,
8720b57cec5SDimitry Andric         ToSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx),
8730b57cec5SDimitry Andric         FromSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx));
8740b57cec5SDimitry Andric     if (Status != Legalized)
8750b57cec5SDimitry Andric       return Status;
8760b57cec5SDimitry Andric     break;
8770b57cec5SDimitry Andric   }
8780b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
8790b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP: {
8800b57cec5SDimitry Andric     // FIXME: Support other types
8810b57cec5SDimitry Andric     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
8820b57cec5SDimitry Andric     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
8830b57cec5SDimitry Andric     if ((FromSize != 32 && FromSize != 64) || (ToSize != 32 && ToSize != 64))
8840b57cec5SDimitry Andric       return UnableToLegalize;
8850b57cec5SDimitry Andric     LegalizeResult Status = conversionLibcall(
8860b57cec5SDimitry Andric         MI, MIRBuilder,
8870b57cec5SDimitry Andric         ToSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx),
8880b57cec5SDimitry Andric         FromSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx));
8890b57cec5SDimitry Andric     if (Status != Legalized)
8900b57cec5SDimitry Andric       return Status;
8910b57cec5SDimitry Andric     break;
8920b57cec5SDimitry Andric   }
893fe6060f1SDimitry Andric   case TargetOpcode::G_BZERO:
894e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMCPY:
895e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMMOVE:
896e8d8bef9SDimitry Andric   case TargetOpcode::G_MEMSET: {
897fe6060f1SDimitry Andric     LegalizeResult Result =
898fe6060f1SDimitry Andric         createMemLibcall(MIRBuilder, *MIRBuilder.getMRI(), MI, LocObserver);
899fe6060f1SDimitry Andric     if (Result != Legalized)
900fe6060f1SDimitry Andric       return Result;
901e8d8bef9SDimitry Andric     MI.eraseFromParent();
902e8d8bef9SDimitry Andric     return Result;
903e8d8bef9SDimitry Andric   }
9040b57cec5SDimitry Andric   }
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   MI.eraseFromParent();
9070b57cec5SDimitry Andric   return Legalized;
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::narrowScalar(MachineInstr &MI,
9110b57cec5SDimitry Andric                                                               unsigned TypeIdx,
9120b57cec5SDimitry Andric                                                               LLT NarrowTy) {
9130b57cec5SDimitry Andric   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
9140b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   switch (MI.getOpcode()) {
9170b57cec5SDimitry Andric   default:
9180b57cec5SDimitry Andric     return UnableToLegalize;
9190b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
9205ffd83dbSDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
9215ffd83dbSDimitry Andric     LLT DstTy = MRI.getType(DstReg);
9225ffd83dbSDimitry Andric 
9235ffd83dbSDimitry Andric     // If SizeOp0 is not an exact multiple of NarrowSize, emit
9245ffd83dbSDimitry Andric     // G_ANYEXT(G_IMPLICIT_DEF). Cast result to vector if needed.
9255ffd83dbSDimitry Andric     // FIXME: Although this would also be legal for the general case, it causes
9265ffd83dbSDimitry Andric     //  a lot of regressions in the emitted code (superfluous COPYs, artifact
9275ffd83dbSDimitry Andric     //  combines not being hit). This seems to be a problem related to the
9285ffd83dbSDimitry Andric     //  artifact combiner.
9295ffd83dbSDimitry Andric     if (SizeOp0 % NarrowSize != 0) {
9305ffd83dbSDimitry Andric       LLT ImplicitTy = NarrowTy;
9315ffd83dbSDimitry Andric       if (DstTy.isVector())
932fe6060f1SDimitry Andric         ImplicitTy = LLT::vector(DstTy.getElementCount(), ImplicitTy);
9335ffd83dbSDimitry Andric 
9345ffd83dbSDimitry Andric       Register ImplicitReg = MIRBuilder.buildUndef(ImplicitTy).getReg(0);
9355ffd83dbSDimitry Andric       MIRBuilder.buildAnyExt(DstReg, ImplicitReg);
9365ffd83dbSDimitry Andric 
9375ffd83dbSDimitry Andric       MI.eraseFromParent();
9385ffd83dbSDimitry Andric       return Legalized;
9395ffd83dbSDimitry Andric     }
9405ffd83dbSDimitry Andric 
9410b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric     SmallVector<Register, 2> DstRegs;
9440b57cec5SDimitry Andric     for (int i = 0; i < NumParts; ++i)
9455ffd83dbSDimitry Andric       DstRegs.push_back(MIRBuilder.buildUndef(NarrowTy).getReg(0));
9460b57cec5SDimitry Andric 
9475ffd83dbSDimitry Andric     if (DstTy.isVector())
9480b57cec5SDimitry Andric       MIRBuilder.buildBuildVector(DstReg, DstRegs);
9490b57cec5SDimitry Andric     else
950bdd1243dSDimitry Andric       MIRBuilder.buildMergeLikeInstr(DstReg, DstRegs);
9510b57cec5SDimitry Andric     MI.eraseFromParent();
9520b57cec5SDimitry Andric     return Legalized;
9530b57cec5SDimitry Andric   }
9540b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
9550b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
9560b57cec5SDimitry Andric     const APInt &Val = MI.getOperand(1).getCImm()->getValue();
9570b57cec5SDimitry Andric     unsigned TotalSize = Ty.getSizeInBits();
9580b57cec5SDimitry Andric     unsigned NarrowSize = NarrowTy.getSizeInBits();
9590b57cec5SDimitry Andric     int NumParts = TotalSize / NarrowSize;
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric     SmallVector<Register, 4> PartRegs;
9620b57cec5SDimitry Andric     for (int I = 0; I != NumParts; ++I) {
9630b57cec5SDimitry Andric       unsigned Offset = I * NarrowSize;
9640b57cec5SDimitry Andric       auto K = MIRBuilder.buildConstant(NarrowTy,
9650b57cec5SDimitry Andric                                         Val.lshr(Offset).trunc(NarrowSize));
9660b57cec5SDimitry Andric       PartRegs.push_back(K.getReg(0));
9670b57cec5SDimitry Andric     }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric     LLT LeftoverTy;
9700b57cec5SDimitry Andric     unsigned LeftoverBits = TotalSize - NumParts * NarrowSize;
9710b57cec5SDimitry Andric     SmallVector<Register, 1> LeftoverRegs;
9720b57cec5SDimitry Andric     if (LeftoverBits != 0) {
9730b57cec5SDimitry Andric       LeftoverTy = LLT::scalar(LeftoverBits);
9740b57cec5SDimitry Andric       auto K = MIRBuilder.buildConstant(
9750b57cec5SDimitry Andric         LeftoverTy,
9760b57cec5SDimitry Andric         Val.lshr(NumParts * NarrowSize).trunc(LeftoverBits));
9770b57cec5SDimitry Andric       LeftoverRegs.push_back(K.getReg(0));
9780b57cec5SDimitry Andric     }
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric     insertParts(MI.getOperand(0).getReg(),
9810b57cec5SDimitry Andric                 Ty, NarrowTy, PartRegs, LeftoverTy, LeftoverRegs);
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     MI.eraseFromParent();
9840b57cec5SDimitry Andric     return Legalized;
9850b57cec5SDimitry Andric   }
9865ffd83dbSDimitry Andric   case TargetOpcode::G_SEXT:
9875ffd83dbSDimitry Andric   case TargetOpcode::G_ZEXT:
9885ffd83dbSDimitry Andric   case TargetOpcode::G_ANYEXT:
9895ffd83dbSDimitry Andric     return narrowScalarExt(MI, TypeIdx, NarrowTy);
9908bcb0991SDimitry Andric   case TargetOpcode::G_TRUNC: {
9918bcb0991SDimitry Andric     if (TypeIdx != 1)
9928bcb0991SDimitry Andric       return UnableToLegalize;
9938bcb0991SDimitry Andric 
9948bcb0991SDimitry Andric     uint64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
9958bcb0991SDimitry Andric     if (NarrowTy.getSizeInBits() * 2 != SizeOp1) {
9968bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Can't narrow trunc to type " << NarrowTy << "\n");
9978bcb0991SDimitry Andric       return UnableToLegalize;
9988bcb0991SDimitry Andric     }
9998bcb0991SDimitry Andric 
10005ffd83dbSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
10015ffd83dbSDimitry Andric     MIRBuilder.buildCopy(MI.getOperand(0), Unmerge.getReg(0));
10028bcb0991SDimitry Andric     MI.eraseFromParent();
10038bcb0991SDimitry Andric     return Legalized;
10048bcb0991SDimitry Andric   }
10058bcb0991SDimitry Andric 
10060eae32dcSDimitry Andric   case TargetOpcode::G_FREEZE: {
10070eae32dcSDimitry Andric     if (TypeIdx != 0)
10080eae32dcSDimitry Andric       return UnableToLegalize;
10090eae32dcSDimitry Andric 
10100eae32dcSDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
10110eae32dcSDimitry Andric     // Should widen scalar first
10120eae32dcSDimitry Andric     if (Ty.getSizeInBits() % NarrowTy.getSizeInBits() != 0)
10130eae32dcSDimitry Andric       return UnableToLegalize;
10140eae32dcSDimitry Andric 
10150eae32dcSDimitry Andric     auto Unmerge = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1).getReg());
10160eae32dcSDimitry Andric     SmallVector<Register, 8> Parts;
10170eae32dcSDimitry Andric     for (unsigned i = 0; i < Unmerge->getNumDefs(); ++i) {
10180eae32dcSDimitry Andric       Parts.push_back(
10190eae32dcSDimitry Andric           MIRBuilder.buildFreeze(NarrowTy, Unmerge.getReg(i)).getReg(0));
10200eae32dcSDimitry Andric     }
10210eae32dcSDimitry Andric 
1022bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(MI.getOperand(0).getReg(), Parts);
10230eae32dcSDimitry Andric     MI.eraseFromParent();
10240eae32dcSDimitry Andric     return Legalized;
10250eae32dcSDimitry Andric   }
1026fe6060f1SDimitry Andric   case TargetOpcode::G_ADD:
1027fe6060f1SDimitry Andric   case TargetOpcode::G_SUB:
1028fe6060f1SDimitry Andric   case TargetOpcode::G_SADDO:
1029fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBO:
1030fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
1031fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
1032fe6060f1SDimitry Andric   case TargetOpcode::G_UADDO:
1033fe6060f1SDimitry Andric   case TargetOpcode::G_USUBO:
1034fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
1035fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
1036fe6060f1SDimitry Andric     return narrowScalarAddSub(MI, TypeIdx, NarrowTy);
10370b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
10380b57cec5SDimitry Andric   case TargetOpcode::G_UMULH:
10390b57cec5SDimitry Andric     return narrowScalarMul(MI, NarrowTy);
10400b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
10410b57cec5SDimitry Andric     return narrowScalarExtract(MI, TypeIdx, NarrowTy);
10420b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
10430b57cec5SDimitry Andric     return narrowScalarInsert(MI, TypeIdx, NarrowTy);
10440b57cec5SDimitry Andric   case TargetOpcode::G_LOAD: {
1045fe6060f1SDimitry Andric     auto &LoadMI = cast<GLoad>(MI);
1046fe6060f1SDimitry Andric     Register DstReg = LoadMI.getDstReg();
10470b57cec5SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
10480b57cec5SDimitry Andric     if (DstTy.isVector())
10490b57cec5SDimitry Andric       return UnableToLegalize;
10500b57cec5SDimitry Andric 
1051fe6060f1SDimitry Andric     if (8 * LoadMI.getMemSize() != DstTy.getSizeInBits()) {
10520b57cec5SDimitry Andric       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
1053fe6060f1SDimitry Andric       MIRBuilder.buildLoad(TmpReg, LoadMI.getPointerReg(), LoadMI.getMMO());
10540b57cec5SDimitry Andric       MIRBuilder.buildAnyExt(DstReg, TmpReg);
1055fe6060f1SDimitry Andric       LoadMI.eraseFromParent();
10560b57cec5SDimitry Andric       return Legalized;
10570b57cec5SDimitry Andric     }
10580b57cec5SDimitry Andric 
1059fe6060f1SDimitry Andric     return reduceLoadStoreWidth(LoadMI, TypeIdx, NarrowTy);
10600b57cec5SDimitry Andric   }
10610b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
10620b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD: {
1063fe6060f1SDimitry Andric     auto &LoadMI = cast<GExtLoad>(MI);
1064fe6060f1SDimitry Andric     Register DstReg = LoadMI.getDstReg();
1065fe6060f1SDimitry Andric     Register PtrReg = LoadMI.getPointerReg();
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric     Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
1068fe6060f1SDimitry Andric     auto &MMO = LoadMI.getMMO();
1069e8d8bef9SDimitry Andric     unsigned MemSize = MMO.getSizeInBits();
1070e8d8bef9SDimitry Andric 
1071e8d8bef9SDimitry Andric     if (MemSize == NarrowSize) {
10720b57cec5SDimitry Andric       MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
1073e8d8bef9SDimitry Andric     } else if (MemSize < NarrowSize) {
1074fe6060f1SDimitry Andric       MIRBuilder.buildLoadInstr(LoadMI.getOpcode(), TmpReg, PtrReg, MMO);
1075e8d8bef9SDimitry Andric     } else if (MemSize > NarrowSize) {
1076e8d8bef9SDimitry Andric       // FIXME: Need to split the load.
1077e8d8bef9SDimitry Andric       return UnableToLegalize;
10780b57cec5SDimitry Andric     }
10790b57cec5SDimitry Andric 
1080fe6060f1SDimitry Andric     if (isa<GZExtLoad>(LoadMI))
10810b57cec5SDimitry Andric       MIRBuilder.buildZExt(DstReg, TmpReg);
10820b57cec5SDimitry Andric     else
10830b57cec5SDimitry Andric       MIRBuilder.buildSExt(DstReg, TmpReg);
10840b57cec5SDimitry Andric 
1085fe6060f1SDimitry Andric     LoadMI.eraseFromParent();
10860b57cec5SDimitry Andric     return Legalized;
10870b57cec5SDimitry Andric   }
10880b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
1089fe6060f1SDimitry Andric     auto &StoreMI = cast<GStore>(MI);
10900b57cec5SDimitry Andric 
1091fe6060f1SDimitry Andric     Register SrcReg = StoreMI.getValueReg();
10920b57cec5SDimitry Andric     LLT SrcTy = MRI.getType(SrcReg);
10930b57cec5SDimitry Andric     if (SrcTy.isVector())
10940b57cec5SDimitry Andric       return UnableToLegalize;
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
10970b57cec5SDimitry Andric     unsigned HandledSize = NumParts * NarrowTy.getSizeInBits();
10980b57cec5SDimitry Andric     unsigned LeftoverBits = SrcTy.getSizeInBits() - HandledSize;
10990b57cec5SDimitry Andric     if (SrcTy.isVector() && LeftoverBits != 0)
11000b57cec5SDimitry Andric       return UnableToLegalize;
11010b57cec5SDimitry Andric 
1102fe6060f1SDimitry Andric     if (8 * StoreMI.getMemSize() != SrcTy.getSizeInBits()) {
11030b57cec5SDimitry Andric       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
11040b57cec5SDimitry Andric       MIRBuilder.buildTrunc(TmpReg, SrcReg);
1105fe6060f1SDimitry Andric       MIRBuilder.buildStore(TmpReg, StoreMI.getPointerReg(), StoreMI.getMMO());
1106fe6060f1SDimitry Andric       StoreMI.eraseFromParent();
11070b57cec5SDimitry Andric       return Legalized;
11080b57cec5SDimitry Andric     }
11090b57cec5SDimitry Andric 
1110fe6060f1SDimitry Andric     return reduceLoadStoreWidth(StoreMI, 0, NarrowTy);
11110b57cec5SDimitry Andric   }
11120b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
11130b57cec5SDimitry Andric     return narrowScalarSelect(MI, TypeIdx, NarrowTy);
11140b57cec5SDimitry Andric   case TargetOpcode::G_AND:
11150b57cec5SDimitry Andric   case TargetOpcode::G_OR:
11160b57cec5SDimitry Andric   case TargetOpcode::G_XOR: {
11170b57cec5SDimitry Andric     // Legalize bitwise operation:
11180b57cec5SDimitry Andric     // A = BinOp<Ty> B, C
11190b57cec5SDimitry Andric     // into:
11200b57cec5SDimitry Andric     // B1, ..., BN = G_UNMERGE_VALUES B
11210b57cec5SDimitry Andric     // C1, ..., CN = G_UNMERGE_VALUES C
11220b57cec5SDimitry Andric     // A1 = BinOp<Ty/N> B1, C2
11230b57cec5SDimitry Andric     // ...
11240b57cec5SDimitry Andric     // AN = BinOp<Ty/N> BN, CN
11250b57cec5SDimitry Andric     // A = G_MERGE_VALUES A1, ..., AN
11260b57cec5SDimitry Andric     return narrowScalarBasic(MI, TypeIdx, NarrowTy);
11270b57cec5SDimitry Andric   }
11280b57cec5SDimitry Andric   case TargetOpcode::G_SHL:
11290b57cec5SDimitry Andric   case TargetOpcode::G_LSHR:
11300b57cec5SDimitry Andric   case TargetOpcode::G_ASHR:
11310b57cec5SDimitry Andric     return narrowScalarShift(MI, TypeIdx, NarrowTy);
11320b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
11330b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
11340b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
11350b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
11360b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP:
11375ffd83dbSDimitry Andric     if (TypeIdx == 1)
11385ffd83dbSDimitry Andric       switch (MI.getOpcode()) {
11395ffd83dbSDimitry Andric       case TargetOpcode::G_CTLZ:
11405ffd83dbSDimitry Andric       case TargetOpcode::G_CTLZ_ZERO_UNDEF:
11415ffd83dbSDimitry Andric         return narrowScalarCTLZ(MI, TypeIdx, NarrowTy);
11425ffd83dbSDimitry Andric       case TargetOpcode::G_CTTZ:
11435ffd83dbSDimitry Andric       case TargetOpcode::G_CTTZ_ZERO_UNDEF:
11445ffd83dbSDimitry Andric         return narrowScalarCTTZ(MI, TypeIdx, NarrowTy);
11455ffd83dbSDimitry Andric       case TargetOpcode::G_CTPOP:
11465ffd83dbSDimitry Andric         return narrowScalarCTPOP(MI, TypeIdx, NarrowTy);
11475ffd83dbSDimitry Andric       default:
11485ffd83dbSDimitry Andric         return UnableToLegalize;
11495ffd83dbSDimitry Andric       }
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric     Observer.changingInstr(MI);
11520b57cec5SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
11530b57cec5SDimitry Andric     Observer.changedInstr(MI);
11540b57cec5SDimitry Andric     return Legalized;
11550b57cec5SDimitry Andric   case TargetOpcode::G_INTTOPTR:
11560b57cec5SDimitry Andric     if (TypeIdx != 1)
11570b57cec5SDimitry Andric       return UnableToLegalize;
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric     Observer.changingInstr(MI);
11600b57cec5SDimitry Andric     narrowScalarSrc(MI, NarrowTy, 1);
11610b57cec5SDimitry Andric     Observer.changedInstr(MI);
11620b57cec5SDimitry Andric     return Legalized;
11630b57cec5SDimitry Andric   case TargetOpcode::G_PTRTOINT:
11640b57cec5SDimitry Andric     if (TypeIdx != 0)
11650b57cec5SDimitry Andric       return UnableToLegalize;
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric     Observer.changingInstr(MI);
11680b57cec5SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
11690b57cec5SDimitry Andric     Observer.changedInstr(MI);
11700b57cec5SDimitry Andric     return Legalized;
11710b57cec5SDimitry Andric   case TargetOpcode::G_PHI: {
1172d409305fSDimitry Andric     // FIXME: add support for when SizeOp0 isn't an exact multiple of
1173d409305fSDimitry Andric     // NarrowSize.
1174d409305fSDimitry Andric     if (SizeOp0 % NarrowSize != 0)
1175d409305fSDimitry Andric       return UnableToLegalize;
1176d409305fSDimitry Andric 
11770b57cec5SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
11785ffd83dbSDimitry Andric     SmallVector<Register, 2> DstRegs(NumParts);
11795ffd83dbSDimitry Andric     SmallVector<SmallVector<Register, 2>, 2> SrcRegs(MI.getNumOperands() / 2);
11800b57cec5SDimitry Andric     Observer.changingInstr(MI);
11810b57cec5SDimitry Andric     for (unsigned i = 1; i < MI.getNumOperands(); i += 2) {
11820b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(i + 1).getMBB();
1183bdd1243dSDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminatorForward());
11840b57cec5SDimitry Andric       extractParts(MI.getOperand(i).getReg(), NarrowTy, NumParts,
11850b57cec5SDimitry Andric                    SrcRegs[i / 2]);
11860b57cec5SDimitry Andric     }
11870b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
11880b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, MI);
11890b57cec5SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
11900b57cec5SDimitry Andric       DstRegs[i] = MRI.createGenericVirtualRegister(NarrowTy);
11910b57cec5SDimitry Andric       MachineInstrBuilder MIB =
11920b57cec5SDimitry Andric           MIRBuilder.buildInstr(TargetOpcode::G_PHI).addDef(DstRegs[i]);
11930b57cec5SDimitry Andric       for (unsigned j = 1; j < MI.getNumOperands(); j += 2)
11940b57cec5SDimitry Andric         MIB.addUse(SrcRegs[j / 2][i]).add(MI.getOperand(j + 1));
11950b57cec5SDimitry Andric     }
11968bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MBB, MBB.getFirstNonPHI());
1197bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(MI.getOperand(0), DstRegs);
11980b57cec5SDimitry Andric     Observer.changedInstr(MI);
11990b57cec5SDimitry Andric     MI.eraseFromParent();
12000b57cec5SDimitry Andric     return Legalized;
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
12030b57cec5SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
12040b57cec5SDimitry Andric     if (TypeIdx != 2)
12050b57cec5SDimitry Andric       return UnableToLegalize;
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric     int OpIdx = MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
12080b57cec5SDimitry Andric     Observer.changingInstr(MI);
12090b57cec5SDimitry Andric     narrowScalarSrc(MI, NarrowTy, OpIdx);
12100b57cec5SDimitry Andric     Observer.changedInstr(MI);
12110b57cec5SDimitry Andric     return Legalized;
12120b57cec5SDimitry Andric   }
12130b57cec5SDimitry Andric   case TargetOpcode::G_ICMP: {
1214fe6060f1SDimitry Andric     Register LHS = MI.getOperand(2).getReg();
1215fe6060f1SDimitry Andric     LLT SrcTy = MRI.getType(LHS);
1216fe6060f1SDimitry Andric     uint64_t SrcSize = SrcTy.getSizeInBits();
12170b57cec5SDimitry Andric     CmpInst::Predicate Pred =
12180b57cec5SDimitry Andric         static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
12190b57cec5SDimitry Andric 
1220fe6060f1SDimitry Andric     // TODO: Handle the non-equality case for weird sizes.
1221fe6060f1SDimitry Andric     if (NarrowSize * 2 != SrcSize && !ICmpInst::isEquality(Pred))
1222fe6060f1SDimitry Andric       return UnableToLegalize;
1223fe6060f1SDimitry Andric 
1224fe6060f1SDimitry Andric     LLT LeftoverTy; // Example: s88 -> s64 (NarrowTy) + s24 (leftover)
1225fe6060f1SDimitry Andric     SmallVector<Register, 4> LHSPartRegs, LHSLeftoverRegs;
1226fe6060f1SDimitry Andric     if (!extractParts(LHS, SrcTy, NarrowTy, LeftoverTy, LHSPartRegs,
1227fe6060f1SDimitry Andric                       LHSLeftoverRegs))
1228fe6060f1SDimitry Andric       return UnableToLegalize;
1229fe6060f1SDimitry Andric 
1230fe6060f1SDimitry Andric     LLT Unused; // Matches LeftoverTy; G_ICMP LHS and RHS are the same type.
1231fe6060f1SDimitry Andric     SmallVector<Register, 4> RHSPartRegs, RHSLeftoverRegs;
1232fe6060f1SDimitry Andric     if (!extractParts(MI.getOperand(3).getReg(), SrcTy, NarrowTy, Unused,
1233fe6060f1SDimitry Andric                       RHSPartRegs, RHSLeftoverRegs))
1234fe6060f1SDimitry Andric       return UnableToLegalize;
1235fe6060f1SDimitry Andric 
1236fe6060f1SDimitry Andric     // We now have the LHS and RHS of the compare split into narrow-type
1237fe6060f1SDimitry Andric     // registers, plus potentially some leftover type.
1238fe6060f1SDimitry Andric     Register Dst = MI.getOperand(0).getReg();
1239fe6060f1SDimitry Andric     LLT ResTy = MRI.getType(Dst);
1240fe6060f1SDimitry Andric     if (ICmpInst::isEquality(Pred)) {
1241fe6060f1SDimitry Andric       // For each part on the LHS and RHS, keep track of the result of XOR-ing
1242fe6060f1SDimitry Andric       // them together. For each equal part, the result should be all 0s. For
1243fe6060f1SDimitry Andric       // each non-equal part, we'll get at least one 1.
1244fe6060f1SDimitry Andric       auto Zero = MIRBuilder.buildConstant(NarrowTy, 0);
1245fe6060f1SDimitry Andric       SmallVector<Register, 4> Xors;
1246fe6060f1SDimitry Andric       for (auto LHSAndRHS : zip(LHSPartRegs, RHSPartRegs)) {
1247fe6060f1SDimitry Andric         auto LHS = std::get<0>(LHSAndRHS);
1248fe6060f1SDimitry Andric         auto RHS = std::get<1>(LHSAndRHS);
1249fe6060f1SDimitry Andric         auto Xor = MIRBuilder.buildXor(NarrowTy, LHS, RHS).getReg(0);
1250fe6060f1SDimitry Andric         Xors.push_back(Xor);
1251fe6060f1SDimitry Andric       }
1252fe6060f1SDimitry Andric 
1253fe6060f1SDimitry Andric       // Build a G_XOR for each leftover register. Each G_XOR must be widened
1254fe6060f1SDimitry Andric       // to the desired narrow type so that we can OR them together later.
1255fe6060f1SDimitry Andric       SmallVector<Register, 4> WidenedXors;
1256fe6060f1SDimitry Andric       for (auto LHSAndRHS : zip(LHSLeftoverRegs, RHSLeftoverRegs)) {
1257fe6060f1SDimitry Andric         auto LHS = std::get<0>(LHSAndRHS);
1258fe6060f1SDimitry Andric         auto RHS = std::get<1>(LHSAndRHS);
1259fe6060f1SDimitry Andric         auto Xor = MIRBuilder.buildXor(LeftoverTy, LHS, RHS).getReg(0);
1260fe6060f1SDimitry Andric         LLT GCDTy = extractGCDType(WidenedXors, NarrowTy, LeftoverTy, Xor);
1261fe6060f1SDimitry Andric         buildLCMMergePieces(LeftoverTy, NarrowTy, GCDTy, WidenedXors,
1262fe6060f1SDimitry Andric                             /* PadStrategy = */ TargetOpcode::G_ZEXT);
1263fe6060f1SDimitry Andric         Xors.insert(Xors.end(), WidenedXors.begin(), WidenedXors.end());
1264fe6060f1SDimitry Andric       }
1265fe6060f1SDimitry Andric 
1266fe6060f1SDimitry Andric       // Now, for each part we broke up, we know if they are equal/not equal
1267fe6060f1SDimitry Andric       // based off the G_XOR. We can OR these all together and compare against
1268fe6060f1SDimitry Andric       // 0 to get the result.
1269fe6060f1SDimitry Andric       assert(Xors.size() >= 2 && "Should have gotten at least two Xors?");
1270fe6060f1SDimitry Andric       auto Or = MIRBuilder.buildOr(NarrowTy, Xors[0], Xors[1]);
1271fe6060f1SDimitry Andric       for (unsigned I = 2, E = Xors.size(); I < E; ++I)
1272fe6060f1SDimitry Andric         Or = MIRBuilder.buildOr(NarrowTy, Or, Xors[I]);
1273fe6060f1SDimitry Andric       MIRBuilder.buildICmp(Pred, Dst, Or, Zero);
12740b57cec5SDimitry Andric     } else {
1275fe6060f1SDimitry Andric       // TODO: Handle non-power-of-two types.
1276fe6060f1SDimitry Andric       assert(LHSPartRegs.size() == 2 && "Expected exactly 2 LHS part regs?");
1277fe6060f1SDimitry Andric       assert(RHSPartRegs.size() == 2 && "Expected exactly 2 RHS part regs?");
1278fe6060f1SDimitry Andric       Register LHSL = LHSPartRegs[0];
1279fe6060f1SDimitry Andric       Register LHSH = LHSPartRegs[1];
1280fe6060f1SDimitry Andric       Register RHSL = RHSPartRegs[0];
1281fe6060f1SDimitry Andric       Register RHSH = RHSPartRegs[1];
12828bcb0991SDimitry Andric       MachineInstrBuilder CmpH = MIRBuilder.buildICmp(Pred, ResTy, LHSH, RHSH);
12830b57cec5SDimitry Andric       MachineInstrBuilder CmpHEQ =
12848bcb0991SDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, ResTy, LHSH, RHSH);
12850b57cec5SDimitry Andric       MachineInstrBuilder CmpLU = MIRBuilder.buildICmp(
12868bcb0991SDimitry Andric           ICmpInst::getUnsignedPredicate(Pred), ResTy, LHSL, RHSL);
1287fe6060f1SDimitry Andric       MIRBuilder.buildSelect(Dst, CmpHEQ, CmpLU, CmpH);
12880b57cec5SDimitry Andric     }
12890b57cec5SDimitry Andric     MI.eraseFromParent();
12900b57cec5SDimitry Andric     return Legalized;
12910b57cec5SDimitry Andric   }
12928bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
12938bcb0991SDimitry Andric     if (TypeIdx != 0)
12948bcb0991SDimitry Andric       return UnableToLegalize;
12958bcb0991SDimitry Andric 
12968bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
12978bcb0991SDimitry Andric 
12988bcb0991SDimitry Andric     // So long as the new type has more bits than the bits we're extending we
12998bcb0991SDimitry Andric     // don't need to break it apart.
13008bcb0991SDimitry Andric     if (NarrowTy.getScalarSizeInBits() >= SizeInBits) {
13018bcb0991SDimitry Andric       Observer.changingInstr(MI);
13028bcb0991SDimitry Andric       // We don't lose any non-extension bits by truncating the src and
13038bcb0991SDimitry Andric       // sign-extending the dst.
13048bcb0991SDimitry Andric       MachineOperand &MO1 = MI.getOperand(1);
13055ffd83dbSDimitry Andric       auto TruncMIB = MIRBuilder.buildTrunc(NarrowTy, MO1);
13065ffd83dbSDimitry Andric       MO1.setReg(TruncMIB.getReg(0));
13078bcb0991SDimitry Andric 
13088bcb0991SDimitry Andric       MachineOperand &MO2 = MI.getOperand(0);
13098bcb0991SDimitry Andric       Register DstExt = MRI.createGenericVirtualRegister(NarrowTy);
13108bcb0991SDimitry Andric       MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
13115ffd83dbSDimitry Andric       MIRBuilder.buildSExt(MO2, DstExt);
13128bcb0991SDimitry Andric       MO2.setReg(DstExt);
13138bcb0991SDimitry Andric       Observer.changedInstr(MI);
13148bcb0991SDimitry Andric       return Legalized;
13158bcb0991SDimitry Andric     }
13168bcb0991SDimitry Andric 
13178bcb0991SDimitry Andric     // Break it apart. Components below the extension point are unmodified. The
13188bcb0991SDimitry Andric     // component containing the extension point becomes a narrower SEXT_INREG.
13198bcb0991SDimitry Andric     // Components above it are ashr'd from the component containing the
13208bcb0991SDimitry Andric     // extension point.
13218bcb0991SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
13228bcb0991SDimitry Andric       return UnableToLegalize;
13238bcb0991SDimitry Andric     int NumParts = SizeOp0 / NarrowSize;
13248bcb0991SDimitry Andric 
13258bcb0991SDimitry Andric     // List the registers where the destination will be scattered.
13268bcb0991SDimitry Andric     SmallVector<Register, 2> DstRegs;
13278bcb0991SDimitry Andric     // List the registers where the source will be split.
13288bcb0991SDimitry Andric     SmallVector<Register, 2> SrcRegs;
13298bcb0991SDimitry Andric 
13308bcb0991SDimitry Andric     // Create all the temporary registers.
13318bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
13328bcb0991SDimitry Andric       Register SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
13338bcb0991SDimitry Andric 
13348bcb0991SDimitry Andric       SrcRegs.push_back(SrcReg);
13358bcb0991SDimitry Andric     }
13368bcb0991SDimitry Andric 
13378bcb0991SDimitry Andric     // Explode the big arguments into smaller chunks.
13385ffd83dbSDimitry Andric     MIRBuilder.buildUnmerge(SrcRegs, MI.getOperand(1));
13398bcb0991SDimitry Andric 
13408bcb0991SDimitry Andric     Register AshrCstReg =
13418bcb0991SDimitry Andric         MIRBuilder.buildConstant(NarrowTy, NarrowTy.getScalarSizeInBits() - 1)
13425ffd83dbSDimitry Andric             .getReg(0);
13438bcb0991SDimitry Andric     Register FullExtensionReg = 0;
13448bcb0991SDimitry Andric     Register PartialExtensionReg = 0;
13458bcb0991SDimitry Andric 
13468bcb0991SDimitry Andric     // Do the operation on each small part.
13478bcb0991SDimitry Andric     for (int i = 0; i < NumParts; ++i) {
13488bcb0991SDimitry Andric       if ((i + 1) * NarrowTy.getScalarSizeInBits() < SizeInBits)
13498bcb0991SDimitry Andric         DstRegs.push_back(SrcRegs[i]);
13508bcb0991SDimitry Andric       else if (i * NarrowTy.getScalarSizeInBits() > SizeInBits) {
13518bcb0991SDimitry Andric         assert(PartialExtensionReg &&
13528bcb0991SDimitry Andric                "Expected to visit partial extension before full");
13538bcb0991SDimitry Andric         if (FullExtensionReg) {
13548bcb0991SDimitry Andric           DstRegs.push_back(FullExtensionReg);
13558bcb0991SDimitry Andric           continue;
13568bcb0991SDimitry Andric         }
13575ffd83dbSDimitry Andric         DstRegs.push_back(
13585ffd83dbSDimitry Andric             MIRBuilder.buildAShr(NarrowTy, PartialExtensionReg, AshrCstReg)
13595ffd83dbSDimitry Andric                 .getReg(0));
13608bcb0991SDimitry Andric         FullExtensionReg = DstRegs.back();
13618bcb0991SDimitry Andric       } else {
13628bcb0991SDimitry Andric         DstRegs.push_back(
13638bcb0991SDimitry Andric             MIRBuilder
13648bcb0991SDimitry Andric                 .buildInstr(
13658bcb0991SDimitry Andric                     TargetOpcode::G_SEXT_INREG, {NarrowTy},
13668bcb0991SDimitry Andric                     {SrcRegs[i], SizeInBits % NarrowTy.getScalarSizeInBits()})
13675ffd83dbSDimitry Andric                 .getReg(0));
13688bcb0991SDimitry Andric         PartialExtensionReg = DstRegs.back();
13698bcb0991SDimitry Andric       }
13708bcb0991SDimitry Andric     }
13718bcb0991SDimitry Andric 
13728bcb0991SDimitry Andric     // Gather the destination registers into the final destination.
13738bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
1374bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(DstReg, DstRegs);
13758bcb0991SDimitry Andric     MI.eraseFromParent();
13768bcb0991SDimitry Andric     return Legalized;
13778bcb0991SDimitry Andric   }
1378480093f4SDimitry Andric   case TargetOpcode::G_BSWAP:
1379480093f4SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
1380480093f4SDimitry Andric     if (SizeOp0 % NarrowSize != 0)
1381480093f4SDimitry Andric       return UnableToLegalize;
1382480093f4SDimitry Andric 
1383480093f4SDimitry Andric     Observer.changingInstr(MI);
1384480093f4SDimitry Andric     SmallVector<Register, 2> SrcRegs, DstRegs;
1385480093f4SDimitry Andric     unsigned NumParts = SizeOp0 / NarrowSize;
1386480093f4SDimitry Andric     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
1387480093f4SDimitry Andric 
1388480093f4SDimitry Andric     for (unsigned i = 0; i < NumParts; ++i) {
1389480093f4SDimitry Andric       auto DstPart = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
1390480093f4SDimitry Andric                                            {SrcRegs[NumParts - 1 - i]});
1391480093f4SDimitry Andric       DstRegs.push_back(DstPart.getReg(0));
1392480093f4SDimitry Andric     }
1393480093f4SDimitry Andric 
1394bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(MI.getOperand(0), DstRegs);
1395480093f4SDimitry Andric 
1396480093f4SDimitry Andric     Observer.changedInstr(MI);
1397480093f4SDimitry Andric     MI.eraseFromParent();
1398480093f4SDimitry Andric     return Legalized;
1399480093f4SDimitry Andric   }
1400e8d8bef9SDimitry Andric   case TargetOpcode::G_PTR_ADD:
14015ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
14025ffd83dbSDimitry Andric     if (TypeIdx != 1)
14035ffd83dbSDimitry Andric       return UnableToLegalize;
14045ffd83dbSDimitry Andric     Observer.changingInstr(MI);
14055ffd83dbSDimitry Andric     narrowScalarSrc(MI, NarrowTy, 2);
14065ffd83dbSDimitry Andric     Observer.changedInstr(MI);
14075ffd83dbSDimitry Andric     return Legalized;
14080b57cec5SDimitry Andric   }
140923408297SDimitry Andric   case TargetOpcode::G_FPTOUI:
141023408297SDimitry Andric   case TargetOpcode::G_FPTOSI:
141123408297SDimitry Andric     return narrowScalarFPTOI(MI, TypeIdx, NarrowTy);
1412e8d8bef9SDimitry Andric   case TargetOpcode::G_FPEXT:
1413e8d8bef9SDimitry Andric     if (TypeIdx != 0)
1414e8d8bef9SDimitry Andric       return UnableToLegalize;
1415e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
1416e8d8bef9SDimitry Andric     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_FPEXT);
1417e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
1418e8d8bef9SDimitry Andric     return Legalized;
1419*06c3fb27SDimitry Andric   case TargetOpcode::G_FLDEXP:
1420*06c3fb27SDimitry Andric   case TargetOpcode::G_STRICT_FLDEXP:
1421*06c3fb27SDimitry Andric     return narrowScalarFLDEXP(MI, TypeIdx, NarrowTy);
14220b57cec5SDimitry Andric   }
14235ffd83dbSDimitry Andric }
14245ffd83dbSDimitry Andric 
14255ffd83dbSDimitry Andric Register LegalizerHelper::coerceToScalar(Register Val) {
14265ffd83dbSDimitry Andric   LLT Ty = MRI.getType(Val);
14275ffd83dbSDimitry Andric   if (Ty.isScalar())
14285ffd83dbSDimitry Andric     return Val;
14295ffd83dbSDimitry Andric 
14305ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
14315ffd83dbSDimitry Andric   LLT NewTy = LLT::scalar(Ty.getSizeInBits());
14325ffd83dbSDimitry Andric   if (Ty.isPointer()) {
14335ffd83dbSDimitry Andric     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
14345ffd83dbSDimitry Andric       return Register();
14355ffd83dbSDimitry Andric     return MIRBuilder.buildPtrToInt(NewTy, Val).getReg(0);
14365ffd83dbSDimitry Andric   }
14375ffd83dbSDimitry Andric 
14385ffd83dbSDimitry Andric   Register NewVal = Val;
14395ffd83dbSDimitry Andric 
14405ffd83dbSDimitry Andric   assert(Ty.isVector());
14415ffd83dbSDimitry Andric   LLT EltTy = Ty.getElementType();
14425ffd83dbSDimitry Andric   if (EltTy.isPointer())
14435ffd83dbSDimitry Andric     NewVal = MIRBuilder.buildPtrToInt(NewTy, NewVal).getReg(0);
14445ffd83dbSDimitry Andric   return MIRBuilder.buildBitcast(NewTy, NewVal).getReg(0);
14455ffd83dbSDimitry Andric }
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric void LegalizerHelper::widenScalarSrc(MachineInstr &MI, LLT WideTy,
14480b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned ExtOpcode) {
14490b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14505ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MO});
14515ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
14520b57cec5SDimitry Andric }
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric void LegalizerHelper::narrowScalarSrc(MachineInstr &MI, LLT NarrowTy,
14550b57cec5SDimitry Andric                                       unsigned OpIdx) {
14560b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14575ffd83dbSDimitry Andric   auto ExtB = MIRBuilder.buildTrunc(NarrowTy, MO);
14585ffd83dbSDimitry Andric   MO.setReg(ExtB.getReg(0));
14590b57cec5SDimitry Andric }
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric void LegalizerHelper::widenScalarDst(MachineInstr &MI, LLT WideTy,
14620b57cec5SDimitry Andric                                      unsigned OpIdx, unsigned TruncOpcode) {
14630b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14640b57cec5SDimitry Andric   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
14650b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
14665ffd83dbSDimitry Andric   MIRBuilder.buildInstr(TruncOpcode, {MO}, {DstExt});
14670b57cec5SDimitry Andric   MO.setReg(DstExt);
14680b57cec5SDimitry Andric }
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric void LegalizerHelper::narrowScalarDst(MachineInstr &MI, LLT NarrowTy,
14710b57cec5SDimitry Andric                                       unsigned OpIdx, unsigned ExtOpcode) {
14720b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14730b57cec5SDimitry Andric   Register DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
14740b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
14755ffd83dbSDimitry Andric   MIRBuilder.buildInstr(ExtOpcode, {MO}, {DstTrunc});
14760b57cec5SDimitry Andric   MO.setReg(DstTrunc);
14770b57cec5SDimitry Andric }
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorDst(MachineInstr &MI, LLT WideTy,
14800b57cec5SDimitry Andric                                             unsigned OpIdx) {
14810b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14820b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
14830eae32dcSDimitry Andric   Register Dst = MO.getReg();
14840eae32dcSDimitry Andric   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
14850eae32dcSDimitry Andric   MO.setReg(DstExt);
14860eae32dcSDimitry Andric   MIRBuilder.buildDeleteTrailingVectorElements(Dst, DstExt);
14870b57cec5SDimitry Andric }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric void LegalizerHelper::moreElementsVectorSrc(MachineInstr &MI, LLT MoreTy,
14900b57cec5SDimitry Andric                                             unsigned OpIdx) {
14910b57cec5SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
14920eae32dcSDimitry Andric   SmallVector<Register, 8> Regs;
14930eae32dcSDimitry Andric   MO.setReg(MIRBuilder.buildPadVectorWithUndefElements(MoreTy, MO).getReg(0));
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric 
14965ffd83dbSDimitry Andric void LegalizerHelper::bitcastSrc(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
14975ffd83dbSDimitry Andric   MachineOperand &Op = MI.getOperand(OpIdx);
14985ffd83dbSDimitry Andric   Op.setReg(MIRBuilder.buildBitcast(CastTy, Op).getReg(0));
14995ffd83dbSDimitry Andric }
15005ffd83dbSDimitry Andric 
15015ffd83dbSDimitry Andric void LegalizerHelper::bitcastDst(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
15025ffd83dbSDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
15035ffd83dbSDimitry Andric   Register CastDst = MRI.createGenericVirtualRegister(CastTy);
15045ffd83dbSDimitry Andric   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
15055ffd83dbSDimitry Andric   MIRBuilder.buildBitcast(MO, CastDst);
15065ffd83dbSDimitry Andric   MO.setReg(CastDst);
15075ffd83dbSDimitry Andric }
15085ffd83dbSDimitry Andric 
15090b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
15100b57cec5SDimitry Andric LegalizerHelper::widenScalarMergeValues(MachineInstr &MI, unsigned TypeIdx,
15110b57cec5SDimitry Andric                                         LLT WideTy) {
15120b57cec5SDimitry Andric   if (TypeIdx != 1)
15130b57cec5SDimitry Andric     return UnableToLegalize;
15140b57cec5SDimitry Andric 
1515*06c3fb27SDimitry Andric   auto [DstReg, DstTy, Src1Reg, Src1Ty] = MI.getFirst2RegLLTs();
15160b57cec5SDimitry Andric   if (DstTy.isVector())
15170b57cec5SDimitry Andric     return UnableToLegalize;
15180b57cec5SDimitry Andric 
1519*06c3fb27SDimitry Andric   LLT SrcTy = MRI.getType(Src1Reg);
15200b57cec5SDimitry Andric   const int DstSize = DstTy.getSizeInBits();
15210b57cec5SDimitry Andric   const int SrcSize = SrcTy.getSizeInBits();
15220b57cec5SDimitry Andric   const int WideSize = WideTy.getSizeInBits();
15230b57cec5SDimitry Andric   const int NumMerge = (DstSize + WideSize - 1) / WideSize;
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   unsigned NumOps = MI.getNumOperands();
15260b57cec5SDimitry Andric   unsigned NumSrc = MI.getNumOperands() - 1;
15270b57cec5SDimitry Andric   unsigned PartSize = DstTy.getSizeInBits() / NumSrc;
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric   if (WideSize >= DstSize) {
15300b57cec5SDimitry Andric     // Directly pack the bits in the target type.
1531*06c3fb27SDimitry Andric     Register ResultReg = MIRBuilder.buildZExt(WideTy, Src1Reg).getReg(0);
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric     for (unsigned I = 2; I != NumOps; ++I) {
15340b57cec5SDimitry Andric       const unsigned Offset = (I - 1) * PartSize;
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric       Register SrcReg = MI.getOperand(I).getReg();
15370b57cec5SDimitry Andric       assert(MRI.getType(SrcReg) == LLT::scalar(PartSize));
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric       auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
15400b57cec5SDimitry Andric 
15418bcb0991SDimitry Andric       Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
15420b57cec5SDimitry Andric         MRI.createGenericVirtualRegister(WideTy);
15430b57cec5SDimitry Andric 
15440b57cec5SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
15450b57cec5SDimitry Andric       auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
15460b57cec5SDimitry Andric       MIRBuilder.buildOr(NextResult, ResultReg, Shl);
15470b57cec5SDimitry Andric       ResultReg = NextResult;
15480b57cec5SDimitry Andric     }
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric     if (WideSize > DstSize)
15510b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg, ResultReg);
15528bcb0991SDimitry Andric     else if (DstTy.isPointer())
15538bcb0991SDimitry Andric       MIRBuilder.buildIntToPtr(DstReg, ResultReg);
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric     MI.eraseFromParent();
15560b57cec5SDimitry Andric     return Legalized;
15570b57cec5SDimitry Andric   }
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric   // Unmerge the original values to the GCD type, and recombine to the next
15600b57cec5SDimitry Andric   // multiple greater than the original type.
15610b57cec5SDimitry Andric   //
15620b57cec5SDimitry Andric   // %3:_(s12) = G_MERGE_VALUES %0:_(s4), %1:_(s4), %2:_(s4) -> s6
15630b57cec5SDimitry Andric   // %4:_(s2), %5:_(s2) = G_UNMERGE_VALUES %0
15640b57cec5SDimitry Andric   // %6:_(s2), %7:_(s2) = G_UNMERGE_VALUES %1
15650b57cec5SDimitry Andric   // %8:_(s2), %9:_(s2) = G_UNMERGE_VALUES %2
15660b57cec5SDimitry Andric   // %10:_(s6) = G_MERGE_VALUES %4, %5, %6
15670b57cec5SDimitry Andric   // %11:_(s6) = G_MERGE_VALUES %7, %8, %9
15680b57cec5SDimitry Andric   // %12:_(s12) = G_MERGE_VALUES %10, %11
15690b57cec5SDimitry Andric   //
15700b57cec5SDimitry Andric   // Padding with undef if necessary:
15710b57cec5SDimitry Andric   //
15720b57cec5SDimitry Andric   // %2:_(s8) = G_MERGE_VALUES %0:_(s4), %1:_(s4) -> s6
15730b57cec5SDimitry Andric   // %3:_(s2), %4:_(s2) = G_UNMERGE_VALUES %0
15740b57cec5SDimitry Andric   // %5:_(s2), %6:_(s2) = G_UNMERGE_VALUES %1
15750b57cec5SDimitry Andric   // %7:_(s2) = G_IMPLICIT_DEF
15760b57cec5SDimitry Andric   // %8:_(s6) = G_MERGE_VALUES %3, %4, %5
15770b57cec5SDimitry Andric   // %9:_(s6) = G_MERGE_VALUES %6, %7, %7
15780b57cec5SDimitry Andric   // %10:_(s12) = G_MERGE_VALUES %8, %9
15790b57cec5SDimitry Andric 
1580bdd1243dSDimitry Andric   const int GCD = std::gcd(SrcSize, WideSize);
15810b57cec5SDimitry Andric   LLT GCDTy = LLT::scalar(GCD);
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   SmallVector<Register, 8> Parts;
15840b57cec5SDimitry Andric   SmallVector<Register, 8> NewMergeRegs;
15850b57cec5SDimitry Andric   SmallVector<Register, 8> Unmerges;
15860b57cec5SDimitry Andric   LLT WideDstTy = LLT::scalar(NumMerge * WideSize);
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   // Decompose the original operands if they don't evenly divide.
15894824e7fdSDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
15904824e7fdSDimitry Andric     Register SrcReg = MO.getReg();
15910b57cec5SDimitry Andric     if (GCD == SrcSize) {
15920b57cec5SDimitry Andric       Unmerges.push_back(SrcReg);
15930b57cec5SDimitry Andric     } else {
15940b57cec5SDimitry Andric       auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
15950b57cec5SDimitry Andric       for (int J = 0, JE = Unmerge->getNumOperands() - 1; J != JE; ++J)
15960b57cec5SDimitry Andric         Unmerges.push_back(Unmerge.getReg(J));
15970b57cec5SDimitry Andric     }
15980b57cec5SDimitry Andric   }
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric   // Pad with undef to the next size that is a multiple of the requested size.
16010b57cec5SDimitry Andric   if (static_cast<int>(Unmerges.size()) != NumMerge * WideSize) {
16020b57cec5SDimitry Andric     Register UndefReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
16030b57cec5SDimitry Andric     for (int I = Unmerges.size(); I != NumMerge * WideSize; ++I)
16040b57cec5SDimitry Andric       Unmerges.push_back(UndefReg);
16050b57cec5SDimitry Andric   }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric   const int PartsPerGCD = WideSize / GCD;
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric   // Build merges of each piece.
16100b57cec5SDimitry Andric   ArrayRef<Register> Slicer(Unmerges);
16110b57cec5SDimitry Andric   for (int I = 0; I != NumMerge; ++I, Slicer = Slicer.drop_front(PartsPerGCD)) {
1612bdd1243dSDimitry Andric     auto Merge =
1613bdd1243dSDimitry Andric         MIRBuilder.buildMergeLikeInstr(WideTy, Slicer.take_front(PartsPerGCD));
16140b57cec5SDimitry Andric     NewMergeRegs.push_back(Merge.getReg(0));
16150b57cec5SDimitry Andric   }
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   // A truncate may be necessary if the requested type doesn't evenly divide the
16180b57cec5SDimitry Andric   // original result type.
16190b57cec5SDimitry Andric   if (DstTy.getSizeInBits() == WideDstTy.getSizeInBits()) {
1620bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(DstReg, NewMergeRegs);
16210b57cec5SDimitry Andric   } else {
1622bdd1243dSDimitry Andric     auto FinalMerge = MIRBuilder.buildMergeLikeInstr(WideDstTy, NewMergeRegs);
16230b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, FinalMerge.getReg(0));
16240b57cec5SDimitry Andric   }
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   MI.eraseFromParent();
16270b57cec5SDimitry Andric   return Legalized;
16280b57cec5SDimitry Andric }
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
16310b57cec5SDimitry Andric LegalizerHelper::widenScalarUnmergeValues(MachineInstr &MI, unsigned TypeIdx,
16320b57cec5SDimitry Andric                                           LLT WideTy) {
16330b57cec5SDimitry Andric   if (TypeIdx != 0)
16340b57cec5SDimitry Andric     return UnableToLegalize;
16350b57cec5SDimitry Andric 
16365ffd83dbSDimitry Andric   int NumDst = MI.getNumOperands() - 1;
16370b57cec5SDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
16380b57cec5SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
16395ffd83dbSDimitry Andric   if (SrcTy.isVector())
16400b57cec5SDimitry Andric     return UnableToLegalize;
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
16430b57cec5SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
16440b57cec5SDimitry Andric   if (!DstTy.isScalar())
16450b57cec5SDimitry Andric     return UnableToLegalize;
16460b57cec5SDimitry Andric 
16475ffd83dbSDimitry Andric   if (WideTy.getSizeInBits() >= SrcTy.getSizeInBits()) {
16485ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
16495ffd83dbSDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
16505ffd83dbSDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace())) {
16515ffd83dbSDimitry Andric         LLVM_DEBUG(
16525ffd83dbSDimitry Andric             dbgs() << "Not casting non-integral address space integer\n");
16535ffd83dbSDimitry Andric         return UnableToLegalize;
16540b57cec5SDimitry Andric       }
16550b57cec5SDimitry Andric 
16565ffd83dbSDimitry Andric       SrcTy = LLT::scalar(SrcTy.getSizeInBits());
16575ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildPtrToInt(SrcTy, SrcReg).getReg(0);
16585ffd83dbSDimitry Andric     }
16590b57cec5SDimitry Andric 
16605ffd83dbSDimitry Andric     // Widen SrcTy to WideTy. This does not affect the result, but since the
16615ffd83dbSDimitry Andric     // user requested this size, it is probably better handled than SrcTy and
166204eeddc0SDimitry Andric     // should reduce the total number of legalization artifacts.
16635ffd83dbSDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
16645ffd83dbSDimitry Andric       SrcTy = WideTy;
16655ffd83dbSDimitry Andric       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
16665ffd83dbSDimitry Andric     }
16670b57cec5SDimitry Andric 
16685ffd83dbSDimitry Andric     // Theres no unmerge type to target. Directly extract the bits from the
16695ffd83dbSDimitry Andric     // source type
16705ffd83dbSDimitry Andric     unsigned DstSize = DstTy.getSizeInBits();
16710b57cec5SDimitry Andric 
16725ffd83dbSDimitry Andric     MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
16735ffd83dbSDimitry Andric     for (int I = 1; I != NumDst; ++I) {
16745ffd83dbSDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcTy, DstSize * I);
16755ffd83dbSDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcTy, SrcReg, ShiftAmt);
16765ffd83dbSDimitry Andric       MIRBuilder.buildTrunc(MI.getOperand(I), Shr);
16775ffd83dbSDimitry Andric     }
16785ffd83dbSDimitry Andric 
16795ffd83dbSDimitry Andric     MI.eraseFromParent();
16805ffd83dbSDimitry Andric     return Legalized;
16815ffd83dbSDimitry Andric   }
16825ffd83dbSDimitry Andric 
16835ffd83dbSDimitry Andric   // Extend the source to a wider type.
16845ffd83dbSDimitry Andric   LLT LCMTy = getLCMType(SrcTy, WideTy);
16855ffd83dbSDimitry Andric 
16865ffd83dbSDimitry Andric   Register WideSrc = SrcReg;
16875ffd83dbSDimitry Andric   if (LCMTy.getSizeInBits() != SrcTy.getSizeInBits()) {
16885ffd83dbSDimitry Andric     // TODO: If this is an integral address space, cast to integer and anyext.
16895ffd83dbSDimitry Andric     if (SrcTy.isPointer()) {
16905ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Widening pointer source types not implemented\n");
16915ffd83dbSDimitry Andric       return UnableToLegalize;
16925ffd83dbSDimitry Andric     }
16935ffd83dbSDimitry Andric 
16945ffd83dbSDimitry Andric     WideSrc = MIRBuilder.buildAnyExt(LCMTy, WideSrc).getReg(0);
16955ffd83dbSDimitry Andric   }
16965ffd83dbSDimitry Andric 
16975ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(WideTy, WideSrc);
16985ffd83dbSDimitry Andric 
1699e8d8bef9SDimitry Andric   // Create a sequence of unmerges and merges to the original results. Since we
1700e8d8bef9SDimitry Andric   // may have widened the source, we will need to pad the results with dead defs
1701e8d8bef9SDimitry Andric   // to cover the source register.
1702e8d8bef9SDimitry Andric   // e.g. widen s48 to s64:
1703e8d8bef9SDimitry Andric   // %1:_(s48), %2:_(s48) = G_UNMERGE_VALUES %0:_(s96)
17045ffd83dbSDimitry Andric   //
17055ffd83dbSDimitry Andric   // =>
1706e8d8bef9SDimitry Andric   //  %4:_(s192) = G_ANYEXT %0:_(s96)
1707e8d8bef9SDimitry Andric   //  %5:_(s64), %6, %7 = G_UNMERGE_VALUES %4 ; Requested unmerge
1708e8d8bef9SDimitry Andric   //  ; unpack to GCD type, with extra dead defs
1709e8d8bef9SDimitry Andric   //  %8:_(s16), %9, %10, %11 = G_UNMERGE_VALUES %5:_(s64)
1710e8d8bef9SDimitry Andric   //  %12:_(s16), %13, dead %14, dead %15 = G_UNMERGE_VALUES %6:_(s64)
1711e8d8bef9SDimitry Andric   //  dead %16:_(s16), dead %17, dead %18, dead %18 = G_UNMERGE_VALUES %7:_(s64)
1712e8d8bef9SDimitry Andric   //  %1:_(s48) = G_MERGE_VALUES %8:_(s16), %9, %10   ; Remerge to destination
1713e8d8bef9SDimitry Andric   //  %2:_(s48) = G_MERGE_VALUES %11:_(s16), %12, %13 ; Remerge to destination
1714e8d8bef9SDimitry Andric   const LLT GCDTy = getGCDType(WideTy, DstTy);
17155ffd83dbSDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
1716e8d8bef9SDimitry Andric   const int PartsPerRemerge = DstTy.getSizeInBits() / GCDTy.getSizeInBits();
1717e8d8bef9SDimitry Andric 
1718e8d8bef9SDimitry Andric   // Directly unmerge to the destination without going through a GCD type
1719e8d8bef9SDimitry Andric   // if possible
1720e8d8bef9SDimitry Andric   if (PartsPerRemerge == 1) {
17215ffd83dbSDimitry Andric     const int PartsPerUnmerge = WideTy.getSizeInBits() / DstTy.getSizeInBits();
17225ffd83dbSDimitry Andric 
17235ffd83dbSDimitry Andric     for (int I = 0; I != NumUnmerge; ++I) {
17245ffd83dbSDimitry Andric       auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
17255ffd83dbSDimitry Andric 
17265ffd83dbSDimitry Andric       for (int J = 0; J != PartsPerUnmerge; ++J) {
17275ffd83dbSDimitry Andric         int Idx = I * PartsPerUnmerge + J;
17285ffd83dbSDimitry Andric         if (Idx < NumDst)
17295ffd83dbSDimitry Andric           MIB.addDef(MI.getOperand(Idx).getReg());
17305ffd83dbSDimitry Andric         else {
17315ffd83dbSDimitry Andric           // Create dead def for excess components.
17325ffd83dbSDimitry Andric           MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
17335ffd83dbSDimitry Andric         }
17345ffd83dbSDimitry Andric       }
17355ffd83dbSDimitry Andric 
17365ffd83dbSDimitry Andric       MIB.addUse(Unmerge.getReg(I));
17375ffd83dbSDimitry Andric     }
1738e8d8bef9SDimitry Andric   } else {
1739e8d8bef9SDimitry Andric     SmallVector<Register, 16> Parts;
1740e8d8bef9SDimitry Andric     for (int J = 0; J != NumUnmerge; ++J)
1741e8d8bef9SDimitry Andric       extractGCDType(Parts, GCDTy, Unmerge.getReg(J));
1742e8d8bef9SDimitry Andric 
1743e8d8bef9SDimitry Andric     SmallVector<Register, 8> RemergeParts;
1744e8d8bef9SDimitry Andric     for (int I = 0; I != NumDst; ++I) {
1745e8d8bef9SDimitry Andric       for (int J = 0; J < PartsPerRemerge; ++J) {
1746e8d8bef9SDimitry Andric         const int Idx = I * PartsPerRemerge + J;
1747e8d8bef9SDimitry Andric         RemergeParts.emplace_back(Parts[Idx]);
1748e8d8bef9SDimitry Andric       }
1749e8d8bef9SDimitry Andric 
1750bdd1243dSDimitry Andric       MIRBuilder.buildMergeLikeInstr(MI.getOperand(I).getReg(), RemergeParts);
1751e8d8bef9SDimitry Andric       RemergeParts.clear();
1752e8d8bef9SDimitry Andric     }
1753e8d8bef9SDimitry Andric   }
17545ffd83dbSDimitry Andric 
17555ffd83dbSDimitry Andric   MI.eraseFromParent();
17560b57cec5SDimitry Andric   return Legalized;
17570b57cec5SDimitry Andric }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
17600b57cec5SDimitry Andric LegalizerHelper::widenScalarExtract(MachineInstr &MI, unsigned TypeIdx,
17610b57cec5SDimitry Andric                                     LLT WideTy) {
1762*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
17630b57cec5SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   if (TypeIdx == 0) {
17660b57cec5SDimitry Andric     if (SrcTy.isVector() || DstTy.isVector())
17670b57cec5SDimitry Andric       return UnableToLegalize;
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric     SrcOp Src(SrcReg);
17700b57cec5SDimitry Andric     if (SrcTy.isPointer()) {
17710b57cec5SDimitry Andric       // Extracts from pointers can be handled only if they are really just
17720b57cec5SDimitry Andric       // simple integers.
17730b57cec5SDimitry Andric       const DataLayout &DL = MIRBuilder.getDataLayout();
17740b57cec5SDimitry Andric       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace()))
17750b57cec5SDimitry Andric         return UnableToLegalize;
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric       LLT SrcAsIntTy = LLT::scalar(SrcTy.getSizeInBits());
17780b57cec5SDimitry Andric       Src = MIRBuilder.buildPtrToInt(SrcAsIntTy, Src);
17790b57cec5SDimitry Andric       SrcTy = SrcAsIntTy;
17800b57cec5SDimitry Andric     }
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric     if (DstTy.isPointer())
17830b57cec5SDimitry Andric       return UnableToLegalize;
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric     if (Offset == 0) {
17860b57cec5SDimitry Andric       // Avoid a shift in the degenerate case.
17870b57cec5SDimitry Andric       MIRBuilder.buildTrunc(DstReg,
17880b57cec5SDimitry Andric                             MIRBuilder.buildAnyExtOrTrunc(WideTy, Src));
17890b57cec5SDimitry Andric       MI.eraseFromParent();
17900b57cec5SDimitry Andric       return Legalized;
17910b57cec5SDimitry Andric     }
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric     // Do a shift in the source type.
17940b57cec5SDimitry Andric     LLT ShiftTy = SrcTy;
17950b57cec5SDimitry Andric     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
17960b57cec5SDimitry Andric       Src = MIRBuilder.buildAnyExt(WideTy, Src);
17970b57cec5SDimitry Andric       ShiftTy = WideTy;
1798e8d8bef9SDimitry Andric     }
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric     auto LShr = MIRBuilder.buildLShr(
18010b57cec5SDimitry Andric       ShiftTy, Src, MIRBuilder.buildConstant(ShiftTy, Offset));
18020b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, LShr);
18030b57cec5SDimitry Andric     MI.eraseFromParent();
18040b57cec5SDimitry Andric     return Legalized;
18050b57cec5SDimitry Andric   }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   if (SrcTy.isScalar()) {
18080b57cec5SDimitry Andric     Observer.changingInstr(MI);
18090b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
18100b57cec5SDimitry Andric     Observer.changedInstr(MI);
18110b57cec5SDimitry Andric     return Legalized;
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   if (!SrcTy.isVector())
18150b57cec5SDimitry Andric     return UnableToLegalize;
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric   if (DstTy != SrcTy.getElementType())
18180b57cec5SDimitry Andric     return UnableToLegalize;
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   if (Offset % SrcTy.getScalarSizeInBits() != 0)
18210b57cec5SDimitry Andric     return UnableToLegalize;
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   Observer.changingInstr(MI);
18240b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
18250b57cec5SDimitry Andric 
18260b57cec5SDimitry Andric   MI.getOperand(2).setImm((WideTy.getSizeInBits() / SrcTy.getSizeInBits()) *
18270b57cec5SDimitry Andric                           Offset);
18280b57cec5SDimitry Andric   widenScalarDst(MI, WideTy.getScalarType(), 0);
18290b57cec5SDimitry Andric   Observer.changedInstr(MI);
18300b57cec5SDimitry Andric   return Legalized;
18310b57cec5SDimitry Andric }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
18340b57cec5SDimitry Andric LegalizerHelper::widenScalarInsert(MachineInstr &MI, unsigned TypeIdx,
18350b57cec5SDimitry Andric                                    LLT WideTy) {
1836e8d8bef9SDimitry Andric   if (TypeIdx != 0 || WideTy.isVector())
18370b57cec5SDimitry Andric     return UnableToLegalize;
18380b57cec5SDimitry Andric   Observer.changingInstr(MI);
18390b57cec5SDimitry Andric   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
18400b57cec5SDimitry Andric   widenScalarDst(MI, WideTy);
18410b57cec5SDimitry Andric   Observer.changedInstr(MI);
18420b57cec5SDimitry Andric   return Legalized;
18430b57cec5SDimitry Andric }
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
1846fe6060f1SDimitry Andric LegalizerHelper::widenScalarAddSubOverflow(MachineInstr &MI, unsigned TypeIdx,
1847e8d8bef9SDimitry Andric                                            LLT WideTy) {
1848fe6060f1SDimitry Andric   unsigned Opcode;
1849fe6060f1SDimitry Andric   unsigned ExtOpcode;
1850bdd1243dSDimitry Andric   std::optional<Register> CarryIn;
1851fe6060f1SDimitry Andric   switch (MI.getOpcode()) {
1852fe6060f1SDimitry Andric   default:
1853fe6060f1SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1854fe6060f1SDimitry Andric   case TargetOpcode::G_SADDO:
1855fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_ADD;
1856fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1857fe6060f1SDimitry Andric     break;
1858fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBO:
1859fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_SUB;
1860fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1861fe6060f1SDimitry Andric     break;
1862fe6060f1SDimitry Andric   case TargetOpcode::G_UADDO:
1863fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_ADD;
1864fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1865fe6060f1SDimitry Andric     break;
1866fe6060f1SDimitry Andric   case TargetOpcode::G_USUBO:
1867fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_SUB;
1868fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1869fe6060f1SDimitry Andric     break;
1870fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
1871fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_UADDE;
1872fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1873fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1874fe6060f1SDimitry Andric     break;
1875fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
1876fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_USUBE;
1877fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_SEXT;
1878fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1879fe6060f1SDimitry Andric     break;
1880fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
1881fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_UADDE;
1882fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1883fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1884fe6060f1SDimitry Andric     break;
1885fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
1886fe6060f1SDimitry Andric     Opcode = TargetOpcode::G_USUBE;
1887fe6060f1SDimitry Andric     ExtOpcode = TargetOpcode::G_ZEXT;
1888fe6060f1SDimitry Andric     CarryIn = MI.getOperand(4).getReg();
1889fe6060f1SDimitry Andric     break;
1890fe6060f1SDimitry Andric   }
1891fe6060f1SDimitry Andric 
189281ad6265SDimitry Andric   if (TypeIdx == 1) {
189381ad6265SDimitry Andric     unsigned BoolExtOp = MIRBuilder.getBoolExtOp(WideTy.isVector(), false);
189481ad6265SDimitry Andric 
189581ad6265SDimitry Andric     Observer.changingInstr(MI);
189681ad6265SDimitry Andric     if (CarryIn)
189781ad6265SDimitry Andric       widenScalarSrc(MI, WideTy, 4, BoolExtOp);
1898bdd1243dSDimitry Andric     widenScalarDst(MI, WideTy, 1);
189981ad6265SDimitry Andric 
190081ad6265SDimitry Andric     Observer.changedInstr(MI);
190181ad6265SDimitry Andric     return Legalized;
190281ad6265SDimitry Andric   }
190381ad6265SDimitry Andric 
1904e8d8bef9SDimitry Andric   auto LHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(2)});
1905e8d8bef9SDimitry Andric   auto RHSExt = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MI.getOperand(3)});
1906e8d8bef9SDimitry Andric   // Do the arithmetic in the larger type.
1907fe6060f1SDimitry Andric   Register NewOp;
1908fe6060f1SDimitry Andric   if (CarryIn) {
1909fe6060f1SDimitry Andric     LLT CarryOutTy = MRI.getType(MI.getOperand(1).getReg());
1910fe6060f1SDimitry Andric     NewOp = MIRBuilder
1911fe6060f1SDimitry Andric                 .buildInstr(Opcode, {WideTy, CarryOutTy},
1912fe6060f1SDimitry Andric                             {LHSExt, RHSExt, *CarryIn})
1913fe6060f1SDimitry Andric                 .getReg(0);
1914fe6060f1SDimitry Andric   } else {
1915fe6060f1SDimitry Andric     NewOp = MIRBuilder.buildInstr(Opcode, {WideTy}, {LHSExt, RHSExt}).getReg(0);
1916fe6060f1SDimitry Andric   }
1917e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(MI.getOperand(0).getReg());
1918e8d8bef9SDimitry Andric   auto TruncOp = MIRBuilder.buildTrunc(OrigTy, NewOp);
1919e8d8bef9SDimitry Andric   auto ExtOp = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {TruncOp});
1920e8d8bef9SDimitry Andric   // There is no overflow if the ExtOp is the same as NewOp.
1921e8d8bef9SDimitry Andric   MIRBuilder.buildICmp(CmpInst::ICMP_NE, MI.getOperand(1), NewOp, ExtOp);
1922e8d8bef9SDimitry Andric   // Now trunc the NewOp to the original result.
1923e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(MI.getOperand(0), NewOp);
1924e8d8bef9SDimitry Andric   MI.eraseFromParent();
1925e8d8bef9SDimitry Andric   return Legalized;
1926e8d8bef9SDimitry Andric }
1927e8d8bef9SDimitry Andric 
1928e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
1929e8d8bef9SDimitry Andric LegalizerHelper::widenScalarAddSubShlSat(MachineInstr &MI, unsigned TypeIdx,
19305ffd83dbSDimitry Andric                                          LLT WideTy) {
19315ffd83dbSDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SADDSAT ||
1932e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSUBSAT ||
1933e8d8bef9SDimitry Andric                   MI.getOpcode() == TargetOpcode::G_SSHLSAT;
1934e8d8bef9SDimitry Andric   bool IsShift = MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
1935e8d8bef9SDimitry Andric                  MI.getOpcode() == TargetOpcode::G_USHLSAT;
19365ffd83dbSDimitry Andric   // We can convert this to:
19375ffd83dbSDimitry Andric   //   1. Any extend iN to iM
19385ffd83dbSDimitry Andric   //   2. SHL by M-N
1939e8d8bef9SDimitry Andric   //   3. [US][ADD|SUB|SHL]SAT
19405ffd83dbSDimitry Andric   //   4. L/ASHR by M-N
19415ffd83dbSDimitry Andric   //
19425ffd83dbSDimitry Andric   // It may be more efficient to lower this to a min and a max operation in
19435ffd83dbSDimitry Andric   // the higher precision arithmetic if the promoted operation isn't legal,
19445ffd83dbSDimitry Andric   // but this decision is up to the target's lowering request.
19455ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
19460b57cec5SDimitry Andric 
19475ffd83dbSDimitry Andric   unsigned NewBits = WideTy.getScalarSizeInBits();
19485ffd83dbSDimitry Andric   unsigned SHLAmount = NewBits - MRI.getType(DstReg).getScalarSizeInBits();
19495ffd83dbSDimitry Andric 
1950e8d8bef9SDimitry Andric   // Shifts must zero-extend the RHS to preserve the unsigned quantity, and
1951e8d8bef9SDimitry Andric   // must not left shift the RHS to preserve the shift amount.
19525ffd83dbSDimitry Andric   auto LHS = MIRBuilder.buildAnyExt(WideTy, MI.getOperand(1));
1953e8d8bef9SDimitry Andric   auto RHS = IsShift ? MIRBuilder.buildZExt(WideTy, MI.getOperand(2))
1954e8d8bef9SDimitry Andric                      : MIRBuilder.buildAnyExt(WideTy, MI.getOperand(2));
19555ffd83dbSDimitry Andric   auto ShiftK = MIRBuilder.buildConstant(WideTy, SHLAmount);
19565ffd83dbSDimitry Andric   auto ShiftL = MIRBuilder.buildShl(WideTy, LHS, ShiftK);
1957e8d8bef9SDimitry Andric   auto ShiftR = IsShift ? RHS : MIRBuilder.buildShl(WideTy, RHS, ShiftK);
19585ffd83dbSDimitry Andric 
19595ffd83dbSDimitry Andric   auto WideInst = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy},
19605ffd83dbSDimitry Andric                                         {ShiftL, ShiftR}, MI.getFlags());
19615ffd83dbSDimitry Andric 
19625ffd83dbSDimitry Andric   // Use a shift that will preserve the number of sign bits when the trunc is
19635ffd83dbSDimitry Andric   // folded away.
19645ffd83dbSDimitry Andric   auto Result = IsSigned ? MIRBuilder.buildAShr(WideTy, WideInst, ShiftK)
19655ffd83dbSDimitry Andric                          : MIRBuilder.buildLShr(WideTy, WideInst, ShiftK);
19665ffd83dbSDimitry Andric 
19675ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(DstReg, Result);
19685ffd83dbSDimitry Andric   MI.eraseFromParent();
19695ffd83dbSDimitry Andric   return Legalized;
19705ffd83dbSDimitry Andric }
19715ffd83dbSDimitry Andric 
19725ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
1973fe6060f1SDimitry Andric LegalizerHelper::widenScalarMulo(MachineInstr &MI, unsigned TypeIdx,
1974fe6060f1SDimitry Andric                                  LLT WideTy) {
197581ad6265SDimitry Andric   if (TypeIdx == 1) {
197681ad6265SDimitry Andric     Observer.changingInstr(MI);
197781ad6265SDimitry Andric     widenScalarDst(MI, WideTy, 1);
197881ad6265SDimitry Andric     Observer.changedInstr(MI);
197981ad6265SDimitry Andric     return Legalized;
198081ad6265SDimitry Andric   }
1981fe6060f1SDimitry Andric 
1982fe6060f1SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SMULO;
1983*06c3fb27SDimitry Andric   auto [Result, OriginalOverflow, LHS, RHS] = MI.getFirst4Regs();
1984fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(LHS);
1985fe6060f1SDimitry Andric   LLT OverflowTy = MRI.getType(OriginalOverflow);
1986fe6060f1SDimitry Andric   unsigned SrcBitWidth = SrcTy.getScalarSizeInBits();
1987fe6060f1SDimitry Andric 
1988fe6060f1SDimitry Andric   // To determine if the result overflowed in the larger type, we extend the
1989fe6060f1SDimitry Andric   // input to the larger type, do the multiply (checking if it overflows),
1990fe6060f1SDimitry Andric   // then also check the high bits of the result to see if overflow happened
1991fe6060f1SDimitry Andric   // there.
1992fe6060f1SDimitry Andric   unsigned ExtOp = IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
1993fe6060f1SDimitry Andric   auto LeftOperand = MIRBuilder.buildInstr(ExtOp, {WideTy}, {LHS});
1994fe6060f1SDimitry Andric   auto RightOperand = MIRBuilder.buildInstr(ExtOp, {WideTy}, {RHS});
1995fe6060f1SDimitry Andric 
1996fe6060f1SDimitry Andric   auto Mulo = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy, OverflowTy},
1997fe6060f1SDimitry Andric                                     {LeftOperand, RightOperand});
1998fe6060f1SDimitry Andric   auto Mul = Mulo->getOperand(0);
1999fe6060f1SDimitry Andric   MIRBuilder.buildTrunc(Result, Mul);
2000fe6060f1SDimitry Andric 
2001fe6060f1SDimitry Andric   MachineInstrBuilder ExtResult;
2002fe6060f1SDimitry Andric   // Overflow occurred if it occurred in the larger type, or if the high part
2003fe6060f1SDimitry Andric   // of the result does not zero/sign-extend the low part.  Check this second
2004fe6060f1SDimitry Andric   // possibility first.
2005fe6060f1SDimitry Andric   if (IsSigned) {
2006fe6060f1SDimitry Andric     // For signed, overflow occurred when the high part does not sign-extend
2007fe6060f1SDimitry Andric     // the low part.
2008fe6060f1SDimitry Andric     ExtResult = MIRBuilder.buildSExtInReg(WideTy, Mul, SrcBitWidth);
2009fe6060f1SDimitry Andric   } else {
2010fe6060f1SDimitry Andric     // Unsigned overflow occurred when the high part does not zero-extend the
2011fe6060f1SDimitry Andric     // low part.
2012fe6060f1SDimitry Andric     ExtResult = MIRBuilder.buildZExtInReg(WideTy, Mul, SrcBitWidth);
2013fe6060f1SDimitry Andric   }
2014fe6060f1SDimitry Andric 
2015fe6060f1SDimitry Andric   // Multiplication cannot overflow if the WideTy is >= 2 * original width,
2016fe6060f1SDimitry Andric   // so we don't need to check the overflow result of larger type Mulo.
2017fe6060f1SDimitry Andric   if (WideTy.getScalarSizeInBits() < 2 * SrcBitWidth) {
2018fe6060f1SDimitry Andric     auto Overflow =
2019fe6060f1SDimitry Andric         MIRBuilder.buildICmp(CmpInst::ICMP_NE, OverflowTy, Mul, ExtResult);
2020fe6060f1SDimitry Andric     // Finally check if the multiplication in the larger type itself overflowed.
2021fe6060f1SDimitry Andric     MIRBuilder.buildOr(OriginalOverflow, Mulo->getOperand(1), Overflow);
2022fe6060f1SDimitry Andric   } else {
2023fe6060f1SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_NE, OriginalOverflow, Mul, ExtResult);
2024fe6060f1SDimitry Andric   }
2025fe6060f1SDimitry Andric   MI.eraseFromParent();
2026fe6060f1SDimitry Andric   return Legalized;
2027fe6060f1SDimitry Andric }
2028fe6060f1SDimitry Andric 
2029fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
20305ffd83dbSDimitry Andric LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
20310b57cec5SDimitry Andric   switch (MI.getOpcode()) {
20320b57cec5SDimitry Andric   default:
20330b57cec5SDimitry Andric     return UnableToLegalize;
2034fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_XCHG:
2035fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_ADD:
2036fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_SUB:
2037fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_AND:
2038fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_OR:
2039fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_XOR:
2040fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_MIN:
2041fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_MAX:
2042fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_UMIN:
2043fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMICRMW_UMAX:
2044fe6060f1SDimitry Andric     assert(TypeIdx == 0 && "atomicrmw with second scalar type");
2045fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2046fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2047fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 0);
2048fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2049fe6060f1SDimitry Andric     return Legalized;
2050fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG:
2051fe6060f1SDimitry Andric     assert(TypeIdx == 0 && "G_ATOMIC_CMPXCHG with second scalar type");
2052fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2053fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2054fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
2055fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 0);
2056fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2057fe6060f1SDimitry Andric     return Legalized;
2058fe6060f1SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS:
2059fe6060f1SDimitry Andric     if (TypeIdx == 0) {
2060fe6060f1SDimitry Andric       Observer.changingInstr(MI);
2061fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
2062fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 4, TargetOpcode::G_ANYEXT);
2063fe6060f1SDimitry Andric       widenScalarDst(MI, WideTy, 0);
2064fe6060f1SDimitry Andric       Observer.changedInstr(MI);
2065fe6060f1SDimitry Andric       return Legalized;
2066fe6060f1SDimitry Andric     }
2067fe6060f1SDimitry Andric     assert(TypeIdx == 1 &&
2068fe6060f1SDimitry Andric            "G_ATOMIC_CMPXCHG_WITH_SUCCESS with third scalar type");
2069fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2070fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 1);
2071fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2072fe6060f1SDimitry Andric     return Legalized;
20730b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
20740b57cec5SDimitry Andric     return widenScalarExtract(MI, TypeIdx, WideTy);
20750b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
20760b57cec5SDimitry Andric     return widenScalarInsert(MI, TypeIdx, WideTy);
20770b57cec5SDimitry Andric   case TargetOpcode::G_MERGE_VALUES:
20780b57cec5SDimitry Andric     return widenScalarMergeValues(MI, TypeIdx, WideTy);
20790b57cec5SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES:
20800b57cec5SDimitry Andric     return widenScalarUnmergeValues(MI, TypeIdx, WideTy);
2081e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
2082e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
20830b57cec5SDimitry Andric   case TargetOpcode::G_UADDO:
2084e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBO:
2085fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
2086fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
2087fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
2088fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
2089fe6060f1SDimitry Andric     return widenScalarAddSubOverflow(MI, TypeIdx, WideTy);
2090fe6060f1SDimitry Andric   case TargetOpcode::G_UMULO:
2091fe6060f1SDimitry Andric   case TargetOpcode::G_SMULO:
2092fe6060f1SDimitry Andric     return widenScalarMulo(MI, TypeIdx, WideTy);
20935ffd83dbSDimitry Andric   case TargetOpcode::G_SADDSAT:
20945ffd83dbSDimitry Andric   case TargetOpcode::G_SSUBSAT:
2095e8d8bef9SDimitry Andric   case TargetOpcode::G_SSHLSAT:
20965ffd83dbSDimitry Andric   case TargetOpcode::G_UADDSAT:
20975ffd83dbSDimitry Andric   case TargetOpcode::G_USUBSAT:
2098e8d8bef9SDimitry Andric   case TargetOpcode::G_USHLSAT:
2099e8d8bef9SDimitry Andric     return widenScalarAddSubShlSat(MI, TypeIdx, WideTy);
21000b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
21010b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
21020b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
21030b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
21040b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP: {
21050b57cec5SDimitry Andric     if (TypeIdx == 0) {
21060b57cec5SDimitry Andric       Observer.changingInstr(MI);
21070b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
21080b57cec5SDimitry Andric       Observer.changedInstr(MI);
21090b57cec5SDimitry Andric       return Legalized;
21100b57cec5SDimitry Andric     }
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
21130b57cec5SDimitry Andric 
2114349cc55cSDimitry Andric     // First extend the input.
2115349cc55cSDimitry Andric     unsigned ExtOpc = MI.getOpcode() == TargetOpcode::G_CTTZ ||
2116349cc55cSDimitry Andric                               MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF
2117349cc55cSDimitry Andric                           ? TargetOpcode::G_ANYEXT
2118349cc55cSDimitry Andric                           : TargetOpcode::G_ZEXT;
2119349cc55cSDimitry Andric     auto MIBSrc = MIRBuilder.buildInstr(ExtOpc, {WideTy}, {SrcReg});
21200b57cec5SDimitry Andric     LLT CurTy = MRI.getType(SrcReg);
2121349cc55cSDimitry Andric     unsigned NewOpc = MI.getOpcode();
2122349cc55cSDimitry Andric     if (NewOpc == TargetOpcode::G_CTTZ) {
21230b57cec5SDimitry Andric       // The count is the same in the larger type except if the original
21240b57cec5SDimitry Andric       // value was zero.  This can be handled by setting the bit just off
21250b57cec5SDimitry Andric       // the top of the original type.
21260b57cec5SDimitry Andric       auto TopBit =
21270b57cec5SDimitry Andric           APInt::getOneBitSet(WideTy.getSizeInBits(), CurTy.getSizeInBits());
21280b57cec5SDimitry Andric       MIBSrc = MIRBuilder.buildOr(
21290b57cec5SDimitry Andric         WideTy, MIBSrc, MIRBuilder.buildConstant(WideTy, TopBit));
2130349cc55cSDimitry Andric       // Now we know the operand is non-zero, use the more relaxed opcode.
2131349cc55cSDimitry Andric       NewOpc = TargetOpcode::G_CTTZ_ZERO_UNDEF;
21320b57cec5SDimitry Andric     }
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric     // Perform the operation at the larger size.
2135349cc55cSDimitry Andric     auto MIBNewOp = MIRBuilder.buildInstr(NewOpc, {WideTy}, {MIBSrc});
21360b57cec5SDimitry Andric     // This is already the correct result for CTPOP and CTTZs
21370b57cec5SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_CTLZ ||
21380b57cec5SDimitry Andric         MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF) {
21390b57cec5SDimitry Andric       // The correct result is NewOp - (Difference in widety and current ty).
21400b57cec5SDimitry Andric       unsigned SizeDiff = WideTy.getSizeInBits() - CurTy.getSizeInBits();
21415ffd83dbSDimitry Andric       MIBNewOp = MIRBuilder.buildSub(
21425ffd83dbSDimitry Andric           WideTy, MIBNewOp, MIRBuilder.buildConstant(WideTy, SizeDiff));
21430b57cec5SDimitry Andric     }
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric     MIRBuilder.buildZExtOrTrunc(MI.getOperand(0), MIBNewOp);
21460b57cec5SDimitry Andric     MI.eraseFromParent();
21470b57cec5SDimitry Andric     return Legalized;
21480b57cec5SDimitry Andric   }
21490b57cec5SDimitry Andric   case TargetOpcode::G_BSWAP: {
21500b57cec5SDimitry Andric     Observer.changingInstr(MI);
21510b57cec5SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric     Register ShrReg = MRI.createGenericVirtualRegister(WideTy);
21540b57cec5SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
21550b57cec5SDimitry Andric     Register ShiftAmtReg = MRI.createGenericVirtualRegister(WideTy);
21560b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21570b57cec5SDimitry Andric 
21580b57cec5SDimitry Andric     MI.getOperand(0).setReg(DstExt);
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric     LLT Ty = MRI.getType(DstReg);
21630b57cec5SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
21640b57cec5SDimitry Andric     MIRBuilder.buildConstant(ShiftAmtReg, DiffBits);
21655ffd83dbSDimitry Andric     MIRBuilder.buildLShr(ShrReg, DstExt, ShiftAmtReg);
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric     MIRBuilder.buildTrunc(DstReg, ShrReg);
21680b57cec5SDimitry Andric     Observer.changedInstr(MI);
21690b57cec5SDimitry Andric     return Legalized;
21700b57cec5SDimitry Andric   }
21718bcb0991SDimitry Andric   case TargetOpcode::G_BITREVERSE: {
21728bcb0991SDimitry Andric     Observer.changingInstr(MI);
21738bcb0991SDimitry Andric 
21748bcb0991SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
21758bcb0991SDimitry Andric     LLT Ty = MRI.getType(DstReg);
21768bcb0991SDimitry Andric     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
21778bcb0991SDimitry Andric 
21788bcb0991SDimitry Andric     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
21798bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21808bcb0991SDimitry Andric     MI.getOperand(0).setReg(DstExt);
21818bcb0991SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
21828bcb0991SDimitry Andric 
21838bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, DiffBits);
21848bcb0991SDimitry Andric     auto Shift = MIRBuilder.buildLShr(WideTy, DstExt, ShiftAmt);
21858bcb0991SDimitry Andric     MIRBuilder.buildTrunc(DstReg, Shift);
21868bcb0991SDimitry Andric     Observer.changedInstr(MI);
21878bcb0991SDimitry Andric     return Legalized;
21888bcb0991SDimitry Andric   }
21895ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
21905ffd83dbSDimitry Andric     Observer.changingInstr(MI);
21915ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
21925ffd83dbSDimitry Andric     widenScalarDst(MI, WideTy);
21935ffd83dbSDimitry Andric     Observer.changedInstr(MI);
21945ffd83dbSDimitry Andric     return Legalized;
21955ffd83dbSDimitry Andric 
2196fe6060f1SDimitry Andric   case TargetOpcode::G_ABS:
2197fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2198fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
2199fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy);
2200fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2201fe6060f1SDimitry Andric     return Legalized;
2202fe6060f1SDimitry Andric 
22030b57cec5SDimitry Andric   case TargetOpcode::G_ADD:
22040b57cec5SDimitry Andric   case TargetOpcode::G_AND:
22050b57cec5SDimitry Andric   case TargetOpcode::G_MUL:
22060b57cec5SDimitry Andric   case TargetOpcode::G_OR:
22070b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
22080b57cec5SDimitry Andric   case TargetOpcode::G_SUB:
22090b57cec5SDimitry Andric     // Perform operation at larger width (any extension is fines here, high bits
22100b57cec5SDimitry Andric     // don't affect the result) and then truncate the result back to the
22110b57cec5SDimitry Andric     // original type.
22120b57cec5SDimitry Andric     Observer.changingInstr(MI);
22130b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
22140b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
22150b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
22160b57cec5SDimitry Andric     Observer.changedInstr(MI);
22170b57cec5SDimitry Andric     return Legalized;
22180b57cec5SDimitry Andric 
2219fe6060f1SDimitry Andric   case TargetOpcode::G_SBFX:
2220fe6060f1SDimitry Andric   case TargetOpcode::G_UBFX:
2221fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2222fe6060f1SDimitry Andric 
2223fe6060f1SDimitry Andric     if (TypeIdx == 0) {
2224fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
2225fe6060f1SDimitry Andric       widenScalarDst(MI, WideTy);
2226fe6060f1SDimitry Andric     } else {
2227fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
2228fe6060f1SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ZEXT);
2229fe6060f1SDimitry Andric     }
2230fe6060f1SDimitry Andric 
2231fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2232fe6060f1SDimitry Andric     return Legalized;
2233fe6060f1SDimitry Andric 
22340b57cec5SDimitry Andric   case TargetOpcode::G_SHL:
22350b57cec5SDimitry Andric     Observer.changingInstr(MI);
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric     if (TypeIdx == 0) {
22380b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
22390b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
22400b57cec5SDimitry Andric     } else {
22410b57cec5SDimitry Andric       assert(TypeIdx == 1);
22420b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
22430b57cec5SDimitry Andric       // unsigned integer:
22440b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
22450b57cec5SDimitry Andric     }
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric     Observer.changedInstr(MI);
22480b57cec5SDimitry Andric     return Legalized;
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric   case TargetOpcode::G_SDIV:
22510b57cec5SDimitry Andric   case TargetOpcode::G_SREM:
22520b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
22530b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
22540b57cec5SDimitry Andric     Observer.changingInstr(MI);
22550b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
22560b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
22570b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
22580b57cec5SDimitry Andric     Observer.changedInstr(MI);
22590b57cec5SDimitry Andric     return Legalized;
22600b57cec5SDimitry Andric 
2261fe6060f1SDimitry Andric   case TargetOpcode::G_SDIVREM:
2262fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2263fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
2264fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2265fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy);
2266fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 1);
2267fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2268fe6060f1SDimitry Andric     return Legalized;
2269fe6060f1SDimitry Andric 
22700b57cec5SDimitry Andric   case TargetOpcode::G_ASHR:
22710b57cec5SDimitry Andric   case TargetOpcode::G_LSHR:
22720b57cec5SDimitry Andric     Observer.changingInstr(MI);
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric     if (TypeIdx == 0) {
22750b57cec5SDimitry Andric       unsigned CvtOp = MI.getOpcode() == TargetOpcode::G_ASHR ?
22760b57cec5SDimitry Andric         TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, CvtOp);
22790b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
22800b57cec5SDimitry Andric     } else {
22810b57cec5SDimitry Andric       assert(TypeIdx == 1);
22820b57cec5SDimitry Andric       // The "number of bits to shift" operand must preserve its value as an
22830b57cec5SDimitry Andric       // unsigned integer:
22840b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
22850b57cec5SDimitry Andric     }
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric     Observer.changedInstr(MI);
22880b57cec5SDimitry Andric     return Legalized;
22890b57cec5SDimitry Andric   case TargetOpcode::G_UDIV:
22900b57cec5SDimitry Andric   case TargetOpcode::G_UREM:
22910b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
22920b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
22930b57cec5SDimitry Andric     Observer.changingInstr(MI);
22940b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
22950b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
22960b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
22970b57cec5SDimitry Andric     Observer.changedInstr(MI);
22980b57cec5SDimitry Andric     return Legalized;
22990b57cec5SDimitry Andric 
2300fe6060f1SDimitry Andric   case TargetOpcode::G_UDIVREM:
2301fe6060f1SDimitry Andric     Observer.changingInstr(MI);
2302fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
2303fe6060f1SDimitry Andric     widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ZEXT);
2304fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy);
2305fe6060f1SDimitry Andric     widenScalarDst(MI, WideTy, 1);
2306fe6060f1SDimitry Andric     Observer.changedInstr(MI);
2307fe6060f1SDimitry Andric     return Legalized;
2308fe6060f1SDimitry Andric 
23090b57cec5SDimitry Andric   case TargetOpcode::G_SELECT:
23100b57cec5SDimitry Andric     Observer.changingInstr(MI);
23110b57cec5SDimitry Andric     if (TypeIdx == 0) {
23120b57cec5SDimitry Andric       // Perform operation at larger width (any extension is fine here, high
23130b57cec5SDimitry Andric       // bits don't affect the result) and then truncate the result back to the
23140b57cec5SDimitry Andric       // original type.
23150b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
23160b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
23170b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
23180b57cec5SDimitry Andric     } else {
23190b57cec5SDimitry Andric       bool IsVec = MRI.getType(MI.getOperand(1).getReg()).isVector();
23200b57cec5SDimitry Andric       // Explicit extension is required here since high bits affect the result.
23210b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, MIRBuilder.getBoolExtOp(IsVec, false));
23220b57cec5SDimitry Andric     }
23230b57cec5SDimitry Andric     Observer.changedInstr(MI);
23240b57cec5SDimitry Andric     return Legalized;
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   case TargetOpcode::G_FPTOSI:
23270b57cec5SDimitry Andric   case TargetOpcode::G_FPTOUI:
23280b57cec5SDimitry Andric     Observer.changingInstr(MI);
23298bcb0991SDimitry Andric 
23308bcb0991SDimitry Andric     if (TypeIdx == 0)
23310b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
23328bcb0991SDimitry Andric     else
23338bcb0991SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
23348bcb0991SDimitry Andric 
23350b57cec5SDimitry Andric     Observer.changedInstr(MI);
23360b57cec5SDimitry Andric     return Legalized;
23370b57cec5SDimitry Andric   case TargetOpcode::G_SITOFP:
23380b57cec5SDimitry Andric     Observer.changingInstr(MI);
2339e8d8bef9SDimitry Andric 
2340e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2341e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2342e8d8bef9SDimitry Andric     else
23430b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
2344e8d8bef9SDimitry Andric 
23450b57cec5SDimitry Andric     Observer.changedInstr(MI);
23460b57cec5SDimitry Andric     return Legalized;
23470b57cec5SDimitry Andric   case TargetOpcode::G_UITOFP:
23480b57cec5SDimitry Andric     Observer.changingInstr(MI);
2349e8d8bef9SDimitry Andric 
2350e8d8bef9SDimitry Andric     if (TypeIdx == 0)
2351e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2352e8d8bef9SDimitry Andric     else
23530b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
2354e8d8bef9SDimitry Andric 
23550b57cec5SDimitry Andric     Observer.changedInstr(MI);
23560b57cec5SDimitry Andric     return Legalized;
23570b57cec5SDimitry Andric   case TargetOpcode::G_LOAD:
23580b57cec5SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
23590b57cec5SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
23600b57cec5SDimitry Andric     Observer.changingInstr(MI);
23610b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
23620b57cec5SDimitry Andric     Observer.changedInstr(MI);
23630b57cec5SDimitry Andric     return Legalized;
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric   case TargetOpcode::G_STORE: {
23660b57cec5SDimitry Andric     if (TypeIdx != 0)
23670b57cec5SDimitry Andric       return UnableToLegalize;
23680b57cec5SDimitry Andric 
23690b57cec5SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2370e8d8bef9SDimitry Andric     if (!Ty.isScalar())
23710b57cec5SDimitry Andric       return UnableToLegalize;
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric     Observer.changingInstr(MI);
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric     unsigned ExtType = Ty.getScalarSizeInBits() == 1 ?
23760b57cec5SDimitry Andric       TargetOpcode::G_ZEXT : TargetOpcode::G_ANYEXT;
23770b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, ExtType);
23780b57cec5SDimitry Andric 
23790b57cec5SDimitry Andric     Observer.changedInstr(MI);
23800b57cec5SDimitry Andric     return Legalized;
23810b57cec5SDimitry Andric   }
23820b57cec5SDimitry Andric   case TargetOpcode::G_CONSTANT: {
23830b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
23840b57cec5SDimitry Andric     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
2385480093f4SDimitry Andric     unsigned ExtOpc = LI.getExtOpcodeForWideningConstant(
2386480093f4SDimitry Andric         MRI.getType(MI.getOperand(0).getReg()));
2387480093f4SDimitry Andric     assert((ExtOpc == TargetOpcode::G_ZEXT || ExtOpc == TargetOpcode::G_SEXT ||
2388480093f4SDimitry Andric             ExtOpc == TargetOpcode::G_ANYEXT) &&
2389480093f4SDimitry Andric            "Illegal Extend");
2390480093f4SDimitry Andric     const APInt &SrcVal = SrcMO.getCImm()->getValue();
2391480093f4SDimitry Andric     const APInt &Val = (ExtOpc == TargetOpcode::G_SEXT)
2392480093f4SDimitry Andric                            ? SrcVal.sext(WideTy.getSizeInBits())
2393480093f4SDimitry Andric                            : SrcVal.zext(WideTy.getSizeInBits());
23940b57cec5SDimitry Andric     Observer.changingInstr(MI);
23950b57cec5SDimitry Andric     SrcMO.setCImm(ConstantInt::get(Ctx, Val));
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
23980b57cec5SDimitry Andric     Observer.changedInstr(MI);
23990b57cec5SDimitry Andric     return Legalized;
24000b57cec5SDimitry Andric   }
24010b57cec5SDimitry Andric   case TargetOpcode::G_FCONSTANT: {
2402fcaf7f86SDimitry Andric     // To avoid changing the bits of the constant due to extension to a larger
2403fcaf7f86SDimitry Andric     // type and then using G_FPTRUNC, we simply convert to a G_CONSTANT.
24040b57cec5SDimitry Andric     MachineOperand &SrcMO = MI.getOperand(1);
2405fcaf7f86SDimitry Andric     APInt Val = SrcMO.getFPImm()->getValueAPF().bitcastToAPInt();
2406fcaf7f86SDimitry Andric     MIRBuilder.setInstrAndDebugLoc(MI);
2407fcaf7f86SDimitry Andric     auto IntCst = MIRBuilder.buildConstant(MI.getOperand(0).getReg(), Val);
2408fcaf7f86SDimitry Andric     widenScalarDst(*IntCst, WideTy, 0, TargetOpcode::G_TRUNC);
2409fcaf7f86SDimitry Andric     MI.eraseFromParent();
24100b57cec5SDimitry Andric     return Legalized;
24110b57cec5SDimitry Andric   }
24120b57cec5SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF: {
24130b57cec5SDimitry Andric     Observer.changingInstr(MI);
24140b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
24150b57cec5SDimitry Andric     Observer.changedInstr(MI);
24160b57cec5SDimitry Andric     return Legalized;
24170b57cec5SDimitry Andric   }
24180b57cec5SDimitry Andric   case TargetOpcode::G_BRCOND:
24190b57cec5SDimitry Andric     Observer.changingInstr(MI);
24200b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 0, MIRBuilder.getBoolExtOp(false, false));
24210b57cec5SDimitry Andric     Observer.changedInstr(MI);
24220b57cec5SDimitry Andric     return Legalized;
24230b57cec5SDimitry Andric 
24240b57cec5SDimitry Andric   case TargetOpcode::G_FCMP:
24250b57cec5SDimitry Andric     Observer.changingInstr(MI);
24260b57cec5SDimitry Andric     if (TypeIdx == 0)
24270b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
24280b57cec5SDimitry Andric     else {
24290b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
24300b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_FPEXT);
24310b57cec5SDimitry Andric     }
24320b57cec5SDimitry Andric     Observer.changedInstr(MI);
24330b57cec5SDimitry Andric     return Legalized;
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric   case TargetOpcode::G_ICMP:
24360b57cec5SDimitry Andric     Observer.changingInstr(MI);
24370b57cec5SDimitry Andric     if (TypeIdx == 0)
24380b57cec5SDimitry Andric       widenScalarDst(MI, WideTy);
24390b57cec5SDimitry Andric     else {
24400b57cec5SDimitry Andric       unsigned ExtOpcode = CmpInst::isSigned(static_cast<CmpInst::Predicate>(
24410b57cec5SDimitry Andric                                MI.getOperand(1).getPredicate()))
24420b57cec5SDimitry Andric                                ? TargetOpcode::G_SEXT
24430b57cec5SDimitry Andric                                : TargetOpcode::G_ZEXT;
24440b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 2, ExtOpcode);
24450b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, 3, ExtOpcode);
24460b57cec5SDimitry Andric     }
24470b57cec5SDimitry Andric     Observer.changedInstr(MI);
24480b57cec5SDimitry Andric     return Legalized;
24490b57cec5SDimitry Andric 
2450480093f4SDimitry Andric   case TargetOpcode::G_PTR_ADD:
2451480093f4SDimitry Andric     assert(TypeIdx == 1 && "unable to legalize pointer of G_PTR_ADD");
24520b57cec5SDimitry Andric     Observer.changingInstr(MI);
24530b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
24540b57cec5SDimitry Andric     Observer.changedInstr(MI);
24550b57cec5SDimitry Andric     return Legalized;
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   case TargetOpcode::G_PHI: {
24580b57cec5SDimitry Andric     assert(TypeIdx == 0 && "Expecting only Idx 0");
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric     Observer.changingInstr(MI);
24610b57cec5SDimitry Andric     for (unsigned I = 1; I < MI.getNumOperands(); I += 2) {
24620b57cec5SDimitry Andric       MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
2463bdd1243dSDimitry Andric       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminatorForward());
24640b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_ANYEXT);
24650b57cec5SDimitry Andric     }
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric     MachineBasicBlock &MBB = *MI.getParent();
24680b57cec5SDimitry Andric     MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
24690b57cec5SDimitry Andric     widenScalarDst(MI, WideTy);
24700b57cec5SDimitry Andric     Observer.changedInstr(MI);
24710b57cec5SDimitry Andric     return Legalized;
24720b57cec5SDimitry Andric   }
24730b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
24740b57cec5SDimitry Andric     if (TypeIdx == 0) {
24750b57cec5SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
24760b57cec5SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
24770b57cec5SDimitry Andric       Observer.changingInstr(MI);
24780b57cec5SDimitry Andric 
2479fe6060f1SDimitry Andric       widenScalarSrc(
2480fe6060f1SDimitry Andric           MI, LLT::vector(VecTy.getElementCount(), WideTy.getSizeInBits()), 1,
2481349cc55cSDimitry Andric           TargetOpcode::G_ANYEXT);
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
24840b57cec5SDimitry Andric       Observer.changedInstr(MI);
24850b57cec5SDimitry Andric       return Legalized;
24860b57cec5SDimitry Andric     }
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric     if (TypeIdx != 2)
24890b57cec5SDimitry Andric       return UnableToLegalize;
24900b57cec5SDimitry Andric     Observer.changingInstr(MI);
2491480093f4SDimitry Andric     // TODO: Probably should be zext
24920b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
24930b57cec5SDimitry Andric     Observer.changedInstr(MI);
24940b57cec5SDimitry Andric     return Legalized;
24950b57cec5SDimitry Andric   }
2496480093f4SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT: {
2497480093f4SDimitry Andric     if (TypeIdx == 1) {
2498480093f4SDimitry Andric       Observer.changingInstr(MI);
2499480093f4SDimitry Andric 
2500480093f4SDimitry Andric       Register VecReg = MI.getOperand(1).getReg();
2501480093f4SDimitry Andric       LLT VecTy = MRI.getType(VecReg);
2502fe6060f1SDimitry Andric       LLT WideVecTy = LLT::vector(VecTy.getElementCount(), WideTy);
2503480093f4SDimitry Andric 
2504480093f4SDimitry Andric       widenScalarSrc(MI, WideVecTy, 1, TargetOpcode::G_ANYEXT);
2505480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2506480093f4SDimitry Andric       widenScalarDst(MI, WideVecTy, 0);
2507480093f4SDimitry Andric       Observer.changedInstr(MI);
2508480093f4SDimitry Andric       return Legalized;
2509480093f4SDimitry Andric     }
2510480093f4SDimitry Andric 
2511480093f4SDimitry Andric     if (TypeIdx == 2) {
2512480093f4SDimitry Andric       Observer.changingInstr(MI);
2513480093f4SDimitry Andric       // TODO: Probably should be zext
2514480093f4SDimitry Andric       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2515480093f4SDimitry Andric       Observer.changedInstr(MI);
25165ffd83dbSDimitry Andric       return Legalized;
2517480093f4SDimitry Andric     }
2518480093f4SDimitry Andric 
25195ffd83dbSDimitry Andric     return UnableToLegalize;
2520480093f4SDimitry Andric   }
25210b57cec5SDimitry Andric   case TargetOpcode::G_FADD:
25220b57cec5SDimitry Andric   case TargetOpcode::G_FMUL:
25230b57cec5SDimitry Andric   case TargetOpcode::G_FSUB:
25240b57cec5SDimitry Andric   case TargetOpcode::G_FMA:
25258bcb0991SDimitry Andric   case TargetOpcode::G_FMAD:
25260b57cec5SDimitry Andric   case TargetOpcode::G_FNEG:
25270b57cec5SDimitry Andric   case TargetOpcode::G_FABS:
25280b57cec5SDimitry Andric   case TargetOpcode::G_FCANONICALIZE:
25290b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM:
25300b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM:
25310b57cec5SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
25320b57cec5SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
25330b57cec5SDimitry Andric   case TargetOpcode::G_FMINIMUM:
25340b57cec5SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
25350b57cec5SDimitry Andric   case TargetOpcode::G_FDIV:
25360b57cec5SDimitry Andric   case TargetOpcode::G_FREM:
25370b57cec5SDimitry Andric   case TargetOpcode::G_FCEIL:
25380b57cec5SDimitry Andric   case TargetOpcode::G_FFLOOR:
25390b57cec5SDimitry Andric   case TargetOpcode::G_FCOS:
25400b57cec5SDimitry Andric   case TargetOpcode::G_FSIN:
25410b57cec5SDimitry Andric   case TargetOpcode::G_FLOG10:
25420b57cec5SDimitry Andric   case TargetOpcode::G_FLOG:
25430b57cec5SDimitry Andric   case TargetOpcode::G_FLOG2:
25440b57cec5SDimitry Andric   case TargetOpcode::G_FRINT:
25450b57cec5SDimitry Andric   case TargetOpcode::G_FNEARBYINT:
25460b57cec5SDimitry Andric   case TargetOpcode::G_FSQRT:
25470b57cec5SDimitry Andric   case TargetOpcode::G_FEXP:
25480b57cec5SDimitry Andric   case TargetOpcode::G_FEXP2:
25490b57cec5SDimitry Andric   case TargetOpcode::G_FPOW:
25500b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_TRUNC:
25510b57cec5SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
2552e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
25530b57cec5SDimitry Andric     assert(TypeIdx == 0);
25540b57cec5SDimitry Andric     Observer.changingInstr(MI);
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
25570b57cec5SDimitry Andric       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_FPEXT);
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
25600b57cec5SDimitry Andric     Observer.changedInstr(MI);
25610b57cec5SDimitry Andric     return Legalized;
2562*06c3fb27SDimitry Andric   case TargetOpcode::G_FPOWI:
2563*06c3fb27SDimitry Andric   case TargetOpcode::G_FLDEXP:
2564*06c3fb27SDimitry Andric   case TargetOpcode::G_STRICT_FLDEXP: {
2565*06c3fb27SDimitry Andric     if (TypeIdx == 0) {
2566*06c3fb27SDimitry Andric       if (MI.getOpcode() == TargetOpcode::G_STRICT_FLDEXP)
2567e8d8bef9SDimitry Andric         return UnableToLegalize;
2568*06c3fb27SDimitry Andric 
2569e8d8bef9SDimitry Andric       Observer.changingInstr(MI);
2570e8d8bef9SDimitry Andric       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
2571e8d8bef9SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2572e8d8bef9SDimitry Andric       Observer.changedInstr(MI);
2573e8d8bef9SDimitry Andric       return Legalized;
2574e8d8bef9SDimitry Andric     }
2575*06c3fb27SDimitry Andric 
2576*06c3fb27SDimitry Andric     if (TypeIdx == 1) {
2577*06c3fb27SDimitry Andric       // For some reason SelectionDAG tries to promote to a libcall without
2578*06c3fb27SDimitry Andric       // actually changing the integer type for promotion.
2579*06c3fb27SDimitry Andric       Observer.changingInstr(MI);
2580*06c3fb27SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
2581*06c3fb27SDimitry Andric       Observer.changedInstr(MI);
2582*06c3fb27SDimitry Andric       return Legalized;
2583*06c3fb27SDimitry Andric     }
2584*06c3fb27SDimitry Andric 
2585*06c3fb27SDimitry Andric     return UnableToLegalize;
2586*06c3fb27SDimitry Andric   }
2587*06c3fb27SDimitry Andric   case TargetOpcode::G_FFREXP: {
2588*06c3fb27SDimitry Andric     Observer.changingInstr(MI);
2589*06c3fb27SDimitry Andric 
2590*06c3fb27SDimitry Andric     if (TypeIdx == 0) {
2591*06c3fb27SDimitry Andric       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
2592*06c3fb27SDimitry Andric       widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2593*06c3fb27SDimitry Andric     } else {
2594*06c3fb27SDimitry Andric       widenScalarDst(MI, WideTy, 1);
2595*06c3fb27SDimitry Andric     }
2596*06c3fb27SDimitry Andric 
2597*06c3fb27SDimitry Andric     Observer.changedInstr(MI);
2598*06c3fb27SDimitry Andric     return Legalized;
2599*06c3fb27SDimitry Andric   }
26000b57cec5SDimitry Andric   case TargetOpcode::G_INTTOPTR:
26010b57cec5SDimitry Andric     if (TypeIdx != 1)
26020b57cec5SDimitry Andric       return UnableToLegalize;
26030b57cec5SDimitry Andric 
26040b57cec5SDimitry Andric     Observer.changingInstr(MI);
26050b57cec5SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
26060b57cec5SDimitry Andric     Observer.changedInstr(MI);
26070b57cec5SDimitry Andric     return Legalized;
26080b57cec5SDimitry Andric   case TargetOpcode::G_PTRTOINT:
26090b57cec5SDimitry Andric     if (TypeIdx != 0)
26100b57cec5SDimitry Andric       return UnableToLegalize;
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric     Observer.changingInstr(MI);
26130b57cec5SDimitry Andric     widenScalarDst(MI, WideTy, 0);
26140b57cec5SDimitry Andric     Observer.changedInstr(MI);
26150b57cec5SDimitry Andric     return Legalized;
26160b57cec5SDimitry Andric   case TargetOpcode::G_BUILD_VECTOR: {
26170b57cec5SDimitry Andric     Observer.changingInstr(MI);
26180b57cec5SDimitry Andric 
26190b57cec5SDimitry Andric     const LLT WideEltTy = TypeIdx == 1 ? WideTy : WideTy.getElementType();
26200b57cec5SDimitry Andric     for (int I = 1, E = MI.getNumOperands(); I != E; ++I)
26210b57cec5SDimitry Andric       widenScalarSrc(MI, WideEltTy, I, TargetOpcode::G_ANYEXT);
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric     // Avoid changing the result vector type if the source element type was
26240b57cec5SDimitry Andric     // requested.
26250b57cec5SDimitry Andric     if (TypeIdx == 1) {
2626e8d8bef9SDimitry Andric       MI.setDesc(MIRBuilder.getTII().get(TargetOpcode::G_BUILD_VECTOR_TRUNC));
26270b57cec5SDimitry Andric     } else {
26280b57cec5SDimitry Andric       widenScalarDst(MI, WideTy, 0);
26290b57cec5SDimitry Andric     }
26300b57cec5SDimitry Andric 
26310b57cec5SDimitry Andric     Observer.changedInstr(MI);
26320b57cec5SDimitry Andric     return Legalized;
26330b57cec5SDimitry Andric   }
26348bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG:
26358bcb0991SDimitry Andric     if (TypeIdx != 0)
26368bcb0991SDimitry Andric       return UnableToLegalize;
26378bcb0991SDimitry Andric 
26388bcb0991SDimitry Andric     Observer.changingInstr(MI);
26398bcb0991SDimitry Andric     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
26408bcb0991SDimitry Andric     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_TRUNC);
26418bcb0991SDimitry Andric     Observer.changedInstr(MI);
26428bcb0991SDimitry Andric     return Legalized;
26435ffd83dbSDimitry Andric   case TargetOpcode::G_PTRMASK: {
26445ffd83dbSDimitry Andric     if (TypeIdx != 1)
26455ffd83dbSDimitry Andric       return UnableToLegalize;
26465ffd83dbSDimitry Andric     Observer.changingInstr(MI);
26475ffd83dbSDimitry Andric     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
26485ffd83dbSDimitry Andric     Observer.changedInstr(MI);
26495ffd83dbSDimitry Andric     return Legalized;
26505ffd83dbSDimitry Andric   }
26515ffd83dbSDimitry Andric   }
26525ffd83dbSDimitry Andric }
26535ffd83dbSDimitry Andric 
26545ffd83dbSDimitry Andric static void getUnmergePieces(SmallVectorImpl<Register> &Pieces,
26555ffd83dbSDimitry Andric                              MachineIRBuilder &B, Register Src, LLT Ty) {
26565ffd83dbSDimitry Andric   auto Unmerge = B.buildUnmerge(Ty, Src);
26575ffd83dbSDimitry Andric   for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
26585ffd83dbSDimitry Andric     Pieces.push_back(Unmerge.getReg(I));
26595ffd83dbSDimitry Andric }
26605ffd83dbSDimitry Andric 
26615ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
2662*06c3fb27SDimitry Andric LegalizerHelper::lowerFConstant(MachineInstr &MI) {
26635ffd83dbSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
26645ffd83dbSDimitry Andric 
2665*06c3fb27SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
2666*06c3fb27SDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
2667*06c3fb27SDimitry Andric 
2668*06c3fb27SDimitry Andric   unsigned AddrSpace = DL.getDefaultGlobalsAddressSpace();
2669*06c3fb27SDimitry Andric   LLT AddrPtrTy = LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace));
2670*06c3fb27SDimitry Andric   Align Alignment = Align(DL.getABITypeAlign(
2671*06c3fb27SDimitry Andric       getFloatTypeForLLT(MF.getFunction().getContext(), MRI.getType(Dst))));
2672*06c3fb27SDimitry Andric 
2673*06c3fb27SDimitry Andric   auto Addr = MIRBuilder.buildConstantPool(
2674*06c3fb27SDimitry Andric       AddrPtrTy, MF.getConstantPool()->getConstantPoolIndex(
2675*06c3fb27SDimitry Andric                      MI.getOperand(1).getFPImm(), Alignment));
2676*06c3fb27SDimitry Andric 
2677*06c3fb27SDimitry Andric   MachineMemOperand *MMO = MF.getMachineMemOperand(
2678*06c3fb27SDimitry Andric       MachinePointerInfo::getConstantPool(MF), MachineMemOperand::MOLoad,
2679*06c3fb27SDimitry Andric       MRI.getType(Dst), Alignment);
2680*06c3fb27SDimitry Andric 
2681*06c3fb27SDimitry Andric   MIRBuilder.buildLoadInstr(TargetOpcode::G_LOAD, Dst, Addr, *MMO);
2682*06c3fb27SDimitry Andric   MI.eraseFromParent();
2683*06c3fb27SDimitry Andric 
2684*06c3fb27SDimitry Andric   return Legalized;
2685*06c3fb27SDimitry Andric }
2686*06c3fb27SDimitry Andric 
2687*06c3fb27SDimitry Andric LegalizerHelper::LegalizeResult
2688*06c3fb27SDimitry Andric LegalizerHelper::lowerBitcast(MachineInstr &MI) {
2689*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy] = MI.getFirst2RegLLTs();
26905ffd83dbSDimitry Andric   if (SrcTy.isVector()) {
26915ffd83dbSDimitry Andric     LLT SrcEltTy = SrcTy.getElementType();
26925ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
26935ffd83dbSDimitry Andric 
26945ffd83dbSDimitry Andric     if (DstTy.isVector()) {
26955ffd83dbSDimitry Andric       int NumDstElt = DstTy.getNumElements();
26965ffd83dbSDimitry Andric       int NumSrcElt = SrcTy.getNumElements();
26975ffd83dbSDimitry Andric 
26985ffd83dbSDimitry Andric       LLT DstEltTy = DstTy.getElementType();
26995ffd83dbSDimitry Andric       LLT DstCastTy = DstEltTy; // Intermediate bitcast result type
27005ffd83dbSDimitry Andric       LLT SrcPartTy = SrcEltTy; // Original unmerge result type.
27015ffd83dbSDimitry Andric 
27025ffd83dbSDimitry Andric       // If there's an element size mismatch, insert intermediate casts to match
27035ffd83dbSDimitry Andric       // the result element type.
27045ffd83dbSDimitry Andric       if (NumSrcElt < NumDstElt) { // Source element type is larger.
27055ffd83dbSDimitry Andric         // %1:_(<4 x s8>) = G_BITCAST %0:_(<2 x s16>)
27065ffd83dbSDimitry Andric         //
27075ffd83dbSDimitry Andric         // =>
27085ffd83dbSDimitry Andric         //
27095ffd83dbSDimitry Andric         // %2:_(s16), %3:_(s16) = G_UNMERGE_VALUES %0
27105ffd83dbSDimitry Andric         // %3:_(<2 x s8>) = G_BITCAST %2
27115ffd83dbSDimitry Andric         // %4:_(<2 x s8>) = G_BITCAST %3
27125ffd83dbSDimitry Andric         // %1:_(<4 x s16>) = G_CONCAT_VECTORS %3, %4
2713fe6060f1SDimitry Andric         DstCastTy = LLT::fixed_vector(NumDstElt / NumSrcElt, DstEltTy);
27145ffd83dbSDimitry Andric         SrcPartTy = SrcEltTy;
27155ffd83dbSDimitry Andric       } else if (NumSrcElt > NumDstElt) { // Source element type is smaller.
27165ffd83dbSDimitry Andric         //
27175ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BITCAST %0:_(<4 x s8>)
27185ffd83dbSDimitry Andric         //
27195ffd83dbSDimitry Andric         // =>
27205ffd83dbSDimitry Andric         //
27215ffd83dbSDimitry Andric         // %2:_(<2 x s8>), %3:_(<2 x s8>) = G_UNMERGE_VALUES %0
27225ffd83dbSDimitry Andric         // %3:_(s16) = G_BITCAST %2
27235ffd83dbSDimitry Andric         // %4:_(s16) = G_BITCAST %3
27245ffd83dbSDimitry Andric         // %1:_(<2 x s16>) = G_BUILD_VECTOR %3, %4
2725fe6060f1SDimitry Andric         SrcPartTy = LLT::fixed_vector(NumSrcElt / NumDstElt, SrcEltTy);
27265ffd83dbSDimitry Andric         DstCastTy = DstEltTy;
27275ffd83dbSDimitry Andric       }
27285ffd83dbSDimitry Andric 
27295ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcPartTy);
27305ffd83dbSDimitry Andric       for (Register &SrcReg : SrcRegs)
27315ffd83dbSDimitry Andric         SrcReg = MIRBuilder.buildBitcast(DstCastTy, SrcReg).getReg(0);
27325ffd83dbSDimitry Andric     } else
27335ffd83dbSDimitry Andric       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcEltTy);
27345ffd83dbSDimitry Andric 
2735bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(Dst, SrcRegs);
27365ffd83dbSDimitry Andric     MI.eraseFromParent();
27375ffd83dbSDimitry Andric     return Legalized;
27385ffd83dbSDimitry Andric   }
27395ffd83dbSDimitry Andric 
27405ffd83dbSDimitry Andric   if (DstTy.isVector()) {
27415ffd83dbSDimitry Andric     SmallVector<Register, 8> SrcRegs;
27425ffd83dbSDimitry Andric     getUnmergePieces(SrcRegs, MIRBuilder, Src, DstTy.getElementType());
2743bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(Dst, SrcRegs);
27445ffd83dbSDimitry Andric     MI.eraseFromParent();
27455ffd83dbSDimitry Andric     return Legalized;
27465ffd83dbSDimitry Andric   }
27475ffd83dbSDimitry Andric 
27485ffd83dbSDimitry Andric   return UnableToLegalize;
27495ffd83dbSDimitry Andric }
27505ffd83dbSDimitry Andric 
2751e8d8bef9SDimitry Andric /// Figure out the bit offset into a register when coercing a vector index for
2752e8d8bef9SDimitry Andric /// the wide element type. This is only for the case when promoting vector to
2753e8d8bef9SDimitry Andric /// one with larger elements.
2754e8d8bef9SDimitry Andric //
2755e8d8bef9SDimitry Andric ///
2756e8d8bef9SDimitry Andric /// %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2757e8d8bef9SDimitry Andric /// %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2758e8d8bef9SDimitry Andric static Register getBitcastWiderVectorElementOffset(MachineIRBuilder &B,
2759e8d8bef9SDimitry Andric                                                    Register Idx,
2760e8d8bef9SDimitry Andric                                                    unsigned NewEltSize,
2761e8d8bef9SDimitry Andric                                                    unsigned OldEltSize) {
2762e8d8bef9SDimitry Andric   const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2763e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(Idx);
2764e8d8bef9SDimitry Andric 
2765e8d8bef9SDimitry Andric   // Now figure out the amount we need to shift to get the target bits.
2766e8d8bef9SDimitry Andric   auto OffsetMask = B.buildConstant(
2767349cc55cSDimitry Andric       IdxTy, ~(APInt::getAllOnes(IdxTy.getSizeInBits()) << Log2EltRatio));
2768e8d8bef9SDimitry Andric   auto OffsetIdx = B.buildAnd(IdxTy, Idx, OffsetMask);
2769e8d8bef9SDimitry Andric   return B.buildShl(IdxTy, OffsetIdx,
2770e8d8bef9SDimitry Andric                     B.buildConstant(IdxTy, Log2_32(OldEltSize))).getReg(0);
2771e8d8bef9SDimitry Andric }
2772e8d8bef9SDimitry Andric 
2773e8d8bef9SDimitry Andric /// Perform a G_EXTRACT_VECTOR_ELT in a different sized vector element. If this
2774e8d8bef9SDimitry Andric /// is casting to a vector with a smaller element size, perform multiple element
2775e8d8bef9SDimitry Andric /// extracts and merge the results. If this is coercing to a vector with larger
2776e8d8bef9SDimitry Andric /// elements, index the bitcasted vector and extract the target element with bit
2777e8d8bef9SDimitry Andric /// operations. This is intended to force the indexing in the native register
2778e8d8bef9SDimitry Andric /// size for architectures that can dynamically index the register file.
27795ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
2780e8d8bef9SDimitry Andric LegalizerHelper::bitcastExtractVectorElt(MachineInstr &MI, unsigned TypeIdx,
2781e8d8bef9SDimitry Andric                                          LLT CastTy) {
2782e8d8bef9SDimitry Andric   if (TypeIdx != 1)
2783e8d8bef9SDimitry Andric     return UnableToLegalize;
2784e8d8bef9SDimitry Andric 
2785*06c3fb27SDimitry Andric   auto [Dst, DstTy, SrcVec, SrcVecTy, Idx, IdxTy] = MI.getFirst3RegLLTs();
2786e8d8bef9SDimitry Andric 
2787e8d8bef9SDimitry Andric   LLT SrcEltTy = SrcVecTy.getElementType();
2788e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2789e8d8bef9SDimitry Andric   unsigned OldNumElts = SrcVecTy.getNumElements();
2790e8d8bef9SDimitry Andric 
2791e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2792e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2793e8d8bef9SDimitry Andric 
2794e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2795e8d8bef9SDimitry Andric   const unsigned OldEltSize = SrcEltTy.getSizeInBits();
2796e8d8bef9SDimitry Andric   if (NewNumElts > OldNumElts) {
2797e8d8bef9SDimitry Andric     // Decreasing the vector element size
2798e8d8bef9SDimitry Andric     //
2799e8d8bef9SDimitry Andric     // e.g. i64 = extract_vector_elt x:v2i64, y:i32
2800e8d8bef9SDimitry Andric     //  =>
2801e8d8bef9SDimitry Andric     //  v4i32:castx = bitcast x:v2i64
2802e8d8bef9SDimitry Andric     //
2803e8d8bef9SDimitry Andric     // i64 = bitcast
2804e8d8bef9SDimitry Andric     //   (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
2805e8d8bef9SDimitry Andric     //                       (i32 (extract_vector_elt castx, (2 * y + 1)))
2806e8d8bef9SDimitry Andric     //
2807e8d8bef9SDimitry Andric     if (NewNumElts % OldNumElts != 0)
2808e8d8bef9SDimitry Andric       return UnableToLegalize;
2809e8d8bef9SDimitry Andric 
2810e8d8bef9SDimitry Andric     // Type of the intermediate result vector.
2811e8d8bef9SDimitry Andric     const unsigned NewEltsPerOldElt = NewNumElts / OldNumElts;
2812fe6060f1SDimitry Andric     LLT MidTy =
2813fe6060f1SDimitry Andric         LLT::scalarOrVector(ElementCount::getFixed(NewEltsPerOldElt), NewEltTy);
2814e8d8bef9SDimitry Andric 
2815e8d8bef9SDimitry Andric     auto NewEltsPerOldEltK = MIRBuilder.buildConstant(IdxTy, NewEltsPerOldElt);
2816e8d8bef9SDimitry Andric 
2817e8d8bef9SDimitry Andric     SmallVector<Register, 8> NewOps(NewEltsPerOldElt);
2818e8d8bef9SDimitry Andric     auto NewBaseIdx = MIRBuilder.buildMul(IdxTy, Idx, NewEltsPerOldEltK);
2819e8d8bef9SDimitry Andric 
2820e8d8bef9SDimitry Andric     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
2821e8d8bef9SDimitry Andric       auto IdxOffset = MIRBuilder.buildConstant(IdxTy, I);
2822e8d8bef9SDimitry Andric       auto TmpIdx = MIRBuilder.buildAdd(IdxTy, NewBaseIdx, IdxOffset);
2823e8d8bef9SDimitry Andric       auto Elt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec, TmpIdx);
2824e8d8bef9SDimitry Andric       NewOps[I] = Elt.getReg(0);
2825e8d8bef9SDimitry Andric     }
2826e8d8bef9SDimitry Andric 
2827e8d8bef9SDimitry Andric     auto NewVec = MIRBuilder.buildBuildVector(MidTy, NewOps);
2828e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, NewVec);
2829e8d8bef9SDimitry Andric     MI.eraseFromParent();
2830e8d8bef9SDimitry Andric     return Legalized;
2831e8d8bef9SDimitry Andric   }
2832e8d8bef9SDimitry Andric 
2833e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2834e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
2835e8d8bef9SDimitry Andric       return UnableToLegalize;
2836e8d8bef9SDimitry Andric 
2837e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2838e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2839e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2840e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
2841e8d8bef9SDimitry Andric       return UnableToLegalize;
2842e8d8bef9SDimitry Andric 
2843e8d8bef9SDimitry Andric     // Increasing the vector element size.
2844e8d8bef9SDimitry Andric     // %elt:_(small_elt) = G_EXTRACT_VECTOR_ELT %vec:_(<N x small_elt>), %idx
2845e8d8bef9SDimitry Andric     //
2846e8d8bef9SDimitry Andric     //   =>
2847e8d8bef9SDimitry Andric     //
2848e8d8bef9SDimitry Andric     // %cast = G_BITCAST %vec
2849e8d8bef9SDimitry Andric     // %scaled_idx = G_LSHR %idx, Log2(DstEltSize / SrcEltSize)
2850e8d8bef9SDimitry Andric     // %wide_elt  = G_EXTRACT_VECTOR_ELT %cast, %scaled_idx
2851e8d8bef9SDimitry Andric     // %offset_idx = G_AND %idx, ~(-1 << Log2(DstEltSize / SrcEltSize))
2852e8d8bef9SDimitry Andric     // %offset_bits = G_SHL %offset_idx, Log2(SrcEltSize)
2853e8d8bef9SDimitry Andric     // %elt_bits = G_LSHR %wide_elt, %offset_bits
2854e8d8bef9SDimitry Andric     // %elt = G_TRUNC %elt_bits
2855e8d8bef9SDimitry Andric 
2856e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2857e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2858e8d8bef9SDimitry Andric 
2859e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2860e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2861e8d8bef9SDimitry Andric 
2862e8d8bef9SDimitry Andric     Register WideElt = CastVec;
2863e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2864e8d8bef9SDimitry Andric       WideElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2865e8d8bef9SDimitry Andric                                                      ScaledIdx).getReg(0);
2866e8d8bef9SDimitry Andric     }
2867e8d8bef9SDimitry Andric 
2868e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2869e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2870e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2871e8d8bef9SDimitry Andric 
2872e8d8bef9SDimitry Andric     // Shift the wide element to get the target element.
2873e8d8bef9SDimitry Andric     auto ExtractedBits = MIRBuilder.buildLShr(NewEltTy, WideElt, OffsetBits);
2874e8d8bef9SDimitry Andric     MIRBuilder.buildTrunc(Dst, ExtractedBits);
2875e8d8bef9SDimitry Andric     MI.eraseFromParent();
2876e8d8bef9SDimitry Andric     return Legalized;
2877e8d8bef9SDimitry Andric   }
2878e8d8bef9SDimitry Andric 
2879e8d8bef9SDimitry Andric   return UnableToLegalize;
2880e8d8bef9SDimitry Andric }
2881e8d8bef9SDimitry Andric 
2882e8d8bef9SDimitry Andric /// Emit code to insert \p InsertReg into \p TargetRet at \p OffsetBits in \p
2883e8d8bef9SDimitry Andric /// TargetReg, while preserving other bits in \p TargetReg.
2884e8d8bef9SDimitry Andric ///
2885e8d8bef9SDimitry Andric /// (InsertReg << Offset) | (TargetReg & ~(-1 >> InsertReg.size()) << Offset)
2886e8d8bef9SDimitry Andric static Register buildBitFieldInsert(MachineIRBuilder &B,
2887e8d8bef9SDimitry Andric                                     Register TargetReg, Register InsertReg,
2888e8d8bef9SDimitry Andric                                     Register OffsetBits) {
2889e8d8bef9SDimitry Andric   LLT TargetTy = B.getMRI()->getType(TargetReg);
2890e8d8bef9SDimitry Andric   LLT InsertTy = B.getMRI()->getType(InsertReg);
2891e8d8bef9SDimitry Andric   auto ZextVal = B.buildZExt(TargetTy, InsertReg);
2892e8d8bef9SDimitry Andric   auto ShiftedInsertVal = B.buildShl(TargetTy, ZextVal, OffsetBits);
2893e8d8bef9SDimitry Andric 
2894e8d8bef9SDimitry Andric   // Produce a bitmask of the value to insert
2895e8d8bef9SDimitry Andric   auto EltMask = B.buildConstant(
2896e8d8bef9SDimitry Andric     TargetTy, APInt::getLowBitsSet(TargetTy.getSizeInBits(),
2897e8d8bef9SDimitry Andric                                    InsertTy.getSizeInBits()));
2898e8d8bef9SDimitry Andric   // Shift it into position
2899e8d8bef9SDimitry Andric   auto ShiftedMask = B.buildShl(TargetTy, EltMask, OffsetBits);
2900e8d8bef9SDimitry Andric   auto InvShiftedMask = B.buildNot(TargetTy, ShiftedMask);
2901e8d8bef9SDimitry Andric 
2902e8d8bef9SDimitry Andric   // Clear out the bits in the wide element
2903e8d8bef9SDimitry Andric   auto MaskedOldElt = B.buildAnd(TargetTy, TargetReg, InvShiftedMask);
2904e8d8bef9SDimitry Andric 
2905e8d8bef9SDimitry Andric   // The value to insert has all zeros already, so stick it into the masked
2906e8d8bef9SDimitry Andric   // wide element.
2907e8d8bef9SDimitry Andric   return B.buildOr(TargetTy, MaskedOldElt, ShiftedInsertVal).getReg(0);
2908e8d8bef9SDimitry Andric }
2909e8d8bef9SDimitry Andric 
2910e8d8bef9SDimitry Andric /// Perform a G_INSERT_VECTOR_ELT in a different sized vector element. If this
2911e8d8bef9SDimitry Andric /// is increasing the element size, perform the indexing in the target element
2912e8d8bef9SDimitry Andric /// type, and use bit operations to insert at the element position. This is
2913e8d8bef9SDimitry Andric /// intended for architectures that can dynamically index the register file and
2914e8d8bef9SDimitry Andric /// want to force indexing in the native register size.
2915e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
2916e8d8bef9SDimitry Andric LegalizerHelper::bitcastInsertVectorElt(MachineInstr &MI, unsigned TypeIdx,
2917e8d8bef9SDimitry Andric                                         LLT CastTy) {
29185ffd83dbSDimitry Andric   if (TypeIdx != 0)
29195ffd83dbSDimitry Andric     return UnableToLegalize;
29205ffd83dbSDimitry Andric 
2921*06c3fb27SDimitry Andric   auto [Dst, DstTy, SrcVec, SrcVecTy, Val, ValTy, Idx, IdxTy] =
2922*06c3fb27SDimitry Andric       MI.getFirst4RegLLTs();
2923*06c3fb27SDimitry Andric   LLT VecTy = DstTy;
2924e8d8bef9SDimitry Andric 
2925e8d8bef9SDimitry Andric   LLT VecEltTy = VecTy.getElementType();
2926e8d8bef9SDimitry Andric   LLT NewEltTy = CastTy.isVector() ? CastTy.getElementType() : CastTy;
2927e8d8bef9SDimitry Andric   const unsigned NewEltSize = NewEltTy.getSizeInBits();
2928e8d8bef9SDimitry Andric   const unsigned OldEltSize = VecEltTy.getSizeInBits();
2929e8d8bef9SDimitry Andric 
2930e8d8bef9SDimitry Andric   unsigned NewNumElts = CastTy.isVector() ? CastTy.getNumElements() : 1;
2931e8d8bef9SDimitry Andric   unsigned OldNumElts = VecTy.getNumElements();
2932e8d8bef9SDimitry Andric 
2933e8d8bef9SDimitry Andric   Register CastVec = MIRBuilder.buildBitcast(CastTy, SrcVec).getReg(0);
2934e8d8bef9SDimitry Andric   if (NewNumElts < OldNumElts) {
2935e8d8bef9SDimitry Andric     if (NewEltSize % OldEltSize != 0)
29365ffd83dbSDimitry Andric       return UnableToLegalize;
29375ffd83dbSDimitry Andric 
2938e8d8bef9SDimitry Andric     // This only depends on powers of 2 because we use bit tricks to figure out
2939e8d8bef9SDimitry Andric     // the bit offset we need to shift to get the target element. A general
2940e8d8bef9SDimitry Andric     // expansion could emit division/multiply.
2941e8d8bef9SDimitry Andric     if (!isPowerOf2_32(NewEltSize / OldEltSize))
29425ffd83dbSDimitry Andric       return UnableToLegalize;
29435ffd83dbSDimitry Andric 
2944e8d8bef9SDimitry Andric     const unsigned Log2EltRatio = Log2_32(NewEltSize / OldEltSize);
2945e8d8bef9SDimitry Andric     auto Log2Ratio = MIRBuilder.buildConstant(IdxTy, Log2EltRatio);
2946e8d8bef9SDimitry Andric 
2947e8d8bef9SDimitry Andric     // Divide to get the index in the wider element type.
2948e8d8bef9SDimitry Andric     auto ScaledIdx = MIRBuilder.buildLShr(IdxTy, Idx, Log2Ratio);
2949e8d8bef9SDimitry Andric 
2950e8d8bef9SDimitry Andric     Register ExtractedElt = CastVec;
2951e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2952e8d8bef9SDimitry Andric       ExtractedElt = MIRBuilder.buildExtractVectorElement(NewEltTy, CastVec,
2953e8d8bef9SDimitry Andric                                                           ScaledIdx).getReg(0);
29545ffd83dbSDimitry Andric     }
29555ffd83dbSDimitry Andric 
2956e8d8bef9SDimitry Andric     // Compute the bit offset into the register of the target element.
2957e8d8bef9SDimitry Andric     Register OffsetBits = getBitcastWiderVectorElementOffset(
2958e8d8bef9SDimitry Andric       MIRBuilder, Idx, NewEltSize, OldEltSize);
2959e8d8bef9SDimitry Andric 
2960e8d8bef9SDimitry Andric     Register InsertedElt = buildBitFieldInsert(MIRBuilder, ExtractedElt,
2961e8d8bef9SDimitry Andric                                                Val, OffsetBits);
2962e8d8bef9SDimitry Andric     if (CastTy.isVector()) {
2963e8d8bef9SDimitry Andric       InsertedElt = MIRBuilder.buildInsertVectorElement(
2964e8d8bef9SDimitry Andric         CastTy, CastVec, InsertedElt, ScaledIdx).getReg(0);
2965e8d8bef9SDimitry Andric     }
2966e8d8bef9SDimitry Andric 
2967e8d8bef9SDimitry Andric     MIRBuilder.buildBitcast(Dst, InsertedElt);
2968e8d8bef9SDimitry Andric     MI.eraseFromParent();
29695ffd83dbSDimitry Andric     return Legalized;
29705ffd83dbSDimitry Andric   }
2971e8d8bef9SDimitry Andric 
29725ffd83dbSDimitry Andric   return UnableToLegalize;
29730b57cec5SDimitry Andric }
29740b57cec5SDimitry Andric 
2975fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerLoad(GAnyLoad &LoadMI) {
29760b57cec5SDimitry Andric   // Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
2977fe6060f1SDimitry Andric   Register DstReg = LoadMI.getDstReg();
2978fe6060f1SDimitry Andric   Register PtrReg = LoadMI.getPointerReg();
29790b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2980fe6060f1SDimitry Andric   MachineMemOperand &MMO = LoadMI.getMMO();
2981fe6060f1SDimitry Andric   LLT MemTy = MMO.getMemoryType();
2982fe6060f1SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
29830b57cec5SDimitry Andric 
2984fe6060f1SDimitry Andric   unsigned MemSizeInBits = MemTy.getSizeInBits();
2985fe6060f1SDimitry Andric   unsigned MemStoreSizeInBits = 8 * MemTy.getSizeInBytes();
2986fe6060f1SDimitry Andric 
2987fe6060f1SDimitry Andric   if (MemSizeInBits != MemStoreSizeInBits) {
2988349cc55cSDimitry Andric     if (MemTy.isVector())
2989349cc55cSDimitry Andric       return UnableToLegalize;
2990349cc55cSDimitry Andric 
2991fe6060f1SDimitry Andric     // Promote to a byte-sized load if not loading an integral number of
2992fe6060f1SDimitry Andric     // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
2993fe6060f1SDimitry Andric     LLT WideMemTy = LLT::scalar(MemStoreSizeInBits);
2994fe6060f1SDimitry Andric     MachineMemOperand *NewMMO =
2995fe6060f1SDimitry Andric         MF.getMachineMemOperand(&MMO, MMO.getPointerInfo(), WideMemTy);
2996fe6060f1SDimitry Andric 
2997fe6060f1SDimitry Andric     Register LoadReg = DstReg;
2998fe6060f1SDimitry Andric     LLT LoadTy = DstTy;
2999fe6060f1SDimitry Andric 
3000fe6060f1SDimitry Andric     // If this wasn't already an extending load, we need to widen the result
3001fe6060f1SDimitry Andric     // register to avoid creating a load with a narrower result than the source.
3002fe6060f1SDimitry Andric     if (MemStoreSizeInBits > DstTy.getSizeInBits()) {
3003fe6060f1SDimitry Andric       LoadTy = WideMemTy;
3004fe6060f1SDimitry Andric       LoadReg = MRI.createGenericVirtualRegister(WideMemTy);
3005fe6060f1SDimitry Andric     }
3006fe6060f1SDimitry Andric 
3007fe6060f1SDimitry Andric     if (isa<GSExtLoad>(LoadMI)) {
3008fe6060f1SDimitry Andric       auto NewLoad = MIRBuilder.buildLoad(LoadTy, PtrReg, *NewMMO);
3009fe6060f1SDimitry Andric       MIRBuilder.buildSExtInReg(LoadReg, NewLoad, MemSizeInBits);
301081ad6265SDimitry Andric     } else if (isa<GZExtLoad>(LoadMI) || WideMemTy == LoadTy) {
3011fe6060f1SDimitry Andric       auto NewLoad = MIRBuilder.buildLoad(LoadTy, PtrReg, *NewMMO);
3012fe6060f1SDimitry Andric       // The extra bits are guaranteed to be zero, since we stored them that
3013fe6060f1SDimitry Andric       // way.  A zext load from Wide thus automatically gives zext from MemVT.
3014fe6060f1SDimitry Andric       MIRBuilder.buildAssertZExt(LoadReg, NewLoad, MemSizeInBits);
3015fe6060f1SDimitry Andric     } else {
3016fe6060f1SDimitry Andric       MIRBuilder.buildLoad(LoadReg, PtrReg, *NewMMO);
3017fe6060f1SDimitry Andric     }
3018fe6060f1SDimitry Andric 
3019fe6060f1SDimitry Andric     if (DstTy != LoadTy)
3020fe6060f1SDimitry Andric       MIRBuilder.buildTrunc(DstReg, LoadReg);
3021fe6060f1SDimitry Andric 
3022fe6060f1SDimitry Andric     LoadMI.eraseFromParent();
3023fe6060f1SDimitry Andric     return Legalized;
3024fe6060f1SDimitry Andric   }
3025fe6060f1SDimitry Andric 
3026fe6060f1SDimitry Andric   // Big endian lowering not implemented.
3027fe6060f1SDimitry Andric   if (MIRBuilder.getDataLayout().isBigEndian())
3028fe6060f1SDimitry Andric     return UnableToLegalize;
3029fe6060f1SDimitry Andric 
3030349cc55cSDimitry Andric   // This load needs splitting into power of 2 sized loads.
3031349cc55cSDimitry Andric   //
30328bcb0991SDimitry Andric   // Our strategy here is to generate anyextending loads for the smaller
30338bcb0991SDimitry Andric   // types up to next power-2 result type, and then combine the two larger
30348bcb0991SDimitry Andric   // result values together, before truncating back down to the non-pow-2
30358bcb0991SDimitry Andric   // type.
30368bcb0991SDimitry Andric   // E.g. v1 = i24 load =>
30375ffd83dbSDimitry Andric   // v2 = i32 zextload (2 byte)
30388bcb0991SDimitry Andric   // v3 = i32 load (1 byte)
30398bcb0991SDimitry Andric   // v4 = i32 shl v3, 16
30408bcb0991SDimitry Andric   // v5 = i32 or v4, v2
30418bcb0991SDimitry Andric   // v1 = i24 trunc v5
30428bcb0991SDimitry Andric   // By doing this we generate the correct truncate which should get
30438bcb0991SDimitry Andric   // combined away as an artifact with a matching extend.
3044349cc55cSDimitry Andric 
3045349cc55cSDimitry Andric   uint64_t LargeSplitSize, SmallSplitSize;
3046349cc55cSDimitry Andric 
3047349cc55cSDimitry Andric   if (!isPowerOf2_32(MemSizeInBits)) {
3048349cc55cSDimitry Andric     // This load needs splitting into power of 2 sized loads.
3049*06c3fb27SDimitry Andric     LargeSplitSize = llvm::bit_floor(MemSizeInBits);
3050349cc55cSDimitry Andric     SmallSplitSize = MemSizeInBits - LargeSplitSize;
3051349cc55cSDimitry Andric   } else {
3052349cc55cSDimitry Andric     // This is already a power of 2, but we still need to split this in half.
3053349cc55cSDimitry Andric     //
3054349cc55cSDimitry Andric     // Assume we're being asked to decompose an unaligned load.
3055349cc55cSDimitry Andric     // TODO: If this requires multiple splits, handle them all at once.
3056349cc55cSDimitry Andric     auto &Ctx = MF.getFunction().getContext();
3057349cc55cSDimitry Andric     if (TLI.allowsMemoryAccess(Ctx, MIRBuilder.getDataLayout(), MemTy, MMO))
3058349cc55cSDimitry Andric       return UnableToLegalize;
3059349cc55cSDimitry Andric 
3060349cc55cSDimitry Andric     SmallSplitSize = LargeSplitSize = MemSizeInBits / 2;
3061349cc55cSDimitry Andric   }
3062349cc55cSDimitry Andric 
3063349cc55cSDimitry Andric   if (MemTy.isVector()) {
3064349cc55cSDimitry Andric     // TODO: Handle vector extloads
3065349cc55cSDimitry Andric     if (MemTy != DstTy)
3066349cc55cSDimitry Andric       return UnableToLegalize;
3067349cc55cSDimitry Andric 
3068349cc55cSDimitry Andric     // TODO: We can do better than scalarizing the vector and at least split it
3069349cc55cSDimitry Andric     // in half.
3070349cc55cSDimitry Andric     return reduceLoadStoreWidth(LoadMI, 0, DstTy.getElementType());
3071349cc55cSDimitry Andric   }
30728bcb0991SDimitry Andric 
30738bcb0991SDimitry Andric   MachineMemOperand *LargeMMO =
30748bcb0991SDimitry Andric       MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
3075fe6060f1SDimitry Andric   MachineMemOperand *SmallMMO =
3076fe6060f1SDimitry Andric       MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
30778bcb0991SDimitry Andric 
30788bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(PtrReg);
3079fe6060f1SDimitry Andric   unsigned AnyExtSize = PowerOf2Ceil(DstTy.getSizeInBits());
30808bcb0991SDimitry Andric   LLT AnyExtTy = LLT::scalar(AnyExtSize);
3081fe6060f1SDimitry Andric   auto LargeLoad = MIRBuilder.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, AnyExtTy,
3082fe6060f1SDimitry Andric                                              PtrReg, *LargeMMO);
30838bcb0991SDimitry Andric 
3084fe6060f1SDimitry Andric   auto OffsetCst = MIRBuilder.buildConstant(LLT::scalar(PtrTy.getSizeInBits()),
3085fe6060f1SDimitry Andric                                             LargeSplitSize / 8);
3086480093f4SDimitry Andric   Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
3087fe6060f1SDimitry Andric   auto SmallPtr = MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst);
3088fe6060f1SDimitry Andric   auto SmallLoad = MIRBuilder.buildLoadInstr(LoadMI.getOpcode(), AnyExtTy,
3089fe6060f1SDimitry Andric                                              SmallPtr, *SmallMMO);
30908bcb0991SDimitry Andric 
30918bcb0991SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(AnyExtTy, LargeSplitSize);
30928bcb0991SDimitry Andric   auto Shift = MIRBuilder.buildShl(AnyExtTy, SmallLoad, ShiftAmt);
3093fe6060f1SDimitry Andric 
3094fe6060f1SDimitry Andric   if (AnyExtTy == DstTy)
3095fe6060f1SDimitry Andric     MIRBuilder.buildOr(DstReg, Shift, LargeLoad);
3096349cc55cSDimitry Andric   else if (AnyExtTy.getSizeInBits() != DstTy.getSizeInBits()) {
30978bcb0991SDimitry Andric     auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
3098fe6060f1SDimitry Andric     MIRBuilder.buildTrunc(DstReg, {Or});
3099349cc55cSDimitry Andric   } else {
3100349cc55cSDimitry Andric     assert(DstTy.isPointer() && "expected pointer");
3101349cc55cSDimitry Andric     auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
3102349cc55cSDimitry Andric 
3103349cc55cSDimitry Andric     // FIXME: We currently consider this to be illegal for non-integral address
3104349cc55cSDimitry Andric     // spaces, but we need still need a way to reinterpret the bits.
3105349cc55cSDimitry Andric     MIRBuilder.buildIntToPtr(DstReg, Or);
3106fe6060f1SDimitry Andric   }
3107fe6060f1SDimitry Andric 
3108fe6060f1SDimitry Andric   LoadMI.eraseFromParent();
31098bcb0991SDimitry Andric   return Legalized;
31108bcb0991SDimitry Andric }
3111e8d8bef9SDimitry Andric 
3112fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerStore(GStore &StoreMI) {
31138bcb0991SDimitry Andric   // Lower a non-power of 2 store into multiple pow-2 stores.
31148bcb0991SDimitry Andric   // E.g. split an i24 store into an i16 store + i8 store.
31158bcb0991SDimitry Andric   // We do this by first extending the stored value to the next largest power
31168bcb0991SDimitry Andric   // of 2 type, and then using truncating stores to store the components.
31178bcb0991SDimitry Andric   // By doing this, likewise with G_LOAD, generate an extend that can be
31188bcb0991SDimitry Andric   // artifact-combined away instead of leaving behind extracts.
3119fe6060f1SDimitry Andric   Register SrcReg = StoreMI.getValueReg();
3120fe6060f1SDimitry Andric   Register PtrReg = StoreMI.getPointerReg();
31218bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
3122fe6060f1SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
3123fe6060f1SDimitry Andric   MachineMemOperand &MMO = **StoreMI.memoperands_begin();
3124fe6060f1SDimitry Andric   LLT MemTy = MMO.getMemoryType();
3125fe6060f1SDimitry Andric 
3126fe6060f1SDimitry Andric   unsigned StoreWidth = MemTy.getSizeInBits();
3127fe6060f1SDimitry Andric   unsigned StoreSizeInBits = 8 * MemTy.getSizeInBytes();
3128fe6060f1SDimitry Andric 
3129fe6060f1SDimitry Andric   if (StoreWidth != StoreSizeInBits) {
3130349cc55cSDimitry Andric     if (SrcTy.isVector())
3131349cc55cSDimitry Andric       return UnableToLegalize;
3132349cc55cSDimitry Andric 
3133fe6060f1SDimitry Andric     // Promote to a byte-sized store with upper bits zero if not
3134fe6060f1SDimitry Andric     // storing an integral number of bytes.  For example, promote
3135fe6060f1SDimitry Andric     // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
3136fe6060f1SDimitry Andric     LLT WideTy = LLT::scalar(StoreSizeInBits);
3137fe6060f1SDimitry Andric 
3138fe6060f1SDimitry Andric     if (StoreSizeInBits > SrcTy.getSizeInBits()) {
3139fe6060f1SDimitry Andric       // Avoid creating a store with a narrower source than result.
3140fe6060f1SDimitry Andric       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
3141fe6060f1SDimitry Andric       SrcTy = WideTy;
3142fe6060f1SDimitry Andric     }
3143fe6060f1SDimitry Andric 
3144fe6060f1SDimitry Andric     auto ZextInReg = MIRBuilder.buildZExtInReg(SrcTy, SrcReg, StoreWidth);
3145fe6060f1SDimitry Andric 
3146fe6060f1SDimitry Andric     MachineMemOperand *NewMMO =
3147fe6060f1SDimitry Andric         MF.getMachineMemOperand(&MMO, MMO.getPointerInfo(), WideTy);
3148fe6060f1SDimitry Andric     MIRBuilder.buildStore(ZextInReg, PtrReg, *NewMMO);
3149fe6060f1SDimitry Andric     StoreMI.eraseFromParent();
3150fe6060f1SDimitry Andric     return Legalized;
3151fe6060f1SDimitry Andric   }
3152fe6060f1SDimitry Andric 
3153349cc55cSDimitry Andric   if (MemTy.isVector()) {
3154349cc55cSDimitry Andric     // TODO: Handle vector trunc stores
3155349cc55cSDimitry Andric     if (MemTy != SrcTy)
3156349cc55cSDimitry Andric       return UnableToLegalize;
3157349cc55cSDimitry Andric 
3158349cc55cSDimitry Andric     // TODO: We can do better than scalarizing the vector and at least split it
3159349cc55cSDimitry Andric     // in half.
3160349cc55cSDimitry Andric     return reduceLoadStoreWidth(StoreMI, 0, SrcTy.getElementType());
3161349cc55cSDimitry Andric   }
3162349cc55cSDimitry Andric 
3163349cc55cSDimitry Andric   unsigned MemSizeInBits = MemTy.getSizeInBits();
3164349cc55cSDimitry Andric   uint64_t LargeSplitSize, SmallSplitSize;
3165349cc55cSDimitry Andric 
3166349cc55cSDimitry Andric   if (!isPowerOf2_32(MemSizeInBits)) {
3167*06c3fb27SDimitry Andric     LargeSplitSize = llvm::bit_floor<uint64_t>(MemTy.getSizeInBits());
3168349cc55cSDimitry Andric     SmallSplitSize = MemTy.getSizeInBits() - LargeSplitSize;
3169349cc55cSDimitry Andric   } else {
3170349cc55cSDimitry Andric     auto &Ctx = MF.getFunction().getContext();
3171349cc55cSDimitry Andric     if (TLI.allowsMemoryAccess(Ctx, MIRBuilder.getDataLayout(), MemTy, MMO))
31728bcb0991SDimitry Andric       return UnableToLegalize; // Don't know what we're being asked to do.
31738bcb0991SDimitry Andric 
3174349cc55cSDimitry Andric     SmallSplitSize = LargeSplitSize = MemSizeInBits / 2;
3175349cc55cSDimitry Andric   }
3176349cc55cSDimitry Andric 
3177fe6060f1SDimitry Andric   // Extend to the next pow-2. If this store was itself the result of lowering,
3178fe6060f1SDimitry Andric   // e.g. an s56 store being broken into s32 + s24, we might have a stored type
3179349cc55cSDimitry Andric   // that's wider than the stored size.
3180349cc55cSDimitry Andric   unsigned AnyExtSize = PowerOf2Ceil(MemTy.getSizeInBits());
3181349cc55cSDimitry Andric   const LLT NewSrcTy = LLT::scalar(AnyExtSize);
3182349cc55cSDimitry Andric 
3183349cc55cSDimitry Andric   if (SrcTy.isPointer()) {
3184349cc55cSDimitry Andric     const LLT IntPtrTy = LLT::scalar(SrcTy.getSizeInBits());
3185349cc55cSDimitry Andric     SrcReg = MIRBuilder.buildPtrToInt(IntPtrTy, SrcReg).getReg(0);
3186349cc55cSDimitry Andric   }
3187349cc55cSDimitry Andric 
3188fe6060f1SDimitry Andric   auto ExtVal = MIRBuilder.buildAnyExtOrTrunc(NewSrcTy, SrcReg);
31898bcb0991SDimitry Andric 
31908bcb0991SDimitry Andric   // Obtain the smaller value by shifting away the larger value.
3191fe6060f1SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(NewSrcTy, LargeSplitSize);
3192fe6060f1SDimitry Andric   auto SmallVal = MIRBuilder.buildLShr(NewSrcTy, ExtVal, ShiftAmt);
31938bcb0991SDimitry Andric 
3194480093f4SDimitry Andric   // Generate the PtrAdd and truncating stores.
31958bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(PtrReg);
31965ffd83dbSDimitry Andric   auto OffsetCst = MIRBuilder.buildConstant(
31975ffd83dbSDimitry Andric     LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
3198480093f4SDimitry Andric   auto SmallPtr =
3199349cc55cSDimitry Andric     MIRBuilder.buildPtrAdd(PtrTy, PtrReg, OffsetCst);
32008bcb0991SDimitry Andric 
32018bcb0991SDimitry Andric   MachineMemOperand *LargeMMO =
32028bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
32038bcb0991SDimitry Andric   MachineMemOperand *SmallMMO =
32048bcb0991SDimitry Andric     MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
3205fe6060f1SDimitry Andric   MIRBuilder.buildStore(ExtVal, PtrReg, *LargeMMO);
3206fe6060f1SDimitry Andric   MIRBuilder.buildStore(SmallVal, SmallPtr, *SmallMMO);
3207fe6060f1SDimitry Andric   StoreMI.eraseFromParent();
32088bcb0991SDimitry Andric   return Legalized;
32098bcb0991SDimitry Andric }
3210e8d8bef9SDimitry Andric 
3211e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3212e8d8bef9SDimitry Andric LegalizerHelper::bitcast(MachineInstr &MI, unsigned TypeIdx, LLT CastTy) {
3213e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
3214e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD: {
3215e8d8bef9SDimitry Andric     if (TypeIdx != 0)
3216e8d8bef9SDimitry Andric       return UnableToLegalize;
3217fe6060f1SDimitry Andric     MachineMemOperand &MMO = **MI.memoperands_begin();
3218fe6060f1SDimitry Andric 
3219fe6060f1SDimitry Andric     // Not sure how to interpret a bitcast of an extending load.
3220fe6060f1SDimitry Andric     if (MMO.getMemoryType().getSizeInBits() != CastTy.getSizeInBits())
3221fe6060f1SDimitry Andric       return UnableToLegalize;
3222e8d8bef9SDimitry Andric 
3223e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3224e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
3225fe6060f1SDimitry Andric     MMO.setType(CastTy);
3226e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3227e8d8bef9SDimitry Andric     return Legalized;
3228e8d8bef9SDimitry Andric   }
3229e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE: {
3230e8d8bef9SDimitry Andric     if (TypeIdx != 0)
3231e8d8bef9SDimitry Andric       return UnableToLegalize;
3232e8d8bef9SDimitry Andric 
3233fe6060f1SDimitry Andric     MachineMemOperand &MMO = **MI.memoperands_begin();
3234fe6060f1SDimitry Andric 
3235fe6060f1SDimitry Andric     // Not sure how to interpret a bitcast of a truncating store.
3236fe6060f1SDimitry Andric     if (MMO.getMemoryType().getSizeInBits() != CastTy.getSizeInBits())
3237fe6060f1SDimitry Andric       return UnableToLegalize;
3238fe6060f1SDimitry Andric 
3239e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3240e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 0);
3241fe6060f1SDimitry Andric     MMO.setType(CastTy);
3242e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3243e8d8bef9SDimitry Andric     return Legalized;
3244e8d8bef9SDimitry Andric   }
3245e8d8bef9SDimitry Andric   case TargetOpcode::G_SELECT: {
3246e8d8bef9SDimitry Andric     if (TypeIdx != 0)
3247e8d8bef9SDimitry Andric       return UnableToLegalize;
3248e8d8bef9SDimitry Andric 
3249e8d8bef9SDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector()) {
3250e8d8bef9SDimitry Andric       LLVM_DEBUG(
3251e8d8bef9SDimitry Andric           dbgs() << "bitcast action not implemented for vector select\n");
3252e8d8bef9SDimitry Andric       return UnableToLegalize;
3253e8d8bef9SDimitry Andric     }
3254e8d8bef9SDimitry Andric 
3255e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3256e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
3257e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 3);
3258e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
3259e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3260e8d8bef9SDimitry Andric     return Legalized;
3261e8d8bef9SDimitry Andric   }
3262e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
3263e8d8bef9SDimitry Andric   case TargetOpcode::G_OR:
3264e8d8bef9SDimitry Andric   case TargetOpcode::G_XOR: {
3265e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3266e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 1);
3267e8d8bef9SDimitry Andric     bitcastSrc(MI, CastTy, 2);
3268e8d8bef9SDimitry Andric     bitcastDst(MI, CastTy, 0);
3269e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3270e8d8bef9SDimitry Andric     return Legalized;
3271e8d8bef9SDimitry Andric   }
3272e8d8bef9SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
3273e8d8bef9SDimitry Andric     return bitcastExtractVectorElt(MI, TypeIdx, CastTy);
3274e8d8bef9SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT:
3275e8d8bef9SDimitry Andric     return bitcastInsertVectorElt(MI, TypeIdx, CastTy);
3276e8d8bef9SDimitry Andric   default:
3277e8d8bef9SDimitry Andric     return UnableToLegalize;
3278e8d8bef9SDimitry Andric   }
3279e8d8bef9SDimitry Andric }
3280e8d8bef9SDimitry Andric 
3281e8d8bef9SDimitry Andric // Legalize an instruction by changing the opcode in place.
3282e8d8bef9SDimitry Andric void LegalizerHelper::changeOpcode(MachineInstr &MI, unsigned NewOpcode) {
3283e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3284e8d8bef9SDimitry Andric     MI.setDesc(MIRBuilder.getTII().get(NewOpcode));
3285e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3286e8d8bef9SDimitry Andric }
3287e8d8bef9SDimitry Andric 
3288e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3289e8d8bef9SDimitry Andric LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT LowerHintTy) {
3290e8d8bef9SDimitry Andric   using namespace TargetOpcode;
3291e8d8bef9SDimitry Andric 
3292e8d8bef9SDimitry Andric   switch(MI.getOpcode()) {
3293e8d8bef9SDimitry Andric   default:
3294e8d8bef9SDimitry Andric     return UnableToLegalize;
3295*06c3fb27SDimitry Andric   case TargetOpcode::G_FCONSTANT:
3296*06c3fb27SDimitry Andric     return lowerFConstant(MI);
3297e8d8bef9SDimitry Andric   case TargetOpcode::G_BITCAST:
3298e8d8bef9SDimitry Andric     return lowerBitcast(MI);
3299e8d8bef9SDimitry Andric   case TargetOpcode::G_SREM:
3300e8d8bef9SDimitry Andric   case TargetOpcode::G_UREM: {
3301e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3302e8d8bef9SDimitry Andric     auto Quot =
3303e8d8bef9SDimitry Andric         MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV, {Ty},
3304e8d8bef9SDimitry Andric                               {MI.getOperand(1), MI.getOperand(2)});
3305e8d8bef9SDimitry Andric 
3306e8d8bef9SDimitry Andric     auto Prod = MIRBuilder.buildMul(Ty, Quot, MI.getOperand(2));
3307e8d8bef9SDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MI.getOperand(1), Prod);
3308e8d8bef9SDimitry Andric     MI.eraseFromParent();
3309e8d8bef9SDimitry Andric     return Legalized;
3310e8d8bef9SDimitry Andric   }
3311e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDO:
3312e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBO:
3313e8d8bef9SDimitry Andric     return lowerSADDO_SSUBO(MI);
3314e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULH:
3315e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULH:
3316e8d8bef9SDimitry Andric     return lowerSMULH_UMULH(MI);
3317e8d8bef9SDimitry Andric   case TargetOpcode::G_SMULO:
3318e8d8bef9SDimitry Andric   case TargetOpcode::G_UMULO: {
3319e8d8bef9SDimitry Andric     // Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
3320e8d8bef9SDimitry Andric     // result.
3321*06c3fb27SDimitry Andric     auto [Res, Overflow, LHS, RHS] = MI.getFirst4Regs();
3322e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
3323e8d8bef9SDimitry Andric 
3324e8d8bef9SDimitry Andric     unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
3325e8d8bef9SDimitry Andric                           ? TargetOpcode::G_SMULH
3326e8d8bef9SDimitry Andric                           : TargetOpcode::G_UMULH;
3327e8d8bef9SDimitry Andric 
3328e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
3329e8d8bef9SDimitry Andric     const auto &TII = MIRBuilder.getTII();
3330e8d8bef9SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_MUL));
333181ad6265SDimitry Andric     MI.removeOperand(1);
3332e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
3333e8d8bef9SDimitry Andric 
3334e8d8bef9SDimitry Andric     auto HiPart = MIRBuilder.buildInstr(Opcode, {Ty}, {LHS, RHS});
3335e8d8bef9SDimitry Andric     auto Zero = MIRBuilder.buildConstant(Ty, 0);
3336e8d8bef9SDimitry Andric 
3337e8d8bef9SDimitry Andric     // Move insert point forward so we can use the Res register if needed.
3338e8d8bef9SDimitry Andric     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
3339e8d8bef9SDimitry Andric 
3340e8d8bef9SDimitry Andric     // For *signed* multiply, overflow is detected by checking:
3341e8d8bef9SDimitry Andric     // (hi != (lo >> bitwidth-1))
3342e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SMULH) {
3343e8d8bef9SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(Ty, Ty.getSizeInBits() - 1);
3344e8d8bef9SDimitry Andric       auto Shifted = MIRBuilder.buildAShr(Ty, Res, ShiftAmt);
3345e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
3346e8d8bef9SDimitry Andric     } else {
3347e8d8bef9SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
3348e8d8bef9SDimitry Andric     }
3349e8d8bef9SDimitry Andric     return Legalized;
3350e8d8bef9SDimitry Andric   }
3351e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
3352*06c3fb27SDimitry Andric     auto [Res, SubByReg] = MI.getFirst2Regs();
3353e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
3354e8d8bef9SDimitry Andric 
3355e8d8bef9SDimitry Andric     // TODO: Handle vector types once we are able to
3356e8d8bef9SDimitry Andric     // represent them.
3357e8d8bef9SDimitry Andric     if (Ty.isVector())
3358e8d8bef9SDimitry Andric       return UnableToLegalize;
3359e8d8bef9SDimitry Andric     auto SignMask =
3360e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignMask(Ty.getSizeInBits()));
3361e8d8bef9SDimitry Andric     MIRBuilder.buildXor(Res, SubByReg, SignMask);
3362e8d8bef9SDimitry Andric     MI.eraseFromParent();
3363e8d8bef9SDimitry Andric     return Legalized;
3364e8d8bef9SDimitry Andric   }
3365bdd1243dSDimitry Andric   case TargetOpcode::G_FSUB:
3366bdd1243dSDimitry Andric   case TargetOpcode::G_STRICT_FSUB: {
3367*06c3fb27SDimitry Andric     auto [Res, LHS, RHS] = MI.getFirst3Regs();
3368e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(Res);
3369e8d8bef9SDimitry Andric 
3370e8d8bef9SDimitry Andric     // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
3371bdd1243dSDimitry Andric     auto Neg = MIRBuilder.buildFNeg(Ty, RHS);
3372bdd1243dSDimitry Andric 
3373bdd1243dSDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_STRICT_FSUB)
3374bdd1243dSDimitry Andric       MIRBuilder.buildStrictFAdd(Res, LHS, Neg, MI.getFlags());
3375bdd1243dSDimitry Andric     else
3376e8d8bef9SDimitry Andric       MIRBuilder.buildFAdd(Res, LHS, Neg, MI.getFlags());
3377bdd1243dSDimitry Andric 
3378e8d8bef9SDimitry Andric     MI.eraseFromParent();
3379e8d8bef9SDimitry Andric     return Legalized;
3380e8d8bef9SDimitry Andric   }
3381e8d8bef9SDimitry Andric   case TargetOpcode::G_FMAD:
3382e8d8bef9SDimitry Andric     return lowerFMad(MI);
3383e8d8bef9SDimitry Andric   case TargetOpcode::G_FFLOOR:
3384e8d8bef9SDimitry Andric     return lowerFFloor(MI);
3385e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUND:
3386e8d8bef9SDimitry Andric     return lowerIntrinsicRound(MI);
3387e8d8bef9SDimitry Andric   case TargetOpcode::G_INTRINSIC_ROUNDEVEN: {
3388e8d8bef9SDimitry Andric     // Since round even is the assumed rounding mode for unconstrained FP
3389e8d8bef9SDimitry Andric     // operations, rint and roundeven are the same operation.
3390e8d8bef9SDimitry Andric     changeOpcode(MI, TargetOpcode::G_FRINT);
3391e8d8bef9SDimitry Andric     return Legalized;
3392e8d8bef9SDimitry Andric   }
3393e8d8bef9SDimitry Andric   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
3394*06c3fb27SDimitry Andric     auto [OldValRes, SuccessRes, Addr, CmpVal, NewVal] = MI.getFirst5Regs();
3395e8d8bef9SDimitry Andric     MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
3396e8d8bef9SDimitry Andric                                   **MI.memoperands_begin());
3397e8d8bef9SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
3398e8d8bef9SDimitry Andric     MI.eraseFromParent();
3399e8d8bef9SDimitry Andric     return Legalized;
3400e8d8bef9SDimitry Andric   }
3401e8d8bef9SDimitry Andric   case TargetOpcode::G_LOAD:
3402e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
3403e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
3404fe6060f1SDimitry Andric     return lowerLoad(cast<GAnyLoad>(MI));
3405e8d8bef9SDimitry Andric   case TargetOpcode::G_STORE:
3406fe6060f1SDimitry Andric     return lowerStore(cast<GStore>(MI));
34070b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
34080b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
34090b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ:
34100b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ:
34110b57cec5SDimitry Andric   case TargetOpcode::G_CTPOP:
3412e8d8bef9SDimitry Andric     return lowerBitCount(MI);
34130b57cec5SDimitry Andric   case G_UADDO: {
3414*06c3fb27SDimitry Andric     auto [Res, CarryOut, LHS, RHS] = MI.getFirst4Regs();
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, LHS, RHS);
34170b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, RHS);
34180b57cec5SDimitry Andric 
34190b57cec5SDimitry Andric     MI.eraseFromParent();
34200b57cec5SDimitry Andric     return Legalized;
34210b57cec5SDimitry Andric   }
34220b57cec5SDimitry Andric   case G_UADDE: {
3423*06c3fb27SDimitry Andric     auto [Res, CarryOut, LHS, RHS, CarryIn] = MI.getFirst5Regs();
34245ffd83dbSDimitry Andric     LLT Ty = MRI.getType(Res);
34250b57cec5SDimitry Andric 
34265ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildAdd(Ty, LHS, RHS);
34275ffd83dbSDimitry Andric     auto ZExtCarryIn = MIRBuilder.buildZExt(Ty, CarryIn);
34280b57cec5SDimitry Andric     MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
34290b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
34300b57cec5SDimitry Andric 
34310b57cec5SDimitry Andric     MI.eraseFromParent();
34320b57cec5SDimitry Andric     return Legalized;
34330b57cec5SDimitry Andric   }
34340b57cec5SDimitry Andric   case G_USUBO: {
3435*06c3fb27SDimitry Andric     auto [Res, BorrowOut, LHS, RHS] = MI.getFirst4Regs();
34360b57cec5SDimitry Andric 
34370b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, LHS, RHS);
34380b57cec5SDimitry Andric     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric     MI.eraseFromParent();
34410b57cec5SDimitry Andric     return Legalized;
34420b57cec5SDimitry Andric   }
34430b57cec5SDimitry Andric   case G_USUBE: {
3444*06c3fb27SDimitry Andric     auto [Res, BorrowOut, LHS, RHS, BorrowIn] = MI.getFirst5Regs();
34455ffd83dbSDimitry Andric     const LLT CondTy = MRI.getType(BorrowOut);
34465ffd83dbSDimitry Andric     const LLT Ty = MRI.getType(Res);
34470b57cec5SDimitry Andric 
34485ffd83dbSDimitry Andric     auto TmpRes = MIRBuilder.buildSub(Ty, LHS, RHS);
34495ffd83dbSDimitry Andric     auto ZExtBorrowIn = MIRBuilder.buildZExt(Ty, BorrowIn);
34500b57cec5SDimitry Andric     MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
34515ffd83dbSDimitry Andric 
34525ffd83dbSDimitry Andric     auto LHS_EQ_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, CondTy, LHS, RHS);
34535ffd83dbSDimitry Andric     auto LHS_ULT_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CondTy, LHS, RHS);
34540b57cec5SDimitry Andric     MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric     MI.eraseFromParent();
34570b57cec5SDimitry Andric     return Legalized;
34580b57cec5SDimitry Andric   }
34590b57cec5SDimitry Andric   case G_UITOFP:
3460e8d8bef9SDimitry Andric     return lowerUITOFP(MI);
34610b57cec5SDimitry Andric   case G_SITOFP:
3462e8d8bef9SDimitry Andric     return lowerSITOFP(MI);
34638bcb0991SDimitry Andric   case G_FPTOUI:
3464e8d8bef9SDimitry Andric     return lowerFPTOUI(MI);
34655ffd83dbSDimitry Andric   case G_FPTOSI:
34665ffd83dbSDimitry Andric     return lowerFPTOSI(MI);
34675ffd83dbSDimitry Andric   case G_FPTRUNC:
3468e8d8bef9SDimitry Andric     return lowerFPTRUNC(MI);
3469e8d8bef9SDimitry Andric   case G_FPOWI:
3470e8d8bef9SDimitry Andric     return lowerFPOWI(MI);
34710b57cec5SDimitry Andric   case G_SMIN:
34720b57cec5SDimitry Andric   case G_SMAX:
34730b57cec5SDimitry Andric   case G_UMIN:
34740b57cec5SDimitry Andric   case G_UMAX:
3475e8d8bef9SDimitry Andric     return lowerMinMax(MI);
34760b57cec5SDimitry Andric   case G_FCOPYSIGN:
3477e8d8bef9SDimitry Andric     return lowerFCopySign(MI);
34780b57cec5SDimitry Andric   case G_FMINNUM:
34790b57cec5SDimitry Andric   case G_FMAXNUM:
34800b57cec5SDimitry Andric     return lowerFMinNumMaxNum(MI);
34815ffd83dbSDimitry Andric   case G_MERGE_VALUES:
34825ffd83dbSDimitry Andric     return lowerMergeValues(MI);
34838bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
34848bcb0991SDimitry Andric     return lowerUnmergeValues(MI);
34858bcb0991SDimitry Andric   case TargetOpcode::G_SEXT_INREG: {
34868bcb0991SDimitry Andric     assert(MI.getOperand(2).isImm() && "Expected immediate");
34878bcb0991SDimitry Andric     int64_t SizeInBits = MI.getOperand(2).getImm();
34888bcb0991SDimitry Andric 
3489*06c3fb27SDimitry Andric     auto [DstReg, SrcReg] = MI.getFirst2Regs();
34908bcb0991SDimitry Andric     LLT DstTy = MRI.getType(DstReg);
34918bcb0991SDimitry Andric     Register TmpRes = MRI.createGenericVirtualRegister(DstTy);
34928bcb0991SDimitry Andric 
34938bcb0991SDimitry Andric     auto MIBSz = MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - SizeInBits);
34945ffd83dbSDimitry Andric     MIRBuilder.buildShl(TmpRes, SrcReg, MIBSz->getOperand(0));
34955ffd83dbSDimitry Andric     MIRBuilder.buildAShr(DstReg, TmpRes, MIBSz->getOperand(0));
34968bcb0991SDimitry Andric     MI.eraseFromParent();
34978bcb0991SDimitry Andric     return Legalized;
34988bcb0991SDimitry Andric   }
3499e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
3500e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
3501e8d8bef9SDimitry Andric     return lowerExtractInsertVectorElt(MI);
35028bcb0991SDimitry Andric   case G_SHUFFLE_VECTOR:
35038bcb0991SDimitry Andric     return lowerShuffleVector(MI);
35048bcb0991SDimitry Andric   case G_DYN_STACKALLOC:
35058bcb0991SDimitry Andric     return lowerDynStackAlloc(MI);
35068bcb0991SDimitry Andric   case G_EXTRACT:
35078bcb0991SDimitry Andric     return lowerExtract(MI);
35088bcb0991SDimitry Andric   case G_INSERT:
35098bcb0991SDimitry Andric     return lowerInsert(MI);
3510480093f4SDimitry Andric   case G_BSWAP:
3511480093f4SDimitry Andric     return lowerBswap(MI);
3512480093f4SDimitry Andric   case G_BITREVERSE:
3513480093f4SDimitry Andric     return lowerBitreverse(MI);
3514480093f4SDimitry Andric   case G_READ_REGISTER:
35155ffd83dbSDimitry Andric   case G_WRITE_REGISTER:
35165ffd83dbSDimitry Andric     return lowerReadWriteRegister(MI);
3517e8d8bef9SDimitry Andric   case G_UADDSAT:
3518e8d8bef9SDimitry Andric   case G_USUBSAT: {
3519e8d8bef9SDimitry Andric     // Try to make a reasonable guess about which lowering strategy to use. The
3520e8d8bef9SDimitry Andric     // target can override this with custom lowering and calling the
3521e8d8bef9SDimitry Andric     // implementation functions.
3522e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3523e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_UMIN, Ty}))
3524e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3525e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
35260b57cec5SDimitry Andric   }
3527e8d8bef9SDimitry Andric   case G_SADDSAT:
3528e8d8bef9SDimitry Andric   case G_SSUBSAT: {
3529e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3530e8d8bef9SDimitry Andric 
3531e8d8bef9SDimitry Andric     // FIXME: It would probably make more sense to see if G_SADDO is preferred,
3532e8d8bef9SDimitry Andric     // since it's a shorter expansion. However, we would need to figure out the
3533e8d8bef9SDimitry Andric     // preferred boolean type for the carry out for the query.
3534e8d8bef9SDimitry Andric     if (LI.isLegalOrCustom({G_SMIN, Ty}) && LI.isLegalOrCustom({G_SMAX, Ty}))
3535e8d8bef9SDimitry Andric       return lowerAddSubSatToMinMax(MI);
3536e8d8bef9SDimitry Andric     return lowerAddSubSatToAddoSubo(MI);
3537e8d8bef9SDimitry Andric   }
3538e8d8bef9SDimitry Andric   case G_SSHLSAT:
3539e8d8bef9SDimitry Andric   case G_USHLSAT:
3540e8d8bef9SDimitry Andric     return lowerShlSat(MI);
3541fe6060f1SDimitry Andric   case G_ABS:
3542fe6060f1SDimitry Andric     return lowerAbsToAddXor(MI);
3543e8d8bef9SDimitry Andric   case G_SELECT:
3544e8d8bef9SDimitry Andric     return lowerSelect(MI);
3545bdd1243dSDimitry Andric   case G_IS_FPCLASS:
3546bdd1243dSDimitry Andric     return lowerISFPCLASS(MI);
3547fe6060f1SDimitry Andric   case G_SDIVREM:
3548fe6060f1SDimitry Andric   case G_UDIVREM:
3549fe6060f1SDimitry Andric     return lowerDIVREM(MI);
3550fe6060f1SDimitry Andric   case G_FSHL:
3551fe6060f1SDimitry Andric   case G_FSHR:
3552fe6060f1SDimitry Andric     return lowerFunnelShift(MI);
3553fe6060f1SDimitry Andric   case G_ROTL:
3554fe6060f1SDimitry Andric   case G_ROTR:
3555fe6060f1SDimitry Andric     return lowerRotate(MI);
3556349cc55cSDimitry Andric   case G_MEMSET:
3557349cc55cSDimitry Andric   case G_MEMCPY:
3558349cc55cSDimitry Andric   case G_MEMMOVE:
3559349cc55cSDimitry Andric     return lowerMemCpyFamily(MI);
3560349cc55cSDimitry Andric   case G_MEMCPY_INLINE:
3561349cc55cSDimitry Andric     return lowerMemcpyInline(MI);
3562349cc55cSDimitry Andric   GISEL_VECREDUCE_CASES_NONSEQ
3563349cc55cSDimitry Andric     return lowerVectorReduction(MI);
3564e8d8bef9SDimitry Andric   }
3565e8d8bef9SDimitry Andric }
3566e8d8bef9SDimitry Andric 
3567e8d8bef9SDimitry Andric Align LegalizerHelper::getStackTemporaryAlignment(LLT Ty,
3568e8d8bef9SDimitry Andric                                                   Align MinAlign) const {
3569e8d8bef9SDimitry Andric   // FIXME: We're missing a way to go back from LLT to llvm::Type to query the
3570e8d8bef9SDimitry Andric   // datalayout for the preferred alignment. Also there should be a target hook
3571e8d8bef9SDimitry Andric   // for this to allow targets to reduce the alignment and ignore the
3572e8d8bef9SDimitry Andric   // datalayout. e.g. AMDGPU should always use a 4-byte alignment, regardless of
3573e8d8bef9SDimitry Andric   // the type.
3574e8d8bef9SDimitry Andric   return std::max(Align(PowerOf2Ceil(Ty.getSizeInBytes())), MinAlign);
3575e8d8bef9SDimitry Andric }
3576e8d8bef9SDimitry Andric 
3577e8d8bef9SDimitry Andric MachineInstrBuilder
3578e8d8bef9SDimitry Andric LegalizerHelper::createStackTemporary(TypeSize Bytes, Align Alignment,
3579e8d8bef9SDimitry Andric                                       MachinePointerInfo &PtrInfo) {
3580e8d8bef9SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
3581e8d8bef9SDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
3582e8d8bef9SDimitry Andric   int FrameIdx = MF.getFrameInfo().CreateStackObject(Bytes, Alignment, false);
3583e8d8bef9SDimitry Andric 
3584e8d8bef9SDimitry Andric   unsigned AddrSpace = DL.getAllocaAddrSpace();
3585e8d8bef9SDimitry Andric   LLT FramePtrTy = LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace));
3586e8d8bef9SDimitry Andric 
3587e8d8bef9SDimitry Andric   PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIdx);
3588e8d8bef9SDimitry Andric   return MIRBuilder.buildFrameIndex(FramePtrTy, FrameIdx);
3589e8d8bef9SDimitry Andric }
3590e8d8bef9SDimitry Andric 
3591e8d8bef9SDimitry Andric static Register clampDynamicVectorIndex(MachineIRBuilder &B, Register IdxReg,
3592e8d8bef9SDimitry Andric                                         LLT VecTy) {
3593e8d8bef9SDimitry Andric   int64_t IdxVal;
3594e8d8bef9SDimitry Andric   if (mi_match(IdxReg, *B.getMRI(), m_ICst(IdxVal)))
3595e8d8bef9SDimitry Andric     return IdxReg;
3596e8d8bef9SDimitry Andric 
3597e8d8bef9SDimitry Andric   LLT IdxTy = B.getMRI()->getType(IdxReg);
3598e8d8bef9SDimitry Andric   unsigned NElts = VecTy.getNumElements();
3599e8d8bef9SDimitry Andric   if (isPowerOf2_32(NElts)) {
3600e8d8bef9SDimitry Andric     APInt Imm = APInt::getLowBitsSet(IdxTy.getSizeInBits(), Log2_32(NElts));
3601e8d8bef9SDimitry Andric     return B.buildAnd(IdxTy, IdxReg, B.buildConstant(IdxTy, Imm)).getReg(0);
3602e8d8bef9SDimitry Andric   }
3603e8d8bef9SDimitry Andric 
3604e8d8bef9SDimitry Andric   return B.buildUMin(IdxTy, IdxReg, B.buildConstant(IdxTy, NElts - 1))
3605e8d8bef9SDimitry Andric       .getReg(0);
3606e8d8bef9SDimitry Andric }
3607e8d8bef9SDimitry Andric 
3608e8d8bef9SDimitry Andric Register LegalizerHelper::getVectorElementPointer(Register VecPtr, LLT VecTy,
3609e8d8bef9SDimitry Andric                                                   Register Index) {
3610e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
3611e8d8bef9SDimitry Andric 
3612e8d8bef9SDimitry Andric   // Calculate the element offset and add it to the pointer.
3613e8d8bef9SDimitry Andric   unsigned EltSize = EltTy.getSizeInBits() / 8; // FIXME: should be ABI size.
3614e8d8bef9SDimitry Andric   assert(EltSize * 8 == EltTy.getSizeInBits() &&
3615e8d8bef9SDimitry Andric          "Converting bits to bytes lost precision");
3616e8d8bef9SDimitry Andric 
3617e8d8bef9SDimitry Andric   Index = clampDynamicVectorIndex(MIRBuilder, Index, VecTy);
3618e8d8bef9SDimitry Andric 
3619e8d8bef9SDimitry Andric   LLT IdxTy = MRI.getType(Index);
3620e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(IdxTy, Index,
3621e8d8bef9SDimitry Andric                                  MIRBuilder.buildConstant(IdxTy, EltSize));
3622e8d8bef9SDimitry Andric 
3623e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(VecPtr);
3624e8d8bef9SDimitry Andric   return MIRBuilder.buildPtrAdd(PtrTy, VecPtr, Mul).getReg(0);
36250b57cec5SDimitry Andric }
36260b57cec5SDimitry Andric 
36270eae32dcSDimitry Andric #ifndef NDEBUG
36280eae32dcSDimitry Andric /// Check that all vector operands have same number of elements. Other operands
36290eae32dcSDimitry Andric /// should be listed in NonVecOp.
36300eae32dcSDimitry Andric static bool hasSameNumEltsOnAllVectorOperands(
36310eae32dcSDimitry Andric     GenericMachineInstr &MI, MachineRegisterInfo &MRI,
36320eae32dcSDimitry Andric     std::initializer_list<unsigned> NonVecOpIndices) {
36330eae32dcSDimitry Andric   if (MI.getNumMemOperands() != 0)
36340eae32dcSDimitry Andric     return false;
36350b57cec5SDimitry Andric 
36360eae32dcSDimitry Andric   LLT VecTy = MRI.getType(MI.getReg(0));
36370eae32dcSDimitry Andric   if (!VecTy.isVector())
36380eae32dcSDimitry Andric     return false;
36390eae32dcSDimitry Andric   unsigned NumElts = VecTy.getNumElements();
36400b57cec5SDimitry Andric 
36410eae32dcSDimitry Andric   for (unsigned OpIdx = 1; OpIdx < MI.getNumOperands(); ++OpIdx) {
36420eae32dcSDimitry Andric     MachineOperand &Op = MI.getOperand(OpIdx);
36430eae32dcSDimitry Andric     if (!Op.isReg()) {
36440eae32dcSDimitry Andric       if (!is_contained(NonVecOpIndices, OpIdx))
36450eae32dcSDimitry Andric         return false;
36460eae32dcSDimitry Andric       continue;
36470eae32dcSDimitry Andric     }
36480b57cec5SDimitry Andric 
36490eae32dcSDimitry Andric     LLT Ty = MRI.getType(Op.getReg());
36500eae32dcSDimitry Andric     if (!Ty.isVector()) {
36510eae32dcSDimitry Andric       if (!is_contained(NonVecOpIndices, OpIdx))
36520eae32dcSDimitry Andric         return false;
36530eae32dcSDimitry Andric       continue;
36540eae32dcSDimitry Andric     }
36550eae32dcSDimitry Andric 
36560eae32dcSDimitry Andric     if (Ty.getNumElements() != NumElts)
36570eae32dcSDimitry Andric       return false;
36580eae32dcSDimitry Andric   }
36590eae32dcSDimitry Andric 
36600eae32dcSDimitry Andric   return true;
36610eae32dcSDimitry Andric }
36620eae32dcSDimitry Andric #endif
36630eae32dcSDimitry Andric 
36640eae32dcSDimitry Andric /// Fill \p DstOps with DstOps that have same number of elements combined as
36650eae32dcSDimitry Andric /// the Ty. These DstOps have either scalar type when \p NumElts = 1 or are
36660eae32dcSDimitry Andric /// vectors with \p NumElts elements. When Ty.getNumElements() is not multiple
36670eae32dcSDimitry Andric /// of \p NumElts last DstOp (leftover) has fewer then \p NumElts elements.
36680eae32dcSDimitry Andric static void makeDstOps(SmallVectorImpl<DstOp> &DstOps, LLT Ty,
36690eae32dcSDimitry Andric                        unsigned NumElts) {
36700eae32dcSDimitry Andric   LLT LeftoverTy;
36710eae32dcSDimitry Andric   assert(Ty.isVector() && "Expected vector type");
36720eae32dcSDimitry Andric   LLT EltTy = Ty.getElementType();
36730eae32dcSDimitry Andric   LLT NarrowTy = (NumElts == 1) ? EltTy : LLT::fixed_vector(NumElts, EltTy);
36740eae32dcSDimitry Andric   int NumParts, NumLeftover;
36750eae32dcSDimitry Andric   std::tie(NumParts, NumLeftover) =
36760eae32dcSDimitry Andric       getNarrowTypeBreakDown(Ty, NarrowTy, LeftoverTy);
36770eae32dcSDimitry Andric 
36780eae32dcSDimitry Andric   assert(NumParts > 0 && "Error in getNarrowTypeBreakDown");
36790eae32dcSDimitry Andric   for (int i = 0; i < NumParts; ++i) {
36800eae32dcSDimitry Andric     DstOps.push_back(NarrowTy);
36810eae32dcSDimitry Andric   }
36820eae32dcSDimitry Andric 
36830eae32dcSDimitry Andric   if (LeftoverTy.isValid()) {
36840eae32dcSDimitry Andric     assert(NumLeftover == 1 && "expected exactly one leftover");
36850eae32dcSDimitry Andric     DstOps.push_back(LeftoverTy);
36860eae32dcSDimitry Andric   }
36870eae32dcSDimitry Andric }
36880eae32dcSDimitry Andric 
36890eae32dcSDimitry Andric /// Operand \p Op is used on \p N sub-instructions. Fill \p Ops with \p N SrcOps
36900eae32dcSDimitry Andric /// made from \p Op depending on operand type.
36910eae32dcSDimitry Andric static void broadcastSrcOp(SmallVectorImpl<SrcOp> &Ops, unsigned N,
36920eae32dcSDimitry Andric                            MachineOperand &Op) {
36930eae32dcSDimitry Andric   for (unsigned i = 0; i < N; ++i) {
36940eae32dcSDimitry Andric     if (Op.isReg())
36950eae32dcSDimitry Andric       Ops.push_back(Op.getReg());
36960eae32dcSDimitry Andric     else if (Op.isImm())
36970eae32dcSDimitry Andric       Ops.push_back(Op.getImm());
36980eae32dcSDimitry Andric     else if (Op.isPredicate())
36990eae32dcSDimitry Andric       Ops.push_back(static_cast<CmpInst::Predicate>(Op.getPredicate()));
37000eae32dcSDimitry Andric     else
37010eae32dcSDimitry Andric       llvm_unreachable("Unsupported type");
37020eae32dcSDimitry Andric   }
37030b57cec5SDimitry Andric }
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric // Handle splitting vector operations which need to have the same number of
37060b57cec5SDimitry Andric // elements in each type index, but each type index may have a different element
37070b57cec5SDimitry Andric // type.
37080b57cec5SDimitry Andric //
37090b57cec5SDimitry Andric // e.g.  <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
37100b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
37110b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
37120b57cec5SDimitry Andric //
37130b57cec5SDimitry Andric // Also handles some irregular breakdown cases, e.g.
37140b57cec5SDimitry Andric // e.g.  <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
37150b57cec5SDimitry Andric //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
37160b57cec5SDimitry Andric //             s64 = G_SHL s64, s32
37170b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
37180b57cec5SDimitry Andric LegalizerHelper::fewerElementsVectorMultiEltType(
37190eae32dcSDimitry Andric     GenericMachineInstr &MI, unsigned NumElts,
37200eae32dcSDimitry Andric     std::initializer_list<unsigned> NonVecOpIndices) {
37210eae32dcSDimitry Andric   assert(hasSameNumEltsOnAllVectorOperands(MI, MRI, NonVecOpIndices) &&
37220eae32dcSDimitry Andric          "Non-compatible opcode or not specified non-vector operands");
37230eae32dcSDimitry Andric   unsigned OrigNumElts = MRI.getType(MI.getReg(0)).getNumElements();
37240b57cec5SDimitry Andric 
37250eae32dcSDimitry Andric   unsigned NumInputs = MI.getNumOperands() - MI.getNumDefs();
37260eae32dcSDimitry Andric   unsigned NumDefs = MI.getNumDefs();
37270b57cec5SDimitry Andric 
37280eae32dcSDimitry Andric   // Create DstOps (sub-vectors with NumElts elts + Leftover) for each output.
37290eae32dcSDimitry Andric   // Build instructions with DstOps to use instruction found by CSE directly.
37300eae32dcSDimitry Andric   // CSE copies found instruction into given vreg when building with vreg dest.
37310eae32dcSDimitry Andric   SmallVector<SmallVector<DstOp, 8>, 2> OutputOpsPieces(NumDefs);
37320eae32dcSDimitry Andric   // Output registers will be taken from created instructions.
37330eae32dcSDimitry Andric   SmallVector<SmallVector<Register, 8>, 2> OutputRegs(NumDefs);
37340eae32dcSDimitry Andric   for (unsigned i = 0; i < NumDefs; ++i) {
37350eae32dcSDimitry Andric     makeDstOps(OutputOpsPieces[i], MRI.getType(MI.getReg(i)), NumElts);
37360b57cec5SDimitry Andric   }
37370b57cec5SDimitry Andric 
37380eae32dcSDimitry Andric   // Split vector input operands into sub-vectors with NumElts elts + Leftover.
37390eae32dcSDimitry Andric   // Operands listed in NonVecOpIndices will be used as is without splitting;
37400eae32dcSDimitry Andric   // examples: compare predicate in icmp and fcmp (op 1), vector select with i1
37410eae32dcSDimitry Andric   // scalar condition (op 1), immediate in sext_inreg (op 2).
37420eae32dcSDimitry Andric   SmallVector<SmallVector<SrcOp, 8>, 3> InputOpsPieces(NumInputs);
37430eae32dcSDimitry Andric   for (unsigned UseIdx = NumDefs, UseNo = 0; UseIdx < MI.getNumOperands();
37440eae32dcSDimitry Andric        ++UseIdx, ++UseNo) {
37450eae32dcSDimitry Andric     if (is_contained(NonVecOpIndices, UseIdx)) {
37460eae32dcSDimitry Andric       broadcastSrcOp(InputOpsPieces[UseNo], OutputOpsPieces[0].size(),
37470eae32dcSDimitry Andric                      MI.getOperand(UseIdx));
37480b57cec5SDimitry Andric     } else {
37490eae32dcSDimitry Andric       SmallVector<Register, 8> SplitPieces;
37500eae32dcSDimitry Andric       extractVectorParts(MI.getReg(UseIdx), NumElts, SplitPieces);
37510eae32dcSDimitry Andric       for (auto Reg : SplitPieces)
37520eae32dcSDimitry Andric         InputOpsPieces[UseNo].push_back(Reg);
37530eae32dcSDimitry Andric     }
37540b57cec5SDimitry Andric   }
37550b57cec5SDimitry Andric 
37560eae32dcSDimitry Andric   unsigned NumLeftovers = OrigNumElts % NumElts ? 1 : 0;
37570eae32dcSDimitry Andric 
37580eae32dcSDimitry Andric   // Take i-th piece of each input operand split and build sub-vector/scalar
37590eae32dcSDimitry Andric   // instruction. Set i-th DstOp(s) from OutputOpsPieces as destination(s).
37600eae32dcSDimitry Andric   for (unsigned i = 0; i < OrigNumElts / NumElts + NumLeftovers; ++i) {
37610eae32dcSDimitry Andric     SmallVector<DstOp, 2> Defs;
37620eae32dcSDimitry Andric     for (unsigned DstNo = 0; DstNo < NumDefs; ++DstNo)
37630eae32dcSDimitry Andric       Defs.push_back(OutputOpsPieces[DstNo][i]);
37640eae32dcSDimitry Andric 
37650eae32dcSDimitry Andric     SmallVector<SrcOp, 3> Uses;
37660eae32dcSDimitry Andric     for (unsigned InputNo = 0; InputNo < NumInputs; ++InputNo)
37670eae32dcSDimitry Andric       Uses.push_back(InputOpsPieces[InputNo][i]);
37680eae32dcSDimitry Andric 
37690eae32dcSDimitry Andric     auto I = MIRBuilder.buildInstr(MI.getOpcode(), Defs, Uses, MI.getFlags());
37700eae32dcSDimitry Andric     for (unsigned DstNo = 0; DstNo < NumDefs; ++DstNo)
37710eae32dcSDimitry Andric       OutputRegs[DstNo].push_back(I.getReg(DstNo));
37720b57cec5SDimitry Andric   }
37730b57cec5SDimitry Andric 
37740eae32dcSDimitry Andric   // Merge small outputs into MI's output for each def operand.
37750eae32dcSDimitry Andric   if (NumLeftovers) {
37760eae32dcSDimitry Andric     for (unsigned i = 0; i < NumDefs; ++i)
37770eae32dcSDimitry Andric       mergeMixedSubvectors(MI.getReg(i), OutputRegs[i]);
37780eae32dcSDimitry Andric   } else {
37790eae32dcSDimitry Andric     for (unsigned i = 0; i < NumDefs; ++i)
3780bdd1243dSDimitry Andric       MIRBuilder.buildMergeLikeInstr(MI.getReg(i), OutputRegs[i]);
37810eae32dcSDimitry Andric   }
37820b57cec5SDimitry Andric 
37830b57cec5SDimitry Andric   MI.eraseFromParent();
37840b57cec5SDimitry Andric   return Legalized;
37850b57cec5SDimitry Andric }
37860b57cec5SDimitry Andric 
37870b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
37880eae32dcSDimitry Andric LegalizerHelper::fewerElementsVectorPhi(GenericMachineInstr &MI,
37890eae32dcSDimitry Andric                                         unsigned NumElts) {
37900eae32dcSDimitry Andric   unsigned OrigNumElts = MRI.getType(MI.getReg(0)).getNumElements();
37910b57cec5SDimitry Andric 
37920eae32dcSDimitry Andric   unsigned NumInputs = MI.getNumOperands() - MI.getNumDefs();
37930eae32dcSDimitry Andric   unsigned NumDefs = MI.getNumDefs();
37940b57cec5SDimitry Andric 
37950eae32dcSDimitry Andric   SmallVector<DstOp, 8> OutputOpsPieces;
37960eae32dcSDimitry Andric   SmallVector<Register, 8> OutputRegs;
37970eae32dcSDimitry Andric   makeDstOps(OutputOpsPieces, MRI.getType(MI.getReg(0)), NumElts);
37980b57cec5SDimitry Andric 
37990eae32dcSDimitry Andric   // Instructions that perform register split will be inserted in basic block
38000eae32dcSDimitry Andric   // where register is defined (basic block is in the next operand).
38010eae32dcSDimitry Andric   SmallVector<SmallVector<Register, 8>, 3> InputOpsPieces(NumInputs / 2);
38020eae32dcSDimitry Andric   for (unsigned UseIdx = NumDefs, UseNo = 0; UseIdx < MI.getNumOperands();
38030eae32dcSDimitry Andric        UseIdx += 2, ++UseNo) {
38040eae32dcSDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(UseIdx + 1).getMBB();
3805bdd1243dSDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminatorForward());
38060eae32dcSDimitry Andric     extractVectorParts(MI.getReg(UseIdx), NumElts, InputOpsPieces[UseNo]);
38070b57cec5SDimitry Andric   }
38080eae32dcSDimitry Andric 
38090eae32dcSDimitry Andric   // Build PHIs with fewer elements.
38100eae32dcSDimitry Andric   unsigned NumLeftovers = OrigNumElts % NumElts ? 1 : 0;
38110eae32dcSDimitry Andric   MIRBuilder.setInsertPt(*MI.getParent(), MI);
38120eae32dcSDimitry Andric   for (unsigned i = 0; i < OrigNumElts / NumElts + NumLeftovers; ++i) {
38130eae32dcSDimitry Andric     auto Phi = MIRBuilder.buildInstr(TargetOpcode::G_PHI);
38140eae32dcSDimitry Andric     Phi.addDef(
38150eae32dcSDimitry Andric         MRI.createGenericVirtualRegister(OutputOpsPieces[i].getLLTTy(MRI)));
38160eae32dcSDimitry Andric     OutputRegs.push_back(Phi.getReg(0));
38170eae32dcSDimitry Andric 
38180eae32dcSDimitry Andric     for (unsigned j = 0; j < NumInputs / 2; ++j) {
38190eae32dcSDimitry Andric       Phi.addUse(InputOpsPieces[j][i]);
38200eae32dcSDimitry Andric       Phi.add(MI.getOperand(1 + j * 2 + 1));
38210eae32dcSDimitry Andric     }
38220eae32dcSDimitry Andric   }
38230eae32dcSDimitry Andric 
38240eae32dcSDimitry Andric   // Merge small outputs into MI's def.
38250eae32dcSDimitry Andric   if (NumLeftovers) {
38260eae32dcSDimitry Andric     mergeMixedSubvectors(MI.getReg(0), OutputRegs);
38270eae32dcSDimitry Andric   } else {
3828bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(MI.getReg(0), OutputRegs);
38290b57cec5SDimitry Andric   }
38300b57cec5SDimitry Andric 
38310b57cec5SDimitry Andric   MI.eraseFromParent();
38320b57cec5SDimitry Andric   return Legalized;
38330b57cec5SDimitry Andric }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
38368bcb0991SDimitry Andric LegalizerHelper::fewerElementsVectorUnmergeValues(MachineInstr &MI,
38378bcb0991SDimitry Andric                                                   unsigned TypeIdx,
38388bcb0991SDimitry Andric                                                   LLT NarrowTy) {
38398bcb0991SDimitry Andric   const int NumDst = MI.getNumOperands() - 1;
38408bcb0991SDimitry Andric   const Register SrcReg = MI.getOperand(NumDst).getReg();
38410eae32dcSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
38428bcb0991SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
38438bcb0991SDimitry Andric 
38440eae32dcSDimitry Andric   if (TypeIdx != 1 || NarrowTy == DstTy)
38458bcb0991SDimitry Andric     return UnableToLegalize;
38468bcb0991SDimitry Andric 
38470eae32dcSDimitry Andric   // Requires compatible types. Otherwise SrcReg should have been defined by
38480eae32dcSDimitry Andric   // merge-like instruction that would get artifact combined. Most likely
38490eae32dcSDimitry Andric   // instruction that defines SrcReg has to perform more/fewer elements
38500eae32dcSDimitry Andric   // legalization compatible with NarrowTy.
38510eae32dcSDimitry Andric   assert(SrcTy.isVector() && NarrowTy.isVector() && "Expected vector types");
38520eae32dcSDimitry Andric   assert((SrcTy.getScalarType() == NarrowTy.getScalarType()) && "bad type");
38538bcb0991SDimitry Andric 
38540eae32dcSDimitry Andric   if ((SrcTy.getSizeInBits() % NarrowTy.getSizeInBits() != 0) ||
38550eae32dcSDimitry Andric       (NarrowTy.getSizeInBits() % DstTy.getSizeInBits() != 0))
38560eae32dcSDimitry Andric     return UnableToLegalize;
38570eae32dcSDimitry Andric 
38580eae32dcSDimitry Andric   // This is most likely DstTy (smaller then register size) packed in SrcTy
38590eae32dcSDimitry Andric   // (larger then register size) and since unmerge was not combined it will be
38600eae32dcSDimitry Andric   // lowered to bit sequence extracts from register. Unpack SrcTy to NarrowTy
38610eae32dcSDimitry Andric   // (register size) pieces first. Then unpack each of NarrowTy pieces to DstTy.
38620eae32dcSDimitry Andric 
38630eae32dcSDimitry Andric   // %1:_(DstTy), %2, %3, %4 = G_UNMERGE_VALUES %0:_(SrcTy)
38640eae32dcSDimitry Andric   //
38650eae32dcSDimitry Andric   // %5:_(NarrowTy), %6 = G_UNMERGE_VALUES %0:_(SrcTy) - reg sequence
38660eae32dcSDimitry Andric   // %1:_(DstTy), %2 = G_UNMERGE_VALUES %5:_(NarrowTy) - sequence of bits in reg
38670eae32dcSDimitry Andric   // %3:_(DstTy), %4 = G_UNMERGE_VALUES %6:_(NarrowTy)
38680eae32dcSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(NarrowTy, SrcReg);
38698bcb0991SDimitry Andric   const int NumUnmerge = Unmerge->getNumOperands() - 1;
38708bcb0991SDimitry Andric   const int PartsPerUnmerge = NumDst / NumUnmerge;
38718bcb0991SDimitry Andric 
38728bcb0991SDimitry Andric   for (int I = 0; I != NumUnmerge; ++I) {
38738bcb0991SDimitry Andric     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
38748bcb0991SDimitry Andric 
38758bcb0991SDimitry Andric     for (int J = 0; J != PartsPerUnmerge; ++J)
38768bcb0991SDimitry Andric       MIB.addDef(MI.getOperand(I * PartsPerUnmerge + J).getReg());
38778bcb0991SDimitry Andric     MIB.addUse(Unmerge.getReg(I));
38788bcb0991SDimitry Andric   }
38798bcb0991SDimitry Andric 
38808bcb0991SDimitry Andric   MI.eraseFromParent();
38818bcb0991SDimitry Andric   return Legalized;
38828bcb0991SDimitry Andric }
38838bcb0991SDimitry Andric 
3884fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
3885e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorMerge(MachineInstr &MI, unsigned TypeIdx,
3886e8d8bef9SDimitry Andric                                           LLT NarrowTy) {
3887*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
38880eae32dcSDimitry Andric   // Requires compatible types. Otherwise user of DstReg did not perform unmerge
38890eae32dcSDimitry Andric   // that should have been artifact combined. Most likely instruction that uses
38900eae32dcSDimitry Andric   // DstReg has to do more/fewer elements legalization compatible with NarrowTy.
38910eae32dcSDimitry Andric   assert(DstTy.isVector() && NarrowTy.isVector() && "Expected vector types");
38920eae32dcSDimitry Andric   assert((DstTy.getScalarType() == NarrowTy.getScalarType()) && "bad type");
38930eae32dcSDimitry Andric   if (NarrowTy == SrcTy)
38940eae32dcSDimitry Andric     return UnableToLegalize;
38958bcb0991SDimitry Andric 
38960eae32dcSDimitry Andric   // This attempts to lower part of LCMTy merge/unmerge sequence. Intended use
38970eae32dcSDimitry Andric   // is for old mir tests. Since the changes to more/fewer elements it should no
38980eae32dcSDimitry Andric   // longer be possible to generate MIR like this when starting from llvm-ir
38990eae32dcSDimitry Andric   // because LCMTy approach was replaced with merge/unmerge to vector elements.
39000eae32dcSDimitry Andric   if (TypeIdx == 1) {
39010eae32dcSDimitry Andric     assert(SrcTy.isVector() && "Expected vector types");
39020eae32dcSDimitry Andric     assert((SrcTy.getScalarType() == NarrowTy.getScalarType()) && "bad type");
39030eae32dcSDimitry Andric     if ((DstTy.getSizeInBits() % NarrowTy.getSizeInBits() != 0) ||
39040eae32dcSDimitry Andric         (NarrowTy.getNumElements() >= SrcTy.getNumElements()))
39050eae32dcSDimitry Andric       return UnableToLegalize;
39060eae32dcSDimitry Andric     // %2:_(DstTy) = G_CONCAT_VECTORS %0:_(SrcTy), %1:_(SrcTy)
39070eae32dcSDimitry Andric     //
39080eae32dcSDimitry Andric     // %3:_(EltTy), %4, %5 = G_UNMERGE_VALUES %0:_(SrcTy)
39090eae32dcSDimitry Andric     // %6:_(EltTy), %7, %8 = G_UNMERGE_VALUES %1:_(SrcTy)
39100eae32dcSDimitry Andric     // %9:_(NarrowTy) = G_BUILD_VECTOR %3:_(EltTy), %4
39110eae32dcSDimitry Andric     // %10:_(NarrowTy) = G_BUILD_VECTOR %5:_(EltTy), %6
39120eae32dcSDimitry Andric     // %11:_(NarrowTy) = G_BUILD_VECTOR %7:_(EltTy), %8
39130eae32dcSDimitry Andric     // %2:_(DstTy) = G_CONCAT_VECTORS %9:_(NarrowTy), %10, %11
3914e8d8bef9SDimitry Andric 
39150eae32dcSDimitry Andric     SmallVector<Register, 8> Elts;
39160eae32dcSDimitry Andric     LLT EltTy = MRI.getType(MI.getOperand(1).getReg()).getScalarType();
39170eae32dcSDimitry Andric     for (unsigned i = 1; i < MI.getNumOperands(); ++i) {
39180eae32dcSDimitry Andric       auto Unmerge = MIRBuilder.buildUnmerge(EltTy, MI.getOperand(i).getReg());
39190eae32dcSDimitry Andric       for (unsigned j = 0; j < Unmerge->getNumDefs(); ++j)
39200eae32dcSDimitry Andric         Elts.push_back(Unmerge.getReg(j));
39210eae32dcSDimitry Andric     }
3922e8d8bef9SDimitry Andric 
39230eae32dcSDimitry Andric     SmallVector<Register, 8> NarrowTyElts;
39240eae32dcSDimitry Andric     unsigned NumNarrowTyElts = NarrowTy.getNumElements();
39250eae32dcSDimitry Andric     unsigned NumNarrowTyPieces = DstTy.getNumElements() / NumNarrowTyElts;
39260eae32dcSDimitry Andric     for (unsigned i = 0, Offset = 0; i < NumNarrowTyPieces;
39270eae32dcSDimitry Andric          ++i, Offset += NumNarrowTyElts) {
39280eae32dcSDimitry Andric       ArrayRef<Register> Pieces(&Elts[Offset], NumNarrowTyElts);
3929bdd1243dSDimitry Andric       NarrowTyElts.push_back(
3930bdd1243dSDimitry Andric           MIRBuilder.buildMergeLikeInstr(NarrowTy, Pieces).getReg(0));
39310eae32dcSDimitry Andric     }
3932e8d8bef9SDimitry Andric 
3933bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(DstReg, NarrowTyElts);
39340eae32dcSDimitry Andric     MI.eraseFromParent();
39350eae32dcSDimitry Andric     return Legalized;
39360eae32dcSDimitry Andric   }
39370eae32dcSDimitry Andric 
39380eae32dcSDimitry Andric   assert(TypeIdx == 0 && "Bad type index");
39390eae32dcSDimitry Andric   if ((NarrowTy.getSizeInBits() % SrcTy.getSizeInBits() != 0) ||
39400eae32dcSDimitry Andric       (DstTy.getSizeInBits() % NarrowTy.getSizeInBits() != 0))
39410eae32dcSDimitry Andric     return UnableToLegalize;
39420eae32dcSDimitry Andric 
39430eae32dcSDimitry Andric   // This is most likely SrcTy (smaller then register size) packed in DstTy
39440eae32dcSDimitry Andric   // (larger then register size) and since merge was not combined it will be
39450eae32dcSDimitry Andric   // lowered to bit sequence packing into register. Merge SrcTy to NarrowTy
39460eae32dcSDimitry Andric   // (register size) pieces first. Then merge each of NarrowTy pieces to DstTy.
39470eae32dcSDimitry Andric 
39480eae32dcSDimitry Andric   // %0:_(DstTy) = G_MERGE_VALUES %1:_(SrcTy), %2, %3, %4
39490eae32dcSDimitry Andric   //
39500eae32dcSDimitry Andric   // %5:_(NarrowTy) = G_MERGE_VALUES %1:_(SrcTy), %2 - sequence of bits in reg
39510eae32dcSDimitry Andric   // %6:_(NarrowTy) = G_MERGE_VALUES %3:_(SrcTy), %4
39520eae32dcSDimitry Andric   // %0:_(DstTy)  = G_MERGE_VALUES %5:_(NarrowTy), %6 - reg sequence
39530eae32dcSDimitry Andric   SmallVector<Register, 8> NarrowTyElts;
39540eae32dcSDimitry Andric   unsigned NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
39550eae32dcSDimitry Andric   unsigned NumSrcElts = SrcTy.isVector() ? SrcTy.getNumElements() : 1;
39560eae32dcSDimitry Andric   unsigned NumElts = NarrowTy.getNumElements() / NumSrcElts;
39570eae32dcSDimitry Andric   for (unsigned i = 0; i < NumParts; ++i) {
39580eae32dcSDimitry Andric     SmallVector<Register, 8> Sources;
39590eae32dcSDimitry Andric     for (unsigned j = 0; j < NumElts; ++j)
39600eae32dcSDimitry Andric       Sources.push_back(MI.getOperand(1 + i * NumElts + j).getReg());
3961bdd1243dSDimitry Andric     NarrowTyElts.push_back(
3962bdd1243dSDimitry Andric         MIRBuilder.buildMergeLikeInstr(NarrowTy, Sources).getReg(0));
39630eae32dcSDimitry Andric   }
39640eae32dcSDimitry Andric 
3965bdd1243dSDimitry Andric   MIRBuilder.buildMergeLikeInstr(DstReg, NarrowTyElts);
3966e8d8bef9SDimitry Andric   MI.eraseFromParent();
3967e8d8bef9SDimitry Andric   return Legalized;
39688bcb0991SDimitry Andric }
39698bcb0991SDimitry Andric 
3970e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
3971e8d8bef9SDimitry Andric LegalizerHelper::fewerElementsVectorExtractInsertVectorElt(MachineInstr &MI,
3972e8d8bef9SDimitry Andric                                                            unsigned TypeIdx,
3973e8d8bef9SDimitry Andric                                                            LLT NarrowVecTy) {
3974*06c3fb27SDimitry Andric   auto [DstReg, SrcVec] = MI.getFirst2Regs();
3975e8d8bef9SDimitry Andric   Register InsertVal;
3976e8d8bef9SDimitry Andric   bool IsInsert = MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT;
3977e8d8bef9SDimitry Andric 
3978e8d8bef9SDimitry Andric   assert((IsInsert ? TypeIdx == 0 : TypeIdx == 1) && "not a vector type index");
3979e8d8bef9SDimitry Andric   if (IsInsert)
3980e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
3981e8d8bef9SDimitry Andric 
3982e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
3983e8d8bef9SDimitry Andric 
3984e8d8bef9SDimitry Andric   // TODO: Handle total scalarization case.
3985e8d8bef9SDimitry Andric   if (!NarrowVecTy.isVector())
3986e8d8bef9SDimitry Andric     return UnableToLegalize;
3987e8d8bef9SDimitry Andric 
3988e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
3989e8d8bef9SDimitry Andric 
3990e8d8bef9SDimitry Andric   // If the index is a constant, we can really break this down as you would
3991e8d8bef9SDimitry Andric   // expect, and index into the target size pieces.
3992e8d8bef9SDimitry Andric   int64_t IdxVal;
3993349cc55cSDimitry Andric   auto MaybeCst = getIConstantVRegValWithLookThrough(Idx, MRI);
3994fe6060f1SDimitry Andric   if (MaybeCst) {
3995fe6060f1SDimitry Andric     IdxVal = MaybeCst->Value.getSExtValue();
3996e8d8bef9SDimitry Andric     // Avoid out of bounds indexing the pieces.
3997e8d8bef9SDimitry Andric     if (IdxVal >= VecTy.getNumElements()) {
3998e8d8bef9SDimitry Andric       MIRBuilder.buildUndef(DstReg);
3999e8d8bef9SDimitry Andric       MI.eraseFromParent();
4000e8d8bef9SDimitry Andric       return Legalized;
40018bcb0991SDimitry Andric     }
40028bcb0991SDimitry Andric 
4003e8d8bef9SDimitry Andric     SmallVector<Register, 8> VecParts;
4004e8d8bef9SDimitry Andric     LLT GCDTy = extractGCDType(VecParts, VecTy, NarrowVecTy, SrcVec);
4005e8d8bef9SDimitry Andric 
4006e8d8bef9SDimitry Andric     // Build a sequence of NarrowTy pieces in VecParts for this operand.
4007e8d8bef9SDimitry Andric     LLT LCMTy = buildLCMMergePieces(VecTy, NarrowVecTy, GCDTy, VecParts,
4008e8d8bef9SDimitry Andric                                     TargetOpcode::G_ANYEXT);
4009e8d8bef9SDimitry Andric 
4010e8d8bef9SDimitry Andric     unsigned NewNumElts = NarrowVecTy.getNumElements();
4011e8d8bef9SDimitry Andric 
4012e8d8bef9SDimitry Andric     LLT IdxTy = MRI.getType(Idx);
4013e8d8bef9SDimitry Andric     int64_t PartIdx = IdxVal / NewNumElts;
4014e8d8bef9SDimitry Andric     auto NewIdx =
4015e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(IdxTy, IdxVal - NewNumElts * PartIdx);
4016e8d8bef9SDimitry Andric 
4017e8d8bef9SDimitry Andric     if (IsInsert) {
4018e8d8bef9SDimitry Andric       LLT PartTy = MRI.getType(VecParts[PartIdx]);
4019e8d8bef9SDimitry Andric 
4020e8d8bef9SDimitry Andric       // Use the adjusted index to insert into one of the subvectors.
4021e8d8bef9SDimitry Andric       auto InsertPart = MIRBuilder.buildInsertVectorElement(
4022e8d8bef9SDimitry Andric           PartTy, VecParts[PartIdx], InsertVal, NewIdx);
4023e8d8bef9SDimitry Andric       VecParts[PartIdx] = InsertPart.getReg(0);
4024e8d8bef9SDimitry Andric 
4025e8d8bef9SDimitry Andric       // Recombine the inserted subvector with the others to reform the result
4026e8d8bef9SDimitry Andric       // vector.
4027e8d8bef9SDimitry Andric       buildWidenedRemergeToDst(DstReg, LCMTy, VecParts);
4028e8d8bef9SDimitry Andric     } else {
4029e8d8bef9SDimitry Andric       MIRBuilder.buildExtractVectorElement(DstReg, VecParts[PartIdx], NewIdx);
40308bcb0991SDimitry Andric     }
40318bcb0991SDimitry Andric 
40328bcb0991SDimitry Andric     MI.eraseFromParent();
40338bcb0991SDimitry Andric     return Legalized;
40348bcb0991SDimitry Andric   }
40358bcb0991SDimitry Andric 
4036e8d8bef9SDimitry Andric   // With a variable index, we can't perform the operation in a smaller type, so
4037e8d8bef9SDimitry Andric   // we're forced to expand this.
4038e8d8bef9SDimitry Andric   //
4039e8d8bef9SDimitry Andric   // TODO: We could emit a chain of compare/select to figure out which piece to
4040e8d8bef9SDimitry Andric   // index.
4041e8d8bef9SDimitry Andric   return lowerExtractInsertVectorElt(MI);
4042e8d8bef9SDimitry Andric }
4043e8d8bef9SDimitry Andric 
40448bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
4045fe6060f1SDimitry Andric LegalizerHelper::reduceLoadStoreWidth(GLoadStore &LdStMI, unsigned TypeIdx,
40460b57cec5SDimitry Andric                                       LLT NarrowTy) {
40470b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
40480b57cec5SDimitry Andric   if (TypeIdx != 0)
40490b57cec5SDimitry Andric     return UnableToLegalize;
40500b57cec5SDimitry Andric 
40510b57cec5SDimitry Andric   // This implementation doesn't work for atomics. Give up instead of doing
40520b57cec5SDimitry Andric   // something invalid.
4053fe6060f1SDimitry Andric   if (LdStMI.isAtomic())
40540b57cec5SDimitry Andric     return UnableToLegalize;
40550b57cec5SDimitry Andric 
4056fe6060f1SDimitry Andric   bool IsLoad = isa<GLoad>(LdStMI);
4057fe6060f1SDimitry Andric   Register ValReg = LdStMI.getReg(0);
4058fe6060f1SDimitry Andric   Register AddrReg = LdStMI.getPointerReg();
40590b57cec5SDimitry Andric   LLT ValTy = MRI.getType(ValReg);
40600b57cec5SDimitry Andric 
40615ffd83dbSDimitry Andric   // FIXME: Do we need a distinct NarrowMemory legalize action?
4062fe6060f1SDimitry Andric   if (ValTy.getSizeInBits() != 8 * LdStMI.getMemSize()) {
40635ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Can't narrow extload/truncstore\n");
40645ffd83dbSDimitry Andric     return UnableToLegalize;
40655ffd83dbSDimitry Andric   }
40665ffd83dbSDimitry Andric 
40670b57cec5SDimitry Andric   int NumParts = -1;
40680b57cec5SDimitry Andric   int NumLeftover = -1;
40690b57cec5SDimitry Andric   LLT LeftoverTy;
40700b57cec5SDimitry Andric   SmallVector<Register, 8> NarrowRegs, NarrowLeftoverRegs;
40710b57cec5SDimitry Andric   if (IsLoad) {
40720b57cec5SDimitry Andric     std::tie(NumParts, NumLeftover) = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
40730b57cec5SDimitry Andric   } else {
40740b57cec5SDimitry Andric     if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
40750b57cec5SDimitry Andric                      NarrowLeftoverRegs)) {
40760b57cec5SDimitry Andric       NumParts = NarrowRegs.size();
40770b57cec5SDimitry Andric       NumLeftover = NarrowLeftoverRegs.size();
40780b57cec5SDimitry Andric     }
40790b57cec5SDimitry Andric   }
40800b57cec5SDimitry Andric 
40810b57cec5SDimitry Andric   if (NumParts == -1)
40820b57cec5SDimitry Andric     return UnableToLegalize;
40830b57cec5SDimitry Andric 
4084e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(AddrReg);
4085e8d8bef9SDimitry Andric   const LLT OffsetTy = LLT::scalar(PtrTy.getSizeInBits());
40860b57cec5SDimitry Andric 
40870b57cec5SDimitry Andric   unsigned TotalSize = ValTy.getSizeInBits();
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric   // Split the load/store into PartTy sized pieces starting at Offset. If this
40900b57cec5SDimitry Andric   // is a load, return the new registers in ValRegs. For a store, each elements
40910b57cec5SDimitry Andric   // of ValRegs should be PartTy. Returns the next offset that needs to be
40920b57cec5SDimitry Andric   // handled.
409381ad6265SDimitry Andric   bool isBigEndian = MIRBuilder.getDataLayout().isBigEndian();
4094fe6060f1SDimitry Andric   auto MMO = LdStMI.getMMO();
40950b57cec5SDimitry Andric   auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<Register> &ValRegs,
409681ad6265SDimitry Andric                              unsigned NumParts, unsigned Offset) -> unsigned {
40970b57cec5SDimitry Andric     MachineFunction &MF = MIRBuilder.getMF();
40980b57cec5SDimitry Andric     unsigned PartSize = PartTy.getSizeInBits();
40990b57cec5SDimitry Andric     for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
410081ad6265SDimitry Andric          ++Idx) {
41010b57cec5SDimitry Andric       unsigned ByteOffset = Offset / 8;
41020b57cec5SDimitry Andric       Register NewAddrReg;
41030b57cec5SDimitry Andric 
4104480093f4SDimitry Andric       MIRBuilder.materializePtrAdd(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric       MachineMemOperand *NewMMO =
4107fe6060f1SDimitry Andric           MF.getMachineMemOperand(&MMO, ByteOffset, PartTy);
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric       if (IsLoad) {
41100b57cec5SDimitry Andric         Register Dst = MRI.createGenericVirtualRegister(PartTy);
41110b57cec5SDimitry Andric         ValRegs.push_back(Dst);
41120b57cec5SDimitry Andric         MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
41130b57cec5SDimitry Andric       } else {
41140b57cec5SDimitry Andric         MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
41150b57cec5SDimitry Andric       }
411681ad6265SDimitry Andric       Offset = isBigEndian ? Offset - PartSize : Offset + PartSize;
41170b57cec5SDimitry Andric     }
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric     return Offset;
41200b57cec5SDimitry Andric   };
41210b57cec5SDimitry Andric 
412281ad6265SDimitry Andric   unsigned Offset = isBigEndian ? TotalSize - NarrowTy.getSizeInBits() : 0;
412381ad6265SDimitry Andric   unsigned HandledOffset =
412481ad6265SDimitry Andric       splitTypePieces(NarrowTy, NarrowRegs, NumParts, Offset);
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric   // Handle the rest of the register if this isn't an even type breakdown.
41270b57cec5SDimitry Andric   if (LeftoverTy.isValid())
412881ad6265SDimitry Andric     splitTypePieces(LeftoverTy, NarrowLeftoverRegs, NumLeftover, HandledOffset);
41290b57cec5SDimitry Andric 
41300b57cec5SDimitry Andric   if (IsLoad) {
41310b57cec5SDimitry Andric     insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
41320b57cec5SDimitry Andric                 LeftoverTy, NarrowLeftoverRegs);
41330b57cec5SDimitry Andric   }
41340b57cec5SDimitry Andric 
4135fe6060f1SDimitry Andric   LdStMI.eraseFromParent();
41360b57cec5SDimitry Andric   return Legalized;
41370b57cec5SDimitry Andric }
41380b57cec5SDimitry Andric 
41390b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
41400b57cec5SDimitry Andric LegalizerHelper::fewerElementsVector(MachineInstr &MI, unsigned TypeIdx,
41410b57cec5SDimitry Andric                                      LLT NarrowTy) {
41420b57cec5SDimitry Andric   using namespace TargetOpcode;
41430eae32dcSDimitry Andric   GenericMachineInstr &GMI = cast<GenericMachineInstr>(MI);
41440eae32dcSDimitry Andric   unsigned NumElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
41450b57cec5SDimitry Andric 
41460b57cec5SDimitry Andric   switch (MI.getOpcode()) {
41470b57cec5SDimitry Andric   case G_IMPLICIT_DEF:
41485ffd83dbSDimitry Andric   case G_TRUNC:
41490b57cec5SDimitry Andric   case G_AND:
41500b57cec5SDimitry Andric   case G_OR:
41510b57cec5SDimitry Andric   case G_XOR:
41520b57cec5SDimitry Andric   case G_ADD:
41530b57cec5SDimitry Andric   case G_SUB:
41540b57cec5SDimitry Andric   case G_MUL:
4155e8d8bef9SDimitry Andric   case G_PTR_ADD:
41560b57cec5SDimitry Andric   case G_SMULH:
41570b57cec5SDimitry Andric   case G_UMULH:
41580b57cec5SDimitry Andric   case G_FADD:
41590b57cec5SDimitry Andric   case G_FMUL:
41600b57cec5SDimitry Andric   case G_FSUB:
41610b57cec5SDimitry Andric   case G_FNEG:
41620b57cec5SDimitry Andric   case G_FABS:
41630b57cec5SDimitry Andric   case G_FCANONICALIZE:
41640b57cec5SDimitry Andric   case G_FDIV:
41650b57cec5SDimitry Andric   case G_FREM:
41660b57cec5SDimitry Andric   case G_FMA:
41678bcb0991SDimitry Andric   case G_FMAD:
41680b57cec5SDimitry Andric   case G_FPOW:
41690b57cec5SDimitry Andric   case G_FEXP:
41700b57cec5SDimitry Andric   case G_FEXP2:
41710b57cec5SDimitry Andric   case G_FLOG:
41720b57cec5SDimitry Andric   case G_FLOG2:
41730b57cec5SDimitry Andric   case G_FLOG10:
4174*06c3fb27SDimitry Andric   case G_FLDEXP:
41750b57cec5SDimitry Andric   case G_FNEARBYINT:
41760b57cec5SDimitry Andric   case G_FCEIL:
41770b57cec5SDimitry Andric   case G_FFLOOR:
41780b57cec5SDimitry Andric   case G_FRINT:
41790b57cec5SDimitry Andric   case G_INTRINSIC_ROUND:
4180e8d8bef9SDimitry Andric   case G_INTRINSIC_ROUNDEVEN:
41810b57cec5SDimitry Andric   case G_INTRINSIC_TRUNC:
41820b57cec5SDimitry Andric   case G_FCOS:
41830b57cec5SDimitry Andric   case G_FSIN:
41840b57cec5SDimitry Andric   case G_FSQRT:
41850b57cec5SDimitry Andric   case G_BSWAP:
41868bcb0991SDimitry Andric   case G_BITREVERSE:
41870b57cec5SDimitry Andric   case G_SDIV:
4188480093f4SDimitry Andric   case G_UDIV:
4189480093f4SDimitry Andric   case G_SREM:
4190480093f4SDimitry Andric   case G_UREM:
4191fe6060f1SDimitry Andric   case G_SDIVREM:
4192fe6060f1SDimitry Andric   case G_UDIVREM:
41930b57cec5SDimitry Andric   case G_SMIN:
41940b57cec5SDimitry Andric   case G_SMAX:
41950b57cec5SDimitry Andric   case G_UMIN:
41960b57cec5SDimitry Andric   case G_UMAX:
4197fe6060f1SDimitry Andric   case G_ABS:
41980b57cec5SDimitry Andric   case G_FMINNUM:
41990b57cec5SDimitry Andric   case G_FMAXNUM:
42000b57cec5SDimitry Andric   case G_FMINNUM_IEEE:
42010b57cec5SDimitry Andric   case G_FMAXNUM_IEEE:
42020b57cec5SDimitry Andric   case G_FMINIMUM:
42030b57cec5SDimitry Andric   case G_FMAXIMUM:
42045ffd83dbSDimitry Andric   case G_FSHL:
42055ffd83dbSDimitry Andric   case G_FSHR:
4206349cc55cSDimitry Andric   case G_ROTL:
4207349cc55cSDimitry Andric   case G_ROTR:
42085ffd83dbSDimitry Andric   case G_FREEZE:
42095ffd83dbSDimitry Andric   case G_SADDSAT:
42105ffd83dbSDimitry Andric   case G_SSUBSAT:
42115ffd83dbSDimitry Andric   case G_UADDSAT:
42125ffd83dbSDimitry Andric   case G_USUBSAT:
4213fe6060f1SDimitry Andric   case G_UMULO:
4214fe6060f1SDimitry Andric   case G_SMULO:
42150b57cec5SDimitry Andric   case G_SHL:
42160b57cec5SDimitry Andric   case G_LSHR:
42170b57cec5SDimitry Andric   case G_ASHR:
4218e8d8bef9SDimitry Andric   case G_SSHLSAT:
4219e8d8bef9SDimitry Andric   case G_USHLSAT:
42200b57cec5SDimitry Andric   case G_CTLZ:
42210b57cec5SDimitry Andric   case G_CTLZ_ZERO_UNDEF:
42220b57cec5SDimitry Andric   case G_CTTZ:
42230b57cec5SDimitry Andric   case G_CTTZ_ZERO_UNDEF:
42240b57cec5SDimitry Andric   case G_CTPOP:
42250b57cec5SDimitry Andric   case G_FCOPYSIGN:
42260b57cec5SDimitry Andric   case G_ZEXT:
42270b57cec5SDimitry Andric   case G_SEXT:
42280b57cec5SDimitry Andric   case G_ANYEXT:
42290b57cec5SDimitry Andric   case G_FPEXT:
42300b57cec5SDimitry Andric   case G_FPTRUNC:
42310b57cec5SDimitry Andric   case G_SITOFP:
42320b57cec5SDimitry Andric   case G_UITOFP:
42330b57cec5SDimitry Andric   case G_FPTOSI:
42340b57cec5SDimitry Andric   case G_FPTOUI:
42350b57cec5SDimitry Andric   case G_INTTOPTR:
42360b57cec5SDimitry Andric   case G_PTRTOINT:
42370b57cec5SDimitry Andric   case G_ADDRSPACE_CAST:
423881ad6265SDimitry Andric   case G_UADDO:
423981ad6265SDimitry Andric   case G_USUBO:
424081ad6265SDimitry Andric   case G_UADDE:
424181ad6265SDimitry Andric   case G_USUBE:
424281ad6265SDimitry Andric   case G_SADDO:
424381ad6265SDimitry Andric   case G_SSUBO:
424481ad6265SDimitry Andric   case G_SADDE:
424581ad6265SDimitry Andric   case G_SSUBE:
4246bdd1243dSDimitry Andric   case G_STRICT_FADD:
4247bdd1243dSDimitry Andric   case G_STRICT_FSUB:
4248bdd1243dSDimitry Andric   case G_STRICT_FMUL:
4249bdd1243dSDimitry Andric   case G_STRICT_FMA:
4250*06c3fb27SDimitry Andric   case G_STRICT_FLDEXP:
4251*06c3fb27SDimitry Andric   case G_FFREXP:
42520eae32dcSDimitry Andric     return fewerElementsVectorMultiEltType(GMI, NumElts);
42530b57cec5SDimitry Andric   case G_ICMP:
42540b57cec5SDimitry Andric   case G_FCMP:
42550eae32dcSDimitry Andric     return fewerElementsVectorMultiEltType(GMI, NumElts, {1 /*cpm predicate*/});
4256bdd1243dSDimitry Andric   case G_IS_FPCLASS:
4257bdd1243dSDimitry Andric     return fewerElementsVectorMultiEltType(GMI, NumElts, {2, 3 /*mask,fpsem*/});
42580b57cec5SDimitry Andric   case G_SELECT:
42590eae32dcSDimitry Andric     if (MRI.getType(MI.getOperand(1).getReg()).isVector())
42600eae32dcSDimitry Andric       return fewerElementsVectorMultiEltType(GMI, NumElts);
42610eae32dcSDimitry Andric     return fewerElementsVectorMultiEltType(GMI, NumElts, {1 /*scalar cond*/});
42620b57cec5SDimitry Andric   case G_PHI:
42630eae32dcSDimitry Andric     return fewerElementsVectorPhi(GMI, NumElts);
42648bcb0991SDimitry Andric   case G_UNMERGE_VALUES:
42658bcb0991SDimitry Andric     return fewerElementsVectorUnmergeValues(MI, TypeIdx, NarrowTy);
42668bcb0991SDimitry Andric   case G_BUILD_VECTOR:
4267e8d8bef9SDimitry Andric     assert(TypeIdx == 0 && "not a vector type index");
4268e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4269e8d8bef9SDimitry Andric   case G_CONCAT_VECTORS:
4270e8d8bef9SDimitry Andric     if (TypeIdx != 1) // TODO: This probably does work as expected already.
4271e8d8bef9SDimitry Andric       return UnableToLegalize;
4272e8d8bef9SDimitry Andric     return fewerElementsVectorMerge(MI, TypeIdx, NarrowTy);
4273e8d8bef9SDimitry Andric   case G_EXTRACT_VECTOR_ELT:
4274e8d8bef9SDimitry Andric   case G_INSERT_VECTOR_ELT:
4275e8d8bef9SDimitry Andric     return fewerElementsVectorExtractInsertVectorElt(MI, TypeIdx, NarrowTy);
42760b57cec5SDimitry Andric   case G_LOAD:
42770b57cec5SDimitry Andric   case G_STORE:
4278fe6060f1SDimitry Andric     return reduceLoadStoreWidth(cast<GLoadStore>(MI), TypeIdx, NarrowTy);
42795ffd83dbSDimitry Andric   case G_SEXT_INREG:
42800eae32dcSDimitry Andric     return fewerElementsVectorMultiEltType(GMI, NumElts, {2 /*imm*/});
4281fe6060f1SDimitry Andric   GISEL_VECREDUCE_CASES_NONSEQ
4282fe6060f1SDimitry Andric     return fewerElementsVectorReductions(MI, TypeIdx, NarrowTy);
4283fe6060f1SDimitry Andric   case G_SHUFFLE_VECTOR:
4284fe6060f1SDimitry Andric     return fewerElementsVectorShuffle(MI, TypeIdx, NarrowTy);
42850b57cec5SDimitry Andric   default:
42860b57cec5SDimitry Andric     return UnableToLegalize;
42870b57cec5SDimitry Andric   }
42880b57cec5SDimitry Andric }
42890b57cec5SDimitry Andric 
4290fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorShuffle(
4291fe6060f1SDimitry Andric     MachineInstr &MI, unsigned int TypeIdx, LLT NarrowTy) {
4292fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
4293fe6060f1SDimitry Andric   if (TypeIdx != 0)
4294fe6060f1SDimitry Andric     return UnableToLegalize;
4295fe6060f1SDimitry Andric 
4296*06c3fb27SDimitry Andric   auto [DstReg, DstTy, Src1Reg, Src1Ty, Src2Reg, Src2Ty] =
4297*06c3fb27SDimitry Andric       MI.getFirst3RegLLTs();
4298fe6060f1SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
4299fe6060f1SDimitry Andric   // The shuffle should be canonicalized by now.
4300fe6060f1SDimitry Andric   if (DstTy != Src1Ty)
4301fe6060f1SDimitry Andric     return UnableToLegalize;
4302fe6060f1SDimitry Andric   if (DstTy != Src2Ty)
4303fe6060f1SDimitry Andric     return UnableToLegalize;
4304fe6060f1SDimitry Andric 
4305fe6060f1SDimitry Andric   if (!isPowerOf2_32(DstTy.getNumElements()))
4306fe6060f1SDimitry Andric     return UnableToLegalize;
4307fe6060f1SDimitry Andric 
4308fe6060f1SDimitry Andric   // We only support splitting a shuffle into 2, so adjust NarrowTy accordingly.
4309fe6060f1SDimitry Andric   // Further legalization attempts will be needed to do split further.
4310fe6060f1SDimitry Andric   NarrowTy =
4311fe6060f1SDimitry Andric       DstTy.changeElementCount(DstTy.getElementCount().divideCoefficientBy(2));
4312fe6060f1SDimitry Andric   unsigned NewElts = NarrowTy.getNumElements();
4313fe6060f1SDimitry Andric 
4314fe6060f1SDimitry Andric   SmallVector<Register> SplitSrc1Regs, SplitSrc2Regs;
4315fe6060f1SDimitry Andric   extractParts(Src1Reg, NarrowTy, 2, SplitSrc1Regs);
4316fe6060f1SDimitry Andric   extractParts(Src2Reg, NarrowTy, 2, SplitSrc2Regs);
4317fe6060f1SDimitry Andric   Register Inputs[4] = {SplitSrc1Regs[0], SplitSrc1Regs[1], SplitSrc2Regs[0],
4318fe6060f1SDimitry Andric                         SplitSrc2Regs[1]};
4319fe6060f1SDimitry Andric 
4320fe6060f1SDimitry Andric   Register Hi, Lo;
4321fe6060f1SDimitry Andric 
4322fe6060f1SDimitry Andric   // If Lo or Hi uses elements from at most two of the four input vectors, then
4323fe6060f1SDimitry Andric   // express it as a vector shuffle of those two inputs.  Otherwise extract the
4324fe6060f1SDimitry Andric   // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
4325fe6060f1SDimitry Andric   SmallVector<int, 16> Ops;
4326fe6060f1SDimitry Andric   for (unsigned High = 0; High < 2; ++High) {
4327fe6060f1SDimitry Andric     Register &Output = High ? Hi : Lo;
4328fe6060f1SDimitry Andric 
4329fe6060f1SDimitry Andric     // Build a shuffle mask for the output, discovering on the fly which
4330fe6060f1SDimitry Andric     // input vectors to use as shuffle operands (recorded in InputUsed).
4331fe6060f1SDimitry Andric     // If building a suitable shuffle vector proves too hard, then bail
4332fe6060f1SDimitry Andric     // out with useBuildVector set.
4333fe6060f1SDimitry Andric     unsigned InputUsed[2] = {-1U, -1U}; // Not yet discovered.
4334fe6060f1SDimitry Andric     unsigned FirstMaskIdx = High * NewElts;
4335fe6060f1SDimitry Andric     bool UseBuildVector = false;
4336fe6060f1SDimitry Andric     for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
4337fe6060f1SDimitry Andric       // The mask element.  This indexes into the input.
4338fe6060f1SDimitry Andric       int Idx = Mask[FirstMaskIdx + MaskOffset];
4339fe6060f1SDimitry Andric 
4340fe6060f1SDimitry Andric       // The input vector this mask element indexes into.
4341fe6060f1SDimitry Andric       unsigned Input = (unsigned)Idx / NewElts;
4342fe6060f1SDimitry Andric 
4343bdd1243dSDimitry Andric       if (Input >= std::size(Inputs)) {
4344fe6060f1SDimitry Andric         // The mask element does not index into any input vector.
4345fe6060f1SDimitry Andric         Ops.push_back(-1);
4346fe6060f1SDimitry Andric         continue;
4347fe6060f1SDimitry Andric       }
4348fe6060f1SDimitry Andric 
4349fe6060f1SDimitry Andric       // Turn the index into an offset from the start of the input vector.
4350fe6060f1SDimitry Andric       Idx -= Input * NewElts;
4351fe6060f1SDimitry Andric 
4352fe6060f1SDimitry Andric       // Find or create a shuffle vector operand to hold this input.
4353fe6060f1SDimitry Andric       unsigned OpNo;
4354bdd1243dSDimitry Andric       for (OpNo = 0; OpNo < std::size(InputUsed); ++OpNo) {
4355fe6060f1SDimitry Andric         if (InputUsed[OpNo] == Input) {
4356fe6060f1SDimitry Andric           // This input vector is already an operand.
4357fe6060f1SDimitry Andric           break;
4358fe6060f1SDimitry Andric         } else if (InputUsed[OpNo] == -1U) {
4359fe6060f1SDimitry Andric           // Create a new operand for this input vector.
4360fe6060f1SDimitry Andric           InputUsed[OpNo] = Input;
4361fe6060f1SDimitry Andric           break;
4362fe6060f1SDimitry Andric         }
4363fe6060f1SDimitry Andric       }
4364fe6060f1SDimitry Andric 
4365bdd1243dSDimitry Andric       if (OpNo >= std::size(InputUsed)) {
4366fe6060f1SDimitry Andric         // More than two input vectors used!  Give up on trying to create a
4367fe6060f1SDimitry Andric         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
4368fe6060f1SDimitry Andric         UseBuildVector = true;
4369fe6060f1SDimitry Andric         break;
4370fe6060f1SDimitry Andric       }
4371fe6060f1SDimitry Andric 
4372fe6060f1SDimitry Andric       // Add the mask index for the new shuffle vector.
4373fe6060f1SDimitry Andric       Ops.push_back(Idx + OpNo * NewElts);
4374fe6060f1SDimitry Andric     }
4375fe6060f1SDimitry Andric 
4376fe6060f1SDimitry Andric     if (UseBuildVector) {
4377fe6060f1SDimitry Andric       LLT EltTy = NarrowTy.getElementType();
4378fe6060f1SDimitry Andric       SmallVector<Register, 16> SVOps;
4379fe6060f1SDimitry Andric 
4380fe6060f1SDimitry Andric       // Extract the input elements by hand.
4381fe6060f1SDimitry Andric       for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
4382fe6060f1SDimitry Andric         // The mask element.  This indexes into the input.
4383fe6060f1SDimitry Andric         int Idx = Mask[FirstMaskIdx + MaskOffset];
4384fe6060f1SDimitry Andric 
4385fe6060f1SDimitry Andric         // The input vector this mask element indexes into.
4386fe6060f1SDimitry Andric         unsigned Input = (unsigned)Idx / NewElts;
4387fe6060f1SDimitry Andric 
4388bdd1243dSDimitry Andric         if (Input >= std::size(Inputs)) {
4389fe6060f1SDimitry Andric           // The mask element is "undef" or indexes off the end of the input.
4390fe6060f1SDimitry Andric           SVOps.push_back(MIRBuilder.buildUndef(EltTy).getReg(0));
4391fe6060f1SDimitry Andric           continue;
4392fe6060f1SDimitry Andric         }
4393fe6060f1SDimitry Andric 
4394fe6060f1SDimitry Andric         // Turn the index into an offset from the start of the input vector.
4395fe6060f1SDimitry Andric         Idx -= Input * NewElts;
4396fe6060f1SDimitry Andric 
4397fe6060f1SDimitry Andric         // Extract the vector element by hand.
4398fe6060f1SDimitry Andric         SVOps.push_back(MIRBuilder
4399fe6060f1SDimitry Andric                             .buildExtractVectorElement(
4400fe6060f1SDimitry Andric                                 EltTy, Inputs[Input],
4401fe6060f1SDimitry Andric                                 MIRBuilder.buildConstant(LLT::scalar(32), Idx))
4402fe6060f1SDimitry Andric                             .getReg(0));
4403fe6060f1SDimitry Andric       }
4404fe6060f1SDimitry Andric 
4405fe6060f1SDimitry Andric       // Construct the Lo/Hi output using a G_BUILD_VECTOR.
4406fe6060f1SDimitry Andric       Output = MIRBuilder.buildBuildVector(NarrowTy, SVOps).getReg(0);
4407fe6060f1SDimitry Andric     } else if (InputUsed[0] == -1U) {
4408fe6060f1SDimitry Andric       // No input vectors were used! The result is undefined.
4409fe6060f1SDimitry Andric       Output = MIRBuilder.buildUndef(NarrowTy).getReg(0);
4410fe6060f1SDimitry Andric     } else {
4411fe6060f1SDimitry Andric       Register Op0 = Inputs[InputUsed[0]];
4412fe6060f1SDimitry Andric       // If only one input was used, use an undefined vector for the other.
4413fe6060f1SDimitry Andric       Register Op1 = InputUsed[1] == -1U
4414fe6060f1SDimitry Andric                          ? MIRBuilder.buildUndef(NarrowTy).getReg(0)
4415fe6060f1SDimitry Andric                          : Inputs[InputUsed[1]];
4416fe6060f1SDimitry Andric       // At least one input vector was used. Create a new shuffle vector.
4417fe6060f1SDimitry Andric       Output = MIRBuilder.buildShuffleVector(NarrowTy, Op0, Op1, Ops).getReg(0);
4418fe6060f1SDimitry Andric     }
4419fe6060f1SDimitry Andric 
4420fe6060f1SDimitry Andric     Ops.clear();
4421fe6060f1SDimitry Andric   }
4422fe6060f1SDimitry Andric 
4423fe6060f1SDimitry Andric   MIRBuilder.buildConcatVectors(DstReg, {Lo, Hi});
4424fe6060f1SDimitry Andric   MI.eraseFromParent();
4425fe6060f1SDimitry Andric   return Legalized;
4426fe6060f1SDimitry Andric }
4427fe6060f1SDimitry Andric 
4428349cc55cSDimitry Andric static unsigned getScalarOpcForReduction(unsigned Opc) {
4429fe6060f1SDimitry Andric   unsigned ScalarOpc;
4430fe6060f1SDimitry Andric   switch (Opc) {
4431fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FADD:
4432fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FADD;
4433fe6060f1SDimitry Andric     break;
4434fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FMUL:
4435fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FMUL;
4436fe6060f1SDimitry Andric     break;
4437fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FMAX:
4438fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FMAXNUM;
4439fe6060f1SDimitry Andric     break;
4440fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_FMIN:
4441fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_FMINNUM;
4442fe6060f1SDimitry Andric     break;
4443fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_ADD:
4444fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_ADD;
4445fe6060f1SDimitry Andric     break;
4446fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_MUL:
4447fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_MUL;
4448fe6060f1SDimitry Andric     break;
4449fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_AND:
4450fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_AND;
4451fe6060f1SDimitry Andric     break;
4452fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_OR:
4453fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_OR;
4454fe6060f1SDimitry Andric     break;
4455fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_XOR:
4456fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_XOR;
4457fe6060f1SDimitry Andric     break;
4458fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_SMAX:
4459fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_SMAX;
4460fe6060f1SDimitry Andric     break;
4461fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_SMIN:
4462fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_SMIN;
4463fe6060f1SDimitry Andric     break;
4464fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_UMAX:
4465fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_UMAX;
4466fe6060f1SDimitry Andric     break;
4467fe6060f1SDimitry Andric   case TargetOpcode::G_VECREDUCE_UMIN:
4468fe6060f1SDimitry Andric     ScalarOpc = TargetOpcode::G_UMIN;
4469fe6060f1SDimitry Andric     break;
4470fe6060f1SDimitry Andric   default:
4471349cc55cSDimitry Andric     llvm_unreachable("Unhandled reduction");
4472fe6060f1SDimitry Andric   }
4473349cc55cSDimitry Andric   return ScalarOpc;
4474349cc55cSDimitry Andric }
4475349cc55cSDimitry Andric 
4476349cc55cSDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorReductions(
4477349cc55cSDimitry Andric     MachineInstr &MI, unsigned int TypeIdx, LLT NarrowTy) {
4478349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
4479349cc55cSDimitry Andric   assert(Opc != TargetOpcode::G_VECREDUCE_SEQ_FADD &&
4480349cc55cSDimitry Andric          Opc != TargetOpcode::G_VECREDUCE_SEQ_FMUL &&
4481349cc55cSDimitry Andric          "Sequential reductions not expected");
4482349cc55cSDimitry Andric 
4483349cc55cSDimitry Andric   if (TypeIdx != 1)
4484349cc55cSDimitry Andric     return UnableToLegalize;
4485349cc55cSDimitry Andric 
4486349cc55cSDimitry Andric   // The semantics of the normal non-sequential reductions allow us to freely
4487349cc55cSDimitry Andric   // re-associate the operation.
4488*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
4489349cc55cSDimitry Andric 
4490349cc55cSDimitry Andric   if (NarrowTy.isVector() &&
4491349cc55cSDimitry Andric       (SrcTy.getNumElements() % NarrowTy.getNumElements() != 0))
4492349cc55cSDimitry Andric     return UnableToLegalize;
4493349cc55cSDimitry Andric 
4494349cc55cSDimitry Andric   unsigned ScalarOpc = getScalarOpcForReduction(Opc);
4495349cc55cSDimitry Andric   SmallVector<Register> SplitSrcs;
4496349cc55cSDimitry Andric   // If NarrowTy is a scalar then we're being asked to scalarize.
4497349cc55cSDimitry Andric   const unsigned NumParts =
4498349cc55cSDimitry Andric       NarrowTy.isVector() ? SrcTy.getNumElements() / NarrowTy.getNumElements()
4499349cc55cSDimitry Andric                           : SrcTy.getNumElements();
4500349cc55cSDimitry Andric 
4501349cc55cSDimitry Andric   extractParts(SrcReg, NarrowTy, NumParts, SplitSrcs);
4502349cc55cSDimitry Andric   if (NarrowTy.isScalar()) {
4503349cc55cSDimitry Andric     if (DstTy != NarrowTy)
4504349cc55cSDimitry Andric       return UnableToLegalize; // FIXME: handle implicit extensions.
4505349cc55cSDimitry Andric 
4506349cc55cSDimitry Andric     if (isPowerOf2_32(NumParts)) {
4507349cc55cSDimitry Andric       // Generate a tree of scalar operations to reduce the critical path.
4508349cc55cSDimitry Andric       SmallVector<Register> PartialResults;
4509349cc55cSDimitry Andric       unsigned NumPartsLeft = NumParts;
4510349cc55cSDimitry Andric       while (NumPartsLeft > 1) {
4511349cc55cSDimitry Andric         for (unsigned Idx = 0; Idx < NumPartsLeft - 1; Idx += 2) {
4512349cc55cSDimitry Andric           PartialResults.emplace_back(
4513349cc55cSDimitry Andric               MIRBuilder
4514349cc55cSDimitry Andric                   .buildInstr(ScalarOpc, {NarrowTy},
4515349cc55cSDimitry Andric                               {SplitSrcs[Idx], SplitSrcs[Idx + 1]})
4516349cc55cSDimitry Andric                   .getReg(0));
4517349cc55cSDimitry Andric         }
4518349cc55cSDimitry Andric         SplitSrcs = PartialResults;
4519349cc55cSDimitry Andric         PartialResults.clear();
4520349cc55cSDimitry Andric         NumPartsLeft = SplitSrcs.size();
4521349cc55cSDimitry Andric       }
4522349cc55cSDimitry Andric       assert(SplitSrcs.size() == 1);
4523349cc55cSDimitry Andric       MIRBuilder.buildCopy(DstReg, SplitSrcs[0]);
4524349cc55cSDimitry Andric       MI.eraseFromParent();
4525349cc55cSDimitry Andric       return Legalized;
4526349cc55cSDimitry Andric     }
4527349cc55cSDimitry Andric     // If we can't generate a tree, then just do sequential operations.
4528349cc55cSDimitry Andric     Register Acc = SplitSrcs[0];
4529349cc55cSDimitry Andric     for (unsigned Idx = 1; Idx < NumParts; ++Idx)
4530349cc55cSDimitry Andric       Acc = MIRBuilder.buildInstr(ScalarOpc, {NarrowTy}, {Acc, SplitSrcs[Idx]})
4531349cc55cSDimitry Andric                 .getReg(0);
4532349cc55cSDimitry Andric     MIRBuilder.buildCopy(DstReg, Acc);
4533349cc55cSDimitry Andric     MI.eraseFromParent();
4534349cc55cSDimitry Andric     return Legalized;
4535349cc55cSDimitry Andric   }
4536349cc55cSDimitry Andric   SmallVector<Register> PartialReductions;
4537349cc55cSDimitry Andric   for (unsigned Part = 0; Part < NumParts; ++Part) {
4538349cc55cSDimitry Andric     PartialReductions.push_back(
4539349cc55cSDimitry Andric         MIRBuilder.buildInstr(Opc, {DstTy}, {SplitSrcs[Part]}).getReg(0));
4540349cc55cSDimitry Andric   }
4541349cc55cSDimitry Andric 
4542fe6060f1SDimitry Andric 
4543fe6060f1SDimitry Andric   // If the types involved are powers of 2, we can generate intermediate vector
4544fe6060f1SDimitry Andric   // ops, before generating a final reduction operation.
4545fe6060f1SDimitry Andric   if (isPowerOf2_32(SrcTy.getNumElements()) &&
4546fe6060f1SDimitry Andric       isPowerOf2_32(NarrowTy.getNumElements())) {
4547fe6060f1SDimitry Andric     return tryNarrowPow2Reduction(MI, SrcReg, SrcTy, NarrowTy, ScalarOpc);
4548fe6060f1SDimitry Andric   }
4549fe6060f1SDimitry Andric 
4550fe6060f1SDimitry Andric   Register Acc = PartialReductions[0];
4551fe6060f1SDimitry Andric   for (unsigned Part = 1; Part < NumParts; ++Part) {
4552fe6060f1SDimitry Andric     if (Part == NumParts - 1) {
4553fe6060f1SDimitry Andric       MIRBuilder.buildInstr(ScalarOpc, {DstReg},
4554fe6060f1SDimitry Andric                             {Acc, PartialReductions[Part]});
4555fe6060f1SDimitry Andric     } else {
4556fe6060f1SDimitry Andric       Acc = MIRBuilder
4557fe6060f1SDimitry Andric                 .buildInstr(ScalarOpc, {DstTy}, {Acc, PartialReductions[Part]})
4558fe6060f1SDimitry Andric                 .getReg(0);
4559fe6060f1SDimitry Andric     }
4560fe6060f1SDimitry Andric   }
4561fe6060f1SDimitry Andric   MI.eraseFromParent();
4562fe6060f1SDimitry Andric   return Legalized;
4563fe6060f1SDimitry Andric }
4564fe6060f1SDimitry Andric 
4565fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
4566fe6060f1SDimitry Andric LegalizerHelper::tryNarrowPow2Reduction(MachineInstr &MI, Register SrcReg,
4567fe6060f1SDimitry Andric                                         LLT SrcTy, LLT NarrowTy,
4568fe6060f1SDimitry Andric                                         unsigned ScalarOpc) {
4569fe6060f1SDimitry Andric   SmallVector<Register> SplitSrcs;
4570fe6060f1SDimitry Andric   // Split the sources into NarrowTy size pieces.
4571fe6060f1SDimitry Andric   extractParts(SrcReg, NarrowTy,
4572fe6060f1SDimitry Andric                SrcTy.getNumElements() / NarrowTy.getNumElements(), SplitSrcs);
4573fe6060f1SDimitry Andric   // We're going to do a tree reduction using vector operations until we have
4574fe6060f1SDimitry Andric   // one NarrowTy size value left.
4575fe6060f1SDimitry Andric   while (SplitSrcs.size() > 1) {
4576fe6060f1SDimitry Andric     SmallVector<Register> PartialRdxs;
4577fe6060f1SDimitry Andric     for (unsigned Idx = 0; Idx < SplitSrcs.size()-1; Idx += 2) {
4578fe6060f1SDimitry Andric       Register LHS = SplitSrcs[Idx];
4579fe6060f1SDimitry Andric       Register RHS = SplitSrcs[Idx + 1];
4580fe6060f1SDimitry Andric       // Create the intermediate vector op.
4581fe6060f1SDimitry Andric       Register Res =
4582fe6060f1SDimitry Andric           MIRBuilder.buildInstr(ScalarOpc, {NarrowTy}, {LHS, RHS}).getReg(0);
4583fe6060f1SDimitry Andric       PartialRdxs.push_back(Res);
4584fe6060f1SDimitry Andric     }
4585fe6060f1SDimitry Andric     SplitSrcs = std::move(PartialRdxs);
4586fe6060f1SDimitry Andric   }
4587fe6060f1SDimitry Andric   // Finally generate the requested NarrowTy based reduction.
4588fe6060f1SDimitry Andric   Observer.changingInstr(MI);
4589fe6060f1SDimitry Andric   MI.getOperand(1).setReg(SplitSrcs[0]);
4590fe6060f1SDimitry Andric   Observer.changedInstr(MI);
4591fe6060f1SDimitry Andric   return Legalized;
4592fe6060f1SDimitry Andric }
4593fe6060f1SDimitry Andric 
45940b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
45950b57cec5SDimitry Andric LegalizerHelper::narrowScalarShiftByConstant(MachineInstr &MI, const APInt &Amt,
45960b57cec5SDimitry Andric                                              const LLT HalfTy, const LLT AmtTy) {
45970b57cec5SDimitry Andric 
45980b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
45990b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
46005ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
46010b57cec5SDimitry Andric 
4602349cc55cSDimitry Andric   if (Amt.isZero()) {
4603bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(MI.getOperand(0), {InL, InH});
46040b57cec5SDimitry Andric     MI.eraseFromParent();
46050b57cec5SDimitry Andric     return Legalized;
46060b57cec5SDimitry Andric   }
46070b57cec5SDimitry Andric 
46080b57cec5SDimitry Andric   LLT NVT = HalfTy;
46090b57cec5SDimitry Andric   unsigned NVTBits = HalfTy.getSizeInBits();
46100b57cec5SDimitry Andric   unsigned VTBits = 2 * NVTBits;
46110b57cec5SDimitry Andric 
46120b57cec5SDimitry Andric   SrcOp Lo(Register(0)), Hi(Register(0));
46130b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_SHL) {
46140b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
46150b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
46160b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
46170b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
46180b57cec5SDimitry Andric       Hi = MIRBuilder.buildShl(NVT, InL,
46190b57cec5SDimitry Andric                                MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
46200b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
46210b57cec5SDimitry Andric       Lo = MIRBuilder.buildConstant(NVT, 0);
46220b57cec5SDimitry Andric       Hi = InL;
46230b57cec5SDimitry Andric     } else {
46240b57cec5SDimitry Andric       Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
46250b57cec5SDimitry Andric       auto OrLHS =
46260b57cec5SDimitry Andric           MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
46270b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildLShr(
46280b57cec5SDimitry Andric           NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
46290b57cec5SDimitry Andric       Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
46300b57cec5SDimitry Andric     }
46310b57cec5SDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
46320b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
46330b57cec5SDimitry Andric       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
46340b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
46350b57cec5SDimitry Andric       Lo = MIRBuilder.buildLShr(NVT, InH,
46360b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
46370b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
46380b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
46390b57cec5SDimitry Andric       Lo = InH;
46400b57cec5SDimitry Andric       Hi = MIRBuilder.buildConstant(NVT, 0);
46410b57cec5SDimitry Andric     } else {
46420b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
46430b57cec5SDimitry Andric 
46440b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
46450b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
46460b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
46470b57cec5SDimitry Andric 
46480b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
46490b57cec5SDimitry Andric       Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
46500b57cec5SDimitry Andric     }
46510b57cec5SDimitry Andric   } else {
46520b57cec5SDimitry Andric     if (Amt.ugt(VTBits)) {
46530b57cec5SDimitry Andric       Hi = Lo = MIRBuilder.buildAShr(
46540b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
46550b57cec5SDimitry Andric     } else if (Amt.ugt(NVTBits)) {
46560b57cec5SDimitry Andric       Lo = MIRBuilder.buildAShr(NVT, InH,
46570b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
46580b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
46590b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
46600b57cec5SDimitry Andric     } else if (Amt == NVTBits) {
46610b57cec5SDimitry Andric       Lo = InH;
46620b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH,
46630b57cec5SDimitry Andric                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
46640b57cec5SDimitry Andric     } else {
46650b57cec5SDimitry Andric       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
46660b57cec5SDimitry Andric 
46670b57cec5SDimitry Andric       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
46680b57cec5SDimitry Andric       auto OrRHS = MIRBuilder.buildShl(
46690b57cec5SDimitry Andric           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
46700b57cec5SDimitry Andric 
46710b57cec5SDimitry Andric       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
46720b57cec5SDimitry Andric       Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
46730b57cec5SDimitry Andric     }
46740b57cec5SDimitry Andric   }
46750b57cec5SDimitry Andric 
4676bdd1243dSDimitry Andric   MIRBuilder.buildMergeLikeInstr(MI.getOperand(0), {Lo, Hi});
46770b57cec5SDimitry Andric   MI.eraseFromParent();
46780b57cec5SDimitry Andric 
46790b57cec5SDimitry Andric   return Legalized;
46800b57cec5SDimitry Andric }
46810b57cec5SDimitry Andric 
46820b57cec5SDimitry Andric // TODO: Optimize if constant shift amount.
46830b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
46840b57cec5SDimitry Andric LegalizerHelper::narrowScalarShift(MachineInstr &MI, unsigned TypeIdx,
46850b57cec5SDimitry Andric                                    LLT RequestedTy) {
46860b57cec5SDimitry Andric   if (TypeIdx == 1) {
46870b57cec5SDimitry Andric     Observer.changingInstr(MI);
46880b57cec5SDimitry Andric     narrowScalarSrc(MI, RequestedTy, 2);
46890b57cec5SDimitry Andric     Observer.changedInstr(MI);
46900b57cec5SDimitry Andric     return Legalized;
46910b57cec5SDimitry Andric   }
46920b57cec5SDimitry Andric 
46930b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
46940b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
46950b57cec5SDimitry Andric   if (DstTy.isVector())
46960b57cec5SDimitry Andric     return UnableToLegalize;
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
46990b57cec5SDimitry Andric   LLT ShiftAmtTy = MRI.getType(Amt);
47000b57cec5SDimitry Andric   const unsigned DstEltSize = DstTy.getScalarSizeInBits();
47010b57cec5SDimitry Andric   if (DstEltSize % 2 != 0)
47020b57cec5SDimitry Andric     return UnableToLegalize;
47030b57cec5SDimitry Andric 
47040b57cec5SDimitry Andric   // Ignore the input type. We can only go to exactly half the size of the
47050b57cec5SDimitry Andric   // input. If that isn't small enough, the resulting pieces will be further
47060b57cec5SDimitry Andric   // legalized.
47070b57cec5SDimitry Andric   const unsigned NewBitSize = DstEltSize / 2;
47080b57cec5SDimitry Andric   const LLT HalfTy = LLT::scalar(NewBitSize);
47090b57cec5SDimitry Andric   const LLT CondTy = LLT::scalar(1);
47100b57cec5SDimitry Andric 
4711349cc55cSDimitry Andric   if (auto VRegAndVal = getIConstantVRegValWithLookThrough(Amt, MRI)) {
4712349cc55cSDimitry Andric     return narrowScalarShiftByConstant(MI, VRegAndVal->Value, HalfTy,
4713349cc55cSDimitry Andric                                        ShiftAmtTy);
47140b57cec5SDimitry Andric   }
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric   // TODO: Expand with known bits.
47170b57cec5SDimitry Andric 
47180b57cec5SDimitry Andric   // Handle the fully general expansion by an unknown amount.
47190b57cec5SDimitry Andric   auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
47200b57cec5SDimitry Andric 
47210b57cec5SDimitry Andric   Register InL = MRI.createGenericVirtualRegister(HalfTy);
47220b57cec5SDimitry Andric   Register InH = MRI.createGenericVirtualRegister(HalfTy);
47235ffd83dbSDimitry Andric   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric   auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
47260b57cec5SDimitry Andric   auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
47270b57cec5SDimitry Andric 
47280b57cec5SDimitry Andric   auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
47290b57cec5SDimitry Andric   auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
47300b57cec5SDimitry Andric   auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
47310b57cec5SDimitry Andric 
47320b57cec5SDimitry Andric   Register ResultRegs[2];
47330b57cec5SDimitry Andric   switch (MI.getOpcode()) {
47340b57cec5SDimitry Andric   case TargetOpcode::G_SHL: {
47350b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
47368bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildShl(HalfTy, InL, Amt);
47370b57cec5SDimitry Andric 
47388bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
47398bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, Amt);
47408bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
47410b57cec5SDimitry Andric 
47420b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
47430b57cec5SDimitry Andric     auto LoL = MIRBuilder.buildConstant(HalfTy, 0);         // Lo part is zero.
47440b57cec5SDimitry Andric     auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
47450b57cec5SDimitry Andric 
47460b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
47470b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(
47480b57cec5SDimitry Andric         HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
47490b57cec5SDimitry Andric 
47500b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
47510b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
47520b57cec5SDimitry Andric     break;
47530b57cec5SDimitry Andric   }
47548bcb0991SDimitry Andric   case TargetOpcode::G_LSHR:
47550b57cec5SDimitry Andric   case TargetOpcode::G_ASHR: {
47560b57cec5SDimitry Andric     // Short: ShAmt < NewBitSize
47578bcb0991SDimitry Andric     auto HiS = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy}, {InH, Amt});
47580b57cec5SDimitry Andric 
47598bcb0991SDimitry Andric     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, Amt);
47608bcb0991SDimitry Andric     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
47618bcb0991SDimitry Andric     auto LoS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
47620b57cec5SDimitry Andric 
47630b57cec5SDimitry Andric     // Long: ShAmt >= NewBitSize
47648bcb0991SDimitry Andric     MachineInstrBuilder HiL;
47658bcb0991SDimitry Andric     if (MI.getOpcode() == TargetOpcode::G_LSHR) {
47668bcb0991SDimitry Andric       HiL = MIRBuilder.buildConstant(HalfTy, 0);            // Hi part is zero.
47678bcb0991SDimitry Andric     } else {
47688bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1);
47698bcb0991SDimitry Andric       HiL = MIRBuilder.buildAShr(HalfTy, InH, ShiftAmt);    // Sign of Hi part.
47708bcb0991SDimitry Andric     }
47718bcb0991SDimitry Andric     auto LoL = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy},
47728bcb0991SDimitry Andric                                      {InH, AmtExcess});     // Lo from Hi part.
47730b57cec5SDimitry Andric 
47740b57cec5SDimitry Andric     auto Lo = MIRBuilder.buildSelect(
47750b57cec5SDimitry Andric         HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
47760b57cec5SDimitry Andric 
47770b57cec5SDimitry Andric     auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
47780b57cec5SDimitry Andric 
47790b57cec5SDimitry Andric     ResultRegs[0] = Lo.getReg(0);
47800b57cec5SDimitry Andric     ResultRegs[1] = Hi.getReg(0);
47810b57cec5SDimitry Andric     break;
47820b57cec5SDimitry Andric   }
47830b57cec5SDimitry Andric   default:
47840b57cec5SDimitry Andric     llvm_unreachable("not a shift");
47850b57cec5SDimitry Andric   }
47860b57cec5SDimitry Andric 
4787bdd1243dSDimitry Andric   MIRBuilder.buildMergeLikeInstr(DstReg, ResultRegs);
47880b57cec5SDimitry Andric   MI.eraseFromParent();
47890b57cec5SDimitry Andric   return Legalized;
47900b57cec5SDimitry Andric }
47910b57cec5SDimitry Andric 
47920b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
47930b57cec5SDimitry Andric LegalizerHelper::moreElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
47940b57cec5SDimitry Andric                                        LLT MoreTy) {
47950b57cec5SDimitry Andric   assert(TypeIdx == 0 && "Expecting only Idx 0");
47960b57cec5SDimitry Andric 
47970b57cec5SDimitry Andric   Observer.changingInstr(MI);
47980b57cec5SDimitry Andric   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
47990b57cec5SDimitry Andric     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
48000b57cec5SDimitry Andric     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
48010b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, I);
48020b57cec5SDimitry Andric   }
48030b57cec5SDimitry Andric 
48040b57cec5SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
48050b57cec5SDimitry Andric   MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
48060b57cec5SDimitry Andric   moreElementsVectorDst(MI, MoreTy, 0);
48070b57cec5SDimitry Andric   Observer.changedInstr(MI);
48080b57cec5SDimitry Andric   return Legalized;
48090b57cec5SDimitry Andric }
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
48120b57cec5SDimitry Andric LegalizerHelper::moreElementsVector(MachineInstr &MI, unsigned TypeIdx,
48130b57cec5SDimitry Andric                                     LLT MoreTy) {
48140b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
48150b57cec5SDimitry Andric   switch (Opc) {
48168bcb0991SDimitry Andric   case TargetOpcode::G_IMPLICIT_DEF:
48178bcb0991SDimitry Andric   case TargetOpcode::G_LOAD: {
48188bcb0991SDimitry Andric     if (TypeIdx != 0)
48198bcb0991SDimitry Andric       return UnableToLegalize;
48200b57cec5SDimitry Andric     Observer.changingInstr(MI);
48210b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
48220b57cec5SDimitry Andric     Observer.changedInstr(MI);
48230b57cec5SDimitry Andric     return Legalized;
48240b57cec5SDimitry Andric   }
48258bcb0991SDimitry Andric   case TargetOpcode::G_STORE:
48268bcb0991SDimitry Andric     if (TypeIdx != 0)
48278bcb0991SDimitry Andric       return UnableToLegalize;
48288bcb0991SDimitry Andric     Observer.changingInstr(MI);
48298bcb0991SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 0);
48308bcb0991SDimitry Andric     Observer.changedInstr(MI);
48318bcb0991SDimitry Andric     return Legalized;
48320b57cec5SDimitry Andric   case TargetOpcode::G_AND:
48330b57cec5SDimitry Andric   case TargetOpcode::G_OR:
48340b57cec5SDimitry Andric   case TargetOpcode::G_XOR:
48350eae32dcSDimitry Andric   case TargetOpcode::G_ADD:
48360eae32dcSDimitry Andric   case TargetOpcode::G_SUB:
48370eae32dcSDimitry Andric   case TargetOpcode::G_MUL:
48380eae32dcSDimitry Andric   case TargetOpcode::G_FADD:
48390eae32dcSDimitry Andric   case TargetOpcode::G_FMUL:
48400eae32dcSDimitry Andric   case TargetOpcode::G_UADDSAT:
48410eae32dcSDimitry Andric   case TargetOpcode::G_USUBSAT:
48420eae32dcSDimitry Andric   case TargetOpcode::G_SADDSAT:
48430eae32dcSDimitry Andric   case TargetOpcode::G_SSUBSAT:
48440b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
48450b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
48460b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
4847480093f4SDimitry Andric   case TargetOpcode::G_UMAX:
4848480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM:
4849480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM:
4850480093f4SDimitry Andric   case TargetOpcode::G_FMINNUM_IEEE:
4851480093f4SDimitry Andric   case TargetOpcode::G_FMAXNUM_IEEE:
4852480093f4SDimitry Andric   case TargetOpcode::G_FMINIMUM:
4853bdd1243dSDimitry Andric   case TargetOpcode::G_FMAXIMUM:
4854bdd1243dSDimitry Andric   case TargetOpcode::G_STRICT_FADD:
4855bdd1243dSDimitry Andric   case TargetOpcode::G_STRICT_FSUB:
4856bdd1243dSDimitry Andric   case TargetOpcode::G_STRICT_FMUL: {
48570b57cec5SDimitry Andric     Observer.changingInstr(MI);
48580b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
48590b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
48600b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
48610b57cec5SDimitry Andric     Observer.changedInstr(MI);
48620b57cec5SDimitry Andric     return Legalized;
48630b57cec5SDimitry Andric   }
48640eae32dcSDimitry Andric   case TargetOpcode::G_FMA:
4865bdd1243dSDimitry Andric   case TargetOpcode::G_STRICT_FMA:
48660eae32dcSDimitry Andric   case TargetOpcode::G_FSHR:
48670eae32dcSDimitry Andric   case TargetOpcode::G_FSHL: {
48680eae32dcSDimitry Andric     Observer.changingInstr(MI);
48690eae32dcSDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
48700eae32dcSDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
48710eae32dcSDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 3);
48720eae32dcSDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
48730eae32dcSDimitry Andric     Observer.changedInstr(MI);
48740eae32dcSDimitry Andric     return Legalized;
48750eae32dcSDimitry Andric   }
4876*06c3fb27SDimitry Andric   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
48770b57cec5SDimitry Andric   case TargetOpcode::G_EXTRACT:
48780b57cec5SDimitry Andric     if (TypeIdx != 1)
48790b57cec5SDimitry Andric       return UnableToLegalize;
48800b57cec5SDimitry Andric     Observer.changingInstr(MI);
48810b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
48820b57cec5SDimitry Andric     Observer.changedInstr(MI);
48830b57cec5SDimitry Andric     return Legalized;
48840b57cec5SDimitry Andric   case TargetOpcode::G_INSERT:
4885*06c3fb27SDimitry Andric   case TargetOpcode::G_INSERT_VECTOR_ELT:
48865ffd83dbSDimitry Andric   case TargetOpcode::G_FREEZE:
48870eae32dcSDimitry Andric   case TargetOpcode::G_FNEG:
48880eae32dcSDimitry Andric   case TargetOpcode::G_FABS:
48890eae32dcSDimitry Andric   case TargetOpcode::G_BSWAP:
48900eae32dcSDimitry Andric   case TargetOpcode::G_FCANONICALIZE:
48910eae32dcSDimitry Andric   case TargetOpcode::G_SEXT_INREG:
48920b57cec5SDimitry Andric     if (TypeIdx != 0)
48930b57cec5SDimitry Andric       return UnableToLegalize;
48940b57cec5SDimitry Andric     Observer.changingInstr(MI);
48950b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
48960b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
48970b57cec5SDimitry Andric     Observer.changedInstr(MI);
48980b57cec5SDimitry Andric     return Legalized;
489981ad6265SDimitry Andric   case TargetOpcode::G_SELECT: {
4900*06c3fb27SDimitry Andric     auto [DstReg, DstTy, CondReg, CondTy] = MI.getFirst2RegLLTs();
490181ad6265SDimitry Andric     if (TypeIdx == 1) {
490281ad6265SDimitry Andric       if (!CondTy.isScalar() ||
490381ad6265SDimitry Andric           DstTy.getElementCount() != MoreTy.getElementCount())
49040b57cec5SDimitry Andric         return UnableToLegalize;
490581ad6265SDimitry Andric 
490681ad6265SDimitry Andric       // This is turning a scalar select of vectors into a vector
490781ad6265SDimitry Andric       // select. Broadcast the select condition.
490881ad6265SDimitry Andric       auto ShufSplat = MIRBuilder.buildShuffleSplat(MoreTy, CondReg);
490981ad6265SDimitry Andric       Observer.changingInstr(MI);
491081ad6265SDimitry Andric       MI.getOperand(1).setReg(ShufSplat.getReg(0));
491181ad6265SDimitry Andric       Observer.changedInstr(MI);
491281ad6265SDimitry Andric       return Legalized;
491381ad6265SDimitry Andric     }
491481ad6265SDimitry Andric 
491581ad6265SDimitry Andric     if (CondTy.isVector())
49160b57cec5SDimitry Andric       return UnableToLegalize;
49170b57cec5SDimitry Andric 
49180b57cec5SDimitry Andric     Observer.changingInstr(MI);
49190b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 2);
49200b57cec5SDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 3);
49210b57cec5SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
49220b57cec5SDimitry Andric     Observer.changedInstr(MI);
49230b57cec5SDimitry Andric     return Legalized;
492481ad6265SDimitry Andric   }
49250eae32dcSDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES:
49268bcb0991SDimitry Andric     return UnableToLegalize;
49270b57cec5SDimitry Andric   case TargetOpcode::G_PHI:
49280b57cec5SDimitry Andric     return moreElementsVectorPhi(MI, TypeIdx, MoreTy);
4929fe6060f1SDimitry Andric   case TargetOpcode::G_SHUFFLE_VECTOR:
4930fe6060f1SDimitry Andric     return moreElementsVectorShuffle(MI, TypeIdx, MoreTy);
49310eae32dcSDimitry Andric   case TargetOpcode::G_BUILD_VECTOR: {
49320eae32dcSDimitry Andric     SmallVector<SrcOp, 8> Elts;
49330eae32dcSDimitry Andric     for (auto Op : MI.uses()) {
49340eae32dcSDimitry Andric       Elts.push_back(Op.getReg());
49350eae32dcSDimitry Andric     }
49360eae32dcSDimitry Andric 
49370eae32dcSDimitry Andric     for (unsigned i = Elts.size(); i < MoreTy.getNumElements(); ++i) {
49380eae32dcSDimitry Andric       Elts.push_back(MIRBuilder.buildUndef(MoreTy.getScalarType()));
49390eae32dcSDimitry Andric     }
49400eae32dcSDimitry Andric 
49410eae32dcSDimitry Andric     MIRBuilder.buildDeleteTrailingVectorElements(
49420eae32dcSDimitry Andric         MI.getOperand(0).getReg(), MIRBuilder.buildInstr(Opc, {MoreTy}, Elts));
49430eae32dcSDimitry Andric     MI.eraseFromParent();
49440eae32dcSDimitry Andric     return Legalized;
49450eae32dcSDimitry Andric   }
49460eae32dcSDimitry Andric   case TargetOpcode::G_TRUNC: {
49470eae32dcSDimitry Andric     Observer.changingInstr(MI);
49480eae32dcSDimitry Andric     moreElementsVectorSrc(MI, MoreTy, 1);
49490eae32dcSDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
49500eae32dcSDimitry Andric     Observer.changedInstr(MI);
49510eae32dcSDimitry Andric     return Legalized;
49520eae32dcSDimitry Andric   }
4953*06c3fb27SDimitry Andric   case TargetOpcode::G_FPTRUNC:
4954*06c3fb27SDimitry Andric   case TargetOpcode::G_FPEXT: {
4955*06c3fb27SDimitry Andric     if (TypeIdx != 0)
4956*06c3fb27SDimitry Andric       return UnableToLegalize;
4957*06c3fb27SDimitry Andric     Observer.changingInstr(MI);
4958*06c3fb27SDimitry Andric     LLT SrcTy = LLT::fixed_vector(
4959*06c3fb27SDimitry Andric         MoreTy.getNumElements(),
4960*06c3fb27SDimitry Andric         MRI.getType(MI.getOperand(1).getReg()).getElementType());
4961*06c3fb27SDimitry Andric     moreElementsVectorSrc(MI, SrcTy, 1);
4962*06c3fb27SDimitry Andric     moreElementsVectorDst(MI, MoreTy, 0);
4963*06c3fb27SDimitry Andric     Observer.changedInstr(MI);
4964*06c3fb27SDimitry Andric     return Legalized;
4965*06c3fb27SDimitry Andric   }
49660b57cec5SDimitry Andric   default:
49670b57cec5SDimitry Andric     return UnableToLegalize;
49680b57cec5SDimitry Andric   }
49690b57cec5SDimitry Andric }
49700b57cec5SDimitry Andric 
4971*06c3fb27SDimitry Andric LegalizerHelper::LegalizeResult
4972*06c3fb27SDimitry Andric LegalizerHelper::equalizeVectorShuffleLengths(MachineInstr &MI) {
4973*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
4974bdd1243dSDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
4975bdd1243dSDimitry Andric   unsigned MaskNumElts = Mask.size();
4976bdd1243dSDimitry Andric   unsigned SrcNumElts = SrcTy.getNumElements();
4977bdd1243dSDimitry Andric   LLT DestEltTy = DstTy.getElementType();
4978bdd1243dSDimitry Andric 
4979*06c3fb27SDimitry Andric   if (MaskNumElts == SrcNumElts)
4980*06c3fb27SDimitry Andric     return Legalized;
4981*06c3fb27SDimitry Andric 
4982*06c3fb27SDimitry Andric   if (MaskNumElts < SrcNumElts) {
4983*06c3fb27SDimitry Andric     // Extend mask to match new destination vector size with
4984*06c3fb27SDimitry Andric     // undef values.
4985*06c3fb27SDimitry Andric     SmallVector<int, 16> NewMask(Mask);
4986*06c3fb27SDimitry Andric     for (unsigned I = MaskNumElts; I < SrcNumElts; ++I)
4987*06c3fb27SDimitry Andric       NewMask.push_back(-1);
4988*06c3fb27SDimitry Andric 
4989*06c3fb27SDimitry Andric     moreElementsVectorDst(MI, SrcTy, 0);
4990*06c3fb27SDimitry Andric     MIRBuilder.setInstrAndDebugLoc(MI);
4991*06c3fb27SDimitry Andric     MIRBuilder.buildShuffleVector(MI.getOperand(0).getReg(),
4992*06c3fb27SDimitry Andric                                   MI.getOperand(1).getReg(),
4993*06c3fb27SDimitry Andric                                   MI.getOperand(2).getReg(), NewMask);
4994*06c3fb27SDimitry Andric     MI.eraseFromParent();
4995*06c3fb27SDimitry Andric 
4996*06c3fb27SDimitry Andric     return Legalized;
4997bdd1243dSDimitry Andric   }
4998bdd1243dSDimitry Andric 
4999bdd1243dSDimitry Andric   unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
5000bdd1243dSDimitry Andric   unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
5001bdd1243dSDimitry Andric   LLT PaddedTy = LLT::fixed_vector(PaddedMaskNumElts, DestEltTy);
5002bdd1243dSDimitry Andric 
5003bdd1243dSDimitry Andric   // Create new source vectors by concatenating the initial
5004bdd1243dSDimitry Andric   // source vectors with undefined vectors of the same size.
5005bdd1243dSDimitry Andric   auto Undef = MIRBuilder.buildUndef(SrcTy);
5006bdd1243dSDimitry Andric   SmallVector<Register, 8> MOps1(NumConcat, Undef.getReg(0));
5007bdd1243dSDimitry Andric   SmallVector<Register, 8> MOps2(NumConcat, Undef.getReg(0));
5008bdd1243dSDimitry Andric   MOps1[0] = MI.getOperand(1).getReg();
5009bdd1243dSDimitry Andric   MOps2[0] = MI.getOperand(2).getReg();
5010bdd1243dSDimitry Andric 
5011bdd1243dSDimitry Andric   auto Src1 = MIRBuilder.buildConcatVectors(PaddedTy, MOps1);
5012bdd1243dSDimitry Andric   auto Src2 = MIRBuilder.buildConcatVectors(PaddedTy, MOps2);
5013bdd1243dSDimitry Andric 
5014bdd1243dSDimitry Andric   // Readjust mask for new input vector length.
5015bdd1243dSDimitry Andric   SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
5016bdd1243dSDimitry Andric   for (unsigned I = 0; I != MaskNumElts; ++I) {
5017bdd1243dSDimitry Andric     int Idx = Mask[I];
5018bdd1243dSDimitry Andric     if (Idx >= static_cast<int>(SrcNumElts))
5019bdd1243dSDimitry Andric       Idx += PaddedMaskNumElts - SrcNumElts;
5020bdd1243dSDimitry Andric     MappedOps[I] = Idx;
5021bdd1243dSDimitry Andric   }
5022bdd1243dSDimitry Andric 
5023bdd1243dSDimitry Andric   // If we got more elements than required, extract subvector.
5024bdd1243dSDimitry Andric   if (MaskNumElts != PaddedMaskNumElts) {
5025bdd1243dSDimitry Andric     auto Shuffle =
5026bdd1243dSDimitry Andric         MIRBuilder.buildShuffleVector(PaddedTy, Src1, Src2, MappedOps);
5027bdd1243dSDimitry Andric 
5028bdd1243dSDimitry Andric     SmallVector<Register, 16> Elts(MaskNumElts);
5029bdd1243dSDimitry Andric     for (unsigned I = 0; I < MaskNumElts; ++I) {
5030bdd1243dSDimitry Andric       Elts[I] =
5031bdd1243dSDimitry Andric           MIRBuilder.buildExtractVectorElementConstant(DestEltTy, Shuffle, I)
5032bdd1243dSDimitry Andric               .getReg(0);
5033bdd1243dSDimitry Andric     }
5034bdd1243dSDimitry Andric     MIRBuilder.buildBuildVector(DstReg, Elts);
5035bdd1243dSDimitry Andric   } else {
5036bdd1243dSDimitry Andric     MIRBuilder.buildShuffleVector(DstReg, Src1, Src2, MappedOps);
5037bdd1243dSDimitry Andric   }
5038bdd1243dSDimitry Andric 
5039bdd1243dSDimitry Andric   MI.eraseFromParent();
5040bdd1243dSDimitry Andric   return LegalizerHelper::LegalizeResult::Legalized;
5041bdd1243dSDimitry Andric }
5042bdd1243dSDimitry Andric 
5043fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5044fe6060f1SDimitry Andric LegalizerHelper::moreElementsVectorShuffle(MachineInstr &MI,
5045fe6060f1SDimitry Andric                                            unsigned int TypeIdx, LLT MoreTy) {
5046*06c3fb27SDimitry Andric   auto [DstTy, Src1Ty, Src2Ty] = MI.getFirst3LLTs();
5047fe6060f1SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
5048fe6060f1SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
5049fe6060f1SDimitry Andric   unsigned WidenNumElts = MoreTy.getNumElements();
5050fe6060f1SDimitry Andric 
5051bdd1243dSDimitry Andric   if (DstTy.isVector() && Src1Ty.isVector() &&
5052*06c3fb27SDimitry Andric       DstTy.getNumElements() != Src1Ty.getNumElements()) {
5053*06c3fb27SDimitry Andric     return equalizeVectorShuffleLengths(MI);
5054bdd1243dSDimitry Andric   }
5055bdd1243dSDimitry Andric 
5056bdd1243dSDimitry Andric   if (TypeIdx != 0)
5057bdd1243dSDimitry Andric     return UnableToLegalize;
5058bdd1243dSDimitry Andric 
5059fe6060f1SDimitry Andric   // Expect a canonicalized shuffle.
5060fe6060f1SDimitry Andric   if (DstTy != Src1Ty || DstTy != Src2Ty)
5061fe6060f1SDimitry Andric     return UnableToLegalize;
5062fe6060f1SDimitry Andric 
5063fe6060f1SDimitry Andric   moreElementsVectorSrc(MI, MoreTy, 1);
5064fe6060f1SDimitry Andric   moreElementsVectorSrc(MI, MoreTy, 2);
5065fe6060f1SDimitry Andric 
5066fe6060f1SDimitry Andric   // Adjust mask based on new input vector length.
5067fe6060f1SDimitry Andric   SmallVector<int, 16> NewMask;
5068fe6060f1SDimitry Andric   for (unsigned I = 0; I != NumElts; ++I) {
5069fe6060f1SDimitry Andric     int Idx = Mask[I];
5070fe6060f1SDimitry Andric     if (Idx < static_cast<int>(NumElts))
5071fe6060f1SDimitry Andric       NewMask.push_back(Idx);
5072fe6060f1SDimitry Andric     else
5073fe6060f1SDimitry Andric       NewMask.push_back(Idx - NumElts + WidenNumElts);
5074fe6060f1SDimitry Andric   }
5075fe6060f1SDimitry Andric   for (unsigned I = NumElts; I != WidenNumElts; ++I)
5076fe6060f1SDimitry Andric     NewMask.push_back(-1);
5077fe6060f1SDimitry Andric   moreElementsVectorDst(MI, MoreTy, 0);
5078fe6060f1SDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
5079fe6060f1SDimitry Andric   MIRBuilder.buildShuffleVector(MI.getOperand(0).getReg(),
5080fe6060f1SDimitry Andric                                 MI.getOperand(1).getReg(),
5081fe6060f1SDimitry Andric                                 MI.getOperand(2).getReg(), NewMask);
5082fe6060f1SDimitry Andric   MI.eraseFromParent();
5083fe6060f1SDimitry Andric   return Legalized;
5084fe6060f1SDimitry Andric }
5085fe6060f1SDimitry Andric 
50860b57cec5SDimitry Andric void LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
50870b57cec5SDimitry Andric                                         ArrayRef<Register> Src1Regs,
50880b57cec5SDimitry Andric                                         ArrayRef<Register> Src2Regs,
50890b57cec5SDimitry Andric                                         LLT NarrowTy) {
50900b57cec5SDimitry Andric   MachineIRBuilder &B = MIRBuilder;
50910b57cec5SDimitry Andric   unsigned SrcParts = Src1Regs.size();
50920b57cec5SDimitry Andric   unsigned DstParts = DstRegs.size();
50930b57cec5SDimitry Andric 
50940b57cec5SDimitry Andric   unsigned DstIdx = 0; // Low bits of the result.
50950b57cec5SDimitry Andric   Register FactorSum =
50960b57cec5SDimitry Andric       B.buildMul(NarrowTy, Src1Regs[DstIdx], Src2Regs[DstIdx]).getReg(0);
50970b57cec5SDimitry Andric   DstRegs[DstIdx] = FactorSum;
50980b57cec5SDimitry Andric 
50990b57cec5SDimitry Andric   unsigned CarrySumPrevDstIdx;
51000b57cec5SDimitry Andric   SmallVector<Register, 4> Factors;
51010b57cec5SDimitry Andric 
51020b57cec5SDimitry Andric   for (DstIdx = 1; DstIdx < DstParts; DstIdx++) {
51030b57cec5SDimitry Andric     // Collect low parts of muls for DstIdx.
51040b57cec5SDimitry Andric     for (unsigned i = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
51050b57cec5SDimitry Andric          i <= std::min(DstIdx, SrcParts - 1); ++i) {
51060b57cec5SDimitry Andric       MachineInstrBuilder Mul =
51070b57cec5SDimitry Andric           B.buildMul(NarrowTy, Src1Regs[DstIdx - i], Src2Regs[i]);
51080b57cec5SDimitry Andric       Factors.push_back(Mul.getReg(0));
51090b57cec5SDimitry Andric     }
51100b57cec5SDimitry Andric     // Collect high parts of muls from previous DstIdx.
51110b57cec5SDimitry Andric     for (unsigned i = DstIdx < SrcParts ? 0 : DstIdx - SrcParts;
51120b57cec5SDimitry Andric          i <= std::min(DstIdx - 1, SrcParts - 1); ++i) {
51130b57cec5SDimitry Andric       MachineInstrBuilder Umulh =
51140b57cec5SDimitry Andric           B.buildUMulH(NarrowTy, Src1Regs[DstIdx - 1 - i], Src2Regs[i]);
51150b57cec5SDimitry Andric       Factors.push_back(Umulh.getReg(0));
51160b57cec5SDimitry Andric     }
5117480093f4SDimitry Andric     // Add CarrySum from additions calculated for previous DstIdx.
51180b57cec5SDimitry Andric     if (DstIdx != 1) {
51190b57cec5SDimitry Andric       Factors.push_back(CarrySumPrevDstIdx);
51200b57cec5SDimitry Andric     }
51210b57cec5SDimitry Andric 
51220b57cec5SDimitry Andric     Register CarrySum;
51230b57cec5SDimitry Andric     // Add all factors and accumulate all carries into CarrySum.
51240b57cec5SDimitry Andric     if (DstIdx != DstParts - 1) {
51250b57cec5SDimitry Andric       MachineInstrBuilder Uaddo =
51260b57cec5SDimitry Andric           B.buildUAddo(NarrowTy, LLT::scalar(1), Factors[0], Factors[1]);
51270b57cec5SDimitry Andric       FactorSum = Uaddo.getReg(0);
51280b57cec5SDimitry Andric       CarrySum = B.buildZExt(NarrowTy, Uaddo.getReg(1)).getReg(0);
51290b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i) {
51300b57cec5SDimitry Andric         MachineInstrBuilder Uaddo =
51310b57cec5SDimitry Andric             B.buildUAddo(NarrowTy, LLT::scalar(1), FactorSum, Factors[i]);
51320b57cec5SDimitry Andric         FactorSum = Uaddo.getReg(0);
51330b57cec5SDimitry Andric         MachineInstrBuilder Carry = B.buildZExt(NarrowTy, Uaddo.getReg(1));
51340b57cec5SDimitry Andric         CarrySum = B.buildAdd(NarrowTy, CarrySum, Carry).getReg(0);
51350b57cec5SDimitry Andric       }
51360b57cec5SDimitry Andric     } else {
51370b57cec5SDimitry Andric       // Since value for the next index is not calculated, neither is CarrySum.
51380b57cec5SDimitry Andric       FactorSum = B.buildAdd(NarrowTy, Factors[0], Factors[1]).getReg(0);
51390b57cec5SDimitry Andric       for (unsigned i = 2; i < Factors.size(); ++i)
51400b57cec5SDimitry Andric         FactorSum = B.buildAdd(NarrowTy, FactorSum, Factors[i]).getReg(0);
51410b57cec5SDimitry Andric     }
51420b57cec5SDimitry Andric 
51430b57cec5SDimitry Andric     CarrySumPrevDstIdx = CarrySum;
51440b57cec5SDimitry Andric     DstRegs[DstIdx] = FactorSum;
51450b57cec5SDimitry Andric     Factors.clear();
51460b57cec5SDimitry Andric   }
51470b57cec5SDimitry Andric }
51480b57cec5SDimitry Andric 
51490b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
5150fe6060f1SDimitry Andric LegalizerHelper::narrowScalarAddSub(MachineInstr &MI, unsigned TypeIdx,
5151fe6060f1SDimitry Andric                                     LLT NarrowTy) {
5152fe6060f1SDimitry Andric   if (TypeIdx != 0)
5153fe6060f1SDimitry Andric     return UnableToLegalize;
5154fe6060f1SDimitry Andric 
5155fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5156fe6060f1SDimitry Andric   LLT DstType = MRI.getType(DstReg);
5157fe6060f1SDimitry Andric   // FIXME: add support for vector types
5158fe6060f1SDimitry Andric   if (DstType.isVector())
5159fe6060f1SDimitry Andric     return UnableToLegalize;
5160fe6060f1SDimitry Andric 
5161fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
5162fe6060f1SDimitry Andric   unsigned OpO, OpE, OpF;
5163fe6060f1SDimitry Andric   switch (Opcode) {
5164fe6060f1SDimitry Andric   case TargetOpcode::G_SADDO:
5165fe6060f1SDimitry Andric   case TargetOpcode::G_SADDE:
5166fe6060f1SDimitry Andric   case TargetOpcode::G_UADDO:
5167fe6060f1SDimitry Andric   case TargetOpcode::G_UADDE:
5168fe6060f1SDimitry Andric   case TargetOpcode::G_ADD:
5169fe6060f1SDimitry Andric     OpO = TargetOpcode::G_UADDO;
5170fe6060f1SDimitry Andric     OpE = TargetOpcode::G_UADDE;
5171fe6060f1SDimitry Andric     OpF = TargetOpcode::G_UADDE;
5172fe6060f1SDimitry Andric     if (Opcode == TargetOpcode::G_SADDO || Opcode == TargetOpcode::G_SADDE)
5173fe6060f1SDimitry Andric       OpF = TargetOpcode::G_SADDE;
5174fe6060f1SDimitry Andric     break;
5175fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBO:
5176fe6060f1SDimitry Andric   case TargetOpcode::G_SSUBE:
5177fe6060f1SDimitry Andric   case TargetOpcode::G_USUBO:
5178fe6060f1SDimitry Andric   case TargetOpcode::G_USUBE:
5179fe6060f1SDimitry Andric   case TargetOpcode::G_SUB:
5180fe6060f1SDimitry Andric     OpO = TargetOpcode::G_USUBO;
5181fe6060f1SDimitry Andric     OpE = TargetOpcode::G_USUBE;
5182fe6060f1SDimitry Andric     OpF = TargetOpcode::G_USUBE;
5183fe6060f1SDimitry Andric     if (Opcode == TargetOpcode::G_SSUBO || Opcode == TargetOpcode::G_SSUBE)
5184fe6060f1SDimitry Andric       OpF = TargetOpcode::G_SSUBE;
5185fe6060f1SDimitry Andric     break;
5186fe6060f1SDimitry Andric   default:
5187fe6060f1SDimitry Andric     llvm_unreachable("Unexpected add/sub opcode!");
5188fe6060f1SDimitry Andric   }
5189fe6060f1SDimitry Andric 
5190fe6060f1SDimitry Andric   // 1 for a plain add/sub, 2 if this is an operation with a carry-out.
5191fe6060f1SDimitry Andric   unsigned NumDefs = MI.getNumExplicitDefs();
5192fe6060f1SDimitry Andric   Register Src1 = MI.getOperand(NumDefs).getReg();
5193fe6060f1SDimitry Andric   Register Src2 = MI.getOperand(NumDefs + 1).getReg();
5194fe6060f1SDimitry Andric   Register CarryDst, CarryIn;
5195fe6060f1SDimitry Andric   if (NumDefs == 2)
5196fe6060f1SDimitry Andric     CarryDst = MI.getOperand(1).getReg();
5197fe6060f1SDimitry Andric   if (MI.getNumOperands() == NumDefs + 3)
5198fe6060f1SDimitry Andric     CarryIn = MI.getOperand(NumDefs + 2).getReg();
5199fe6060f1SDimitry Andric 
5200fe6060f1SDimitry Andric   LLT RegTy = MRI.getType(MI.getOperand(0).getReg());
5201fe6060f1SDimitry Andric   LLT LeftoverTy, DummyTy;
5202fe6060f1SDimitry Andric   SmallVector<Register, 2> Src1Regs, Src2Regs, Src1Left, Src2Left, DstRegs;
5203fe6060f1SDimitry Andric   extractParts(Src1, RegTy, NarrowTy, LeftoverTy, Src1Regs, Src1Left);
5204fe6060f1SDimitry Andric   extractParts(Src2, RegTy, NarrowTy, DummyTy, Src2Regs, Src2Left);
5205fe6060f1SDimitry Andric 
5206fe6060f1SDimitry Andric   int NarrowParts = Src1Regs.size();
5207fe6060f1SDimitry Andric   for (int I = 0, E = Src1Left.size(); I != E; ++I) {
5208fe6060f1SDimitry Andric     Src1Regs.push_back(Src1Left[I]);
5209fe6060f1SDimitry Andric     Src2Regs.push_back(Src2Left[I]);
5210fe6060f1SDimitry Andric   }
5211fe6060f1SDimitry Andric   DstRegs.reserve(Src1Regs.size());
5212fe6060f1SDimitry Andric 
5213fe6060f1SDimitry Andric   for (int i = 0, e = Src1Regs.size(); i != e; ++i) {
5214fe6060f1SDimitry Andric     Register DstReg =
5215fe6060f1SDimitry Andric         MRI.createGenericVirtualRegister(MRI.getType(Src1Regs[i]));
5216fe6060f1SDimitry Andric     Register CarryOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
5217fe6060f1SDimitry Andric     // Forward the final carry-out to the destination register
5218fe6060f1SDimitry Andric     if (i == e - 1 && CarryDst)
5219fe6060f1SDimitry Andric       CarryOut = CarryDst;
5220fe6060f1SDimitry Andric 
5221fe6060f1SDimitry Andric     if (!CarryIn) {
5222fe6060f1SDimitry Andric       MIRBuilder.buildInstr(OpO, {DstReg, CarryOut},
5223fe6060f1SDimitry Andric                             {Src1Regs[i], Src2Regs[i]});
5224fe6060f1SDimitry Andric     } else if (i == e - 1) {
5225fe6060f1SDimitry Andric       MIRBuilder.buildInstr(OpF, {DstReg, CarryOut},
5226fe6060f1SDimitry Andric                             {Src1Regs[i], Src2Regs[i], CarryIn});
5227fe6060f1SDimitry Andric     } else {
5228fe6060f1SDimitry Andric       MIRBuilder.buildInstr(OpE, {DstReg, CarryOut},
5229fe6060f1SDimitry Andric                             {Src1Regs[i], Src2Regs[i], CarryIn});
5230fe6060f1SDimitry Andric     }
5231fe6060f1SDimitry Andric 
5232fe6060f1SDimitry Andric     DstRegs.push_back(DstReg);
5233fe6060f1SDimitry Andric     CarryIn = CarryOut;
5234fe6060f1SDimitry Andric   }
5235fe6060f1SDimitry Andric   insertParts(MI.getOperand(0).getReg(), RegTy, NarrowTy,
5236bdd1243dSDimitry Andric               ArrayRef(DstRegs).take_front(NarrowParts), LeftoverTy,
5237bdd1243dSDimitry Andric               ArrayRef(DstRegs).drop_front(NarrowParts));
5238fe6060f1SDimitry Andric 
5239fe6060f1SDimitry Andric   MI.eraseFromParent();
5240fe6060f1SDimitry Andric   return Legalized;
5241fe6060f1SDimitry Andric }
5242fe6060f1SDimitry Andric 
5243fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
52440b57cec5SDimitry Andric LegalizerHelper::narrowScalarMul(MachineInstr &MI, LLT NarrowTy) {
5245*06c3fb27SDimitry Andric   auto [DstReg, Src1, Src2] = MI.getFirst3Regs();
52460b57cec5SDimitry Andric 
52470b57cec5SDimitry Andric   LLT Ty = MRI.getType(DstReg);
52480b57cec5SDimitry Andric   if (Ty.isVector())
52490b57cec5SDimitry Andric     return UnableToLegalize;
52500b57cec5SDimitry Andric 
5251349cc55cSDimitry Andric   unsigned Size = Ty.getSizeInBits();
52520b57cec5SDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
5253349cc55cSDimitry Andric   if (Size % NarrowSize != 0)
52540b57cec5SDimitry Andric     return UnableToLegalize;
52550b57cec5SDimitry Andric 
5256349cc55cSDimitry Andric   unsigned NumParts = Size / NarrowSize;
52570b57cec5SDimitry Andric   bool IsMulHigh = MI.getOpcode() == TargetOpcode::G_UMULH;
5258349cc55cSDimitry Andric   unsigned DstTmpParts = NumParts * (IsMulHigh ? 2 : 1);
52590b57cec5SDimitry Andric 
52605ffd83dbSDimitry Andric   SmallVector<Register, 2> Src1Parts, Src2Parts;
52615ffd83dbSDimitry Andric   SmallVector<Register, 2> DstTmpRegs(DstTmpParts);
5262349cc55cSDimitry Andric   extractParts(Src1, NarrowTy, NumParts, Src1Parts);
5263349cc55cSDimitry Andric   extractParts(Src2, NarrowTy, NumParts, Src2Parts);
52640b57cec5SDimitry Andric   multiplyRegisters(DstTmpRegs, Src1Parts, Src2Parts, NarrowTy);
52650b57cec5SDimitry Andric 
52660b57cec5SDimitry Andric   // Take only high half of registers if this is high mul.
5267349cc55cSDimitry Andric   ArrayRef<Register> DstRegs(&DstTmpRegs[DstTmpParts - NumParts], NumParts);
5268bdd1243dSDimitry Andric   MIRBuilder.buildMergeLikeInstr(DstReg, DstRegs);
52690b57cec5SDimitry Andric   MI.eraseFromParent();
52700b57cec5SDimitry Andric   return Legalized;
52710b57cec5SDimitry Andric }
52720b57cec5SDimitry Andric 
52730b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
527423408297SDimitry Andric LegalizerHelper::narrowScalarFPTOI(MachineInstr &MI, unsigned TypeIdx,
527523408297SDimitry Andric                                    LLT NarrowTy) {
527623408297SDimitry Andric   if (TypeIdx != 0)
527723408297SDimitry Andric     return UnableToLegalize;
527823408297SDimitry Andric 
527923408297SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_FPTOSI;
528023408297SDimitry Andric 
528123408297SDimitry Andric   Register Src = MI.getOperand(1).getReg();
528223408297SDimitry Andric   LLT SrcTy = MRI.getType(Src);
528323408297SDimitry Andric 
528423408297SDimitry Andric   // If all finite floats fit into the narrowed integer type, we can just swap
528523408297SDimitry Andric   // out the result type. This is practically only useful for conversions from
528623408297SDimitry Andric   // half to at least 16-bits, so just handle the one case.
528723408297SDimitry Andric   if (SrcTy.getScalarType() != LLT::scalar(16) ||
5288fe6060f1SDimitry Andric       NarrowTy.getScalarSizeInBits() < (IsSigned ? 17u : 16u))
528923408297SDimitry Andric     return UnableToLegalize;
529023408297SDimitry Andric 
529123408297SDimitry Andric   Observer.changingInstr(MI);
529223408297SDimitry Andric   narrowScalarDst(MI, NarrowTy, 0,
529323408297SDimitry Andric                   IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT);
529423408297SDimitry Andric   Observer.changedInstr(MI);
529523408297SDimitry Andric   return Legalized;
529623408297SDimitry Andric }
529723408297SDimitry Andric 
529823408297SDimitry Andric LegalizerHelper::LegalizeResult
52990b57cec5SDimitry Andric LegalizerHelper::narrowScalarExtract(MachineInstr &MI, unsigned TypeIdx,
53000b57cec5SDimitry Andric                                      LLT NarrowTy) {
53010b57cec5SDimitry Andric   if (TypeIdx != 1)
53020b57cec5SDimitry Andric     return UnableToLegalize;
53030b57cec5SDimitry Andric 
53040b57cec5SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
53050b57cec5SDimitry Andric 
53060b57cec5SDimitry Andric   int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
53070b57cec5SDimitry Andric   // FIXME: add support for when SizeOp1 isn't an exact multiple of
53080b57cec5SDimitry Andric   // NarrowSize.
53090b57cec5SDimitry Andric   if (SizeOp1 % NarrowSize != 0)
53100b57cec5SDimitry Andric     return UnableToLegalize;
53110b57cec5SDimitry Andric   int NumParts = SizeOp1 / NarrowSize;
53120b57cec5SDimitry Andric 
53130b57cec5SDimitry Andric   SmallVector<Register, 2> SrcRegs, DstRegs;
53140b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
53150b57cec5SDimitry Andric   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
53160b57cec5SDimitry Andric 
53170b57cec5SDimitry Andric   Register OpReg = MI.getOperand(0).getReg();
53180b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(2).getImm();
53190b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
53200b57cec5SDimitry Andric   for (int i = 0; i < NumParts; ++i) {
53210b57cec5SDimitry Andric     unsigned SrcStart = i * NarrowSize;
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric     if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
53240b57cec5SDimitry Andric       // No part of the extract uses this subregister, ignore it.
53250b57cec5SDimitry Andric       continue;
53260b57cec5SDimitry Andric     } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
53270b57cec5SDimitry Andric       // The entire subregister is extracted, forward the value.
53280b57cec5SDimitry Andric       DstRegs.push_back(SrcRegs[i]);
53290b57cec5SDimitry Andric       continue;
53300b57cec5SDimitry Andric     }
53310b57cec5SDimitry Andric 
53320b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
53330b57cec5SDimitry Andric     // extended infinitely in both directions.
53340b57cec5SDimitry Andric     int64_t ExtractOffset;
53350b57cec5SDimitry Andric     uint64_t SegSize;
53360b57cec5SDimitry Andric     if (OpStart < SrcStart) {
53370b57cec5SDimitry Andric       ExtractOffset = 0;
53380b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
53390b57cec5SDimitry Andric     } else {
53400b57cec5SDimitry Andric       ExtractOffset = OpStart - SrcStart;
53410b57cec5SDimitry Andric       SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
53420b57cec5SDimitry Andric     }
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric     Register SegReg = SrcRegs[i];
53450b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != NarrowSize) {
53460b57cec5SDimitry Andric       // A genuine extract is needed.
53470b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
53480b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
53490b57cec5SDimitry Andric     }
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric     DstRegs.push_back(SegReg);
53520b57cec5SDimitry Andric   }
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
53550b57cec5SDimitry Andric   if (MRI.getType(DstReg).isVector())
53560b57cec5SDimitry Andric     MIRBuilder.buildBuildVector(DstReg, DstRegs);
53575ffd83dbSDimitry Andric   else if (DstRegs.size() > 1)
5358bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(DstReg, DstRegs);
53595ffd83dbSDimitry Andric   else
53605ffd83dbSDimitry Andric     MIRBuilder.buildCopy(DstReg, DstRegs[0]);
53610b57cec5SDimitry Andric   MI.eraseFromParent();
53620b57cec5SDimitry Andric   return Legalized;
53630b57cec5SDimitry Andric }
53640b57cec5SDimitry Andric 
53650b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
53660b57cec5SDimitry Andric LegalizerHelper::narrowScalarInsert(MachineInstr &MI, unsigned TypeIdx,
53670b57cec5SDimitry Andric                                     LLT NarrowTy) {
53680b57cec5SDimitry Andric   // FIXME: Don't know how to handle secondary types yet.
53690b57cec5SDimitry Andric   if (TypeIdx != 0)
53700b57cec5SDimitry Andric     return UnableToLegalize;
53710b57cec5SDimitry Andric 
5372fe6060f1SDimitry Andric   SmallVector<Register, 2> SrcRegs, LeftoverRegs, DstRegs;
53730b57cec5SDimitry Andric   SmallVector<uint64_t, 2> Indexes;
5374fe6060f1SDimitry Andric   LLT RegTy = MRI.getType(MI.getOperand(0).getReg());
5375fe6060f1SDimitry Andric   LLT LeftoverTy;
5376fe6060f1SDimitry Andric   extractParts(MI.getOperand(1).getReg(), RegTy, NarrowTy, LeftoverTy, SrcRegs,
5377fe6060f1SDimitry Andric                LeftoverRegs);
53780b57cec5SDimitry Andric 
5379fe6060f1SDimitry Andric   for (Register Reg : LeftoverRegs)
5380fe6060f1SDimitry Andric     SrcRegs.push_back(Reg);
5381fe6060f1SDimitry Andric 
5382fe6060f1SDimitry Andric   uint64_t NarrowSize = NarrowTy.getSizeInBits();
53830b57cec5SDimitry Andric   Register OpReg = MI.getOperand(2).getReg();
53840b57cec5SDimitry Andric   uint64_t OpStart = MI.getOperand(3).getImm();
53850b57cec5SDimitry Andric   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
5386fe6060f1SDimitry Andric   for (int I = 0, E = SrcRegs.size(); I != E; ++I) {
5387fe6060f1SDimitry Andric     unsigned DstStart = I * NarrowSize;
53880b57cec5SDimitry Andric 
5389fe6060f1SDimitry Andric     if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
53900b57cec5SDimitry Andric       // The entire subregister is defined by this insert, forward the new
53910b57cec5SDimitry Andric       // value.
53920b57cec5SDimitry Andric       DstRegs.push_back(OpReg);
53930b57cec5SDimitry Andric       continue;
53940b57cec5SDimitry Andric     }
53950b57cec5SDimitry Andric 
5396fe6060f1SDimitry Andric     Register SrcReg = SrcRegs[I];
5397fe6060f1SDimitry Andric     if (MRI.getType(SrcRegs[I]) == LeftoverTy) {
5398fe6060f1SDimitry Andric       // The leftover reg is smaller than NarrowTy, so we need to extend it.
5399fe6060f1SDimitry Andric       SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
5400fe6060f1SDimitry Andric       MIRBuilder.buildAnyExt(SrcReg, SrcRegs[I]);
5401fe6060f1SDimitry Andric     }
5402fe6060f1SDimitry Andric 
5403fe6060f1SDimitry Andric     if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
5404fe6060f1SDimitry Andric       // No part of the insert affects this subregister, forward the original.
5405fe6060f1SDimitry Andric       DstRegs.push_back(SrcReg);
5406fe6060f1SDimitry Andric       continue;
5407fe6060f1SDimitry Andric     }
5408fe6060f1SDimitry Andric 
54090b57cec5SDimitry Andric     // OpSegStart is where this destination segment would start in OpReg if it
54100b57cec5SDimitry Andric     // extended infinitely in both directions.
54110b57cec5SDimitry Andric     int64_t ExtractOffset, InsertOffset;
54120b57cec5SDimitry Andric     uint64_t SegSize;
54130b57cec5SDimitry Andric     if (OpStart < DstStart) {
54140b57cec5SDimitry Andric       InsertOffset = 0;
54150b57cec5SDimitry Andric       ExtractOffset = DstStart - OpStart;
54160b57cec5SDimitry Andric       SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
54170b57cec5SDimitry Andric     } else {
54180b57cec5SDimitry Andric       InsertOffset = OpStart - DstStart;
54190b57cec5SDimitry Andric       ExtractOffset = 0;
54200b57cec5SDimitry Andric       SegSize =
54210b57cec5SDimitry Andric         std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
54220b57cec5SDimitry Andric     }
54230b57cec5SDimitry Andric 
54240b57cec5SDimitry Andric     Register SegReg = OpReg;
54250b57cec5SDimitry Andric     if (ExtractOffset != 0 || SegSize != OpSize) {
54260b57cec5SDimitry Andric       // A genuine extract is needed.
54270b57cec5SDimitry Andric       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
54280b57cec5SDimitry Andric       MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
54290b57cec5SDimitry Andric     }
54300b57cec5SDimitry Andric 
54310b57cec5SDimitry Andric     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
5432fe6060f1SDimitry Andric     MIRBuilder.buildInsert(DstReg, SrcReg, SegReg, InsertOffset);
54330b57cec5SDimitry Andric     DstRegs.push_back(DstReg);
54340b57cec5SDimitry Andric   }
54350b57cec5SDimitry Andric 
5436fe6060f1SDimitry Andric   uint64_t WideSize = DstRegs.size() * NarrowSize;
54370b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
5438fe6060f1SDimitry Andric   if (WideSize > RegTy.getSizeInBits()) {
5439fe6060f1SDimitry Andric     Register MergeReg = MRI.createGenericVirtualRegister(LLT::scalar(WideSize));
5440bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(MergeReg, DstRegs);
5441fe6060f1SDimitry Andric     MIRBuilder.buildTrunc(DstReg, MergeReg);
5442fe6060f1SDimitry Andric   } else
5443bdd1243dSDimitry Andric     MIRBuilder.buildMergeLikeInstr(DstReg, DstRegs);
5444fe6060f1SDimitry Andric 
54450b57cec5SDimitry Andric   MI.eraseFromParent();
54460b57cec5SDimitry Andric   return Legalized;
54470b57cec5SDimitry Andric }
54480b57cec5SDimitry Andric 
54490b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
54500b57cec5SDimitry Andric LegalizerHelper::narrowScalarBasic(MachineInstr &MI, unsigned TypeIdx,
54510b57cec5SDimitry Andric                                    LLT NarrowTy) {
54520b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
54530b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric   assert(MI.getNumOperands() == 3 && TypeIdx == 0);
54560b57cec5SDimitry Andric 
54570b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
54580b57cec5SDimitry Andric   SmallVector<Register, 4> Src0Regs, Src0LeftoverRegs;
54590b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
54600b57cec5SDimitry Andric   LLT LeftoverTy;
54610b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(1).getReg(), DstTy, NarrowTy, LeftoverTy,
54620b57cec5SDimitry Andric                     Src0Regs, Src0LeftoverRegs))
54630b57cec5SDimitry Andric     return UnableToLegalize;
54640b57cec5SDimitry Andric 
54650b57cec5SDimitry Andric   LLT Unused;
54660b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, Unused,
54670b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
54680b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
54710b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
54720b57cec5SDimitry Andric                                         {Src0Regs[I], Src1Regs[I]});
54735ffd83dbSDimitry Andric     DstRegs.push_back(Inst.getReg(0));
54740b57cec5SDimitry Andric   }
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
54770b57cec5SDimitry Andric     auto Inst = MIRBuilder.buildInstr(
54780b57cec5SDimitry Andric       MI.getOpcode(),
54790b57cec5SDimitry Andric       {LeftoverTy}, {Src0LeftoverRegs[I], Src1LeftoverRegs[I]});
54805ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Inst.getReg(0));
54810b57cec5SDimitry Andric   }
54820b57cec5SDimitry Andric 
54830b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
54840b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric   MI.eraseFromParent();
54870b57cec5SDimitry Andric   return Legalized;
54880b57cec5SDimitry Andric }
54890b57cec5SDimitry Andric 
54900b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
54915ffd83dbSDimitry Andric LegalizerHelper::narrowScalarExt(MachineInstr &MI, unsigned TypeIdx,
54925ffd83dbSDimitry Andric                                  LLT NarrowTy) {
54935ffd83dbSDimitry Andric   if (TypeIdx != 0)
54945ffd83dbSDimitry Andric     return UnableToLegalize;
54955ffd83dbSDimitry Andric 
5496*06c3fb27SDimitry Andric   auto [DstReg, SrcReg] = MI.getFirst2Regs();
54975ffd83dbSDimitry Andric 
54985ffd83dbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
54995ffd83dbSDimitry Andric   if (DstTy.isVector())
55005ffd83dbSDimitry Andric     return UnableToLegalize;
55015ffd83dbSDimitry Andric 
55025ffd83dbSDimitry Andric   SmallVector<Register, 8> Parts;
55035ffd83dbSDimitry Andric   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
55045ffd83dbSDimitry Andric   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts, MI.getOpcode());
55055ffd83dbSDimitry Andric   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
55065ffd83dbSDimitry Andric 
55075ffd83dbSDimitry Andric   MI.eraseFromParent();
55085ffd83dbSDimitry Andric   return Legalized;
55095ffd83dbSDimitry Andric }
55105ffd83dbSDimitry Andric 
55115ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55120b57cec5SDimitry Andric LegalizerHelper::narrowScalarSelect(MachineInstr &MI, unsigned TypeIdx,
55130b57cec5SDimitry Andric                                     LLT NarrowTy) {
55140b57cec5SDimitry Andric   if (TypeIdx != 0)
55150b57cec5SDimitry Andric     return UnableToLegalize;
55160b57cec5SDimitry Andric 
55170b57cec5SDimitry Andric   Register CondReg = MI.getOperand(1).getReg();
55180b57cec5SDimitry Andric   LLT CondTy = MRI.getType(CondReg);
55190b57cec5SDimitry Andric   if (CondTy.isVector()) // TODO: Handle vselect
55200b57cec5SDimitry Andric     return UnableToLegalize;
55210b57cec5SDimitry Andric 
55220b57cec5SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
55230b57cec5SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
55240b57cec5SDimitry Andric 
55250b57cec5SDimitry Andric   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
55260b57cec5SDimitry Andric   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
55270b57cec5SDimitry Andric   SmallVector<Register, 4> Src2Regs, Src2LeftoverRegs;
55280b57cec5SDimitry Andric   LLT LeftoverTy;
55290b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
55300b57cec5SDimitry Andric                     Src1Regs, Src1LeftoverRegs))
55310b57cec5SDimitry Andric     return UnableToLegalize;
55320b57cec5SDimitry Andric 
55330b57cec5SDimitry Andric   LLT Unused;
55340b57cec5SDimitry Andric   if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
55350b57cec5SDimitry Andric                     Src2Regs, Src2LeftoverRegs))
55360b57cec5SDimitry Andric     llvm_unreachable("inconsistent extractParts result");
55370b57cec5SDimitry Andric 
55380b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
55390b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(NarrowTy,
55400b57cec5SDimitry Andric                                          CondReg, Src1Regs[I], Src2Regs[I]);
55415ffd83dbSDimitry Andric     DstRegs.push_back(Select.getReg(0));
55420b57cec5SDimitry Andric   }
55430b57cec5SDimitry Andric 
55440b57cec5SDimitry Andric   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
55450b57cec5SDimitry Andric     auto Select = MIRBuilder.buildSelect(
55460b57cec5SDimitry Andric       LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
55475ffd83dbSDimitry Andric     DstLeftoverRegs.push_back(Select.getReg(0));
55480b57cec5SDimitry Andric   }
55490b57cec5SDimitry Andric 
55500b57cec5SDimitry Andric   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
55510b57cec5SDimitry Andric               LeftoverTy, DstLeftoverRegs);
55520b57cec5SDimitry Andric 
55530b57cec5SDimitry Andric   MI.eraseFromParent();
55540b57cec5SDimitry Andric   return Legalized;
55550b57cec5SDimitry Andric }
55560b57cec5SDimitry Andric 
55570b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
55585ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTLZ(MachineInstr &MI, unsigned TypeIdx,
55595ffd83dbSDimitry Andric                                   LLT NarrowTy) {
55605ffd83dbSDimitry Andric   if (TypeIdx != 1)
55615ffd83dbSDimitry Andric     return UnableToLegalize;
55625ffd83dbSDimitry Andric 
5563*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
55645ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
55655ffd83dbSDimitry Andric 
55665ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
55675ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF;
55685ffd83dbSDimitry Andric 
55695ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
55705ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
55715ffd83dbSDimitry Andric     // ctlz(Hi:Lo) -> Hi == 0 ? (NarrowSize + ctlz(Lo)) : ctlz(Hi)
55725ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
55735ffd83dbSDimitry Andric     auto HiIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
55745ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(1), C_0);
55755ffd83dbSDimitry Andric     auto LoCTLZ = IsUndef ?
55765ffd83dbSDimitry Andric       B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0)) :
55775ffd83dbSDimitry Andric       B.buildCTLZ(DstTy, UnmergeSrc.getReg(0));
55785ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
55795ffd83dbSDimitry Andric     auto HiIsZeroCTLZ = B.buildAdd(DstTy, LoCTLZ, C_NarrowSize);
55805ffd83dbSDimitry Andric     auto HiCTLZ = B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1));
55815ffd83dbSDimitry Andric     B.buildSelect(DstReg, HiIsZero, HiIsZeroCTLZ, HiCTLZ);
55825ffd83dbSDimitry Andric 
55835ffd83dbSDimitry Andric     MI.eraseFromParent();
55845ffd83dbSDimitry Andric     return Legalized;
55855ffd83dbSDimitry Andric   }
55865ffd83dbSDimitry Andric 
55875ffd83dbSDimitry Andric   return UnableToLegalize;
55885ffd83dbSDimitry Andric }
55895ffd83dbSDimitry Andric 
55905ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
55915ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTTZ(MachineInstr &MI, unsigned TypeIdx,
55925ffd83dbSDimitry Andric                                   LLT NarrowTy) {
55935ffd83dbSDimitry Andric   if (TypeIdx != 1)
55945ffd83dbSDimitry Andric     return UnableToLegalize;
55955ffd83dbSDimitry Andric 
5596*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
55975ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
55985ffd83dbSDimitry Andric 
55995ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
56005ffd83dbSDimitry Andric     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF;
56015ffd83dbSDimitry Andric 
56025ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
56035ffd83dbSDimitry Andric     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
56045ffd83dbSDimitry Andric     // cttz(Hi:Lo) -> Lo == 0 ? (cttz(Hi) + NarrowSize) : cttz(Lo)
56055ffd83dbSDimitry Andric     auto C_0 = B.buildConstant(NarrowTy, 0);
56065ffd83dbSDimitry Andric     auto LoIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
56075ffd83dbSDimitry Andric                                 UnmergeSrc.getReg(0), C_0);
56085ffd83dbSDimitry Andric     auto HiCTTZ = IsUndef ?
56095ffd83dbSDimitry Andric       B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1)) :
56105ffd83dbSDimitry Andric       B.buildCTTZ(DstTy, UnmergeSrc.getReg(1));
56115ffd83dbSDimitry Andric     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
56125ffd83dbSDimitry Andric     auto LoIsZeroCTTZ = B.buildAdd(DstTy, HiCTTZ, C_NarrowSize);
56135ffd83dbSDimitry Andric     auto LoCTTZ = B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0));
56145ffd83dbSDimitry Andric     B.buildSelect(DstReg, LoIsZero, LoIsZeroCTTZ, LoCTTZ);
56155ffd83dbSDimitry Andric 
56165ffd83dbSDimitry Andric     MI.eraseFromParent();
56175ffd83dbSDimitry Andric     return Legalized;
56185ffd83dbSDimitry Andric   }
56195ffd83dbSDimitry Andric 
56205ffd83dbSDimitry Andric   return UnableToLegalize;
56215ffd83dbSDimitry Andric }
56225ffd83dbSDimitry Andric 
56235ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
56245ffd83dbSDimitry Andric LegalizerHelper::narrowScalarCTPOP(MachineInstr &MI, unsigned TypeIdx,
56255ffd83dbSDimitry Andric                                    LLT NarrowTy) {
56265ffd83dbSDimitry Andric   if (TypeIdx != 1)
56275ffd83dbSDimitry Andric     return UnableToLegalize;
56285ffd83dbSDimitry Andric 
5629*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
56305ffd83dbSDimitry Andric   unsigned NarrowSize = NarrowTy.getSizeInBits();
56315ffd83dbSDimitry Andric 
56325ffd83dbSDimitry Andric   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
56335ffd83dbSDimitry Andric     auto UnmergeSrc = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
56345ffd83dbSDimitry Andric 
56355ffd83dbSDimitry Andric     auto LoCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(0));
56365ffd83dbSDimitry Andric     auto HiCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(1));
56375ffd83dbSDimitry Andric     MIRBuilder.buildAdd(DstReg, HiCTPOP, LoCTPOP);
56385ffd83dbSDimitry Andric 
56395ffd83dbSDimitry Andric     MI.eraseFromParent();
56405ffd83dbSDimitry Andric     return Legalized;
56415ffd83dbSDimitry Andric   }
56425ffd83dbSDimitry Andric 
56435ffd83dbSDimitry Andric   return UnableToLegalize;
56445ffd83dbSDimitry Andric }
56455ffd83dbSDimitry Andric 
56465ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
5647*06c3fb27SDimitry Andric LegalizerHelper::narrowScalarFLDEXP(MachineInstr &MI, unsigned TypeIdx,
5648*06c3fb27SDimitry Andric                                     LLT NarrowTy) {
5649*06c3fb27SDimitry Andric   if (TypeIdx != 1)
5650*06c3fb27SDimitry Andric     return UnableToLegalize;
5651*06c3fb27SDimitry Andric 
5652*06c3fb27SDimitry Andric   MachineIRBuilder &B = MIRBuilder;
5653*06c3fb27SDimitry Andric   Register ExpReg = MI.getOperand(2).getReg();
5654*06c3fb27SDimitry Andric   LLT ExpTy = MRI.getType(ExpReg);
5655*06c3fb27SDimitry Andric 
5656*06c3fb27SDimitry Andric   unsigned ClampSize = NarrowTy.getScalarSizeInBits();
5657*06c3fb27SDimitry Andric 
5658*06c3fb27SDimitry Andric   // Clamp the exponent to the range of the target type.
5659*06c3fb27SDimitry Andric   auto MinExp = B.buildConstant(ExpTy, minIntN(ClampSize));
5660*06c3fb27SDimitry Andric   auto ClampMin = B.buildSMax(ExpTy, ExpReg, MinExp);
5661*06c3fb27SDimitry Andric   auto MaxExp = B.buildConstant(ExpTy, maxIntN(ClampSize));
5662*06c3fb27SDimitry Andric   auto Clamp = B.buildSMin(ExpTy, ClampMin, MaxExp);
5663*06c3fb27SDimitry Andric 
5664*06c3fb27SDimitry Andric   auto Trunc = B.buildTrunc(NarrowTy, Clamp);
5665*06c3fb27SDimitry Andric   Observer.changingInstr(MI);
5666*06c3fb27SDimitry Andric   MI.getOperand(2).setReg(Trunc.getReg(0));
5667*06c3fb27SDimitry Andric   Observer.changedInstr(MI);
5668*06c3fb27SDimitry Andric   return Legalized;
5669*06c3fb27SDimitry Andric }
5670*06c3fb27SDimitry Andric 
5671*06c3fb27SDimitry Andric LegalizerHelper::LegalizeResult
5672e8d8bef9SDimitry Andric LegalizerHelper::lowerBitCount(MachineInstr &MI) {
56730b57cec5SDimitry Andric   unsigned Opc = MI.getOpcode();
5674e8d8bef9SDimitry Andric   const auto &TII = MIRBuilder.getTII();
56750b57cec5SDimitry Andric   auto isSupported = [this](const LegalityQuery &Q) {
56760b57cec5SDimitry Andric     auto QAction = LI.getAction(Q).Action;
56770b57cec5SDimitry Andric     return QAction == Legal || QAction == Libcall || QAction == Custom;
56780b57cec5SDimitry Andric   };
56790b57cec5SDimitry Andric   switch (Opc) {
56800b57cec5SDimitry Andric   default:
56810b57cec5SDimitry Andric     return UnableToLegalize;
56820b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
56830b57cec5SDimitry Andric     // This trivially expands to CTLZ.
56840b57cec5SDimitry Andric     Observer.changingInstr(MI);
56850b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
56860b57cec5SDimitry Andric     Observer.changedInstr(MI);
56870b57cec5SDimitry Andric     return Legalized;
56880b57cec5SDimitry Andric   }
56890b57cec5SDimitry Andric   case TargetOpcode::G_CTLZ: {
5690*06c3fb27SDimitry Andric     auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
56915ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
56925ffd83dbSDimitry Andric 
56935ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
56940b57cec5SDimitry Andric       // If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
56955ffd83dbSDimitry Andric       auto CtlzZU = MIRBuilder.buildCTLZ_ZERO_UNDEF(DstTy, SrcReg);
56965ffd83dbSDimitry Andric       auto ZeroSrc = MIRBuilder.buildConstant(SrcTy, 0);
56975ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
56985ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, SrcTy.changeElementSize(1), SrcReg, ZeroSrc);
56995ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
57005ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CtlzZU);
57010b57cec5SDimitry Andric       MI.eraseFromParent();
57020b57cec5SDimitry Andric       return Legalized;
57030b57cec5SDimitry Andric     }
57040b57cec5SDimitry Andric     // for now, we do this:
57050b57cec5SDimitry Andric     // NewLen = NextPowerOf2(Len);
57060b57cec5SDimitry Andric     // x = x | (x >> 1);
57070b57cec5SDimitry Andric     // x = x | (x >> 2);
57080b57cec5SDimitry Andric     // ...
57090b57cec5SDimitry Andric     // x = x | (x >>16);
57100b57cec5SDimitry Andric     // x = x | (x >>32); // for 64-bit input
57110b57cec5SDimitry Andric     // Upto NewLen/2
57120b57cec5SDimitry Andric     // return Len - popcount(x);
57130b57cec5SDimitry Andric     //
57140b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
57150b57cec5SDimitry Andric     Register Op = SrcReg;
57160b57cec5SDimitry Andric     unsigned NewLen = PowerOf2Ceil(Len);
57170b57cec5SDimitry Andric     for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
57185ffd83dbSDimitry Andric       auto MIBShiftAmt = MIRBuilder.buildConstant(SrcTy, 1ULL << i);
57195ffd83dbSDimitry Andric       auto MIBOp = MIRBuilder.buildOr(
57205ffd83dbSDimitry Andric           SrcTy, Op, MIRBuilder.buildLShr(SrcTy, Op, MIBShiftAmt));
57215ffd83dbSDimitry Andric       Op = MIBOp.getReg(0);
57220b57cec5SDimitry Andric     }
57235ffd83dbSDimitry Andric     auto MIBPop = MIRBuilder.buildCTPOP(DstTy, Op);
57245ffd83dbSDimitry Andric     MIRBuilder.buildSub(MI.getOperand(0), MIRBuilder.buildConstant(DstTy, Len),
57255ffd83dbSDimitry Andric                         MIBPop);
57260b57cec5SDimitry Andric     MI.eraseFromParent();
57270b57cec5SDimitry Andric     return Legalized;
57280b57cec5SDimitry Andric   }
57290b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
57300b57cec5SDimitry Andric     // This trivially expands to CTTZ.
57310b57cec5SDimitry Andric     Observer.changingInstr(MI);
57320b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
57330b57cec5SDimitry Andric     Observer.changedInstr(MI);
57340b57cec5SDimitry Andric     return Legalized;
57350b57cec5SDimitry Andric   }
57360b57cec5SDimitry Andric   case TargetOpcode::G_CTTZ: {
5737*06c3fb27SDimitry Andric     auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
57385ffd83dbSDimitry Andric 
57395ffd83dbSDimitry Andric     unsigned Len = SrcTy.getSizeInBits();
57405ffd83dbSDimitry Andric     if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
57410b57cec5SDimitry Andric       // If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
57420b57cec5SDimitry Andric       // zero.
57435ffd83dbSDimitry Andric       auto CttzZU = MIRBuilder.buildCTTZ_ZERO_UNDEF(DstTy, SrcReg);
57445ffd83dbSDimitry Andric       auto Zero = MIRBuilder.buildConstant(SrcTy, 0);
57455ffd83dbSDimitry Andric       auto ICmp = MIRBuilder.buildICmp(
57465ffd83dbSDimitry Andric           CmpInst::ICMP_EQ, DstTy.changeElementSize(1), SrcReg, Zero);
57475ffd83dbSDimitry Andric       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
57485ffd83dbSDimitry Andric       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CttzZU);
57490b57cec5SDimitry Andric       MI.eraseFromParent();
57500b57cec5SDimitry Andric       return Legalized;
57510b57cec5SDimitry Andric     }
57520b57cec5SDimitry Andric     // for now, we use: { return popcount(~x & (x - 1)); }
57530b57cec5SDimitry Andric     // unless the target has ctlz but not ctpop, in which case we use:
57540b57cec5SDimitry Andric     // { return 32 - nlz(~x & (x-1)); }
57550b57cec5SDimitry Andric     // Ref: "Hacker's Delight" by Henry Warren
5756e8d8bef9SDimitry Andric     auto MIBCstNeg1 = MIRBuilder.buildConstant(SrcTy, -1);
5757e8d8bef9SDimitry Andric     auto MIBNot = MIRBuilder.buildXor(SrcTy, SrcReg, MIBCstNeg1);
57585ffd83dbSDimitry Andric     auto MIBTmp = MIRBuilder.buildAnd(
5759e8d8bef9SDimitry Andric         SrcTy, MIBNot, MIRBuilder.buildAdd(SrcTy, SrcReg, MIBCstNeg1));
5760e8d8bef9SDimitry Andric     if (!isSupported({TargetOpcode::G_CTPOP, {SrcTy, SrcTy}}) &&
5761e8d8bef9SDimitry Andric         isSupported({TargetOpcode::G_CTLZ, {SrcTy, SrcTy}})) {
5762e8d8bef9SDimitry Andric       auto MIBCstLen = MIRBuilder.buildConstant(SrcTy, Len);
57635ffd83dbSDimitry Andric       MIRBuilder.buildSub(MI.getOperand(0), MIBCstLen,
5764e8d8bef9SDimitry Andric                           MIRBuilder.buildCTLZ(SrcTy, MIBTmp));
57650b57cec5SDimitry Andric       MI.eraseFromParent();
57660b57cec5SDimitry Andric       return Legalized;
57670b57cec5SDimitry Andric     }
57680b57cec5SDimitry Andric     MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
57695ffd83dbSDimitry Andric     MI.getOperand(1).setReg(MIBTmp.getReg(0));
57705ffd83dbSDimitry Andric     return Legalized;
57715ffd83dbSDimitry Andric   }
57725ffd83dbSDimitry Andric   case TargetOpcode::G_CTPOP: {
5773e8d8bef9SDimitry Andric     Register SrcReg = MI.getOperand(1).getReg();
5774e8d8bef9SDimitry Andric     LLT Ty = MRI.getType(SrcReg);
57755ffd83dbSDimitry Andric     unsigned Size = Ty.getSizeInBits();
57765ffd83dbSDimitry Andric     MachineIRBuilder &B = MIRBuilder;
57775ffd83dbSDimitry Andric 
57785ffd83dbSDimitry Andric     // Count set bits in blocks of 2 bits. Default approach would be
57795ffd83dbSDimitry Andric     // B2Count = { val & 0x55555555 } + { (val >> 1) & 0x55555555 }
57805ffd83dbSDimitry Andric     // We use following formula instead:
57815ffd83dbSDimitry Andric     // B2Count = val - { (val >> 1) & 0x55555555 }
57825ffd83dbSDimitry Andric     // since it gives same result in blocks of 2 with one instruction less.
57835ffd83dbSDimitry Andric     auto C_1 = B.buildConstant(Ty, 1);
5784e8d8bef9SDimitry Andric     auto B2Set1LoTo1Hi = B.buildLShr(Ty, SrcReg, C_1);
57855ffd83dbSDimitry Andric     APInt B2Mask1HiTo0 = APInt::getSplat(Size, APInt(8, 0x55));
57865ffd83dbSDimitry Andric     auto C_B2Mask1HiTo0 = B.buildConstant(Ty, B2Mask1HiTo0);
57875ffd83dbSDimitry Andric     auto B2Count1Hi = B.buildAnd(Ty, B2Set1LoTo1Hi, C_B2Mask1HiTo0);
5788e8d8bef9SDimitry Andric     auto B2Count = B.buildSub(Ty, SrcReg, B2Count1Hi);
57895ffd83dbSDimitry Andric 
57905ffd83dbSDimitry Andric     // In order to get count in blocks of 4 add values from adjacent block of 2.
57915ffd83dbSDimitry Andric     // B4Count = { B2Count & 0x33333333 } + { (B2Count >> 2) & 0x33333333 }
57925ffd83dbSDimitry Andric     auto C_2 = B.buildConstant(Ty, 2);
57935ffd83dbSDimitry Andric     auto B4Set2LoTo2Hi = B.buildLShr(Ty, B2Count, C_2);
57945ffd83dbSDimitry Andric     APInt B4Mask2HiTo0 = APInt::getSplat(Size, APInt(8, 0x33));
57955ffd83dbSDimitry Andric     auto C_B4Mask2HiTo0 = B.buildConstant(Ty, B4Mask2HiTo0);
57965ffd83dbSDimitry Andric     auto B4HiB2Count = B.buildAnd(Ty, B4Set2LoTo2Hi, C_B4Mask2HiTo0);
57975ffd83dbSDimitry Andric     auto B4LoB2Count = B.buildAnd(Ty, B2Count, C_B4Mask2HiTo0);
57985ffd83dbSDimitry Andric     auto B4Count = B.buildAdd(Ty, B4HiB2Count, B4LoB2Count);
57995ffd83dbSDimitry Andric 
58005ffd83dbSDimitry Andric     // For count in blocks of 8 bits we don't have to mask high 4 bits before
58015ffd83dbSDimitry Andric     // addition since count value sits in range {0,...,8} and 4 bits are enough
58025ffd83dbSDimitry Andric     // to hold such binary values. After addition high 4 bits still hold count
58035ffd83dbSDimitry Andric     // of set bits in high 4 bit block, set them to zero and get 8 bit result.
58045ffd83dbSDimitry Andric     // B8Count = { B4Count + (B4Count >> 4) } & 0x0F0F0F0F
58055ffd83dbSDimitry Andric     auto C_4 = B.buildConstant(Ty, 4);
58065ffd83dbSDimitry Andric     auto B8HiB4Count = B.buildLShr(Ty, B4Count, C_4);
58075ffd83dbSDimitry Andric     auto B8CountDirty4Hi = B.buildAdd(Ty, B8HiB4Count, B4Count);
58085ffd83dbSDimitry Andric     APInt B8Mask4HiTo0 = APInt::getSplat(Size, APInt(8, 0x0F));
58095ffd83dbSDimitry Andric     auto C_B8Mask4HiTo0 = B.buildConstant(Ty, B8Mask4HiTo0);
58105ffd83dbSDimitry Andric     auto B8Count = B.buildAnd(Ty, B8CountDirty4Hi, C_B8Mask4HiTo0);
58115ffd83dbSDimitry Andric 
58125ffd83dbSDimitry Andric     assert(Size<=128 && "Scalar size is too large for CTPOP lower algorithm");
58135ffd83dbSDimitry Andric     // 8 bits can hold CTPOP result of 128 bit int or smaller. Mul with this
58145ffd83dbSDimitry Andric     // bitmask will set 8 msb in ResTmp to sum of all B8Counts in 8 bit blocks.
58155ffd83dbSDimitry Andric     auto MulMask = B.buildConstant(Ty, APInt::getSplat(Size, APInt(8, 0x01)));
58165ffd83dbSDimitry Andric     auto ResTmp = B.buildMul(Ty, B8Count, MulMask);
58175ffd83dbSDimitry Andric 
58185ffd83dbSDimitry Andric     // Shift count result from 8 high bits to low bits.
58195ffd83dbSDimitry Andric     auto C_SizeM8 = B.buildConstant(Ty, Size - 8);
58205ffd83dbSDimitry Andric     B.buildLShr(MI.getOperand(0).getReg(), ResTmp, C_SizeM8);
58215ffd83dbSDimitry Andric 
58225ffd83dbSDimitry Andric     MI.eraseFromParent();
58230b57cec5SDimitry Andric     return Legalized;
58240b57cec5SDimitry Andric   }
58250b57cec5SDimitry Andric   }
58260b57cec5SDimitry Andric }
58270b57cec5SDimitry Andric 
5828fe6060f1SDimitry Andric // Check that (every element of) Reg is undef or not an exact multiple of BW.
5829fe6060f1SDimitry Andric static bool isNonZeroModBitWidthOrUndef(const MachineRegisterInfo &MRI,
5830fe6060f1SDimitry Andric                                         Register Reg, unsigned BW) {
5831fe6060f1SDimitry Andric   return matchUnaryPredicate(
5832fe6060f1SDimitry Andric       MRI, Reg,
5833fe6060f1SDimitry Andric       [=](const Constant *C) {
5834fe6060f1SDimitry Andric         // Null constant here means an undef.
5835fe6060f1SDimitry Andric         const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C);
5836fe6060f1SDimitry Andric         return !CI || CI->getValue().urem(BW) != 0;
5837fe6060f1SDimitry Andric       },
5838fe6060f1SDimitry Andric       /*AllowUndefs*/ true);
5839fe6060f1SDimitry Andric }
5840fe6060f1SDimitry Andric 
5841fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5842fe6060f1SDimitry Andric LegalizerHelper::lowerFunnelShiftWithInverse(MachineInstr &MI) {
5843*06c3fb27SDimitry Andric   auto [Dst, X, Y, Z] = MI.getFirst4Regs();
5844fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
5845fe6060f1SDimitry Andric   LLT ShTy = MRI.getType(Z);
5846fe6060f1SDimitry Andric 
5847fe6060f1SDimitry Andric   unsigned BW = Ty.getScalarSizeInBits();
5848fe6060f1SDimitry Andric 
5849fe6060f1SDimitry Andric   if (!isPowerOf2_32(BW))
5850fe6060f1SDimitry Andric     return UnableToLegalize;
5851fe6060f1SDimitry Andric 
5852fe6060f1SDimitry Andric   const bool IsFSHL = MI.getOpcode() == TargetOpcode::G_FSHL;
5853fe6060f1SDimitry Andric   unsigned RevOpcode = IsFSHL ? TargetOpcode::G_FSHR : TargetOpcode::G_FSHL;
5854fe6060f1SDimitry Andric 
5855fe6060f1SDimitry Andric   if (isNonZeroModBitWidthOrUndef(MRI, Z, BW)) {
5856fe6060f1SDimitry Andric     // fshl X, Y, Z -> fshr X, Y, -Z
5857fe6060f1SDimitry Andric     // fshr X, Y, Z -> fshl X, Y, -Z
5858fe6060f1SDimitry Andric     auto Zero = MIRBuilder.buildConstant(ShTy, 0);
5859fe6060f1SDimitry Andric     Z = MIRBuilder.buildSub(Ty, Zero, Z).getReg(0);
5860fe6060f1SDimitry Andric   } else {
5861fe6060f1SDimitry Andric     // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
5862fe6060f1SDimitry Andric     // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
5863fe6060f1SDimitry Andric     auto One = MIRBuilder.buildConstant(ShTy, 1);
5864fe6060f1SDimitry Andric     if (IsFSHL) {
5865fe6060f1SDimitry Andric       Y = MIRBuilder.buildInstr(RevOpcode, {Ty}, {X, Y, One}).getReg(0);
5866fe6060f1SDimitry Andric       X = MIRBuilder.buildLShr(Ty, X, One).getReg(0);
5867fe6060f1SDimitry Andric     } else {
5868fe6060f1SDimitry Andric       X = MIRBuilder.buildInstr(RevOpcode, {Ty}, {X, Y, One}).getReg(0);
5869fe6060f1SDimitry Andric       Y = MIRBuilder.buildShl(Ty, Y, One).getReg(0);
5870fe6060f1SDimitry Andric     }
5871fe6060f1SDimitry Andric 
5872fe6060f1SDimitry Andric     Z = MIRBuilder.buildNot(ShTy, Z).getReg(0);
5873fe6060f1SDimitry Andric   }
5874fe6060f1SDimitry Andric 
5875fe6060f1SDimitry Andric   MIRBuilder.buildInstr(RevOpcode, {Dst}, {X, Y, Z});
5876fe6060f1SDimitry Andric   MI.eraseFromParent();
5877fe6060f1SDimitry Andric   return Legalized;
5878fe6060f1SDimitry Andric }
5879fe6060f1SDimitry Andric 
5880fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5881fe6060f1SDimitry Andric LegalizerHelper::lowerFunnelShiftAsShifts(MachineInstr &MI) {
5882*06c3fb27SDimitry Andric   auto [Dst, X, Y, Z] = MI.getFirst4Regs();
5883fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
5884fe6060f1SDimitry Andric   LLT ShTy = MRI.getType(Z);
5885fe6060f1SDimitry Andric 
5886fe6060f1SDimitry Andric   const unsigned BW = Ty.getScalarSizeInBits();
5887fe6060f1SDimitry Andric   const bool IsFSHL = MI.getOpcode() == TargetOpcode::G_FSHL;
5888fe6060f1SDimitry Andric 
5889fe6060f1SDimitry Andric   Register ShX, ShY;
5890fe6060f1SDimitry Andric   Register ShAmt, InvShAmt;
5891fe6060f1SDimitry Andric 
5892fe6060f1SDimitry Andric   // FIXME: Emit optimized urem by constant instead of letting it expand later.
5893fe6060f1SDimitry Andric   if (isNonZeroModBitWidthOrUndef(MRI, Z, BW)) {
5894fe6060f1SDimitry Andric     // fshl: X << C | Y >> (BW - C)
5895fe6060f1SDimitry Andric     // fshr: X << (BW - C) | Y >> C
5896fe6060f1SDimitry Andric     // where C = Z % BW is not zero
5897fe6060f1SDimitry Andric     auto BitWidthC = MIRBuilder.buildConstant(ShTy, BW);
5898fe6060f1SDimitry Andric     ShAmt = MIRBuilder.buildURem(ShTy, Z, BitWidthC).getReg(0);
5899fe6060f1SDimitry Andric     InvShAmt = MIRBuilder.buildSub(ShTy, BitWidthC, ShAmt).getReg(0);
5900fe6060f1SDimitry Andric     ShX = MIRBuilder.buildShl(Ty, X, IsFSHL ? ShAmt : InvShAmt).getReg(0);
5901fe6060f1SDimitry Andric     ShY = MIRBuilder.buildLShr(Ty, Y, IsFSHL ? InvShAmt : ShAmt).getReg(0);
5902fe6060f1SDimitry Andric   } else {
5903fe6060f1SDimitry Andric     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
5904fe6060f1SDimitry Andric     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
5905fe6060f1SDimitry Andric     auto Mask = MIRBuilder.buildConstant(ShTy, BW - 1);
5906fe6060f1SDimitry Andric     if (isPowerOf2_32(BW)) {
5907fe6060f1SDimitry Andric       // Z % BW -> Z & (BW - 1)
5908fe6060f1SDimitry Andric       ShAmt = MIRBuilder.buildAnd(ShTy, Z, Mask).getReg(0);
5909fe6060f1SDimitry Andric       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
5910fe6060f1SDimitry Andric       auto NotZ = MIRBuilder.buildNot(ShTy, Z);
5911fe6060f1SDimitry Andric       InvShAmt = MIRBuilder.buildAnd(ShTy, NotZ, Mask).getReg(0);
5912fe6060f1SDimitry Andric     } else {
5913fe6060f1SDimitry Andric       auto BitWidthC = MIRBuilder.buildConstant(ShTy, BW);
5914fe6060f1SDimitry Andric       ShAmt = MIRBuilder.buildURem(ShTy, Z, BitWidthC).getReg(0);
5915fe6060f1SDimitry Andric       InvShAmt = MIRBuilder.buildSub(ShTy, Mask, ShAmt).getReg(0);
5916fe6060f1SDimitry Andric     }
5917fe6060f1SDimitry Andric 
5918fe6060f1SDimitry Andric     auto One = MIRBuilder.buildConstant(ShTy, 1);
5919fe6060f1SDimitry Andric     if (IsFSHL) {
5920fe6060f1SDimitry Andric       ShX = MIRBuilder.buildShl(Ty, X, ShAmt).getReg(0);
5921fe6060f1SDimitry Andric       auto ShY1 = MIRBuilder.buildLShr(Ty, Y, One);
5922fe6060f1SDimitry Andric       ShY = MIRBuilder.buildLShr(Ty, ShY1, InvShAmt).getReg(0);
5923fe6060f1SDimitry Andric     } else {
5924fe6060f1SDimitry Andric       auto ShX1 = MIRBuilder.buildShl(Ty, X, One);
5925fe6060f1SDimitry Andric       ShX = MIRBuilder.buildShl(Ty, ShX1, InvShAmt).getReg(0);
5926fe6060f1SDimitry Andric       ShY = MIRBuilder.buildLShr(Ty, Y, ShAmt).getReg(0);
5927fe6060f1SDimitry Andric     }
5928fe6060f1SDimitry Andric   }
5929fe6060f1SDimitry Andric 
5930fe6060f1SDimitry Andric   MIRBuilder.buildOr(Dst, ShX, ShY);
5931fe6060f1SDimitry Andric   MI.eraseFromParent();
5932fe6060f1SDimitry Andric   return Legalized;
5933fe6060f1SDimitry Andric }
5934fe6060f1SDimitry Andric 
5935fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5936fe6060f1SDimitry Andric LegalizerHelper::lowerFunnelShift(MachineInstr &MI) {
5937fe6060f1SDimitry Andric   // These operations approximately do the following (while avoiding undefined
5938fe6060f1SDimitry Andric   // shifts by BW):
5939fe6060f1SDimitry Andric   // G_FSHL: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5940fe6060f1SDimitry Andric   // G_FSHR: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5941fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5942fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
5943fe6060f1SDimitry Andric   LLT ShTy = MRI.getType(MI.getOperand(3).getReg());
5944fe6060f1SDimitry Andric 
5945fe6060f1SDimitry Andric   bool IsFSHL = MI.getOpcode() == TargetOpcode::G_FSHL;
5946fe6060f1SDimitry Andric   unsigned RevOpcode = IsFSHL ? TargetOpcode::G_FSHR : TargetOpcode::G_FSHL;
5947fe6060f1SDimitry Andric 
5948fe6060f1SDimitry Andric   // TODO: Use smarter heuristic that accounts for vector legalization.
5949fe6060f1SDimitry Andric   if (LI.getAction({RevOpcode, {Ty, ShTy}}).Action == Lower)
5950fe6060f1SDimitry Andric     return lowerFunnelShiftAsShifts(MI);
5951fe6060f1SDimitry Andric 
5952fe6060f1SDimitry Andric   // This only works for powers of 2, fallback to shifts if it fails.
5953fe6060f1SDimitry Andric   LegalizerHelper::LegalizeResult Result = lowerFunnelShiftWithInverse(MI);
5954fe6060f1SDimitry Andric   if (Result == UnableToLegalize)
5955fe6060f1SDimitry Andric     return lowerFunnelShiftAsShifts(MI);
5956fe6060f1SDimitry Andric   return Result;
5957fe6060f1SDimitry Andric }
5958fe6060f1SDimitry Andric 
5959fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
5960fe6060f1SDimitry Andric LegalizerHelper::lowerRotateWithReverseRotate(MachineInstr &MI) {
5961*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy, Amt, AmtTy] = MI.getFirst3RegLLTs();
5962fe6060f1SDimitry Andric   auto Zero = MIRBuilder.buildConstant(AmtTy, 0);
5963fe6060f1SDimitry Andric   bool IsLeft = MI.getOpcode() == TargetOpcode::G_ROTL;
5964fe6060f1SDimitry Andric   unsigned RevRot = IsLeft ? TargetOpcode::G_ROTR : TargetOpcode::G_ROTL;
5965fe6060f1SDimitry Andric   auto Neg = MIRBuilder.buildSub(AmtTy, Zero, Amt);
5966fe6060f1SDimitry Andric   MIRBuilder.buildInstr(RevRot, {Dst}, {Src, Neg});
5967fe6060f1SDimitry Andric   MI.eraseFromParent();
5968fe6060f1SDimitry Andric   return Legalized;
5969fe6060f1SDimitry Andric }
5970fe6060f1SDimitry Andric 
5971fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerRotate(MachineInstr &MI) {
5972*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy, Amt, AmtTy] = MI.getFirst3RegLLTs();
5973fe6060f1SDimitry Andric 
5974fe6060f1SDimitry Andric   unsigned EltSizeInBits = DstTy.getScalarSizeInBits();
5975fe6060f1SDimitry Andric   bool IsLeft = MI.getOpcode() == TargetOpcode::G_ROTL;
5976fe6060f1SDimitry Andric 
5977fe6060f1SDimitry Andric   MIRBuilder.setInstrAndDebugLoc(MI);
5978fe6060f1SDimitry Andric 
5979fe6060f1SDimitry Andric   // If a rotate in the other direction is supported, use it.
5980fe6060f1SDimitry Andric   unsigned RevRot = IsLeft ? TargetOpcode::G_ROTR : TargetOpcode::G_ROTL;
5981fe6060f1SDimitry Andric   if (LI.isLegalOrCustom({RevRot, {DstTy, SrcTy}}) &&
5982fe6060f1SDimitry Andric       isPowerOf2_32(EltSizeInBits))
5983fe6060f1SDimitry Andric     return lowerRotateWithReverseRotate(MI);
5984fe6060f1SDimitry Andric 
5985349cc55cSDimitry Andric   // If a funnel shift is supported, use it.
5986349cc55cSDimitry Andric   unsigned FShOpc = IsLeft ? TargetOpcode::G_FSHL : TargetOpcode::G_FSHR;
5987349cc55cSDimitry Andric   unsigned RevFsh = !IsLeft ? TargetOpcode::G_FSHL : TargetOpcode::G_FSHR;
5988349cc55cSDimitry Andric   bool IsFShLegal = false;
5989349cc55cSDimitry Andric   if ((IsFShLegal = LI.isLegalOrCustom({FShOpc, {DstTy, AmtTy}})) ||
5990349cc55cSDimitry Andric       LI.isLegalOrCustom({RevFsh, {DstTy, AmtTy}})) {
5991349cc55cSDimitry Andric     auto buildFunnelShift = [&](unsigned Opc, Register R1, Register R2,
5992349cc55cSDimitry Andric                                 Register R3) {
5993349cc55cSDimitry Andric       MIRBuilder.buildInstr(Opc, {R1}, {R2, R2, R3});
5994349cc55cSDimitry Andric       MI.eraseFromParent();
5995349cc55cSDimitry Andric       return Legalized;
5996349cc55cSDimitry Andric     };
5997349cc55cSDimitry Andric     // If a funnel shift in the other direction is supported, use it.
5998349cc55cSDimitry Andric     if (IsFShLegal) {
5999349cc55cSDimitry Andric       return buildFunnelShift(FShOpc, Dst, Src, Amt);
6000349cc55cSDimitry Andric     } else if (isPowerOf2_32(EltSizeInBits)) {
6001349cc55cSDimitry Andric       Amt = MIRBuilder.buildNeg(DstTy, Amt).getReg(0);
6002349cc55cSDimitry Andric       return buildFunnelShift(RevFsh, Dst, Src, Amt);
6003349cc55cSDimitry Andric     }
6004349cc55cSDimitry Andric   }
6005349cc55cSDimitry Andric 
6006fe6060f1SDimitry Andric   auto Zero = MIRBuilder.buildConstant(AmtTy, 0);
6007fe6060f1SDimitry Andric   unsigned ShOpc = IsLeft ? TargetOpcode::G_SHL : TargetOpcode::G_LSHR;
6008fe6060f1SDimitry Andric   unsigned RevShiftOpc = IsLeft ? TargetOpcode::G_LSHR : TargetOpcode::G_SHL;
6009fe6060f1SDimitry Andric   auto BitWidthMinusOneC = MIRBuilder.buildConstant(AmtTy, EltSizeInBits - 1);
6010fe6060f1SDimitry Andric   Register ShVal;
6011fe6060f1SDimitry Andric   Register RevShiftVal;
6012fe6060f1SDimitry Andric   if (isPowerOf2_32(EltSizeInBits)) {
6013fe6060f1SDimitry Andric     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
6014fe6060f1SDimitry Andric     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
6015fe6060f1SDimitry Andric     auto NegAmt = MIRBuilder.buildSub(AmtTy, Zero, Amt);
6016fe6060f1SDimitry Andric     auto ShAmt = MIRBuilder.buildAnd(AmtTy, Amt, BitWidthMinusOneC);
6017fe6060f1SDimitry Andric     ShVal = MIRBuilder.buildInstr(ShOpc, {DstTy}, {Src, ShAmt}).getReg(0);
6018fe6060f1SDimitry Andric     auto RevAmt = MIRBuilder.buildAnd(AmtTy, NegAmt, BitWidthMinusOneC);
6019fe6060f1SDimitry Andric     RevShiftVal =
6020fe6060f1SDimitry Andric         MIRBuilder.buildInstr(RevShiftOpc, {DstTy}, {Src, RevAmt}).getReg(0);
6021fe6060f1SDimitry Andric   } else {
6022fe6060f1SDimitry Andric     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
6023fe6060f1SDimitry Andric     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
6024fe6060f1SDimitry Andric     auto BitWidthC = MIRBuilder.buildConstant(AmtTy, EltSizeInBits);
6025fe6060f1SDimitry Andric     auto ShAmt = MIRBuilder.buildURem(AmtTy, Amt, BitWidthC);
6026fe6060f1SDimitry Andric     ShVal = MIRBuilder.buildInstr(ShOpc, {DstTy}, {Src, ShAmt}).getReg(0);
6027fe6060f1SDimitry Andric     auto RevAmt = MIRBuilder.buildSub(AmtTy, BitWidthMinusOneC, ShAmt);
6028fe6060f1SDimitry Andric     auto One = MIRBuilder.buildConstant(AmtTy, 1);
6029fe6060f1SDimitry Andric     auto Inner = MIRBuilder.buildInstr(RevShiftOpc, {DstTy}, {Src, One});
6030fe6060f1SDimitry Andric     RevShiftVal =
6031fe6060f1SDimitry Andric         MIRBuilder.buildInstr(RevShiftOpc, {DstTy}, {Inner, RevAmt}).getReg(0);
6032fe6060f1SDimitry Andric   }
6033fe6060f1SDimitry Andric   MIRBuilder.buildOr(Dst, ShVal, RevShiftVal);
6034fe6060f1SDimitry Andric   MI.eraseFromParent();
6035fe6060f1SDimitry Andric   return Legalized;
6036fe6060f1SDimitry Andric }
6037fe6060f1SDimitry Andric 
60380b57cec5SDimitry Andric // Expand s32 = G_UITOFP s64 using bit operations to an IEEE float
60390b57cec5SDimitry Andric // representation.
60400b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
60410b57cec5SDimitry Andric LegalizerHelper::lowerU64ToF32BitOps(MachineInstr &MI) {
6042*06c3fb27SDimitry Andric   auto [Dst, Src] = MI.getFirst2Regs();
60430b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
60440b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
60450b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
60460b57cec5SDimitry Andric 
60470b57cec5SDimitry Andric   assert(MRI.getType(Src) == S64 && MRI.getType(Dst) == S32);
60480b57cec5SDimitry Andric 
60490b57cec5SDimitry Andric   // unsigned cul2f(ulong u) {
60500b57cec5SDimitry Andric   //   uint lz = clz(u);
60510b57cec5SDimitry Andric   //   uint e = (u != 0) ? 127U + 63U - lz : 0;
60520b57cec5SDimitry Andric   //   u = (u << lz) & 0x7fffffffffffffffUL;
60530b57cec5SDimitry Andric   //   ulong t = u & 0xffffffffffUL;
60540b57cec5SDimitry Andric   //   uint v = (e << 23) | (uint)(u >> 40);
60550b57cec5SDimitry Andric   //   uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
60560b57cec5SDimitry Andric   //   return as_float(v + r);
60570b57cec5SDimitry Andric   // }
60580b57cec5SDimitry Andric 
60590b57cec5SDimitry Andric   auto Zero32 = MIRBuilder.buildConstant(S32, 0);
60600b57cec5SDimitry Andric   auto Zero64 = MIRBuilder.buildConstant(S64, 0);
60610b57cec5SDimitry Andric 
60620b57cec5SDimitry Andric   auto LZ = MIRBuilder.buildCTLZ_ZERO_UNDEF(S32, Src);
60630b57cec5SDimitry Andric 
60640b57cec5SDimitry Andric   auto K = MIRBuilder.buildConstant(S32, 127U + 63U);
60650b57cec5SDimitry Andric   auto Sub = MIRBuilder.buildSub(S32, K, LZ);
60660b57cec5SDimitry Andric 
60670b57cec5SDimitry Andric   auto NotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, Src, Zero64);
60680b57cec5SDimitry Andric   auto E = MIRBuilder.buildSelect(S32, NotZero, Sub, Zero32);
60690b57cec5SDimitry Andric 
60700b57cec5SDimitry Andric   auto Mask0 = MIRBuilder.buildConstant(S64, (-1ULL) >> 1);
60710b57cec5SDimitry Andric   auto ShlLZ = MIRBuilder.buildShl(S64, Src, LZ);
60720b57cec5SDimitry Andric 
60730b57cec5SDimitry Andric   auto U = MIRBuilder.buildAnd(S64, ShlLZ, Mask0);
60740b57cec5SDimitry Andric 
60750b57cec5SDimitry Andric   auto Mask1 = MIRBuilder.buildConstant(S64, 0xffffffffffULL);
60760b57cec5SDimitry Andric   auto T = MIRBuilder.buildAnd(S64, U, Mask1);
60770b57cec5SDimitry Andric 
60780b57cec5SDimitry Andric   auto UShl = MIRBuilder.buildLShr(S64, U, MIRBuilder.buildConstant(S64, 40));
60790b57cec5SDimitry Andric   auto ShlE = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 23));
60800b57cec5SDimitry Andric   auto V = MIRBuilder.buildOr(S32, ShlE, MIRBuilder.buildTrunc(S32, UShl));
60810b57cec5SDimitry Andric 
60820b57cec5SDimitry Andric   auto C = MIRBuilder.buildConstant(S64, 0x8000000000ULL);
60830b57cec5SDimitry Andric   auto RCmp = MIRBuilder.buildICmp(CmpInst::ICMP_UGT, S1, T, C);
60840b57cec5SDimitry Andric   auto TCmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, T, C);
60850b57cec5SDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
60860b57cec5SDimitry Andric 
60870b57cec5SDimitry Andric   auto VTrunc1 = MIRBuilder.buildAnd(S32, V, One);
60880b57cec5SDimitry Andric   auto Select0 = MIRBuilder.buildSelect(S32, TCmp, VTrunc1, Zero32);
60890b57cec5SDimitry Andric   auto R = MIRBuilder.buildSelect(S32, RCmp, One, Select0);
60900b57cec5SDimitry Andric   MIRBuilder.buildAdd(Dst, V, R);
60910b57cec5SDimitry Andric 
60925ffd83dbSDimitry Andric   MI.eraseFromParent();
60930b57cec5SDimitry Andric   return Legalized;
60940b57cec5SDimitry Andric }
60950b57cec5SDimitry Andric 
6096e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerUITOFP(MachineInstr &MI) {
6097*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy] = MI.getFirst2RegLLTs();
60980b57cec5SDimitry Andric 
6099480093f4SDimitry Andric   if (SrcTy == LLT::scalar(1)) {
6100480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, 1.0);
6101480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
6102480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
6103480093f4SDimitry Andric     MI.eraseFromParent();
6104480093f4SDimitry Andric     return Legalized;
6105480093f4SDimitry Andric   }
6106480093f4SDimitry Andric 
61070b57cec5SDimitry Andric   if (SrcTy != LLT::scalar(64))
61080b57cec5SDimitry Andric     return UnableToLegalize;
61090b57cec5SDimitry Andric 
61100b57cec5SDimitry Andric   if (DstTy == LLT::scalar(32)) {
61110b57cec5SDimitry Andric     // TODO: SelectionDAG has several alternative expansions to port which may
61120b57cec5SDimitry Andric     // be more reasonble depending on the available instructions. If a target
61130b57cec5SDimitry Andric     // has sitofp, does not have CTLZ, or can efficiently use f64 as an
61140b57cec5SDimitry Andric     // intermediate type, this is probably worse.
61150b57cec5SDimitry Andric     return lowerU64ToF32BitOps(MI);
61160b57cec5SDimitry Andric   }
61170b57cec5SDimitry Andric 
61180b57cec5SDimitry Andric   return UnableToLegalize;
61190b57cec5SDimitry Andric }
61200b57cec5SDimitry Andric 
6121e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSITOFP(MachineInstr &MI) {
6122*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy] = MI.getFirst2RegLLTs();
61230b57cec5SDimitry Andric 
61240b57cec5SDimitry Andric   const LLT S64 = LLT::scalar(64);
61250b57cec5SDimitry Andric   const LLT S32 = LLT::scalar(32);
61260b57cec5SDimitry Andric   const LLT S1 = LLT::scalar(1);
61270b57cec5SDimitry Andric 
6128480093f4SDimitry Andric   if (SrcTy == S1) {
6129480093f4SDimitry Andric     auto True = MIRBuilder.buildFConstant(DstTy, -1.0);
6130480093f4SDimitry Andric     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
6131480093f4SDimitry Andric     MIRBuilder.buildSelect(Dst, Src, True, False);
6132480093f4SDimitry Andric     MI.eraseFromParent();
6133480093f4SDimitry Andric     return Legalized;
6134480093f4SDimitry Andric   }
6135480093f4SDimitry Andric 
61360b57cec5SDimitry Andric   if (SrcTy != S64)
61370b57cec5SDimitry Andric     return UnableToLegalize;
61380b57cec5SDimitry Andric 
61390b57cec5SDimitry Andric   if (DstTy == S32) {
61400b57cec5SDimitry Andric     // signed cl2f(long l) {
61410b57cec5SDimitry Andric     //   long s = l >> 63;
61420b57cec5SDimitry Andric     //   float r = cul2f((l + s) ^ s);
61430b57cec5SDimitry Andric     //   return s ? -r : r;
61440b57cec5SDimitry Andric     // }
61450b57cec5SDimitry Andric     Register L = Src;
61460b57cec5SDimitry Andric     auto SignBit = MIRBuilder.buildConstant(S64, 63);
61470b57cec5SDimitry Andric     auto S = MIRBuilder.buildAShr(S64, L, SignBit);
61480b57cec5SDimitry Andric 
61490b57cec5SDimitry Andric     auto LPlusS = MIRBuilder.buildAdd(S64, L, S);
61500b57cec5SDimitry Andric     auto Xor = MIRBuilder.buildXor(S64, LPlusS, S);
61510b57cec5SDimitry Andric     auto R = MIRBuilder.buildUITOFP(S32, Xor);
61520b57cec5SDimitry Andric 
61530b57cec5SDimitry Andric     auto RNeg = MIRBuilder.buildFNeg(S32, R);
61540b57cec5SDimitry Andric     auto SignNotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, S,
61550b57cec5SDimitry Andric                                             MIRBuilder.buildConstant(S64, 0));
61560b57cec5SDimitry Andric     MIRBuilder.buildSelect(Dst, SignNotZero, RNeg, R);
61575ffd83dbSDimitry Andric     MI.eraseFromParent();
61580b57cec5SDimitry Andric     return Legalized;
61590b57cec5SDimitry Andric   }
61600b57cec5SDimitry Andric 
61610b57cec5SDimitry Andric   return UnableToLegalize;
61620b57cec5SDimitry Andric }
61630b57cec5SDimitry Andric 
6164e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOUI(MachineInstr &MI) {
6165*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy] = MI.getFirst2RegLLTs();
61668bcb0991SDimitry Andric   const LLT S64 = LLT::scalar(64);
61678bcb0991SDimitry Andric   const LLT S32 = LLT::scalar(32);
61688bcb0991SDimitry Andric 
61698bcb0991SDimitry Andric   if (SrcTy != S64 && SrcTy != S32)
61708bcb0991SDimitry Andric     return UnableToLegalize;
61718bcb0991SDimitry Andric   if (DstTy != S32 && DstTy != S64)
61728bcb0991SDimitry Andric     return UnableToLegalize;
61738bcb0991SDimitry Andric 
61748bcb0991SDimitry Andric   // FPTOSI gives same result as FPTOUI for positive signed integers.
61758bcb0991SDimitry Andric   // FPTOUI needs to deal with fp values that convert to unsigned integers
61768bcb0991SDimitry Andric   // greater or equal to 2^31 for float or 2^63 for double. For brevity 2^Exp.
61778bcb0991SDimitry Andric 
61788bcb0991SDimitry Andric   APInt TwoPExpInt = APInt::getSignMask(DstTy.getSizeInBits());
61798bcb0991SDimitry Andric   APFloat TwoPExpFP(SrcTy.getSizeInBits() == 32 ? APFloat::IEEEsingle()
61808bcb0991SDimitry Andric                                                 : APFloat::IEEEdouble(),
6181349cc55cSDimitry Andric                     APInt::getZero(SrcTy.getSizeInBits()));
61828bcb0991SDimitry Andric   TwoPExpFP.convertFromAPInt(TwoPExpInt, false, APFloat::rmNearestTiesToEven);
61838bcb0991SDimitry Andric 
61848bcb0991SDimitry Andric   MachineInstrBuilder FPTOSI = MIRBuilder.buildFPTOSI(DstTy, Src);
61858bcb0991SDimitry Andric 
61868bcb0991SDimitry Andric   MachineInstrBuilder Threshold = MIRBuilder.buildFConstant(SrcTy, TwoPExpFP);
61878bcb0991SDimitry Andric   // For fp Value greater or equal to Threshold(2^Exp), we use FPTOSI on
61888bcb0991SDimitry Andric   // (Value - 2^Exp) and add 2^Exp by setting highest bit in result to 1.
61898bcb0991SDimitry Andric   MachineInstrBuilder FSub = MIRBuilder.buildFSub(SrcTy, Src, Threshold);
61908bcb0991SDimitry Andric   MachineInstrBuilder ResLowBits = MIRBuilder.buildFPTOSI(DstTy, FSub);
61918bcb0991SDimitry Andric   MachineInstrBuilder ResHighBit = MIRBuilder.buildConstant(DstTy, TwoPExpInt);
61928bcb0991SDimitry Andric   MachineInstrBuilder Res = MIRBuilder.buildXor(DstTy, ResLowBits, ResHighBit);
61938bcb0991SDimitry Andric 
6194480093f4SDimitry Andric   const LLT S1 = LLT::scalar(1);
6195480093f4SDimitry Andric 
61968bcb0991SDimitry Andric   MachineInstrBuilder FCMP =
6197480093f4SDimitry Andric       MIRBuilder.buildFCmp(CmpInst::FCMP_ULT, S1, Src, Threshold);
61988bcb0991SDimitry Andric   MIRBuilder.buildSelect(Dst, FCMP, FPTOSI, Res);
61998bcb0991SDimitry Andric 
62008bcb0991SDimitry Andric   MI.eraseFromParent();
62018bcb0991SDimitry Andric   return Legalized;
62028bcb0991SDimitry Andric }
62038bcb0991SDimitry Andric 
62045ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOSI(MachineInstr &MI) {
6205*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src, SrcTy] = MI.getFirst2RegLLTs();
62065ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
62075ffd83dbSDimitry Andric   const LLT S32 = LLT::scalar(32);
62085ffd83dbSDimitry Andric 
62095ffd83dbSDimitry Andric   // FIXME: Only f32 to i64 conversions are supported.
62105ffd83dbSDimitry Andric   if (SrcTy.getScalarType() != S32 || DstTy.getScalarType() != S64)
62115ffd83dbSDimitry Andric     return UnableToLegalize;
62125ffd83dbSDimitry Andric 
62135ffd83dbSDimitry Andric   // Expand f32 -> i64 conversion
62145ffd83dbSDimitry Andric   // This algorithm comes from compiler-rt's implementation of fixsfdi:
6215fe6060f1SDimitry Andric   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
62165ffd83dbSDimitry Andric 
62175ffd83dbSDimitry Andric   unsigned SrcEltBits = SrcTy.getScalarSizeInBits();
62185ffd83dbSDimitry Andric 
62195ffd83dbSDimitry Andric   auto ExponentMask = MIRBuilder.buildConstant(SrcTy, 0x7F800000);
62205ffd83dbSDimitry Andric   auto ExponentLoBit = MIRBuilder.buildConstant(SrcTy, 23);
62215ffd83dbSDimitry Andric 
62225ffd83dbSDimitry Andric   auto AndExpMask = MIRBuilder.buildAnd(SrcTy, Src, ExponentMask);
62235ffd83dbSDimitry Andric   auto ExponentBits = MIRBuilder.buildLShr(SrcTy, AndExpMask, ExponentLoBit);
62245ffd83dbSDimitry Andric 
62255ffd83dbSDimitry Andric   auto SignMask = MIRBuilder.buildConstant(SrcTy,
62265ffd83dbSDimitry Andric                                            APInt::getSignMask(SrcEltBits));
62275ffd83dbSDimitry Andric   auto AndSignMask = MIRBuilder.buildAnd(SrcTy, Src, SignMask);
62285ffd83dbSDimitry Andric   auto SignLowBit = MIRBuilder.buildConstant(SrcTy, SrcEltBits - 1);
62295ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildAShr(SrcTy, AndSignMask, SignLowBit);
62305ffd83dbSDimitry Andric   Sign = MIRBuilder.buildSExt(DstTy, Sign);
62315ffd83dbSDimitry Andric 
62325ffd83dbSDimitry Andric   auto MantissaMask = MIRBuilder.buildConstant(SrcTy, 0x007FFFFF);
62335ffd83dbSDimitry Andric   auto AndMantissaMask = MIRBuilder.buildAnd(SrcTy, Src, MantissaMask);
62345ffd83dbSDimitry Andric   auto K = MIRBuilder.buildConstant(SrcTy, 0x00800000);
62355ffd83dbSDimitry Andric 
62365ffd83dbSDimitry Andric   auto R = MIRBuilder.buildOr(SrcTy, AndMantissaMask, K);
62375ffd83dbSDimitry Andric   R = MIRBuilder.buildZExt(DstTy, R);
62385ffd83dbSDimitry Andric 
62395ffd83dbSDimitry Andric   auto Bias = MIRBuilder.buildConstant(SrcTy, 127);
62405ffd83dbSDimitry Andric   auto Exponent = MIRBuilder.buildSub(SrcTy, ExponentBits, Bias);
62415ffd83dbSDimitry Andric   auto SubExponent = MIRBuilder.buildSub(SrcTy, Exponent, ExponentLoBit);
62425ffd83dbSDimitry Andric   auto ExponentSub = MIRBuilder.buildSub(SrcTy, ExponentLoBit, Exponent);
62435ffd83dbSDimitry Andric 
62445ffd83dbSDimitry Andric   auto Shl = MIRBuilder.buildShl(DstTy, R, SubExponent);
62455ffd83dbSDimitry Andric   auto Srl = MIRBuilder.buildLShr(DstTy, R, ExponentSub);
62465ffd83dbSDimitry Andric 
62475ffd83dbSDimitry Andric   const LLT S1 = LLT::scalar(1);
62485ffd83dbSDimitry Andric   auto CmpGt = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,
62495ffd83dbSDimitry Andric                                     S1, Exponent, ExponentLoBit);
62505ffd83dbSDimitry Andric 
62515ffd83dbSDimitry Andric   R = MIRBuilder.buildSelect(DstTy, CmpGt, Shl, Srl);
62525ffd83dbSDimitry Andric 
62535ffd83dbSDimitry Andric   auto XorSign = MIRBuilder.buildXor(DstTy, R, Sign);
62545ffd83dbSDimitry Andric   auto Ret = MIRBuilder.buildSub(DstTy, XorSign, Sign);
62555ffd83dbSDimitry Andric 
62565ffd83dbSDimitry Andric   auto ZeroSrcTy = MIRBuilder.buildConstant(SrcTy, 0);
62575ffd83dbSDimitry Andric 
62585ffd83dbSDimitry Andric   auto ExponentLt0 = MIRBuilder.buildICmp(CmpInst::ICMP_SLT,
62595ffd83dbSDimitry Andric                                           S1, Exponent, ZeroSrcTy);
62605ffd83dbSDimitry Andric 
62615ffd83dbSDimitry Andric   auto ZeroDstTy = MIRBuilder.buildConstant(DstTy, 0);
62625ffd83dbSDimitry Andric   MIRBuilder.buildSelect(Dst, ExponentLt0, ZeroDstTy, Ret);
62635ffd83dbSDimitry Andric 
62645ffd83dbSDimitry Andric   MI.eraseFromParent();
62655ffd83dbSDimitry Andric   return Legalized;
62665ffd83dbSDimitry Andric }
62675ffd83dbSDimitry Andric 
62685ffd83dbSDimitry Andric // f64 -> f16 conversion using round-to-nearest-even rounding mode.
62695ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
62705ffd83dbSDimitry Andric LegalizerHelper::lowerFPTRUNC_F64_TO_F16(MachineInstr &MI) {
6271*06c3fb27SDimitry Andric   const LLT S1 = LLT::scalar(1);
6272*06c3fb27SDimitry Andric   const LLT S32 = LLT::scalar(32);
6273*06c3fb27SDimitry Andric 
6274*06c3fb27SDimitry Andric   auto [Dst, Src] = MI.getFirst2Regs();
6275*06c3fb27SDimitry Andric   assert(MRI.getType(Dst).getScalarType() == LLT::scalar(16) &&
6276*06c3fb27SDimitry Andric          MRI.getType(Src).getScalarType() == LLT::scalar(64));
62775ffd83dbSDimitry Andric 
62785ffd83dbSDimitry Andric   if (MRI.getType(Src).isVector()) // TODO: Handle vectors directly.
62795ffd83dbSDimitry Andric     return UnableToLegalize;
62805ffd83dbSDimitry Andric 
6281*06c3fb27SDimitry Andric   if (MIRBuilder.getMF().getTarget().Options.UnsafeFPMath) {
6282*06c3fb27SDimitry Andric     unsigned Flags = MI.getFlags();
6283*06c3fb27SDimitry Andric     auto Src32 = MIRBuilder.buildFPTrunc(S32, Src, Flags);
6284*06c3fb27SDimitry Andric     MIRBuilder.buildFPTrunc(Dst, Src32, Flags);
6285*06c3fb27SDimitry Andric     MI.eraseFromParent();
6286*06c3fb27SDimitry Andric     return Legalized;
6287*06c3fb27SDimitry Andric   }
6288*06c3fb27SDimitry Andric 
62895ffd83dbSDimitry Andric   const unsigned ExpMask = 0x7ff;
62905ffd83dbSDimitry Andric   const unsigned ExpBiasf64 = 1023;
62915ffd83dbSDimitry Andric   const unsigned ExpBiasf16 = 15;
62925ffd83dbSDimitry Andric 
62935ffd83dbSDimitry Andric   auto Unmerge = MIRBuilder.buildUnmerge(S32, Src);
62945ffd83dbSDimitry Andric   Register U = Unmerge.getReg(0);
62955ffd83dbSDimitry Andric   Register UH = Unmerge.getReg(1);
62965ffd83dbSDimitry Andric 
62975ffd83dbSDimitry Andric   auto E = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 20));
62985ffd83dbSDimitry Andric   E = MIRBuilder.buildAnd(S32, E, MIRBuilder.buildConstant(S32, ExpMask));
62995ffd83dbSDimitry Andric 
63005ffd83dbSDimitry Andric   // Subtract the fp64 exponent bias (1023) to get the real exponent and
63015ffd83dbSDimitry Andric   // add the f16 bias (15) to get the biased exponent for the f16 format.
63025ffd83dbSDimitry Andric   E = MIRBuilder.buildAdd(
63035ffd83dbSDimitry Andric     S32, E, MIRBuilder.buildConstant(S32, -ExpBiasf64 + ExpBiasf16));
63045ffd83dbSDimitry Andric 
63055ffd83dbSDimitry Andric   auto M = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 8));
63065ffd83dbSDimitry Andric   M = MIRBuilder.buildAnd(S32, M, MIRBuilder.buildConstant(S32, 0xffe));
63075ffd83dbSDimitry Andric 
63085ffd83dbSDimitry Andric   auto MaskedSig = MIRBuilder.buildAnd(S32, UH,
63095ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1ff));
63105ffd83dbSDimitry Andric   MaskedSig = MIRBuilder.buildOr(S32, MaskedSig, U);
63115ffd83dbSDimitry Andric 
63125ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildConstant(S32, 0);
63135ffd83dbSDimitry Andric   auto SigCmpNE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, MaskedSig, Zero);
63145ffd83dbSDimitry Andric   auto Lo40Set = MIRBuilder.buildZExt(S32, SigCmpNE0);
63155ffd83dbSDimitry Andric   M = MIRBuilder.buildOr(S32, M, Lo40Set);
63165ffd83dbSDimitry Andric 
63175ffd83dbSDimitry Andric   // (M != 0 ? 0x0200 : 0) | 0x7c00;
63185ffd83dbSDimitry Andric   auto Bits0x200 = MIRBuilder.buildConstant(S32, 0x0200);
63195ffd83dbSDimitry Andric   auto CmpM_NE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, M, Zero);
63205ffd83dbSDimitry Andric   auto SelectCC = MIRBuilder.buildSelect(S32, CmpM_NE0, Bits0x200, Zero);
63215ffd83dbSDimitry Andric 
63225ffd83dbSDimitry Andric   auto Bits0x7c00 = MIRBuilder.buildConstant(S32, 0x7c00);
63235ffd83dbSDimitry Andric   auto I = MIRBuilder.buildOr(S32, SelectCC, Bits0x7c00);
63245ffd83dbSDimitry Andric 
63255ffd83dbSDimitry Andric   // N = M | (E << 12);
63265ffd83dbSDimitry Andric   auto EShl12 = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 12));
63275ffd83dbSDimitry Andric   auto N = MIRBuilder.buildOr(S32, M, EShl12);
63285ffd83dbSDimitry Andric 
63295ffd83dbSDimitry Andric   // B = clamp(1-E, 0, 13);
63305ffd83dbSDimitry Andric   auto One = MIRBuilder.buildConstant(S32, 1);
63315ffd83dbSDimitry Andric   auto OneSubExp = MIRBuilder.buildSub(S32, One, E);
63325ffd83dbSDimitry Andric   auto B = MIRBuilder.buildSMax(S32, OneSubExp, Zero);
63335ffd83dbSDimitry Andric   B = MIRBuilder.buildSMin(S32, B, MIRBuilder.buildConstant(S32, 13));
63345ffd83dbSDimitry Andric 
63355ffd83dbSDimitry Andric   auto SigSetHigh = MIRBuilder.buildOr(S32, M,
63365ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 0x1000));
63375ffd83dbSDimitry Andric 
63385ffd83dbSDimitry Andric   auto D = MIRBuilder.buildLShr(S32, SigSetHigh, B);
63395ffd83dbSDimitry Andric   auto D0 = MIRBuilder.buildShl(S32, D, B);
63405ffd83dbSDimitry Andric 
63415ffd83dbSDimitry Andric   auto D0_NE_SigSetHigh = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1,
63425ffd83dbSDimitry Andric                                              D0, SigSetHigh);
63435ffd83dbSDimitry Andric   auto D1 = MIRBuilder.buildZExt(S32, D0_NE_SigSetHigh);
63445ffd83dbSDimitry Andric   D = MIRBuilder.buildOr(S32, D, D1);
63455ffd83dbSDimitry Andric 
63465ffd83dbSDimitry Andric   auto CmpELtOne = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, S1, E, One);
63475ffd83dbSDimitry Andric   auto V = MIRBuilder.buildSelect(S32, CmpELtOne, D, N);
63485ffd83dbSDimitry Andric 
63495ffd83dbSDimitry Andric   auto VLow3 = MIRBuilder.buildAnd(S32, V, MIRBuilder.buildConstant(S32, 7));
63505ffd83dbSDimitry Andric   V = MIRBuilder.buildLShr(S32, V, MIRBuilder.buildConstant(S32, 2));
63515ffd83dbSDimitry Andric 
63525ffd83dbSDimitry Andric   auto VLow3Eq3 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, VLow3,
63535ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 3));
63545ffd83dbSDimitry Andric   auto V0 = MIRBuilder.buildZExt(S32, VLow3Eq3);
63555ffd83dbSDimitry Andric 
63565ffd83dbSDimitry Andric   auto VLow3Gt5 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT, S1, VLow3,
63575ffd83dbSDimitry Andric                                        MIRBuilder.buildConstant(S32, 5));
63585ffd83dbSDimitry Andric   auto V1 = MIRBuilder.buildZExt(S32, VLow3Gt5);
63595ffd83dbSDimitry Andric 
63605ffd83dbSDimitry Andric   V1 = MIRBuilder.buildOr(S32, V0, V1);
63615ffd83dbSDimitry Andric   V = MIRBuilder.buildAdd(S32, V, V1);
63625ffd83dbSDimitry Andric 
63635ffd83dbSDimitry Andric   auto CmpEGt30 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,  S1,
63645ffd83dbSDimitry Andric                                        E, MIRBuilder.buildConstant(S32, 30));
63655ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt30,
63665ffd83dbSDimitry Andric                              MIRBuilder.buildConstant(S32, 0x7c00), V);
63675ffd83dbSDimitry Andric 
63685ffd83dbSDimitry Andric   auto CmpEGt1039 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1,
63695ffd83dbSDimitry Andric                                          E, MIRBuilder.buildConstant(S32, 1039));
63705ffd83dbSDimitry Andric   V = MIRBuilder.buildSelect(S32, CmpEGt1039, I, V);
63715ffd83dbSDimitry Andric 
63725ffd83dbSDimitry Andric   // Extract the sign bit.
63735ffd83dbSDimitry Andric   auto Sign = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 16));
63745ffd83dbSDimitry Andric   Sign = MIRBuilder.buildAnd(S32, Sign, MIRBuilder.buildConstant(S32, 0x8000));
63755ffd83dbSDimitry Andric 
63765ffd83dbSDimitry Andric   // Insert the sign bit
63775ffd83dbSDimitry Andric   V = MIRBuilder.buildOr(S32, Sign, V);
63785ffd83dbSDimitry Andric 
63795ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst, V);
63805ffd83dbSDimitry Andric   MI.eraseFromParent();
63815ffd83dbSDimitry Andric   return Legalized;
63825ffd83dbSDimitry Andric }
63835ffd83dbSDimitry Andric 
63845ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
6385e8d8bef9SDimitry Andric LegalizerHelper::lowerFPTRUNC(MachineInstr &MI) {
6386*06c3fb27SDimitry Andric   auto [DstTy, SrcTy] = MI.getFirst2LLTs();
63875ffd83dbSDimitry Andric   const LLT S64 = LLT::scalar(64);
63885ffd83dbSDimitry Andric   const LLT S16 = LLT::scalar(16);
63895ffd83dbSDimitry Andric 
63905ffd83dbSDimitry Andric   if (DstTy.getScalarType() == S16 && SrcTy.getScalarType() == S64)
63915ffd83dbSDimitry Andric     return lowerFPTRUNC_F64_TO_F16(MI);
63925ffd83dbSDimitry Andric 
63935ffd83dbSDimitry Andric   return UnableToLegalize;
63945ffd83dbSDimitry Andric }
63955ffd83dbSDimitry Andric 
6396e8d8bef9SDimitry Andric // TODO: If RHS is a constant SelectionDAGBuilder expands this into a
6397e8d8bef9SDimitry Andric // multiplication tree.
6398e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPOWI(MachineInstr &MI) {
6399*06c3fb27SDimitry Andric   auto [Dst, Src0, Src1] = MI.getFirst3Regs();
6400e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
6401e8d8bef9SDimitry Andric 
6402e8d8bef9SDimitry Andric   auto CvtSrc1 = MIRBuilder.buildSITOFP(Ty, Src1);
6403e8d8bef9SDimitry Andric   MIRBuilder.buildFPow(Dst, Src0, CvtSrc1, MI.getFlags());
6404e8d8bef9SDimitry Andric   MI.eraseFromParent();
6405e8d8bef9SDimitry Andric   return Legalized;
6406e8d8bef9SDimitry Andric }
6407e8d8bef9SDimitry Andric 
64080b57cec5SDimitry Andric static CmpInst::Predicate minMaxToCompare(unsigned Opc) {
64090b57cec5SDimitry Andric   switch (Opc) {
64100b57cec5SDimitry Andric   case TargetOpcode::G_SMIN:
64110b57cec5SDimitry Andric     return CmpInst::ICMP_SLT;
64120b57cec5SDimitry Andric   case TargetOpcode::G_SMAX:
64130b57cec5SDimitry Andric     return CmpInst::ICMP_SGT;
64140b57cec5SDimitry Andric   case TargetOpcode::G_UMIN:
64150b57cec5SDimitry Andric     return CmpInst::ICMP_ULT;
64160b57cec5SDimitry Andric   case TargetOpcode::G_UMAX:
64170b57cec5SDimitry Andric     return CmpInst::ICMP_UGT;
64180b57cec5SDimitry Andric   default:
64190b57cec5SDimitry Andric     llvm_unreachable("not in integer min/max");
64200b57cec5SDimitry Andric   }
64210b57cec5SDimitry Andric }
64220b57cec5SDimitry Andric 
6423e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerMinMax(MachineInstr &MI) {
6424*06c3fb27SDimitry Andric   auto [Dst, Src0, Src1] = MI.getFirst3Regs();
64250b57cec5SDimitry Andric 
64260b57cec5SDimitry Andric   const CmpInst::Predicate Pred = minMaxToCompare(MI.getOpcode());
64270b57cec5SDimitry Andric   LLT CmpType = MRI.getType(Dst).changeElementSize(1);
64280b57cec5SDimitry Andric 
64290b57cec5SDimitry Andric   auto Cmp = MIRBuilder.buildICmp(Pred, CmpType, Src0, Src1);
64300b57cec5SDimitry Andric   MIRBuilder.buildSelect(Dst, Cmp, Src0, Src1);
64310b57cec5SDimitry Andric 
64320b57cec5SDimitry Andric   MI.eraseFromParent();
64330b57cec5SDimitry Andric   return Legalized;
64340b57cec5SDimitry Andric }
64350b57cec5SDimitry Andric 
64360b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
6437e8d8bef9SDimitry Andric LegalizerHelper::lowerFCopySign(MachineInstr &MI) {
6438*06c3fb27SDimitry Andric   auto [Dst, DstTy, Src0, Src0Ty, Src1, Src1Ty] = MI.getFirst3RegLLTs();
64390b57cec5SDimitry Andric   const int Src0Size = Src0Ty.getScalarSizeInBits();
64400b57cec5SDimitry Andric   const int Src1Size = Src1Ty.getScalarSizeInBits();
64410b57cec5SDimitry Andric 
64420b57cec5SDimitry Andric   auto SignBitMask = MIRBuilder.buildConstant(
64430b57cec5SDimitry Andric     Src0Ty, APInt::getSignMask(Src0Size));
64440b57cec5SDimitry Andric 
64450b57cec5SDimitry Andric   auto NotSignBitMask = MIRBuilder.buildConstant(
64460b57cec5SDimitry Andric     Src0Ty, APInt::getLowBitsSet(Src0Size, Src0Size - 1));
64470b57cec5SDimitry Andric 
6448fe6060f1SDimitry Andric   Register And0 = MIRBuilder.buildAnd(Src0Ty, Src0, NotSignBitMask).getReg(0);
6449fe6060f1SDimitry Andric   Register And1;
64500b57cec5SDimitry Andric   if (Src0Ty == Src1Ty) {
6451fe6060f1SDimitry Andric     And1 = MIRBuilder.buildAnd(Src1Ty, Src1, SignBitMask).getReg(0);
64520b57cec5SDimitry Andric   } else if (Src0Size > Src1Size) {
64530b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src0Ty, Src0Size - Src1Size);
64540b57cec5SDimitry Andric     auto Zext = MIRBuilder.buildZExt(Src0Ty, Src1);
64550b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildShl(Src0Ty, Zext, ShiftAmt);
6456fe6060f1SDimitry Andric     And1 = MIRBuilder.buildAnd(Src0Ty, Shift, SignBitMask).getReg(0);
64570b57cec5SDimitry Andric   } else {
64580b57cec5SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Src1Ty, Src1Size - Src0Size);
64590b57cec5SDimitry Andric     auto Shift = MIRBuilder.buildLShr(Src1Ty, Src1, ShiftAmt);
64600b57cec5SDimitry Andric     auto Trunc = MIRBuilder.buildTrunc(Src0Ty, Shift);
6461fe6060f1SDimitry Andric     And1 = MIRBuilder.buildAnd(Src0Ty, Trunc, SignBitMask).getReg(0);
64620b57cec5SDimitry Andric   }
64630b57cec5SDimitry Andric 
64640b57cec5SDimitry Andric   // Be careful about setting nsz/nnan/ninf on every instruction, since the
64650b57cec5SDimitry Andric   // constants are a nan and -0.0, but the final result should preserve
64660b57cec5SDimitry Andric   // everything.
6467fe6060f1SDimitry Andric   unsigned Flags = MI.getFlags();
6468fe6060f1SDimitry Andric   MIRBuilder.buildOr(Dst, And0, And1, Flags);
64690b57cec5SDimitry Andric 
64700b57cec5SDimitry Andric   MI.eraseFromParent();
64710b57cec5SDimitry Andric   return Legalized;
64720b57cec5SDimitry Andric }
64730b57cec5SDimitry Andric 
64740b57cec5SDimitry Andric LegalizerHelper::LegalizeResult
64750b57cec5SDimitry Andric LegalizerHelper::lowerFMinNumMaxNum(MachineInstr &MI) {
64760b57cec5SDimitry Andric   unsigned NewOp = MI.getOpcode() == TargetOpcode::G_FMINNUM ?
64770b57cec5SDimitry Andric     TargetOpcode::G_FMINNUM_IEEE : TargetOpcode::G_FMAXNUM_IEEE;
64780b57cec5SDimitry Andric 
6479*06c3fb27SDimitry Andric   auto [Dst, Src0, Src1] = MI.getFirst3Regs();
64800b57cec5SDimitry Andric   LLT Ty = MRI.getType(Dst);
64810b57cec5SDimitry Andric 
64820b57cec5SDimitry Andric   if (!MI.getFlag(MachineInstr::FmNoNans)) {
64830b57cec5SDimitry Andric     // Insert canonicalizes if it's possible we need to quiet to get correct
64840b57cec5SDimitry Andric     // sNaN behavior.
64850b57cec5SDimitry Andric 
64860b57cec5SDimitry Andric     // Note this must be done here, and not as an optimization combine in the
64870b57cec5SDimitry Andric     // absence of a dedicate quiet-snan instruction as we're using an
64880b57cec5SDimitry Andric     // omni-purpose G_FCANONICALIZE.
64890b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src0, MRI))
64900b57cec5SDimitry Andric       Src0 = MIRBuilder.buildFCanonicalize(Ty, Src0, MI.getFlags()).getReg(0);
64910b57cec5SDimitry Andric 
64920b57cec5SDimitry Andric     if (!isKnownNeverSNaN(Src1, MRI))
64930b57cec5SDimitry Andric       Src1 = MIRBuilder.buildFCanonicalize(Ty, Src1, MI.getFlags()).getReg(0);
64940b57cec5SDimitry Andric   }
64950b57cec5SDimitry Andric 
64960b57cec5SDimitry Andric   // If there are no nans, it's safe to simply replace this with the non-IEEE
64970b57cec5SDimitry Andric   // version.
64980b57cec5SDimitry Andric   MIRBuilder.buildInstr(NewOp, {Dst}, {Src0, Src1}, MI.getFlags());
64990b57cec5SDimitry Andric   MI.eraseFromParent();
65000b57cec5SDimitry Andric   return Legalized;
65010b57cec5SDimitry Andric }
65028bcb0991SDimitry Andric 
65038bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFMad(MachineInstr &MI) {
65048bcb0991SDimitry Andric   // Expand G_FMAD a, b, c -> G_FADD (G_FMUL a, b), c
65058bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
65068bcb0991SDimitry Andric   LLT Ty = MRI.getType(DstReg);
65078bcb0991SDimitry Andric   unsigned Flags = MI.getFlags();
65088bcb0991SDimitry Andric 
65098bcb0991SDimitry Andric   auto Mul = MIRBuilder.buildFMul(Ty, MI.getOperand(1), MI.getOperand(2),
65108bcb0991SDimitry Andric                                   Flags);
65118bcb0991SDimitry Andric   MIRBuilder.buildFAdd(DstReg, Mul, MI.getOperand(3), Flags);
65128bcb0991SDimitry Andric   MI.eraseFromParent();
65138bcb0991SDimitry Andric   return Legalized;
65148bcb0991SDimitry Andric }
65158bcb0991SDimitry Andric 
65168bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
6517480093f4SDimitry Andric LegalizerHelper::lowerIntrinsicRound(MachineInstr &MI) {
6518*06c3fb27SDimitry Andric   auto [DstReg, X] = MI.getFirst2Regs();
65195ffd83dbSDimitry Andric   const unsigned Flags = MI.getFlags();
65205ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(DstReg);
65215ffd83dbSDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
65225ffd83dbSDimitry Andric 
65235ffd83dbSDimitry Andric   // round(x) =>
65245ffd83dbSDimitry Andric   //  t = trunc(x);
65255ffd83dbSDimitry Andric   //  d = fabs(x - t);
65265ffd83dbSDimitry Andric   //  o = copysign(1.0f, x);
65275ffd83dbSDimitry Andric   //  return t + (d >= 0.5 ? o : 0.0);
65285ffd83dbSDimitry Andric 
65295ffd83dbSDimitry Andric   auto T = MIRBuilder.buildIntrinsicTrunc(Ty, X, Flags);
65305ffd83dbSDimitry Andric 
65315ffd83dbSDimitry Andric   auto Diff = MIRBuilder.buildFSub(Ty, X, T, Flags);
65325ffd83dbSDimitry Andric   auto AbsDiff = MIRBuilder.buildFAbs(Ty, Diff, Flags);
65335ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
65345ffd83dbSDimitry Andric   auto One = MIRBuilder.buildFConstant(Ty, 1.0);
65355ffd83dbSDimitry Andric   auto Half = MIRBuilder.buildFConstant(Ty, 0.5);
65365ffd83dbSDimitry Andric   auto SignOne = MIRBuilder.buildFCopysign(Ty, One, X);
65375ffd83dbSDimitry Andric 
65385ffd83dbSDimitry Andric   auto Cmp = MIRBuilder.buildFCmp(CmpInst::FCMP_OGE, CondTy, AbsDiff, Half,
65395ffd83dbSDimitry Andric                                   Flags);
65405ffd83dbSDimitry Andric   auto Sel = MIRBuilder.buildSelect(Ty, Cmp, SignOne, Zero, Flags);
65415ffd83dbSDimitry Andric 
65425ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, T, Sel, Flags);
65435ffd83dbSDimitry Andric 
65445ffd83dbSDimitry Andric   MI.eraseFromParent();
65455ffd83dbSDimitry Andric   return Legalized;
65465ffd83dbSDimitry Andric }
65475ffd83dbSDimitry Andric 
6548*06c3fb27SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerFFloor(MachineInstr &MI) {
6549*06c3fb27SDimitry Andric   auto [DstReg, SrcReg] = MI.getFirst2Regs();
6550480093f4SDimitry Andric   unsigned Flags = MI.getFlags();
6551480093f4SDimitry Andric   LLT Ty = MRI.getType(DstReg);
6552480093f4SDimitry Andric   const LLT CondTy = Ty.changeElementSize(1);
6553480093f4SDimitry Andric 
6554480093f4SDimitry Andric   // result = trunc(src);
6555480093f4SDimitry Andric   // if (src < 0.0 && src != result)
6556480093f4SDimitry Andric   //   result += -1.0.
6557480093f4SDimitry Andric 
6558480093f4SDimitry Andric   auto Trunc = MIRBuilder.buildIntrinsicTrunc(Ty, SrcReg, Flags);
65595ffd83dbSDimitry Andric   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
6560480093f4SDimitry Andric 
6561480093f4SDimitry Andric   auto Lt0 = MIRBuilder.buildFCmp(CmpInst::FCMP_OLT, CondTy,
6562480093f4SDimitry Andric                                   SrcReg, Zero, Flags);
6563480093f4SDimitry Andric   auto NeTrunc = MIRBuilder.buildFCmp(CmpInst::FCMP_ONE, CondTy,
6564480093f4SDimitry Andric                                       SrcReg, Trunc, Flags);
6565480093f4SDimitry Andric   auto And = MIRBuilder.buildAnd(CondTy, Lt0, NeTrunc);
6566480093f4SDimitry Andric   auto AddVal = MIRBuilder.buildSITOFP(Ty, And);
6567480093f4SDimitry Andric 
65685ffd83dbSDimitry Andric   MIRBuilder.buildFAdd(DstReg, Trunc, AddVal, Flags);
65695ffd83dbSDimitry Andric   MI.eraseFromParent();
65705ffd83dbSDimitry Andric   return Legalized;
65715ffd83dbSDimitry Andric }
65725ffd83dbSDimitry Andric 
65735ffd83dbSDimitry Andric LegalizerHelper::LegalizeResult
65745ffd83dbSDimitry Andric LegalizerHelper::lowerMergeValues(MachineInstr &MI) {
65755ffd83dbSDimitry Andric   const unsigned NumOps = MI.getNumOperands();
6576*06c3fb27SDimitry Andric   auto [DstReg, DstTy, Src0Reg, Src0Ty] = MI.getFirst2RegLLTs();
6577*06c3fb27SDimitry Andric   unsigned PartSize = Src0Ty.getSizeInBits();
65785ffd83dbSDimitry Andric 
65795ffd83dbSDimitry Andric   LLT WideTy = LLT::scalar(DstTy.getSizeInBits());
65805ffd83dbSDimitry Andric   Register ResultReg = MIRBuilder.buildZExt(WideTy, Src0Reg).getReg(0);
65815ffd83dbSDimitry Andric 
65825ffd83dbSDimitry Andric   for (unsigned I = 2; I != NumOps; ++I) {
65835ffd83dbSDimitry Andric     const unsigned Offset = (I - 1) * PartSize;
65845ffd83dbSDimitry Andric 
65855ffd83dbSDimitry Andric     Register SrcReg = MI.getOperand(I).getReg();
65865ffd83dbSDimitry Andric     auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
65875ffd83dbSDimitry Andric 
65885ffd83dbSDimitry Andric     Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
65895ffd83dbSDimitry Andric       MRI.createGenericVirtualRegister(WideTy);
65905ffd83dbSDimitry Andric 
65915ffd83dbSDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
65925ffd83dbSDimitry Andric     auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
65935ffd83dbSDimitry Andric     MIRBuilder.buildOr(NextResult, ResultReg, Shl);
65945ffd83dbSDimitry Andric     ResultReg = NextResult;
65955ffd83dbSDimitry Andric   }
65965ffd83dbSDimitry Andric 
65975ffd83dbSDimitry Andric   if (DstTy.isPointer()) {
65985ffd83dbSDimitry Andric     if (MIRBuilder.getDataLayout().isNonIntegralAddressSpace(
65995ffd83dbSDimitry Andric           DstTy.getAddressSpace())) {
66005ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Not casting nonintegral address space\n");
66015ffd83dbSDimitry Andric       return UnableToLegalize;
66025ffd83dbSDimitry Andric     }
66035ffd83dbSDimitry Andric 
66045ffd83dbSDimitry Andric     MIRBuilder.buildIntToPtr(DstReg, ResultReg);
66055ffd83dbSDimitry Andric   }
66065ffd83dbSDimitry Andric 
6607480093f4SDimitry Andric   MI.eraseFromParent();
6608480093f4SDimitry Andric   return Legalized;
6609480093f4SDimitry Andric }
6610480093f4SDimitry Andric 
6611480093f4SDimitry Andric LegalizerHelper::LegalizeResult
66128bcb0991SDimitry Andric LegalizerHelper::lowerUnmergeValues(MachineInstr &MI) {
66138bcb0991SDimitry Andric   const unsigned NumDst = MI.getNumOperands() - 1;
66145ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(NumDst).getReg();
66158bcb0991SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
66168bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Dst0Reg);
66175ffd83dbSDimitry Andric   if (DstTy.isPointer())
66185ffd83dbSDimitry Andric     return UnableToLegalize; // TODO
66198bcb0991SDimitry Andric 
66205ffd83dbSDimitry Andric   SrcReg = coerceToScalar(SrcReg);
66215ffd83dbSDimitry Andric   if (!SrcReg)
66225ffd83dbSDimitry Andric     return UnableToLegalize;
66238bcb0991SDimitry Andric 
66248bcb0991SDimitry Andric   // Expand scalarizing unmerge as bitcast to integer and shift.
66255ffd83dbSDimitry Andric   LLT IntTy = MRI.getType(SrcReg);
66268bcb0991SDimitry Andric 
66275ffd83dbSDimitry Andric   MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
66288bcb0991SDimitry Andric 
66298bcb0991SDimitry Andric   const unsigned DstSize = DstTy.getSizeInBits();
66308bcb0991SDimitry Andric   unsigned Offset = DstSize;
66318bcb0991SDimitry Andric   for (unsigned I = 1; I != NumDst; ++I, Offset += DstSize) {
66328bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntTy, Offset);
66335ffd83dbSDimitry Andric     auto Shift = MIRBuilder.buildLShr(IntTy, SrcReg, ShiftAmt);
66348bcb0991SDimitry Andric     MIRBuilder.buildTrunc(MI.getOperand(I), Shift);
66358bcb0991SDimitry Andric   }
66368bcb0991SDimitry Andric 
66378bcb0991SDimitry Andric   MI.eraseFromParent();
66388bcb0991SDimitry Andric   return Legalized;
66398bcb0991SDimitry Andric }
66408bcb0991SDimitry Andric 
6641e8d8bef9SDimitry Andric /// Lower a vector extract or insert by writing the vector to a stack temporary
6642e8d8bef9SDimitry Andric /// and reloading the element or vector.
6643e8d8bef9SDimitry Andric ///
6644e8d8bef9SDimitry Andric /// %dst = G_EXTRACT_VECTOR_ELT %vec, %idx
6645e8d8bef9SDimitry Andric ///  =>
6646e8d8bef9SDimitry Andric ///  %stack_temp = G_FRAME_INDEX
6647e8d8bef9SDimitry Andric ///  G_STORE %vec, %stack_temp
6648e8d8bef9SDimitry Andric ///  %idx = clamp(%idx, %vec.getNumElements())
6649e8d8bef9SDimitry Andric ///  %element_ptr = G_PTR_ADD %stack_temp, %idx
6650e8d8bef9SDimitry Andric ///  %dst = G_LOAD %element_ptr
6651e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
6652e8d8bef9SDimitry Andric LegalizerHelper::lowerExtractInsertVectorElt(MachineInstr &MI) {
6653e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
6654e8d8bef9SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
6655e8d8bef9SDimitry Andric   Register InsertVal;
6656e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
6657e8d8bef9SDimitry Andric     InsertVal = MI.getOperand(2).getReg();
6658e8d8bef9SDimitry Andric 
6659e8d8bef9SDimitry Andric   Register Idx = MI.getOperand(MI.getNumOperands() - 1).getReg();
6660e8d8bef9SDimitry Andric 
6661e8d8bef9SDimitry Andric   LLT VecTy = MRI.getType(SrcVec);
6662e8d8bef9SDimitry Andric   LLT EltTy = VecTy.getElementType();
66630eae32dcSDimitry Andric   unsigned NumElts = VecTy.getNumElements();
66640eae32dcSDimitry Andric 
66650eae32dcSDimitry Andric   int64_t IdxVal;
66660eae32dcSDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal)) && IdxVal <= NumElts) {
66670eae32dcSDimitry Andric     SmallVector<Register, 8> SrcRegs;
66680eae32dcSDimitry Andric     extractParts(SrcVec, EltTy, NumElts, SrcRegs);
66690eae32dcSDimitry Andric 
66700eae32dcSDimitry Andric     if (InsertVal) {
66710eae32dcSDimitry Andric       SrcRegs[IdxVal] = MI.getOperand(2).getReg();
6672bdd1243dSDimitry Andric       MIRBuilder.buildMergeLikeInstr(DstReg, SrcRegs);
66730eae32dcSDimitry Andric     } else {
66740eae32dcSDimitry Andric       MIRBuilder.buildCopy(DstReg, SrcRegs[IdxVal]);
66750eae32dcSDimitry Andric     }
66760eae32dcSDimitry Andric 
66770eae32dcSDimitry Andric     MI.eraseFromParent();
66780eae32dcSDimitry Andric     return Legalized;
66790eae32dcSDimitry Andric   }
66800eae32dcSDimitry Andric 
6681e8d8bef9SDimitry Andric   if (!EltTy.isByteSized()) { // Not implemented.
6682e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-byte element vectors yet\n");
6683e8d8bef9SDimitry Andric     return UnableToLegalize;
6684e8d8bef9SDimitry Andric   }
6685e8d8bef9SDimitry Andric 
6686e8d8bef9SDimitry Andric   unsigned EltBytes = EltTy.getSizeInBytes();
6687e8d8bef9SDimitry Andric   Align VecAlign = getStackTemporaryAlignment(VecTy);
6688e8d8bef9SDimitry Andric   Align EltAlign;
6689e8d8bef9SDimitry Andric 
6690e8d8bef9SDimitry Andric   MachinePointerInfo PtrInfo;
6691e8d8bef9SDimitry Andric   auto StackTemp = createStackTemporary(TypeSize::Fixed(VecTy.getSizeInBytes()),
6692e8d8bef9SDimitry Andric                                         VecAlign, PtrInfo);
6693e8d8bef9SDimitry Andric   MIRBuilder.buildStore(SrcVec, StackTemp, PtrInfo, VecAlign);
6694e8d8bef9SDimitry Andric 
6695e8d8bef9SDimitry Andric   // Get the pointer to the element, and be sure not to hit undefined behavior
6696e8d8bef9SDimitry Andric   // if the index is out of bounds.
6697e8d8bef9SDimitry Andric   Register EltPtr = getVectorElementPointer(StackTemp.getReg(0), VecTy, Idx);
6698e8d8bef9SDimitry Andric 
6699e8d8bef9SDimitry Andric   if (mi_match(Idx, MRI, m_ICst(IdxVal))) {
6700e8d8bef9SDimitry Andric     int64_t Offset = IdxVal * EltBytes;
6701e8d8bef9SDimitry Andric     PtrInfo = PtrInfo.getWithOffset(Offset);
6702e8d8bef9SDimitry Andric     EltAlign = commonAlignment(VecAlign, Offset);
6703e8d8bef9SDimitry Andric   } else {
6704e8d8bef9SDimitry Andric     // We lose information with a variable offset.
6705e8d8bef9SDimitry Andric     EltAlign = getStackTemporaryAlignment(EltTy);
6706e8d8bef9SDimitry Andric     PtrInfo = MachinePointerInfo(MRI.getType(EltPtr).getAddressSpace());
6707e8d8bef9SDimitry Andric   }
6708e8d8bef9SDimitry Andric 
6709e8d8bef9SDimitry Andric   if (InsertVal) {
6710e8d8bef9SDimitry Andric     // Write the inserted element
6711e8d8bef9SDimitry Andric     MIRBuilder.buildStore(InsertVal, EltPtr, PtrInfo, EltAlign);
6712e8d8bef9SDimitry Andric 
6713e8d8bef9SDimitry Andric     // Reload the whole vector.
6714e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, StackTemp, PtrInfo, VecAlign);
6715e8d8bef9SDimitry Andric   } else {
6716e8d8bef9SDimitry Andric     MIRBuilder.buildLoad(DstReg, EltPtr, PtrInfo, EltAlign);
6717e8d8bef9SDimitry Andric   }
6718e8d8bef9SDimitry Andric 
6719e8d8bef9SDimitry Andric   MI.eraseFromParent();
6720e8d8bef9SDimitry Andric   return Legalized;
6721e8d8bef9SDimitry Andric }
6722e8d8bef9SDimitry Andric 
67238bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
67248bcb0991SDimitry Andric LegalizerHelper::lowerShuffleVector(MachineInstr &MI) {
6725*06c3fb27SDimitry Andric   auto [DstReg, DstTy, Src0Reg, Src0Ty, Src1Reg, Src1Ty] =
6726*06c3fb27SDimitry Andric       MI.getFirst3RegLLTs();
67278bcb0991SDimitry Andric   LLT IdxTy = LLT::scalar(32);
67288bcb0991SDimitry Andric 
6729480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
67308bcb0991SDimitry Andric 
67318bcb0991SDimitry Andric   if (DstTy.isScalar()) {
67328bcb0991SDimitry Andric     if (Src0Ty.isVector())
67338bcb0991SDimitry Andric       return UnableToLegalize;
67348bcb0991SDimitry Andric 
67358bcb0991SDimitry Andric     // This is just a SELECT.
67368bcb0991SDimitry Andric     assert(Mask.size() == 1 && "Expected a single mask element");
67378bcb0991SDimitry Andric     Register Val;
67388bcb0991SDimitry Andric     if (Mask[0] < 0 || Mask[0] > 1)
67398bcb0991SDimitry Andric       Val = MIRBuilder.buildUndef(DstTy).getReg(0);
67408bcb0991SDimitry Andric     else
67418bcb0991SDimitry Andric       Val = Mask[0] == 0 ? Src0Reg : Src1Reg;
67428bcb0991SDimitry Andric     MIRBuilder.buildCopy(DstReg, Val);
67438bcb0991SDimitry Andric     MI.eraseFromParent();
67448bcb0991SDimitry Andric     return Legalized;
67458bcb0991SDimitry Andric   }
67468bcb0991SDimitry Andric 
67478bcb0991SDimitry Andric   Register Undef;
67488bcb0991SDimitry Andric   SmallVector<Register, 32> BuildVec;
67498bcb0991SDimitry Andric   LLT EltTy = DstTy.getElementType();
67508bcb0991SDimitry Andric 
67518bcb0991SDimitry Andric   for (int Idx : Mask) {
67528bcb0991SDimitry Andric     if (Idx < 0) {
67538bcb0991SDimitry Andric       if (!Undef.isValid())
67548bcb0991SDimitry Andric         Undef = MIRBuilder.buildUndef(EltTy).getReg(0);
67558bcb0991SDimitry Andric       BuildVec.push_back(Undef);
67568bcb0991SDimitry Andric       continue;
67578bcb0991SDimitry Andric     }
67588bcb0991SDimitry Andric 
67598bcb0991SDimitry Andric     if (Src0Ty.isScalar()) {
67608bcb0991SDimitry Andric       BuildVec.push_back(Idx == 0 ? Src0Reg : Src1Reg);
67618bcb0991SDimitry Andric     } else {
67628bcb0991SDimitry Andric       int NumElts = Src0Ty.getNumElements();
67638bcb0991SDimitry Andric       Register SrcVec = Idx < NumElts ? Src0Reg : Src1Reg;
67648bcb0991SDimitry Andric       int ExtractIdx = Idx < NumElts ? Idx : Idx - NumElts;
67658bcb0991SDimitry Andric       auto IdxK = MIRBuilder.buildConstant(IdxTy, ExtractIdx);
67668bcb0991SDimitry Andric       auto Extract = MIRBuilder.buildExtractVectorElement(EltTy, SrcVec, IdxK);
67678bcb0991SDimitry Andric       BuildVec.push_back(Extract.getReg(0));
67688bcb0991SDimitry Andric     }
67698bcb0991SDimitry Andric   }
67708bcb0991SDimitry Andric 
67718bcb0991SDimitry Andric   MIRBuilder.buildBuildVector(DstReg, BuildVec);
67728bcb0991SDimitry Andric   MI.eraseFromParent();
67738bcb0991SDimitry Andric   return Legalized;
67748bcb0991SDimitry Andric }
67758bcb0991SDimitry Andric 
67768bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
67778bcb0991SDimitry Andric LegalizerHelper::lowerDynStackAlloc(MachineInstr &MI) {
67785ffd83dbSDimitry Andric   const auto &MF = *MI.getMF();
67795ffd83dbSDimitry Andric   const auto &TFI = *MF.getSubtarget().getFrameLowering();
67805ffd83dbSDimitry Andric   if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
67815ffd83dbSDimitry Andric     return UnableToLegalize;
67825ffd83dbSDimitry Andric 
67838bcb0991SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
67848bcb0991SDimitry Andric   Register AllocSize = MI.getOperand(1).getReg();
67855ffd83dbSDimitry Andric   Align Alignment = assumeAligned(MI.getOperand(2).getImm());
67868bcb0991SDimitry Andric 
67878bcb0991SDimitry Andric   LLT PtrTy = MRI.getType(Dst);
67888bcb0991SDimitry Andric   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
67898bcb0991SDimitry Andric 
67908bcb0991SDimitry Andric   Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
67918bcb0991SDimitry Andric   auto SPTmp = MIRBuilder.buildCopy(PtrTy, SPReg);
67928bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(IntPtrTy, SPTmp);
67938bcb0991SDimitry Andric 
67948bcb0991SDimitry Andric   // Subtract the final alloc from the SP. We use G_PTRTOINT here so we don't
67958bcb0991SDimitry Andric   // have to generate an extra instruction to negate the alloc and then use
6796480093f4SDimitry Andric   // G_PTR_ADD to add the negative offset.
67978bcb0991SDimitry Andric   auto Alloc = MIRBuilder.buildSub(IntPtrTy, SPTmp, AllocSize);
67985ffd83dbSDimitry Andric   if (Alignment > Align(1)) {
67995ffd83dbSDimitry Andric     APInt AlignMask(IntPtrTy.getSizeInBits(), Alignment.value(), true);
68008bcb0991SDimitry Andric     AlignMask.negate();
68018bcb0991SDimitry Andric     auto AlignCst = MIRBuilder.buildConstant(IntPtrTy, AlignMask);
68028bcb0991SDimitry Andric     Alloc = MIRBuilder.buildAnd(IntPtrTy, Alloc, AlignCst);
68038bcb0991SDimitry Andric   }
68048bcb0991SDimitry Andric 
68058bcb0991SDimitry Andric   SPTmp = MIRBuilder.buildCast(PtrTy, Alloc);
68068bcb0991SDimitry Andric   MIRBuilder.buildCopy(SPReg, SPTmp);
68078bcb0991SDimitry Andric   MIRBuilder.buildCopy(Dst, SPTmp);
68088bcb0991SDimitry Andric 
68098bcb0991SDimitry Andric   MI.eraseFromParent();
68108bcb0991SDimitry Andric   return Legalized;
68118bcb0991SDimitry Andric }
68128bcb0991SDimitry Andric 
68138bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
68148bcb0991SDimitry Andric LegalizerHelper::lowerExtract(MachineInstr &MI) {
6815*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
68168bcb0991SDimitry Andric   unsigned Offset = MI.getOperand(2).getImm();
68178bcb0991SDimitry Andric 
68180eae32dcSDimitry Andric   // Extract sub-vector or one element
68190eae32dcSDimitry Andric   if (SrcTy.isVector()) {
68200eae32dcSDimitry Andric     unsigned SrcEltSize = SrcTy.getElementType().getSizeInBits();
68210eae32dcSDimitry Andric     unsigned DstSize = DstTy.getSizeInBits();
68220eae32dcSDimitry Andric 
68230eae32dcSDimitry Andric     if ((Offset % SrcEltSize == 0) && (DstSize % SrcEltSize == 0) &&
68240eae32dcSDimitry Andric         (Offset + DstSize <= SrcTy.getSizeInBits())) {
68250eae32dcSDimitry Andric       // Unmerge and allow access to each Src element for the artifact combiner.
6826*06c3fb27SDimitry Andric       auto Unmerge = MIRBuilder.buildUnmerge(SrcTy.getElementType(), SrcReg);
68270eae32dcSDimitry Andric 
68280eae32dcSDimitry Andric       // Take element(s) we need to extract and copy it (merge them).
68290eae32dcSDimitry Andric       SmallVector<Register, 8> SubVectorElts;
68300eae32dcSDimitry Andric       for (unsigned Idx = Offset / SrcEltSize;
68310eae32dcSDimitry Andric            Idx < (Offset + DstSize) / SrcEltSize; ++Idx) {
68320eae32dcSDimitry Andric         SubVectorElts.push_back(Unmerge.getReg(Idx));
68330eae32dcSDimitry Andric       }
68340eae32dcSDimitry Andric       if (SubVectorElts.size() == 1)
6835*06c3fb27SDimitry Andric         MIRBuilder.buildCopy(DstReg, SubVectorElts[0]);
68360eae32dcSDimitry Andric       else
6837*06c3fb27SDimitry Andric         MIRBuilder.buildMergeLikeInstr(DstReg, SubVectorElts);
68380eae32dcSDimitry Andric 
68390eae32dcSDimitry Andric       MI.eraseFromParent();
68400eae32dcSDimitry Andric       return Legalized;
68410eae32dcSDimitry Andric     }
68420eae32dcSDimitry Andric   }
68430eae32dcSDimitry Andric 
68448bcb0991SDimitry Andric   if (DstTy.isScalar() &&
68458bcb0991SDimitry Andric       (SrcTy.isScalar() ||
68468bcb0991SDimitry Andric        (SrcTy.isVector() && DstTy == SrcTy.getElementType()))) {
68478bcb0991SDimitry Andric     LLT SrcIntTy = SrcTy;
68488bcb0991SDimitry Andric     if (!SrcTy.isScalar()) {
68498bcb0991SDimitry Andric       SrcIntTy = LLT::scalar(SrcTy.getSizeInBits());
6850*06c3fb27SDimitry Andric       SrcReg = MIRBuilder.buildBitcast(SrcIntTy, SrcReg).getReg(0);
68518bcb0991SDimitry Andric     }
68528bcb0991SDimitry Andric 
68538bcb0991SDimitry Andric     if (Offset == 0)
6854*06c3fb27SDimitry Andric       MIRBuilder.buildTrunc(DstReg, SrcReg);
68558bcb0991SDimitry Andric     else {
68568bcb0991SDimitry Andric       auto ShiftAmt = MIRBuilder.buildConstant(SrcIntTy, Offset);
6857*06c3fb27SDimitry Andric       auto Shr = MIRBuilder.buildLShr(SrcIntTy, SrcReg, ShiftAmt);
6858*06c3fb27SDimitry Andric       MIRBuilder.buildTrunc(DstReg, Shr);
68598bcb0991SDimitry Andric     }
68608bcb0991SDimitry Andric 
68618bcb0991SDimitry Andric     MI.eraseFromParent();
68628bcb0991SDimitry Andric     return Legalized;
68638bcb0991SDimitry Andric   }
68648bcb0991SDimitry Andric 
68658bcb0991SDimitry Andric   return UnableToLegalize;
68668bcb0991SDimitry Andric }
68678bcb0991SDimitry Andric 
68688bcb0991SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerInsert(MachineInstr &MI) {
6869*06c3fb27SDimitry Andric   auto [Dst, Src, InsertSrc] = MI.getFirst3Regs();
68708bcb0991SDimitry Andric   uint64_t Offset = MI.getOperand(3).getImm();
68718bcb0991SDimitry Andric 
68728bcb0991SDimitry Andric   LLT DstTy = MRI.getType(Src);
68738bcb0991SDimitry Andric   LLT InsertTy = MRI.getType(InsertSrc);
68748bcb0991SDimitry Andric 
68750eae32dcSDimitry Andric   // Insert sub-vector or one element
68760eae32dcSDimitry Andric   if (DstTy.isVector() && !InsertTy.isPointer()) {
68770eae32dcSDimitry Andric     LLT EltTy = DstTy.getElementType();
68780eae32dcSDimitry Andric     unsigned EltSize = EltTy.getSizeInBits();
68790eae32dcSDimitry Andric     unsigned InsertSize = InsertTy.getSizeInBits();
68800eae32dcSDimitry Andric 
68810eae32dcSDimitry Andric     if ((Offset % EltSize == 0) && (InsertSize % EltSize == 0) &&
68820eae32dcSDimitry Andric         (Offset + InsertSize <= DstTy.getSizeInBits())) {
68830eae32dcSDimitry Andric       auto UnmergeSrc = MIRBuilder.buildUnmerge(EltTy, Src);
68840eae32dcSDimitry Andric       SmallVector<Register, 8> DstElts;
68850eae32dcSDimitry Andric       unsigned Idx = 0;
68860eae32dcSDimitry Andric       // Elements from Src before insert start Offset
68870eae32dcSDimitry Andric       for (; Idx < Offset / EltSize; ++Idx) {
68880eae32dcSDimitry Andric         DstElts.push_back(UnmergeSrc.getReg(Idx));
68890eae32dcSDimitry Andric       }
68900eae32dcSDimitry Andric 
68910eae32dcSDimitry Andric       // Replace elements in Src with elements from InsertSrc
68920eae32dcSDimitry Andric       if (InsertTy.getSizeInBits() > EltSize) {
68930eae32dcSDimitry Andric         auto UnmergeInsertSrc = MIRBuilder.buildUnmerge(EltTy, InsertSrc);
68940eae32dcSDimitry Andric         for (unsigned i = 0; Idx < (Offset + InsertSize) / EltSize;
68950eae32dcSDimitry Andric              ++Idx, ++i) {
68960eae32dcSDimitry Andric           DstElts.push_back(UnmergeInsertSrc.getReg(i));
68970eae32dcSDimitry Andric         }
68980eae32dcSDimitry Andric       } else {
68990eae32dcSDimitry Andric         DstElts.push_back(InsertSrc);
69000eae32dcSDimitry Andric         ++Idx;
69010eae32dcSDimitry Andric       }
69020eae32dcSDimitry Andric 
69030eae32dcSDimitry Andric       // Remaining elements from Src after insert
69040eae32dcSDimitry Andric       for (; Idx < DstTy.getNumElements(); ++Idx) {
69050eae32dcSDimitry Andric         DstElts.push_back(UnmergeSrc.getReg(Idx));
69060eae32dcSDimitry Andric       }
69070eae32dcSDimitry Andric 
6908bdd1243dSDimitry Andric       MIRBuilder.buildMergeLikeInstr(Dst, DstElts);
69090eae32dcSDimitry Andric       MI.eraseFromParent();
69100eae32dcSDimitry Andric       return Legalized;
69110eae32dcSDimitry Andric     }
69120eae32dcSDimitry Andric   }
69130eae32dcSDimitry Andric 
69145ffd83dbSDimitry Andric   if (InsertTy.isVector() ||
69155ffd83dbSDimitry Andric       (DstTy.isVector() && DstTy.getElementType() != InsertTy))
69165ffd83dbSDimitry Andric     return UnableToLegalize;
69175ffd83dbSDimitry Andric 
69185ffd83dbSDimitry Andric   const DataLayout &DL = MIRBuilder.getDataLayout();
69195ffd83dbSDimitry Andric   if ((DstTy.isPointer() &&
69205ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(DstTy.getAddressSpace())) ||
69215ffd83dbSDimitry Andric       (InsertTy.isPointer() &&
69225ffd83dbSDimitry Andric        DL.isNonIntegralAddressSpace(InsertTy.getAddressSpace()))) {
69235ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Not casting non-integral address space integer\n");
69245ffd83dbSDimitry Andric     return UnableToLegalize;
69255ffd83dbSDimitry Andric   }
69265ffd83dbSDimitry Andric 
69278bcb0991SDimitry Andric   LLT IntDstTy = DstTy;
69285ffd83dbSDimitry Andric 
69298bcb0991SDimitry Andric   if (!DstTy.isScalar()) {
69308bcb0991SDimitry Andric     IntDstTy = LLT::scalar(DstTy.getSizeInBits());
69315ffd83dbSDimitry Andric     Src = MIRBuilder.buildCast(IntDstTy, Src).getReg(0);
69325ffd83dbSDimitry Andric   }
69335ffd83dbSDimitry Andric 
69345ffd83dbSDimitry Andric   if (!InsertTy.isScalar()) {
69355ffd83dbSDimitry Andric     const LLT IntInsertTy = LLT::scalar(InsertTy.getSizeInBits());
69365ffd83dbSDimitry Andric     InsertSrc = MIRBuilder.buildPtrToInt(IntInsertTy, InsertSrc).getReg(0);
69378bcb0991SDimitry Andric   }
69388bcb0991SDimitry Andric 
69398bcb0991SDimitry Andric   Register ExtInsSrc = MIRBuilder.buildZExt(IntDstTy, InsertSrc).getReg(0);
69408bcb0991SDimitry Andric   if (Offset != 0) {
69418bcb0991SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(IntDstTy, Offset);
69428bcb0991SDimitry Andric     ExtInsSrc = MIRBuilder.buildShl(IntDstTy, ExtInsSrc, ShiftAmt).getReg(0);
69438bcb0991SDimitry Andric   }
69448bcb0991SDimitry Andric 
69455ffd83dbSDimitry Andric   APInt MaskVal = APInt::getBitsSetWithWrap(
69465ffd83dbSDimitry Andric       DstTy.getSizeInBits(), Offset + InsertTy.getSizeInBits(), Offset);
69478bcb0991SDimitry Andric 
69488bcb0991SDimitry Andric   auto Mask = MIRBuilder.buildConstant(IntDstTy, MaskVal);
69498bcb0991SDimitry Andric   auto MaskedSrc = MIRBuilder.buildAnd(IntDstTy, Src, Mask);
69508bcb0991SDimitry Andric   auto Or = MIRBuilder.buildOr(IntDstTy, MaskedSrc, ExtInsSrc);
69518bcb0991SDimitry Andric 
69525ffd83dbSDimitry Andric   MIRBuilder.buildCast(Dst, Or);
69538bcb0991SDimitry Andric   MI.eraseFromParent();
69548bcb0991SDimitry Andric   return Legalized;
69558bcb0991SDimitry Andric }
69568bcb0991SDimitry Andric 
69578bcb0991SDimitry Andric LegalizerHelper::LegalizeResult
69588bcb0991SDimitry Andric LegalizerHelper::lowerSADDO_SSUBO(MachineInstr &MI) {
6959*06c3fb27SDimitry Andric   auto [Dst0, Dst0Ty, Dst1, Dst1Ty, LHS, LHSTy, RHS, RHSTy] =
6960*06c3fb27SDimitry Andric       MI.getFirst4RegLLTs();
69618bcb0991SDimitry Andric   const bool IsAdd = MI.getOpcode() == TargetOpcode::G_SADDO;
69628bcb0991SDimitry Andric 
6963*06c3fb27SDimitry Andric   LLT Ty = Dst0Ty;
6964*06c3fb27SDimitry Andric   LLT BoolTy = Dst1Ty;
69658bcb0991SDimitry Andric 
69668bcb0991SDimitry Andric   if (IsAdd)
69678bcb0991SDimitry Andric     MIRBuilder.buildAdd(Dst0, LHS, RHS);
69688bcb0991SDimitry Andric   else
69698bcb0991SDimitry Andric     MIRBuilder.buildSub(Dst0, LHS, RHS);
69708bcb0991SDimitry Andric 
69718bcb0991SDimitry Andric   // TODO: If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
69728bcb0991SDimitry Andric 
69738bcb0991SDimitry Andric   auto Zero = MIRBuilder.buildConstant(Ty, 0);
69748bcb0991SDimitry Andric 
69758bcb0991SDimitry Andric   // For an addition, the result should be less than one of the operands (LHS)
69768bcb0991SDimitry Andric   // if and only if the other operand (RHS) is negative, otherwise there will
69778bcb0991SDimitry Andric   // be overflow.
69788bcb0991SDimitry Andric   // For a subtraction, the result should be less than one of the operands
69798bcb0991SDimitry Andric   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
69808bcb0991SDimitry Andric   // otherwise there will be overflow.
69818bcb0991SDimitry Andric   auto ResultLowerThanLHS =
69828bcb0991SDimitry Andric       MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, Dst0, LHS);
69838bcb0991SDimitry Andric   auto ConditionRHS = MIRBuilder.buildICmp(
69848bcb0991SDimitry Andric       IsAdd ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGT, BoolTy, RHS, Zero);
69858bcb0991SDimitry Andric 
69868bcb0991SDimitry Andric   MIRBuilder.buildXor(Dst1, ConditionRHS, ResultLowerThanLHS);
69878bcb0991SDimitry Andric   MI.eraseFromParent();
69888bcb0991SDimitry Andric   return Legalized;
69898bcb0991SDimitry Andric }
6990480093f4SDimitry Andric 
6991480093f4SDimitry Andric LegalizerHelper::LegalizeResult
6992e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToMinMax(MachineInstr &MI) {
6993*06c3fb27SDimitry Andric   auto [Res, LHS, RHS] = MI.getFirst3Regs();
6994e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
6995e8d8bef9SDimitry Andric   bool IsSigned;
6996e8d8bef9SDimitry Andric   bool IsAdd;
6997e8d8bef9SDimitry Andric   unsigned BaseOp;
6998e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
6999e8d8bef9SDimitry Andric   default:
7000e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
7001e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
7002e8d8bef9SDimitry Andric     IsSigned = false;
7003e8d8bef9SDimitry Andric     IsAdd = true;
7004e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
7005e8d8bef9SDimitry Andric     break;
7006e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
7007e8d8bef9SDimitry Andric     IsSigned = true;
7008e8d8bef9SDimitry Andric     IsAdd = true;
7009e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_ADD;
7010e8d8bef9SDimitry Andric     break;
7011e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
7012e8d8bef9SDimitry Andric     IsSigned = false;
7013e8d8bef9SDimitry Andric     IsAdd = false;
7014e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
7015e8d8bef9SDimitry Andric     break;
7016e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
7017e8d8bef9SDimitry Andric     IsSigned = true;
7018e8d8bef9SDimitry Andric     IsAdd = false;
7019e8d8bef9SDimitry Andric     BaseOp = TargetOpcode::G_SUB;
7020e8d8bef9SDimitry Andric     break;
7021e8d8bef9SDimitry Andric   }
7022e8d8bef9SDimitry Andric 
7023e8d8bef9SDimitry Andric   if (IsSigned) {
7024e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
7025e8d8bef9SDimitry Andric     //   hi = 0x7fffffff - smax(a, 0)
7026e8d8bef9SDimitry Andric     //   lo = 0x80000000 - smin(a, 0)
7027e8d8bef9SDimitry Andric     //   a + smin(smax(lo, b), hi)
7028e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
7029e8d8bef9SDimitry Andric     //   lo = smax(a, -1) - 0x7fffffff
7030e8d8bef9SDimitry Andric     //   hi = smin(a, -1) - 0x80000000
7031e8d8bef9SDimitry Andric     //   a - smin(smax(lo, b), hi)
7032e8d8bef9SDimitry Andric     // TODO: AMDGPU can use a "median of 3" instruction here:
7033e8d8bef9SDimitry Andric     //   a +/- med3(lo, b, hi)
7034e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
7035e8d8bef9SDimitry Andric     auto MaxVal =
7036e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(NumBits));
7037e8d8bef9SDimitry Andric     auto MinVal =
7038e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
7039e8d8bef9SDimitry Andric     MachineInstrBuilder Hi, Lo;
7040e8d8bef9SDimitry Andric     if (IsAdd) {
7041e8d8bef9SDimitry Andric       auto Zero = MIRBuilder.buildConstant(Ty, 0);
7042e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MaxVal, MIRBuilder.buildSMax(Ty, LHS, Zero));
7043e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MinVal, MIRBuilder.buildSMin(Ty, LHS, Zero));
7044e8d8bef9SDimitry Andric     } else {
7045e8d8bef9SDimitry Andric       auto NegOne = MIRBuilder.buildConstant(Ty, -1);
7046e8d8bef9SDimitry Andric       Lo = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMax(Ty, LHS, NegOne),
7047e8d8bef9SDimitry Andric                                MaxVal);
7048e8d8bef9SDimitry Andric       Hi = MIRBuilder.buildSub(Ty, MIRBuilder.buildSMin(Ty, LHS, NegOne),
7049e8d8bef9SDimitry Andric                                MinVal);
7050e8d8bef9SDimitry Andric     }
7051e8d8bef9SDimitry Andric     auto RHSClamped =
7052e8d8bef9SDimitry Andric         MIRBuilder.buildSMin(Ty, MIRBuilder.buildSMax(Ty, Lo, RHS), Hi);
7053e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, RHSClamped});
7054e8d8bef9SDimitry Andric   } else {
7055e8d8bef9SDimitry Andric     // uadd.sat(a, b) -> a + umin(~a, b)
7056e8d8bef9SDimitry Andric     // usub.sat(a, b) -> a - umin(a, b)
7057e8d8bef9SDimitry Andric     Register Not = IsAdd ? MIRBuilder.buildNot(Ty, LHS).getReg(0) : LHS;
7058e8d8bef9SDimitry Andric     auto Min = MIRBuilder.buildUMin(Ty, Not, RHS);
7059e8d8bef9SDimitry Andric     MIRBuilder.buildInstr(BaseOp, {Res}, {LHS, Min});
7060e8d8bef9SDimitry Andric   }
7061e8d8bef9SDimitry Andric 
7062e8d8bef9SDimitry Andric   MI.eraseFromParent();
7063e8d8bef9SDimitry Andric   return Legalized;
7064e8d8bef9SDimitry Andric }
7065e8d8bef9SDimitry Andric 
7066e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
7067e8d8bef9SDimitry Andric LegalizerHelper::lowerAddSubSatToAddoSubo(MachineInstr &MI) {
7068*06c3fb27SDimitry Andric   auto [Res, LHS, RHS] = MI.getFirst3Regs();
7069e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
7070e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
7071e8d8bef9SDimitry Andric   bool IsSigned;
7072e8d8bef9SDimitry Andric   bool IsAdd;
7073e8d8bef9SDimitry Andric   unsigned OverflowOp;
7074e8d8bef9SDimitry Andric   switch (MI.getOpcode()) {
7075e8d8bef9SDimitry Andric   default:
7076e8d8bef9SDimitry Andric     llvm_unreachable("unexpected addsat/subsat opcode");
7077e8d8bef9SDimitry Andric   case TargetOpcode::G_UADDSAT:
7078e8d8bef9SDimitry Andric     IsSigned = false;
7079e8d8bef9SDimitry Andric     IsAdd = true;
7080e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_UADDO;
7081e8d8bef9SDimitry Andric     break;
7082e8d8bef9SDimitry Andric   case TargetOpcode::G_SADDSAT:
7083e8d8bef9SDimitry Andric     IsSigned = true;
7084e8d8bef9SDimitry Andric     IsAdd = true;
7085e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SADDO;
7086e8d8bef9SDimitry Andric     break;
7087e8d8bef9SDimitry Andric   case TargetOpcode::G_USUBSAT:
7088e8d8bef9SDimitry Andric     IsSigned = false;
7089e8d8bef9SDimitry Andric     IsAdd = false;
7090e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_USUBO;
7091e8d8bef9SDimitry Andric     break;
7092e8d8bef9SDimitry Andric   case TargetOpcode::G_SSUBSAT:
7093e8d8bef9SDimitry Andric     IsSigned = true;
7094e8d8bef9SDimitry Andric     IsAdd = false;
7095e8d8bef9SDimitry Andric     OverflowOp = TargetOpcode::G_SSUBO;
7096e8d8bef9SDimitry Andric     break;
7097e8d8bef9SDimitry Andric   }
7098e8d8bef9SDimitry Andric 
7099e8d8bef9SDimitry Andric   auto OverflowRes =
7100e8d8bef9SDimitry Andric       MIRBuilder.buildInstr(OverflowOp, {Ty, BoolTy}, {LHS, RHS});
7101e8d8bef9SDimitry Andric   Register Tmp = OverflowRes.getReg(0);
7102e8d8bef9SDimitry Andric   Register Ov = OverflowRes.getReg(1);
7103e8d8bef9SDimitry Andric   MachineInstrBuilder Clamp;
7104e8d8bef9SDimitry Andric   if (IsSigned) {
7105e8d8bef9SDimitry Andric     // sadd.sat(a, b) ->
7106e8d8bef9SDimitry Andric     //   {tmp, ov} = saddo(a, b)
7107e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
7108e8d8bef9SDimitry Andric     // ssub.sat(a, b) ->
7109e8d8bef9SDimitry Andric     //   {tmp, ov} = ssubo(a, b)
7110e8d8bef9SDimitry Andric     //   ov ? (tmp >>s 31) + 0x80000000 : r
7111e8d8bef9SDimitry Andric     uint64_t NumBits = Ty.getScalarSizeInBits();
7112e8d8bef9SDimitry Andric     auto ShiftAmount = MIRBuilder.buildConstant(Ty, NumBits - 1);
7113e8d8bef9SDimitry Andric     auto Sign = MIRBuilder.buildAShr(Ty, Tmp, ShiftAmount);
7114e8d8bef9SDimitry Andric     auto MinVal =
7115e8d8bef9SDimitry Andric         MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(NumBits));
7116e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildAdd(Ty, Sign, MinVal);
7117e8d8bef9SDimitry Andric   } else {
7118e8d8bef9SDimitry Andric     // uadd.sat(a, b) ->
7119e8d8bef9SDimitry Andric     //   {tmp, ov} = uaddo(a, b)
7120e8d8bef9SDimitry Andric     //   ov ? 0xffffffff : tmp
7121e8d8bef9SDimitry Andric     // usub.sat(a, b) ->
7122e8d8bef9SDimitry Andric     //   {tmp, ov} = usubo(a, b)
7123e8d8bef9SDimitry Andric     //   ov ? 0 : tmp
7124e8d8bef9SDimitry Andric     Clamp = MIRBuilder.buildConstant(Ty, IsAdd ? -1 : 0);
7125e8d8bef9SDimitry Andric   }
7126e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, Clamp, Tmp);
7127e8d8bef9SDimitry Andric 
7128e8d8bef9SDimitry Andric   MI.eraseFromParent();
7129e8d8bef9SDimitry Andric   return Legalized;
7130e8d8bef9SDimitry Andric }
7131e8d8bef9SDimitry Andric 
7132e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
7133e8d8bef9SDimitry Andric LegalizerHelper::lowerShlSat(MachineInstr &MI) {
7134e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SSHLSAT ||
7135e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_USHLSAT) &&
7136e8d8bef9SDimitry Andric          "Expected shlsat opcode!");
7137e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SSHLSAT;
7138*06c3fb27SDimitry Andric   auto [Res, LHS, RHS] = MI.getFirst3Regs();
7139e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Res);
7140e8d8bef9SDimitry Andric   LLT BoolTy = Ty.changeElementSize(1);
7141e8d8bef9SDimitry Andric 
7142e8d8bef9SDimitry Andric   unsigned BW = Ty.getScalarSizeInBits();
7143e8d8bef9SDimitry Andric   auto Result = MIRBuilder.buildShl(Ty, LHS, RHS);
7144e8d8bef9SDimitry Andric   auto Orig = IsSigned ? MIRBuilder.buildAShr(Ty, Result, RHS)
7145e8d8bef9SDimitry Andric                        : MIRBuilder.buildLShr(Ty, Result, RHS);
7146e8d8bef9SDimitry Andric 
7147e8d8bef9SDimitry Andric   MachineInstrBuilder SatVal;
7148e8d8bef9SDimitry Andric   if (IsSigned) {
7149e8d8bef9SDimitry Andric     auto SatMin = MIRBuilder.buildConstant(Ty, APInt::getSignedMinValue(BW));
7150e8d8bef9SDimitry Andric     auto SatMax = MIRBuilder.buildConstant(Ty, APInt::getSignedMaxValue(BW));
7151e8d8bef9SDimitry Andric     auto Cmp = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, LHS,
7152e8d8bef9SDimitry Andric                                     MIRBuilder.buildConstant(Ty, 0));
7153e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildSelect(Ty, Cmp, SatMin, SatMax);
7154e8d8bef9SDimitry Andric   } else {
7155e8d8bef9SDimitry Andric     SatVal = MIRBuilder.buildConstant(Ty, APInt::getMaxValue(BW));
7156e8d8bef9SDimitry Andric   }
7157e8d8bef9SDimitry Andric   auto Ov = MIRBuilder.buildICmp(CmpInst::ICMP_NE, BoolTy, LHS, Orig);
7158e8d8bef9SDimitry Andric   MIRBuilder.buildSelect(Res, Ov, SatVal, Result);
7159e8d8bef9SDimitry Andric 
7160e8d8bef9SDimitry Andric   MI.eraseFromParent();
7161e8d8bef9SDimitry Andric   return Legalized;
7162e8d8bef9SDimitry Andric }
7163e8d8bef9SDimitry Andric 
7164*06c3fb27SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerBswap(MachineInstr &MI) {
7165*06c3fb27SDimitry Andric   auto [Dst, Src] = MI.getFirst2Regs();
7166480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
71675ffd83dbSDimitry Andric   unsigned SizeInBytes = (Ty.getScalarSizeInBits() + 7) / 8;
7168480093f4SDimitry Andric   unsigned BaseShiftAmt = (SizeInBytes - 1) * 8;
7169480093f4SDimitry Andric 
7170480093f4SDimitry Andric   // Swap most and least significant byte, set remaining bytes in Res to zero.
7171480093f4SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt);
7172480093f4SDimitry Andric   auto LSByteShiftedLeft = MIRBuilder.buildShl(Ty, Src, ShiftAmt);
7173480093f4SDimitry Andric   auto MSByteShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
7174480093f4SDimitry Andric   auto Res = MIRBuilder.buildOr(Ty, MSByteShiftedRight, LSByteShiftedLeft);
7175480093f4SDimitry Andric 
7176480093f4SDimitry Andric   // Set i-th high/low byte in Res to i-th low/high byte from Src.
7177480093f4SDimitry Andric   for (unsigned i = 1; i < SizeInBytes / 2; ++i) {
7178480093f4SDimitry Andric     // AND with Mask leaves byte i unchanged and sets remaining bytes to 0.
7179480093f4SDimitry Andric     APInt APMask(SizeInBytes * 8, 0xFF << (i * 8));
7180480093f4SDimitry Andric     auto Mask = MIRBuilder.buildConstant(Ty, APMask);
7181480093f4SDimitry Andric     auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt - 16 * i);
7182480093f4SDimitry Andric     // Low byte shifted left to place of high byte: (Src & Mask) << ShiftAmt.
7183480093f4SDimitry Andric     auto LoByte = MIRBuilder.buildAnd(Ty, Src, Mask);
7184480093f4SDimitry Andric     auto LoShiftedLeft = MIRBuilder.buildShl(Ty, LoByte, ShiftAmt);
7185480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, LoShiftedLeft);
7186480093f4SDimitry Andric     // High byte shifted right to place of low byte: (Src >> ShiftAmt) & Mask.
7187480093f4SDimitry Andric     auto SrcShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
7188480093f4SDimitry Andric     auto HiShiftedRight = MIRBuilder.buildAnd(Ty, SrcShiftedRight, Mask);
7189480093f4SDimitry Andric     Res = MIRBuilder.buildOr(Ty, Res, HiShiftedRight);
7190480093f4SDimitry Andric   }
7191480093f4SDimitry Andric   Res.getInstr()->getOperand(0).setReg(Dst);
7192480093f4SDimitry Andric 
7193480093f4SDimitry Andric   MI.eraseFromParent();
7194480093f4SDimitry Andric   return Legalized;
7195480093f4SDimitry Andric }
7196480093f4SDimitry Andric 
7197480093f4SDimitry Andric //{ (Src & Mask) >> N } | { (Src << N) & Mask }
7198480093f4SDimitry Andric static MachineInstrBuilder SwapN(unsigned N, DstOp Dst, MachineIRBuilder &B,
7199480093f4SDimitry Andric                                  MachineInstrBuilder Src, APInt Mask) {
7200480093f4SDimitry Andric   const LLT Ty = Dst.getLLTTy(*B.getMRI());
7201480093f4SDimitry Andric   MachineInstrBuilder C_N = B.buildConstant(Ty, N);
7202480093f4SDimitry Andric   MachineInstrBuilder MaskLoNTo0 = B.buildConstant(Ty, Mask);
7203480093f4SDimitry Andric   auto LHS = B.buildLShr(Ty, B.buildAnd(Ty, Src, MaskLoNTo0), C_N);
7204480093f4SDimitry Andric   auto RHS = B.buildAnd(Ty, B.buildShl(Ty, Src, C_N), MaskLoNTo0);
7205480093f4SDimitry Andric   return B.buildOr(Dst, LHS, RHS);
7206480093f4SDimitry Andric }
7207480093f4SDimitry Andric 
7208480093f4SDimitry Andric LegalizerHelper::LegalizeResult
7209480093f4SDimitry Andric LegalizerHelper::lowerBitreverse(MachineInstr &MI) {
7210*06c3fb27SDimitry Andric   auto [Dst, Src] = MI.getFirst2Regs();
7211480093f4SDimitry Andric   const LLT Ty = MRI.getType(Src);
7212480093f4SDimitry Andric   unsigned Size = Ty.getSizeInBits();
7213480093f4SDimitry Andric 
7214480093f4SDimitry Andric   MachineInstrBuilder BSWAP =
7215480093f4SDimitry Andric       MIRBuilder.buildInstr(TargetOpcode::G_BSWAP, {Ty}, {Src});
7216480093f4SDimitry Andric 
7217480093f4SDimitry Andric   // swap high and low 4 bits in 8 bit blocks 7654|3210 -> 3210|7654
7218480093f4SDimitry Andric   //    [(val & 0xF0F0F0F0) >> 4] | [(val & 0x0F0F0F0F) << 4]
7219480093f4SDimitry Andric   // -> [(val & 0xF0F0F0F0) >> 4] | [(val << 4) & 0xF0F0F0F0]
7220480093f4SDimitry Andric   MachineInstrBuilder Swap4 =
7221480093f4SDimitry Andric       SwapN(4, Ty, MIRBuilder, BSWAP, APInt::getSplat(Size, APInt(8, 0xF0)));
7222480093f4SDimitry Andric 
7223480093f4SDimitry Andric   // swap high and low 2 bits in 4 bit blocks 32|10 76|54 -> 10|32 54|76
7224480093f4SDimitry Andric   //    [(val & 0xCCCCCCCC) >> 2] & [(val & 0x33333333) << 2]
7225480093f4SDimitry Andric   // -> [(val & 0xCCCCCCCC) >> 2] & [(val << 2) & 0xCCCCCCCC]
7226480093f4SDimitry Andric   MachineInstrBuilder Swap2 =
7227480093f4SDimitry Andric       SwapN(2, Ty, MIRBuilder, Swap4, APInt::getSplat(Size, APInt(8, 0xCC)));
7228480093f4SDimitry Andric 
7229480093f4SDimitry 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
7230480093f4SDimitry Andric   //    [(val & 0xAAAAAAAA) >> 1] & [(val & 0x55555555) << 1]
7231480093f4SDimitry Andric   // -> [(val & 0xAAAAAAAA) >> 1] & [(val << 1) & 0xAAAAAAAA]
7232480093f4SDimitry Andric   SwapN(1, Dst, MIRBuilder, Swap2, APInt::getSplat(Size, APInt(8, 0xAA)));
7233480093f4SDimitry Andric 
7234480093f4SDimitry Andric   MI.eraseFromParent();
7235480093f4SDimitry Andric   return Legalized;
7236480093f4SDimitry Andric }
7237480093f4SDimitry Andric 
7238480093f4SDimitry Andric LegalizerHelper::LegalizeResult
72395ffd83dbSDimitry Andric LegalizerHelper::lowerReadWriteRegister(MachineInstr &MI) {
7240480093f4SDimitry Andric   MachineFunction &MF = MIRBuilder.getMF();
72415ffd83dbSDimitry Andric 
72425ffd83dbSDimitry Andric   bool IsRead = MI.getOpcode() == TargetOpcode::G_READ_REGISTER;
72435ffd83dbSDimitry Andric   int NameOpIdx = IsRead ? 1 : 0;
72445ffd83dbSDimitry Andric   int ValRegIndex = IsRead ? 0 : 1;
72455ffd83dbSDimitry Andric 
72465ffd83dbSDimitry Andric   Register ValReg = MI.getOperand(ValRegIndex).getReg();
72475ffd83dbSDimitry Andric   const LLT Ty = MRI.getType(ValReg);
72485ffd83dbSDimitry Andric   const MDString *RegStr = cast<MDString>(
72495ffd83dbSDimitry Andric     cast<MDNode>(MI.getOperand(NameOpIdx).getMetadata())->getOperand(0));
72505ffd83dbSDimitry Andric 
7251e8d8bef9SDimitry Andric   Register PhysReg = TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
72525ffd83dbSDimitry Andric   if (!PhysReg.isValid())
7253480093f4SDimitry Andric     return UnableToLegalize;
7254480093f4SDimitry Andric 
72555ffd83dbSDimitry Andric   if (IsRead)
72565ffd83dbSDimitry Andric     MIRBuilder.buildCopy(ValReg, PhysReg);
72575ffd83dbSDimitry Andric   else
72585ffd83dbSDimitry Andric     MIRBuilder.buildCopy(PhysReg, ValReg);
72595ffd83dbSDimitry Andric 
7260480093f4SDimitry Andric   MI.eraseFromParent();
7261480093f4SDimitry Andric   return Legalized;
7262480093f4SDimitry Andric }
7263e8d8bef9SDimitry Andric 
7264e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult
7265e8d8bef9SDimitry Andric LegalizerHelper::lowerSMULH_UMULH(MachineInstr &MI) {
7266e8d8bef9SDimitry Andric   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SMULH;
7267e8d8bef9SDimitry Andric   unsigned ExtOp = IsSigned ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
7268e8d8bef9SDimitry Andric   Register Result = MI.getOperand(0).getReg();
7269e8d8bef9SDimitry Andric   LLT OrigTy = MRI.getType(Result);
7270e8d8bef9SDimitry Andric   auto SizeInBits = OrigTy.getScalarSizeInBits();
7271e8d8bef9SDimitry Andric   LLT WideTy = OrigTy.changeElementSize(SizeInBits * 2);
7272e8d8bef9SDimitry Andric 
7273e8d8bef9SDimitry Andric   auto LHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(1)});
7274e8d8bef9SDimitry Andric   auto RHS = MIRBuilder.buildInstr(ExtOp, {WideTy}, {MI.getOperand(2)});
7275e8d8bef9SDimitry Andric   auto Mul = MIRBuilder.buildMul(WideTy, LHS, RHS);
7276e8d8bef9SDimitry Andric   unsigned ShiftOp = IsSigned ? TargetOpcode::G_ASHR : TargetOpcode::G_LSHR;
7277e8d8bef9SDimitry Andric 
7278e8d8bef9SDimitry Andric   auto ShiftAmt = MIRBuilder.buildConstant(WideTy, SizeInBits);
7279e8d8bef9SDimitry Andric   auto Shifted = MIRBuilder.buildInstr(ShiftOp, {WideTy}, {Mul, ShiftAmt});
7280e8d8bef9SDimitry Andric   MIRBuilder.buildTrunc(Result, Shifted);
7281e8d8bef9SDimitry Andric 
7282e8d8bef9SDimitry Andric   MI.eraseFromParent();
7283e8d8bef9SDimitry Andric   return Legalized;
7284e8d8bef9SDimitry Andric }
7285e8d8bef9SDimitry Andric 
7286bdd1243dSDimitry Andric LegalizerHelper::LegalizeResult
7287bdd1243dSDimitry Andric LegalizerHelper::lowerISFPCLASS(MachineInstr &MI) {
7288*06c3fb27SDimitry Andric   auto [DstReg, DstTy, SrcReg, SrcTy] = MI.getFirst2RegLLTs();
7289*06c3fb27SDimitry Andric   FPClassTest Mask = static_cast<FPClassTest>(MI.getOperand(2).getImm());
7290bdd1243dSDimitry Andric 
7291*06c3fb27SDimitry Andric   if (Mask == fcNone) {
7292bdd1243dSDimitry Andric     MIRBuilder.buildConstant(DstReg, 0);
7293bdd1243dSDimitry Andric     MI.eraseFromParent();
7294bdd1243dSDimitry Andric     return Legalized;
7295bdd1243dSDimitry Andric   }
7296*06c3fb27SDimitry Andric   if (Mask == fcAllFlags) {
7297bdd1243dSDimitry Andric     MIRBuilder.buildConstant(DstReg, 1);
7298bdd1243dSDimitry Andric     MI.eraseFromParent();
7299bdd1243dSDimitry Andric     return Legalized;
7300bdd1243dSDimitry Andric   }
7301bdd1243dSDimitry Andric 
7302*06c3fb27SDimitry Andric   // TODO: Try inverting the test with getInvertedFPClassTest like the DAG
7303*06c3fb27SDimitry Andric   // version
7304*06c3fb27SDimitry Andric 
7305bdd1243dSDimitry Andric   unsigned BitSize = SrcTy.getScalarSizeInBits();
7306bdd1243dSDimitry Andric   const fltSemantics &Semantics = getFltSemanticForLLT(SrcTy.getScalarType());
7307bdd1243dSDimitry Andric 
7308bdd1243dSDimitry Andric   LLT IntTy = LLT::scalar(BitSize);
7309bdd1243dSDimitry Andric   if (SrcTy.isVector())
7310bdd1243dSDimitry Andric     IntTy = LLT::vector(SrcTy.getElementCount(), IntTy);
7311bdd1243dSDimitry Andric   auto AsInt = MIRBuilder.buildCopy(IntTy, SrcReg);
7312bdd1243dSDimitry Andric 
7313bdd1243dSDimitry Andric   // Various masks.
7314bdd1243dSDimitry Andric   APInt SignBit = APInt::getSignMask(BitSize);
7315bdd1243dSDimitry Andric   APInt ValueMask = APInt::getSignedMaxValue(BitSize);     // All bits but sign.
7316bdd1243dSDimitry Andric   APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
7317bdd1243dSDimitry Andric   APInt ExpMask = Inf;
7318bdd1243dSDimitry Andric   APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
7319bdd1243dSDimitry Andric   APInt QNaNBitMask =
7320bdd1243dSDimitry Andric       APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
7321*06c3fb27SDimitry Andric   APInt InvertionMask = APInt::getAllOnes(DstTy.getScalarSizeInBits());
7322bdd1243dSDimitry Andric 
7323bdd1243dSDimitry Andric   auto SignBitC = MIRBuilder.buildConstant(IntTy, SignBit);
7324bdd1243dSDimitry Andric   auto ValueMaskC = MIRBuilder.buildConstant(IntTy, ValueMask);
7325bdd1243dSDimitry Andric   auto InfC = MIRBuilder.buildConstant(IntTy, Inf);
7326bdd1243dSDimitry Andric   auto ExpMaskC = MIRBuilder.buildConstant(IntTy, ExpMask);
7327bdd1243dSDimitry Andric   auto ZeroC = MIRBuilder.buildConstant(IntTy, 0);
7328bdd1243dSDimitry Andric 
7329bdd1243dSDimitry Andric   auto Abs = MIRBuilder.buildAnd(IntTy, AsInt, ValueMaskC);
7330bdd1243dSDimitry Andric   auto Sign =
7331bdd1243dSDimitry Andric       MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_NE, DstTy, AsInt, Abs);
7332bdd1243dSDimitry Andric 
7333bdd1243dSDimitry Andric   auto Res = MIRBuilder.buildConstant(DstTy, 0);
7334*06c3fb27SDimitry Andric   // Clang doesn't support capture of structured bindings:
7335*06c3fb27SDimitry Andric   LLT DstTyCopy = DstTy;
7336bdd1243dSDimitry Andric   const auto appendToRes = [&](MachineInstrBuilder ToAppend) {
7337*06c3fb27SDimitry Andric     Res = MIRBuilder.buildOr(DstTyCopy, Res, ToAppend);
7338bdd1243dSDimitry Andric   };
7339bdd1243dSDimitry Andric 
7340bdd1243dSDimitry Andric   // Tests that involve more than one class should be processed first.
7341bdd1243dSDimitry Andric   if ((Mask & fcFinite) == fcFinite) {
7342bdd1243dSDimitry Andric     // finite(V) ==> abs(V) u< exp_mask
7343bdd1243dSDimitry Andric     appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_ULT, DstTy, Abs,
7344bdd1243dSDimitry Andric                                      ExpMaskC));
7345bdd1243dSDimitry Andric     Mask &= ~fcFinite;
7346bdd1243dSDimitry Andric   } else if ((Mask & fcFinite) == fcPosFinite) {
7347bdd1243dSDimitry Andric     // finite(V) && V > 0 ==> V u< exp_mask
7348bdd1243dSDimitry Andric     appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_ULT, DstTy, AsInt,
7349bdd1243dSDimitry Andric                                      ExpMaskC));
7350bdd1243dSDimitry Andric     Mask &= ~fcPosFinite;
7351bdd1243dSDimitry Andric   } else if ((Mask & fcFinite) == fcNegFinite) {
7352bdd1243dSDimitry Andric     // finite(V) && V < 0 ==> abs(V) u< exp_mask && signbit == 1
7353bdd1243dSDimitry Andric     auto Cmp = MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_ULT, DstTy, Abs,
7354bdd1243dSDimitry Andric                                     ExpMaskC);
7355bdd1243dSDimitry Andric     auto And = MIRBuilder.buildAnd(DstTy, Cmp, Sign);
7356bdd1243dSDimitry Andric     appendToRes(And);
7357bdd1243dSDimitry Andric     Mask &= ~fcNegFinite;
7358bdd1243dSDimitry Andric   }
7359bdd1243dSDimitry Andric 
7360*06c3fb27SDimitry Andric   if (FPClassTest PartialCheck = Mask & (fcZero | fcSubnormal)) {
7361*06c3fb27SDimitry Andric     // fcZero | fcSubnormal => test all exponent bits are 0
7362*06c3fb27SDimitry Andric     // TODO: Handle sign bit specific cases
7363*06c3fb27SDimitry Andric     // TODO: Handle inverted case
7364*06c3fb27SDimitry Andric     if (PartialCheck == (fcZero | fcSubnormal)) {
7365*06c3fb27SDimitry Andric       auto ExpBits = MIRBuilder.buildAnd(IntTy, AsInt, ExpMaskC);
7366*06c3fb27SDimitry Andric       appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy,
7367*06c3fb27SDimitry Andric                                        ExpBits, ZeroC));
7368*06c3fb27SDimitry Andric       Mask &= ~PartialCheck;
7369*06c3fb27SDimitry Andric     }
7370*06c3fb27SDimitry Andric   }
7371*06c3fb27SDimitry Andric 
7372bdd1243dSDimitry Andric   // Check for individual classes.
7373*06c3fb27SDimitry Andric   if (FPClassTest PartialCheck = Mask & fcZero) {
7374bdd1243dSDimitry Andric     if (PartialCheck == fcPosZero)
7375bdd1243dSDimitry Andric       appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy,
7376bdd1243dSDimitry Andric                                        AsInt, ZeroC));
7377bdd1243dSDimitry Andric     else if (PartialCheck == fcZero)
7378bdd1243dSDimitry Andric       appendToRes(
7379bdd1243dSDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy, Abs, ZeroC));
7380bdd1243dSDimitry Andric     else // fcNegZero
7381bdd1243dSDimitry Andric       appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy,
7382bdd1243dSDimitry Andric                                        AsInt, SignBitC));
7383bdd1243dSDimitry Andric   }
7384bdd1243dSDimitry Andric 
7385*06c3fb27SDimitry Andric   if (FPClassTest PartialCheck = Mask & fcSubnormal) {
7386*06c3fb27SDimitry Andric     // issubnormal(V) ==> unsigned(abs(V) - 1) u< (all mantissa bits set)
7387*06c3fb27SDimitry Andric     // issubnormal(V) && V>0 ==> unsigned(V - 1) u< (all mantissa bits set)
7388*06c3fb27SDimitry Andric     auto V = (PartialCheck == fcPosSubnormal) ? AsInt : Abs;
7389*06c3fb27SDimitry Andric     auto OneC = MIRBuilder.buildConstant(IntTy, 1);
7390*06c3fb27SDimitry Andric     auto VMinusOne = MIRBuilder.buildSub(IntTy, V, OneC);
7391*06c3fb27SDimitry Andric     auto SubnormalRes =
7392*06c3fb27SDimitry Andric         MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_ULT, DstTy, VMinusOne,
7393*06c3fb27SDimitry Andric                              MIRBuilder.buildConstant(IntTy, AllOneMantissa));
7394*06c3fb27SDimitry Andric     if (PartialCheck == fcNegSubnormal)
7395*06c3fb27SDimitry Andric       SubnormalRes = MIRBuilder.buildAnd(DstTy, SubnormalRes, Sign);
7396*06c3fb27SDimitry Andric     appendToRes(SubnormalRes);
7397*06c3fb27SDimitry Andric   }
7398*06c3fb27SDimitry Andric 
7399*06c3fb27SDimitry Andric   if (FPClassTest PartialCheck = Mask & fcInf) {
7400bdd1243dSDimitry Andric     if (PartialCheck == fcPosInf)
7401bdd1243dSDimitry Andric       appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy,
7402bdd1243dSDimitry Andric                                        AsInt, InfC));
7403bdd1243dSDimitry Andric     else if (PartialCheck == fcInf)
7404bdd1243dSDimitry Andric       appendToRes(
7405bdd1243dSDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy, Abs, InfC));
7406bdd1243dSDimitry Andric     else { // fcNegInf
7407bdd1243dSDimitry Andric       APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
7408bdd1243dSDimitry Andric       auto NegInfC = MIRBuilder.buildConstant(IntTy, NegInf);
7409bdd1243dSDimitry Andric       appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, DstTy,
7410bdd1243dSDimitry Andric                                        AsInt, NegInfC));
7411bdd1243dSDimitry Andric     }
7412bdd1243dSDimitry Andric   }
7413bdd1243dSDimitry Andric 
7414*06c3fb27SDimitry Andric   if (FPClassTest PartialCheck = Mask & fcNan) {
7415bdd1243dSDimitry Andric     auto InfWithQnanBitC = MIRBuilder.buildConstant(IntTy, Inf | QNaNBitMask);
7416bdd1243dSDimitry Andric     if (PartialCheck == fcNan) {
7417bdd1243dSDimitry Andric       // isnan(V) ==> abs(V) u> int(inf)
7418bdd1243dSDimitry Andric       appendToRes(
7419bdd1243dSDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_UGT, DstTy, Abs, InfC));
7420bdd1243dSDimitry Andric     } else if (PartialCheck == fcQNan) {
7421bdd1243dSDimitry Andric       // isquiet(V) ==> abs(V) u>= (unsigned(Inf) | quiet_bit)
7422bdd1243dSDimitry Andric       appendToRes(MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_UGE, DstTy, Abs,
7423bdd1243dSDimitry Andric                                        InfWithQnanBitC));
7424bdd1243dSDimitry Andric     } else { // fcSNan
7425bdd1243dSDimitry Andric       // issignaling(V) ==> abs(V) u> unsigned(Inf) &&
7426bdd1243dSDimitry Andric       //                    abs(V) u< (unsigned(Inf) | quiet_bit)
7427bdd1243dSDimitry Andric       auto IsNan =
7428bdd1243dSDimitry Andric           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_UGT, DstTy, Abs, InfC);
7429bdd1243dSDimitry Andric       auto IsNotQnan = MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_ULT, DstTy,
7430bdd1243dSDimitry Andric                                             Abs, InfWithQnanBitC);
7431bdd1243dSDimitry Andric       appendToRes(MIRBuilder.buildAnd(DstTy, IsNan, IsNotQnan));
7432bdd1243dSDimitry Andric     }
7433bdd1243dSDimitry Andric   }
7434bdd1243dSDimitry Andric 
7435*06c3fb27SDimitry Andric   if (FPClassTest PartialCheck = Mask & fcNormal) {
7436bdd1243dSDimitry Andric     // isnormal(V) ==> (0 u< exp u< max_exp) ==> (unsigned(exp-1) u<
7437bdd1243dSDimitry Andric     // (max_exp-1))
7438bdd1243dSDimitry Andric     APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
7439bdd1243dSDimitry Andric     auto ExpMinusOne = MIRBuilder.buildSub(
7440bdd1243dSDimitry Andric         IntTy, Abs, MIRBuilder.buildConstant(IntTy, ExpLSB));
7441bdd1243dSDimitry Andric     APInt MaxExpMinusOne = ExpMask - ExpLSB;
7442bdd1243dSDimitry Andric     auto NormalRes =
7443bdd1243dSDimitry Andric         MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_ULT, DstTy, ExpMinusOne,
7444bdd1243dSDimitry Andric                              MIRBuilder.buildConstant(IntTy, MaxExpMinusOne));
7445bdd1243dSDimitry Andric     if (PartialCheck == fcNegNormal)
7446bdd1243dSDimitry Andric       NormalRes = MIRBuilder.buildAnd(DstTy, NormalRes, Sign);
7447bdd1243dSDimitry Andric     else if (PartialCheck == fcPosNormal) {
7448bdd1243dSDimitry Andric       auto PosSign = MIRBuilder.buildXor(
7449bdd1243dSDimitry Andric           DstTy, Sign, MIRBuilder.buildConstant(DstTy, InvertionMask));
7450bdd1243dSDimitry Andric       NormalRes = MIRBuilder.buildAnd(DstTy, NormalRes, PosSign);
7451bdd1243dSDimitry Andric     }
7452bdd1243dSDimitry Andric     appendToRes(NormalRes);
7453bdd1243dSDimitry Andric   }
7454bdd1243dSDimitry Andric 
7455bdd1243dSDimitry Andric   MIRBuilder.buildCopy(DstReg, Res);
7456bdd1243dSDimitry Andric   MI.eraseFromParent();
7457bdd1243dSDimitry Andric   return Legalized;
7458bdd1243dSDimitry Andric }
7459bdd1243dSDimitry Andric 
7460e8d8bef9SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerSelect(MachineInstr &MI) {
7461e8d8bef9SDimitry Andric   // Implement vector G_SELECT in terms of XOR, AND, OR.
7462*06c3fb27SDimitry Andric   auto [DstReg, DstTy, MaskReg, MaskTy, Op1Reg, Op1Ty, Op2Reg, Op2Ty] =
7463*06c3fb27SDimitry Andric       MI.getFirst4RegLLTs();
7464e8d8bef9SDimitry Andric   if (!DstTy.isVector())
7465e8d8bef9SDimitry Andric     return UnableToLegalize;
7466e8d8bef9SDimitry Andric 
7467bdd1243dSDimitry Andric   bool IsEltPtr = DstTy.getElementType().isPointer();
7468bdd1243dSDimitry Andric   if (IsEltPtr) {
7469bdd1243dSDimitry Andric     LLT ScalarPtrTy = LLT::scalar(DstTy.getScalarSizeInBits());
7470bdd1243dSDimitry Andric     LLT NewTy = DstTy.changeElementType(ScalarPtrTy);
7471bdd1243dSDimitry Andric     Op1Reg = MIRBuilder.buildPtrToInt(NewTy, Op1Reg).getReg(0);
7472bdd1243dSDimitry Andric     Op2Reg = MIRBuilder.buildPtrToInt(NewTy, Op2Reg).getReg(0);
7473bdd1243dSDimitry Andric     DstTy = NewTy;
7474bdd1243dSDimitry Andric   }
7475bdd1243dSDimitry Andric 
7476e8d8bef9SDimitry Andric   if (MaskTy.isScalar()) {
747781ad6265SDimitry Andric     // Turn the scalar condition into a vector condition mask.
747881ad6265SDimitry Andric 
7479e8d8bef9SDimitry Andric     Register MaskElt = MaskReg;
748081ad6265SDimitry Andric 
748181ad6265SDimitry Andric     // The condition was potentially zero extended before, but we want a sign
748281ad6265SDimitry Andric     // extended boolean.
7483bdd1243dSDimitry Andric     if (MaskTy != LLT::scalar(1))
748481ad6265SDimitry Andric       MaskElt = MIRBuilder.buildSExtInReg(MaskTy, MaskElt, 1).getReg(0);
7485e8d8bef9SDimitry Andric 
748681ad6265SDimitry Andric     // Continue the sign extension (or truncate) to match the data type.
748781ad6265SDimitry Andric     MaskElt = MIRBuilder.buildSExtOrTrunc(DstTy.getElementType(),
748881ad6265SDimitry Andric                                           MaskElt).getReg(0);
748981ad6265SDimitry Andric 
749081ad6265SDimitry Andric     // Generate a vector splat idiom.
749181ad6265SDimitry Andric     auto ShufSplat = MIRBuilder.buildShuffleSplat(DstTy, MaskElt);
749281ad6265SDimitry Andric     MaskReg = ShufSplat.getReg(0);
749381ad6265SDimitry Andric     MaskTy = DstTy;
749481ad6265SDimitry Andric   }
749581ad6265SDimitry Andric 
749681ad6265SDimitry Andric   if (MaskTy.getSizeInBits() != DstTy.getSizeInBits()) {
7497e8d8bef9SDimitry Andric     return UnableToLegalize;
7498e8d8bef9SDimitry Andric   }
7499e8d8bef9SDimitry Andric 
7500e8d8bef9SDimitry Andric   auto NotMask = MIRBuilder.buildNot(MaskTy, MaskReg);
7501e8d8bef9SDimitry Andric   auto NewOp1 = MIRBuilder.buildAnd(MaskTy, Op1Reg, MaskReg);
7502e8d8bef9SDimitry Andric   auto NewOp2 = MIRBuilder.buildAnd(MaskTy, Op2Reg, NotMask);
7503bdd1243dSDimitry Andric   if (IsEltPtr) {
7504bdd1243dSDimitry Andric     auto Or = MIRBuilder.buildOr(DstTy, NewOp1, NewOp2);
7505bdd1243dSDimitry Andric     MIRBuilder.buildIntToPtr(DstReg, Or);
7506bdd1243dSDimitry Andric   } else {
7507e8d8bef9SDimitry Andric     MIRBuilder.buildOr(DstReg, NewOp1, NewOp2);
7508bdd1243dSDimitry Andric   }
7509e8d8bef9SDimitry Andric   MI.eraseFromParent();
7510e8d8bef9SDimitry Andric   return Legalized;
7511e8d8bef9SDimitry Andric }
7512fe6060f1SDimitry Andric 
7513fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult LegalizerHelper::lowerDIVREM(MachineInstr &MI) {
7514fe6060f1SDimitry Andric   // Split DIVREM into individual instructions.
7515fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
7516fe6060f1SDimitry Andric 
7517fe6060f1SDimitry Andric   MIRBuilder.buildInstr(
7518fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIVREM ? TargetOpcode::G_SDIV
7519fe6060f1SDimitry Andric                                         : TargetOpcode::G_UDIV,
7520fe6060f1SDimitry Andric       {MI.getOperand(0).getReg()}, {MI.getOperand(2), MI.getOperand(3)});
7521fe6060f1SDimitry Andric   MIRBuilder.buildInstr(
7522fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIVREM ? TargetOpcode::G_SREM
7523fe6060f1SDimitry Andric                                         : TargetOpcode::G_UREM,
7524fe6060f1SDimitry Andric       {MI.getOperand(1).getReg()}, {MI.getOperand(2), MI.getOperand(3)});
7525fe6060f1SDimitry Andric   MI.eraseFromParent();
7526fe6060f1SDimitry Andric   return Legalized;
7527fe6060f1SDimitry Andric }
7528fe6060f1SDimitry Andric 
7529fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
7530fe6060f1SDimitry Andric LegalizerHelper::lowerAbsToAddXor(MachineInstr &MI) {
7531fe6060f1SDimitry Andric   // Expand %res = G_ABS %a into:
7532fe6060f1SDimitry Andric   // %v1 = G_ASHR %a, scalar_size-1
7533fe6060f1SDimitry Andric   // %v2 = G_ADD %a, %v1
7534fe6060f1SDimitry Andric   // %res = G_XOR %v2, %v1
7535fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
7536fe6060f1SDimitry Andric   Register OpReg = MI.getOperand(1).getReg();
7537fe6060f1SDimitry Andric   auto ShiftAmt =
7538fe6060f1SDimitry Andric       MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - 1);
7539fe6060f1SDimitry Andric   auto Shift = MIRBuilder.buildAShr(DstTy, OpReg, ShiftAmt);
7540fe6060f1SDimitry Andric   auto Add = MIRBuilder.buildAdd(DstTy, OpReg, Shift);
7541fe6060f1SDimitry Andric   MIRBuilder.buildXor(MI.getOperand(0).getReg(), Add, Shift);
7542fe6060f1SDimitry Andric   MI.eraseFromParent();
7543fe6060f1SDimitry Andric   return Legalized;
7544fe6060f1SDimitry Andric }
7545fe6060f1SDimitry Andric 
7546fe6060f1SDimitry Andric LegalizerHelper::LegalizeResult
7547fe6060f1SDimitry Andric LegalizerHelper::lowerAbsToMaxNeg(MachineInstr &MI) {
7548fe6060f1SDimitry Andric   // Expand %res = G_ABS %a into:
7549fe6060f1SDimitry Andric   // %v1 = G_CONSTANT 0
7550fe6060f1SDimitry Andric   // %v2 = G_SUB %v1, %a
7551fe6060f1SDimitry Andric   // %res = G_SMAX %a, %v2
7552fe6060f1SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
7553fe6060f1SDimitry Andric   LLT Ty = MRI.getType(SrcReg);
7554fe6060f1SDimitry Andric   auto Zero = MIRBuilder.buildConstant(Ty, 0).getReg(0);
7555fe6060f1SDimitry Andric   auto Sub = MIRBuilder.buildSub(Ty, Zero, SrcReg).getReg(0);
7556fe6060f1SDimitry Andric   MIRBuilder.buildSMax(MI.getOperand(0), SrcReg, Sub);
7557fe6060f1SDimitry Andric   MI.eraseFromParent();
7558fe6060f1SDimitry Andric   return Legalized;
7559fe6060f1SDimitry Andric }
7560349cc55cSDimitry Andric 
7561349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
7562349cc55cSDimitry Andric LegalizerHelper::lowerVectorReduction(MachineInstr &MI) {
7563349cc55cSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
7564349cc55cSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
7565349cc55cSDimitry Andric   LLT DstTy = MRI.getType(SrcReg);
7566349cc55cSDimitry Andric 
7567349cc55cSDimitry Andric   // The source could be a scalar if the IR type was <1 x sN>.
7568349cc55cSDimitry Andric   if (SrcTy.isScalar()) {
7569349cc55cSDimitry Andric     if (DstTy.getSizeInBits() > SrcTy.getSizeInBits())
7570349cc55cSDimitry Andric       return UnableToLegalize; // FIXME: handle extension.
7571349cc55cSDimitry Andric     // This can be just a plain copy.
7572349cc55cSDimitry Andric     Observer.changingInstr(MI);
7573349cc55cSDimitry Andric     MI.setDesc(MIRBuilder.getTII().get(TargetOpcode::COPY));
7574349cc55cSDimitry Andric     Observer.changedInstr(MI);
7575349cc55cSDimitry Andric     return Legalized;
7576349cc55cSDimitry Andric   }
7577*06c3fb27SDimitry Andric   return UnableToLegalize;
7578349cc55cSDimitry Andric }
7579349cc55cSDimitry Andric 
7580349cc55cSDimitry Andric static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
7581349cc55cSDimitry Andric   // On Darwin, -Os means optimize for size without hurting performance, so
7582349cc55cSDimitry Andric   // only really optimize for size when -Oz (MinSize) is used.
7583349cc55cSDimitry Andric   if (MF.getTarget().getTargetTriple().isOSDarwin())
7584349cc55cSDimitry Andric     return MF.getFunction().hasMinSize();
7585349cc55cSDimitry Andric   return MF.getFunction().hasOptSize();
7586349cc55cSDimitry Andric }
7587349cc55cSDimitry Andric 
7588349cc55cSDimitry Andric // Returns a list of types to use for memory op lowering in MemOps. A partial
7589349cc55cSDimitry Andric // port of findOptimalMemOpLowering in TargetLowering.
7590349cc55cSDimitry Andric static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps,
7591349cc55cSDimitry Andric                                           unsigned Limit, const MemOp &Op,
7592349cc55cSDimitry Andric                                           unsigned DstAS, unsigned SrcAS,
7593349cc55cSDimitry Andric                                           const AttributeList &FuncAttributes,
7594349cc55cSDimitry Andric                                           const TargetLowering &TLI) {
7595349cc55cSDimitry Andric   if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign())
7596349cc55cSDimitry Andric     return false;
7597349cc55cSDimitry Andric 
7598349cc55cSDimitry Andric   LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes);
7599349cc55cSDimitry Andric 
7600349cc55cSDimitry Andric   if (Ty == LLT()) {
7601349cc55cSDimitry Andric     // Use the largest scalar type whose alignment constraints are satisfied.
7602349cc55cSDimitry Andric     // We only need to check DstAlign here as SrcAlign is always greater or
7603349cc55cSDimitry Andric     // equal to DstAlign (or zero).
7604349cc55cSDimitry Andric     Ty = LLT::scalar(64);
7605349cc55cSDimitry Andric     if (Op.isFixedDstAlign())
7606349cc55cSDimitry Andric       while (Op.getDstAlign() < Ty.getSizeInBytes() &&
7607349cc55cSDimitry Andric              !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS, Op.getDstAlign()))
7608349cc55cSDimitry Andric         Ty = LLT::scalar(Ty.getSizeInBytes());
7609349cc55cSDimitry Andric     assert(Ty.getSizeInBits() > 0 && "Could not find valid type");
7610349cc55cSDimitry Andric     // FIXME: check for the largest legal type we can load/store to.
7611349cc55cSDimitry Andric   }
7612349cc55cSDimitry Andric 
7613349cc55cSDimitry Andric   unsigned NumMemOps = 0;
7614349cc55cSDimitry Andric   uint64_t Size = Op.size();
7615349cc55cSDimitry Andric   while (Size) {
7616349cc55cSDimitry Andric     unsigned TySize = Ty.getSizeInBytes();
7617349cc55cSDimitry Andric     while (TySize > Size) {
7618349cc55cSDimitry Andric       // For now, only use non-vector load / store's for the left-over pieces.
7619349cc55cSDimitry Andric       LLT NewTy = Ty;
7620349cc55cSDimitry Andric       // FIXME: check for mem op safety and legality of the types. Not all of
7621349cc55cSDimitry Andric       // SDAGisms map cleanly to GISel concepts.
7622349cc55cSDimitry Andric       if (NewTy.isVector())
7623349cc55cSDimitry Andric         NewTy = NewTy.getSizeInBits() > 64 ? LLT::scalar(64) : LLT::scalar(32);
7624*06c3fb27SDimitry Andric       NewTy = LLT::scalar(llvm::bit_floor(NewTy.getSizeInBits() - 1));
7625349cc55cSDimitry Andric       unsigned NewTySize = NewTy.getSizeInBytes();
7626349cc55cSDimitry Andric       assert(NewTySize > 0 && "Could not find appropriate type");
7627349cc55cSDimitry Andric 
7628349cc55cSDimitry Andric       // If the new LLT cannot cover all of the remaining bits, then consider
7629349cc55cSDimitry Andric       // issuing a (or a pair of) unaligned and overlapping load / store.
7630bdd1243dSDimitry Andric       unsigned Fast;
7631349cc55cSDimitry Andric       // Need to get a VT equivalent for allowMisalignedMemoryAccesses().
7632349cc55cSDimitry Andric       MVT VT = getMVTForLLT(Ty);
7633349cc55cSDimitry Andric       if (NumMemOps && Op.allowOverlap() && NewTySize < Size &&
7634349cc55cSDimitry Andric           TLI.allowsMisalignedMemoryAccesses(
7635349cc55cSDimitry Andric               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
7636349cc55cSDimitry Andric               MachineMemOperand::MONone, &Fast) &&
7637349cc55cSDimitry Andric           Fast)
7638349cc55cSDimitry Andric         TySize = Size;
7639349cc55cSDimitry Andric       else {
7640349cc55cSDimitry Andric         Ty = NewTy;
7641349cc55cSDimitry Andric         TySize = NewTySize;
7642349cc55cSDimitry Andric       }
7643349cc55cSDimitry Andric     }
7644349cc55cSDimitry Andric 
7645349cc55cSDimitry Andric     if (++NumMemOps > Limit)
7646349cc55cSDimitry Andric       return false;
7647349cc55cSDimitry Andric 
7648349cc55cSDimitry Andric     MemOps.push_back(Ty);
7649349cc55cSDimitry Andric     Size -= TySize;
7650349cc55cSDimitry Andric   }
7651349cc55cSDimitry Andric 
7652349cc55cSDimitry Andric   return true;
7653349cc55cSDimitry Andric }
7654349cc55cSDimitry Andric 
7655349cc55cSDimitry Andric static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
7656349cc55cSDimitry Andric   if (Ty.isVector())
7657349cc55cSDimitry Andric     return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
7658349cc55cSDimitry Andric                                 Ty.getNumElements());
7659349cc55cSDimitry Andric   return IntegerType::get(C, Ty.getSizeInBits());
7660349cc55cSDimitry Andric }
7661349cc55cSDimitry Andric 
7662349cc55cSDimitry Andric // Get a vectorized representation of the memset value operand, GISel edition.
7663349cc55cSDimitry Andric static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB) {
7664349cc55cSDimitry Andric   MachineRegisterInfo &MRI = *MIB.getMRI();
7665349cc55cSDimitry Andric   unsigned NumBits = Ty.getScalarSizeInBits();
7666349cc55cSDimitry Andric   auto ValVRegAndVal = getIConstantVRegValWithLookThrough(Val, MRI);
7667349cc55cSDimitry Andric   if (!Ty.isVector() && ValVRegAndVal) {
766881ad6265SDimitry Andric     APInt Scalar = ValVRegAndVal->Value.trunc(8);
7669349cc55cSDimitry Andric     APInt SplatVal = APInt::getSplat(NumBits, Scalar);
7670349cc55cSDimitry Andric     return MIB.buildConstant(Ty, SplatVal).getReg(0);
7671349cc55cSDimitry Andric   }
7672349cc55cSDimitry Andric 
7673349cc55cSDimitry Andric   // Extend the byte value to the larger type, and then multiply by a magic
7674349cc55cSDimitry Andric   // value 0x010101... in order to replicate it across every byte.
7675349cc55cSDimitry Andric   // Unless it's zero, in which case just emit a larger G_CONSTANT 0.
7676349cc55cSDimitry Andric   if (ValVRegAndVal && ValVRegAndVal->Value == 0) {
7677349cc55cSDimitry Andric     return MIB.buildConstant(Ty, 0).getReg(0);
7678349cc55cSDimitry Andric   }
7679349cc55cSDimitry Andric 
7680349cc55cSDimitry Andric   LLT ExtType = Ty.getScalarType();
7681349cc55cSDimitry Andric   auto ZExt = MIB.buildZExtOrTrunc(ExtType, Val);
7682349cc55cSDimitry Andric   if (NumBits > 8) {
7683349cc55cSDimitry Andric     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
7684349cc55cSDimitry Andric     auto MagicMI = MIB.buildConstant(ExtType, Magic);
7685349cc55cSDimitry Andric     Val = MIB.buildMul(ExtType, ZExt, MagicMI).getReg(0);
7686349cc55cSDimitry Andric   }
7687349cc55cSDimitry Andric 
7688349cc55cSDimitry Andric   // For vector types create a G_BUILD_VECTOR.
7689349cc55cSDimitry Andric   if (Ty.isVector())
7690349cc55cSDimitry Andric     Val = MIB.buildSplatVector(Ty, Val).getReg(0);
7691349cc55cSDimitry Andric 
7692349cc55cSDimitry Andric   return Val;
7693349cc55cSDimitry Andric }
7694349cc55cSDimitry Andric 
7695349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
7696349cc55cSDimitry Andric LegalizerHelper::lowerMemset(MachineInstr &MI, Register Dst, Register Val,
7697349cc55cSDimitry Andric                              uint64_t KnownLen, Align Alignment,
7698349cc55cSDimitry Andric                              bool IsVolatile) {
7699349cc55cSDimitry Andric   auto &MF = *MI.getParent()->getParent();
7700349cc55cSDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
7701349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
7702349cc55cSDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
7703349cc55cSDimitry Andric 
7704349cc55cSDimitry Andric   assert(KnownLen != 0 && "Have a zero length memset length!");
7705349cc55cSDimitry Andric 
7706349cc55cSDimitry Andric   bool DstAlignCanChange = false;
7707349cc55cSDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
7708349cc55cSDimitry Andric   bool OptSize = shouldLowerMemFuncForSize(MF);
7709349cc55cSDimitry Andric 
7710349cc55cSDimitry Andric   MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
7711349cc55cSDimitry Andric   if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
7712349cc55cSDimitry Andric     DstAlignCanChange = true;
7713349cc55cSDimitry Andric 
7714349cc55cSDimitry Andric   unsigned Limit = TLI.getMaxStoresPerMemset(OptSize);
7715349cc55cSDimitry Andric   std::vector<LLT> MemOps;
7716349cc55cSDimitry Andric 
7717349cc55cSDimitry Andric   const auto &DstMMO = **MI.memoperands_begin();
7718349cc55cSDimitry Andric   MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
7719349cc55cSDimitry Andric 
7720349cc55cSDimitry Andric   auto ValVRegAndVal = getIConstantVRegValWithLookThrough(Val, MRI);
7721349cc55cSDimitry Andric   bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0;
7722349cc55cSDimitry Andric 
7723349cc55cSDimitry Andric   if (!findGISelOptimalMemOpLowering(MemOps, Limit,
7724349cc55cSDimitry Andric                                      MemOp::Set(KnownLen, DstAlignCanChange,
7725349cc55cSDimitry Andric                                                 Alignment,
7726349cc55cSDimitry Andric                                                 /*IsZeroMemset=*/IsZeroVal,
7727349cc55cSDimitry Andric                                                 /*IsVolatile=*/IsVolatile),
7728349cc55cSDimitry Andric                                      DstPtrInfo.getAddrSpace(), ~0u,
7729349cc55cSDimitry Andric                                      MF.getFunction().getAttributes(), TLI))
7730349cc55cSDimitry Andric     return UnableToLegalize;
7731349cc55cSDimitry Andric 
7732349cc55cSDimitry Andric   if (DstAlignCanChange) {
7733349cc55cSDimitry Andric     // Get an estimate of the type from the LLT.
7734349cc55cSDimitry Andric     Type *IRTy = getTypeForLLT(MemOps[0], C);
7735349cc55cSDimitry Andric     Align NewAlign = DL.getABITypeAlign(IRTy);
7736349cc55cSDimitry Andric     if (NewAlign > Alignment) {
7737349cc55cSDimitry Andric       Alignment = NewAlign;
7738349cc55cSDimitry Andric       unsigned FI = FIDef->getOperand(1).getIndex();
7739349cc55cSDimitry Andric       // Give the stack frame object a larger alignment if needed.
7740349cc55cSDimitry Andric       if (MFI.getObjectAlign(FI) < Alignment)
7741349cc55cSDimitry Andric         MFI.setObjectAlignment(FI, Alignment);
7742349cc55cSDimitry Andric     }
7743349cc55cSDimitry Andric   }
7744349cc55cSDimitry Andric 
7745349cc55cSDimitry Andric   MachineIRBuilder MIB(MI);
7746349cc55cSDimitry Andric   // Find the largest store and generate the bit pattern for it.
7747349cc55cSDimitry Andric   LLT LargestTy = MemOps[0];
7748349cc55cSDimitry Andric   for (unsigned i = 1; i < MemOps.size(); i++)
7749349cc55cSDimitry Andric     if (MemOps[i].getSizeInBits() > LargestTy.getSizeInBits())
7750349cc55cSDimitry Andric       LargestTy = MemOps[i];
7751349cc55cSDimitry Andric 
7752349cc55cSDimitry Andric   // The memset stored value is always defined as an s8, so in order to make it
7753349cc55cSDimitry Andric   // work with larger store types we need to repeat the bit pattern across the
7754349cc55cSDimitry Andric   // wider type.
7755349cc55cSDimitry Andric   Register MemSetValue = getMemsetValue(Val, LargestTy, MIB);
7756349cc55cSDimitry Andric 
7757349cc55cSDimitry Andric   if (!MemSetValue)
7758349cc55cSDimitry Andric     return UnableToLegalize;
7759349cc55cSDimitry Andric 
7760349cc55cSDimitry Andric   // Generate the stores. For each store type in the list, we generate the
7761349cc55cSDimitry Andric   // matching store of that type to the destination address.
7762349cc55cSDimitry Andric   LLT PtrTy = MRI.getType(Dst);
7763349cc55cSDimitry Andric   unsigned DstOff = 0;
7764349cc55cSDimitry Andric   unsigned Size = KnownLen;
7765349cc55cSDimitry Andric   for (unsigned I = 0; I < MemOps.size(); I++) {
7766349cc55cSDimitry Andric     LLT Ty = MemOps[I];
7767349cc55cSDimitry Andric     unsigned TySize = Ty.getSizeInBytes();
7768349cc55cSDimitry Andric     if (TySize > Size) {
7769349cc55cSDimitry Andric       // Issuing an unaligned load / store pair that overlaps with the previous
7770349cc55cSDimitry Andric       // pair. Adjust the offset accordingly.
7771349cc55cSDimitry Andric       assert(I == MemOps.size() - 1 && I != 0);
7772349cc55cSDimitry Andric       DstOff -= TySize - Size;
7773349cc55cSDimitry Andric     }
7774349cc55cSDimitry Andric 
7775349cc55cSDimitry Andric     // If this store is smaller than the largest store see whether we can get
7776349cc55cSDimitry Andric     // the smaller value for free with a truncate.
7777349cc55cSDimitry Andric     Register Value = MemSetValue;
7778349cc55cSDimitry Andric     if (Ty.getSizeInBits() < LargestTy.getSizeInBits()) {
7779349cc55cSDimitry Andric       MVT VT = getMVTForLLT(Ty);
7780349cc55cSDimitry Andric       MVT LargestVT = getMVTForLLT(LargestTy);
7781349cc55cSDimitry Andric       if (!LargestTy.isVector() && !Ty.isVector() &&
7782349cc55cSDimitry Andric           TLI.isTruncateFree(LargestVT, VT))
7783349cc55cSDimitry Andric         Value = MIB.buildTrunc(Ty, MemSetValue).getReg(0);
7784349cc55cSDimitry Andric       else
7785349cc55cSDimitry Andric         Value = getMemsetValue(Val, Ty, MIB);
7786349cc55cSDimitry Andric       if (!Value)
7787349cc55cSDimitry Andric         return UnableToLegalize;
7788349cc55cSDimitry Andric     }
7789349cc55cSDimitry Andric 
7790349cc55cSDimitry Andric     auto *StoreMMO = MF.getMachineMemOperand(&DstMMO, DstOff, Ty);
7791349cc55cSDimitry Andric 
7792349cc55cSDimitry Andric     Register Ptr = Dst;
7793349cc55cSDimitry Andric     if (DstOff != 0) {
7794349cc55cSDimitry Andric       auto Offset =
7795349cc55cSDimitry Andric           MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), DstOff);
7796349cc55cSDimitry Andric       Ptr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0);
7797349cc55cSDimitry Andric     }
7798349cc55cSDimitry Andric 
7799349cc55cSDimitry Andric     MIB.buildStore(Value, Ptr, *StoreMMO);
7800349cc55cSDimitry Andric     DstOff += Ty.getSizeInBytes();
7801349cc55cSDimitry Andric     Size -= TySize;
7802349cc55cSDimitry Andric   }
7803349cc55cSDimitry Andric 
7804349cc55cSDimitry Andric   MI.eraseFromParent();
7805349cc55cSDimitry Andric   return Legalized;
7806349cc55cSDimitry Andric }
7807349cc55cSDimitry Andric 
7808349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
7809349cc55cSDimitry Andric LegalizerHelper::lowerMemcpyInline(MachineInstr &MI) {
7810349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MEMCPY_INLINE);
7811349cc55cSDimitry Andric 
7812*06c3fb27SDimitry Andric   auto [Dst, Src, Len] = MI.getFirst3Regs();
7813349cc55cSDimitry Andric 
7814349cc55cSDimitry Andric   const auto *MMOIt = MI.memoperands_begin();
7815349cc55cSDimitry Andric   const MachineMemOperand *MemOp = *MMOIt;
7816349cc55cSDimitry Andric   bool IsVolatile = MemOp->isVolatile();
7817349cc55cSDimitry Andric 
7818349cc55cSDimitry Andric   // See if this is a constant length copy
7819349cc55cSDimitry Andric   auto LenVRegAndVal = getIConstantVRegValWithLookThrough(Len, MRI);
7820349cc55cSDimitry Andric   // FIXME: support dynamically sized G_MEMCPY_INLINE
782181ad6265SDimitry Andric   assert(LenVRegAndVal &&
7822349cc55cSDimitry Andric          "inline memcpy with dynamic size is not yet supported");
7823349cc55cSDimitry Andric   uint64_t KnownLen = LenVRegAndVal->Value.getZExtValue();
7824349cc55cSDimitry Andric   if (KnownLen == 0) {
7825349cc55cSDimitry Andric     MI.eraseFromParent();
7826349cc55cSDimitry Andric     return Legalized;
7827349cc55cSDimitry Andric   }
7828349cc55cSDimitry Andric 
7829349cc55cSDimitry Andric   const auto &DstMMO = **MI.memoperands_begin();
7830349cc55cSDimitry Andric   const auto &SrcMMO = **std::next(MI.memoperands_begin());
7831349cc55cSDimitry Andric   Align DstAlign = DstMMO.getBaseAlign();
7832349cc55cSDimitry Andric   Align SrcAlign = SrcMMO.getBaseAlign();
7833349cc55cSDimitry Andric 
7834349cc55cSDimitry Andric   return lowerMemcpyInline(MI, Dst, Src, KnownLen, DstAlign, SrcAlign,
7835349cc55cSDimitry Andric                            IsVolatile);
7836349cc55cSDimitry Andric }
7837349cc55cSDimitry Andric 
7838349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
7839349cc55cSDimitry Andric LegalizerHelper::lowerMemcpyInline(MachineInstr &MI, Register Dst, Register Src,
7840349cc55cSDimitry Andric                                    uint64_t KnownLen, Align DstAlign,
7841349cc55cSDimitry Andric                                    Align SrcAlign, bool IsVolatile) {
7842349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MEMCPY_INLINE);
7843349cc55cSDimitry Andric   return lowerMemcpy(MI, Dst, Src, KnownLen,
7844349cc55cSDimitry Andric                      std::numeric_limits<uint64_t>::max(), DstAlign, SrcAlign,
7845349cc55cSDimitry Andric                      IsVolatile);
7846349cc55cSDimitry Andric }
7847349cc55cSDimitry Andric 
7848349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
7849349cc55cSDimitry Andric LegalizerHelper::lowerMemcpy(MachineInstr &MI, Register Dst, Register Src,
7850349cc55cSDimitry Andric                              uint64_t KnownLen, uint64_t Limit, Align DstAlign,
7851349cc55cSDimitry Andric                              Align SrcAlign, bool IsVolatile) {
7852349cc55cSDimitry Andric   auto &MF = *MI.getParent()->getParent();
7853349cc55cSDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
7854349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
7855349cc55cSDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
7856349cc55cSDimitry Andric 
7857349cc55cSDimitry Andric   assert(KnownLen != 0 && "Have a zero length memcpy length!");
7858349cc55cSDimitry Andric 
7859349cc55cSDimitry Andric   bool DstAlignCanChange = false;
7860349cc55cSDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
786181ad6265SDimitry Andric   Align Alignment = std::min(DstAlign, SrcAlign);
7862349cc55cSDimitry Andric 
7863349cc55cSDimitry Andric   MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
7864349cc55cSDimitry Andric   if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
7865349cc55cSDimitry Andric     DstAlignCanChange = true;
7866349cc55cSDimitry Andric 
7867349cc55cSDimitry Andric   // FIXME: infer better src pointer alignment like SelectionDAG does here.
7868349cc55cSDimitry Andric   // FIXME: also use the equivalent of isMemSrcFromConstant and alwaysinlining
7869349cc55cSDimitry Andric   // if the memcpy is in a tail call position.
7870349cc55cSDimitry Andric 
7871349cc55cSDimitry Andric   std::vector<LLT> MemOps;
7872349cc55cSDimitry Andric 
7873349cc55cSDimitry Andric   const auto &DstMMO = **MI.memoperands_begin();
7874349cc55cSDimitry Andric   const auto &SrcMMO = **std::next(MI.memoperands_begin());
7875349cc55cSDimitry Andric   MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
7876349cc55cSDimitry Andric   MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
7877349cc55cSDimitry Andric 
7878349cc55cSDimitry Andric   if (!findGISelOptimalMemOpLowering(
7879349cc55cSDimitry Andric           MemOps, Limit,
7880349cc55cSDimitry Andric           MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign,
7881349cc55cSDimitry Andric                       IsVolatile),
7882349cc55cSDimitry Andric           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
7883349cc55cSDimitry Andric           MF.getFunction().getAttributes(), TLI))
7884349cc55cSDimitry Andric     return UnableToLegalize;
7885349cc55cSDimitry Andric 
7886349cc55cSDimitry Andric   if (DstAlignCanChange) {
7887349cc55cSDimitry Andric     // Get an estimate of the type from the LLT.
7888349cc55cSDimitry Andric     Type *IRTy = getTypeForLLT(MemOps[0], C);
7889349cc55cSDimitry Andric     Align NewAlign = DL.getABITypeAlign(IRTy);
7890349cc55cSDimitry Andric 
7891349cc55cSDimitry Andric     // Don't promote to an alignment that would require dynamic stack
7892349cc55cSDimitry Andric     // realignment.
7893349cc55cSDimitry Andric     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
7894349cc55cSDimitry Andric     if (!TRI->hasStackRealignment(MF))
7895349cc55cSDimitry Andric       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
789681ad6265SDimitry Andric         NewAlign = NewAlign.previous();
7897349cc55cSDimitry Andric 
7898349cc55cSDimitry Andric     if (NewAlign > Alignment) {
7899349cc55cSDimitry Andric       Alignment = NewAlign;
7900349cc55cSDimitry Andric       unsigned FI = FIDef->getOperand(1).getIndex();
7901349cc55cSDimitry Andric       // Give the stack frame object a larger alignment if needed.
7902349cc55cSDimitry Andric       if (MFI.getObjectAlign(FI) < Alignment)
7903349cc55cSDimitry Andric         MFI.setObjectAlignment(FI, Alignment);
7904349cc55cSDimitry Andric     }
7905349cc55cSDimitry Andric   }
7906349cc55cSDimitry Andric 
7907349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Inlining memcpy: " << MI << " into loads & stores\n");
7908349cc55cSDimitry Andric 
7909349cc55cSDimitry Andric   MachineIRBuilder MIB(MI);
7910349cc55cSDimitry Andric   // Now we need to emit a pair of load and stores for each of the types we've
7911349cc55cSDimitry Andric   // collected. I.e. for each type, generate a load from the source pointer of
7912349cc55cSDimitry Andric   // that type width, and then generate a corresponding store to the dest buffer
7913349cc55cSDimitry Andric   // of that value loaded. This can result in a sequence of loads and stores
7914349cc55cSDimitry Andric   // mixed types, depending on what the target specifies as good types to use.
7915349cc55cSDimitry Andric   unsigned CurrOffset = 0;
7916349cc55cSDimitry Andric   unsigned Size = KnownLen;
7917349cc55cSDimitry Andric   for (auto CopyTy : MemOps) {
7918349cc55cSDimitry Andric     // Issuing an unaligned load / store pair  that overlaps with the previous
7919349cc55cSDimitry Andric     // pair. Adjust the offset accordingly.
7920349cc55cSDimitry Andric     if (CopyTy.getSizeInBytes() > Size)
7921349cc55cSDimitry Andric       CurrOffset -= CopyTy.getSizeInBytes() - Size;
7922349cc55cSDimitry Andric 
7923349cc55cSDimitry Andric     // Construct MMOs for the accesses.
7924349cc55cSDimitry Andric     auto *LoadMMO =
7925349cc55cSDimitry Andric         MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes());
7926349cc55cSDimitry Andric     auto *StoreMMO =
7927349cc55cSDimitry Andric         MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes());
7928349cc55cSDimitry Andric 
7929349cc55cSDimitry Andric     // Create the load.
7930349cc55cSDimitry Andric     Register LoadPtr = Src;
7931349cc55cSDimitry Andric     Register Offset;
7932349cc55cSDimitry Andric     if (CurrOffset != 0) {
79334824e7fdSDimitry Andric       LLT SrcTy = MRI.getType(Src);
79344824e7fdSDimitry Andric       Offset = MIB.buildConstant(LLT::scalar(SrcTy.getSizeInBits()), CurrOffset)
7935349cc55cSDimitry Andric                    .getReg(0);
79364824e7fdSDimitry Andric       LoadPtr = MIB.buildPtrAdd(SrcTy, Src, Offset).getReg(0);
7937349cc55cSDimitry Andric     }
7938349cc55cSDimitry Andric     auto LdVal = MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO);
7939349cc55cSDimitry Andric 
7940349cc55cSDimitry Andric     // Create the store.
79414824e7fdSDimitry Andric     Register StorePtr = Dst;
79424824e7fdSDimitry Andric     if (CurrOffset != 0) {
79434824e7fdSDimitry Andric       LLT DstTy = MRI.getType(Dst);
79444824e7fdSDimitry Andric       StorePtr = MIB.buildPtrAdd(DstTy, Dst, Offset).getReg(0);
79454824e7fdSDimitry Andric     }
7946349cc55cSDimitry Andric     MIB.buildStore(LdVal, StorePtr, *StoreMMO);
7947349cc55cSDimitry Andric     CurrOffset += CopyTy.getSizeInBytes();
7948349cc55cSDimitry Andric     Size -= CopyTy.getSizeInBytes();
7949349cc55cSDimitry Andric   }
7950349cc55cSDimitry Andric 
7951349cc55cSDimitry Andric   MI.eraseFromParent();
7952349cc55cSDimitry Andric   return Legalized;
7953349cc55cSDimitry Andric }
7954349cc55cSDimitry Andric 
7955349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
7956349cc55cSDimitry Andric LegalizerHelper::lowerMemmove(MachineInstr &MI, Register Dst, Register Src,
7957349cc55cSDimitry Andric                               uint64_t KnownLen, Align DstAlign, Align SrcAlign,
7958349cc55cSDimitry Andric                               bool IsVolatile) {
7959349cc55cSDimitry Andric   auto &MF = *MI.getParent()->getParent();
7960349cc55cSDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
7961349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
7962349cc55cSDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
7963349cc55cSDimitry Andric 
7964349cc55cSDimitry Andric   assert(KnownLen != 0 && "Have a zero length memmove length!");
7965349cc55cSDimitry Andric 
7966349cc55cSDimitry Andric   bool DstAlignCanChange = false;
7967349cc55cSDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
7968349cc55cSDimitry Andric   bool OptSize = shouldLowerMemFuncForSize(MF);
796981ad6265SDimitry Andric   Align Alignment = std::min(DstAlign, SrcAlign);
7970349cc55cSDimitry Andric 
7971349cc55cSDimitry Andric   MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
7972349cc55cSDimitry Andric   if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
7973349cc55cSDimitry Andric     DstAlignCanChange = true;
7974349cc55cSDimitry Andric 
7975349cc55cSDimitry Andric   unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize);
7976349cc55cSDimitry Andric   std::vector<LLT> MemOps;
7977349cc55cSDimitry Andric 
7978349cc55cSDimitry Andric   const auto &DstMMO = **MI.memoperands_begin();
7979349cc55cSDimitry Andric   const auto &SrcMMO = **std::next(MI.memoperands_begin());
7980349cc55cSDimitry Andric   MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
7981349cc55cSDimitry Andric   MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
7982349cc55cSDimitry Andric 
7983349cc55cSDimitry Andric   // FIXME: SelectionDAG always passes false for 'AllowOverlap', apparently due
7984349cc55cSDimitry Andric   // to a bug in it's findOptimalMemOpLowering implementation. For now do the
7985349cc55cSDimitry Andric   // same thing here.
7986349cc55cSDimitry Andric   if (!findGISelOptimalMemOpLowering(
7987349cc55cSDimitry Andric           MemOps, Limit,
7988349cc55cSDimitry Andric           MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign,
7989349cc55cSDimitry Andric                       /*IsVolatile*/ true),
7990349cc55cSDimitry Andric           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
7991349cc55cSDimitry Andric           MF.getFunction().getAttributes(), TLI))
7992349cc55cSDimitry Andric     return UnableToLegalize;
7993349cc55cSDimitry Andric 
7994349cc55cSDimitry Andric   if (DstAlignCanChange) {
7995349cc55cSDimitry Andric     // Get an estimate of the type from the LLT.
7996349cc55cSDimitry Andric     Type *IRTy = getTypeForLLT(MemOps[0], C);
7997349cc55cSDimitry Andric     Align NewAlign = DL.getABITypeAlign(IRTy);
7998349cc55cSDimitry Andric 
7999349cc55cSDimitry Andric     // Don't promote to an alignment that would require dynamic stack
8000349cc55cSDimitry Andric     // realignment.
8001349cc55cSDimitry Andric     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
8002349cc55cSDimitry Andric     if (!TRI->hasStackRealignment(MF))
8003349cc55cSDimitry Andric       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
800481ad6265SDimitry Andric         NewAlign = NewAlign.previous();
8005349cc55cSDimitry Andric 
8006349cc55cSDimitry Andric     if (NewAlign > Alignment) {
8007349cc55cSDimitry Andric       Alignment = NewAlign;
8008349cc55cSDimitry Andric       unsigned FI = FIDef->getOperand(1).getIndex();
8009349cc55cSDimitry Andric       // Give the stack frame object a larger alignment if needed.
8010349cc55cSDimitry Andric       if (MFI.getObjectAlign(FI) < Alignment)
8011349cc55cSDimitry Andric         MFI.setObjectAlignment(FI, Alignment);
8012349cc55cSDimitry Andric     }
8013349cc55cSDimitry Andric   }
8014349cc55cSDimitry Andric 
8015349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Inlining memmove: " << MI << " into loads & stores\n");
8016349cc55cSDimitry Andric 
8017349cc55cSDimitry Andric   MachineIRBuilder MIB(MI);
8018349cc55cSDimitry Andric   // Memmove requires that we perform the loads first before issuing the stores.
8019349cc55cSDimitry Andric   // Apart from that, this loop is pretty much doing the same thing as the
8020349cc55cSDimitry Andric   // memcpy codegen function.
8021349cc55cSDimitry Andric   unsigned CurrOffset = 0;
8022349cc55cSDimitry Andric   SmallVector<Register, 16> LoadVals;
8023349cc55cSDimitry Andric   for (auto CopyTy : MemOps) {
8024349cc55cSDimitry Andric     // Construct MMO for the load.
8025349cc55cSDimitry Andric     auto *LoadMMO =
8026349cc55cSDimitry Andric         MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes());
8027349cc55cSDimitry Andric 
8028349cc55cSDimitry Andric     // Create the load.
8029349cc55cSDimitry Andric     Register LoadPtr = Src;
8030349cc55cSDimitry Andric     if (CurrOffset != 0) {
80314824e7fdSDimitry Andric       LLT SrcTy = MRI.getType(Src);
8032349cc55cSDimitry Andric       auto Offset =
80334824e7fdSDimitry Andric           MIB.buildConstant(LLT::scalar(SrcTy.getSizeInBits()), CurrOffset);
80344824e7fdSDimitry Andric       LoadPtr = MIB.buildPtrAdd(SrcTy, Src, Offset).getReg(0);
8035349cc55cSDimitry Andric     }
8036349cc55cSDimitry Andric     LoadVals.push_back(MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO).getReg(0));
8037349cc55cSDimitry Andric     CurrOffset += CopyTy.getSizeInBytes();
8038349cc55cSDimitry Andric   }
8039349cc55cSDimitry Andric 
8040349cc55cSDimitry Andric   CurrOffset = 0;
8041349cc55cSDimitry Andric   for (unsigned I = 0; I < MemOps.size(); ++I) {
8042349cc55cSDimitry Andric     LLT CopyTy = MemOps[I];
8043349cc55cSDimitry Andric     // Now store the values loaded.
8044349cc55cSDimitry Andric     auto *StoreMMO =
8045349cc55cSDimitry Andric         MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes());
8046349cc55cSDimitry Andric 
8047349cc55cSDimitry Andric     Register StorePtr = Dst;
8048349cc55cSDimitry Andric     if (CurrOffset != 0) {
80494824e7fdSDimitry Andric       LLT DstTy = MRI.getType(Dst);
8050349cc55cSDimitry Andric       auto Offset =
80514824e7fdSDimitry Andric           MIB.buildConstant(LLT::scalar(DstTy.getSizeInBits()), CurrOffset);
80524824e7fdSDimitry Andric       StorePtr = MIB.buildPtrAdd(DstTy, Dst, Offset).getReg(0);
8053349cc55cSDimitry Andric     }
8054349cc55cSDimitry Andric     MIB.buildStore(LoadVals[I], StorePtr, *StoreMMO);
8055349cc55cSDimitry Andric     CurrOffset += CopyTy.getSizeInBytes();
8056349cc55cSDimitry Andric   }
8057349cc55cSDimitry Andric   MI.eraseFromParent();
8058349cc55cSDimitry Andric   return Legalized;
8059349cc55cSDimitry Andric }
8060349cc55cSDimitry Andric 
8061349cc55cSDimitry Andric LegalizerHelper::LegalizeResult
8062349cc55cSDimitry Andric LegalizerHelper::lowerMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
8063349cc55cSDimitry Andric   const unsigned Opc = MI.getOpcode();
8064349cc55cSDimitry Andric   // This combine is fairly complex so it's not written with a separate
8065349cc55cSDimitry Andric   // matcher function.
8066349cc55cSDimitry Andric   assert((Opc == TargetOpcode::G_MEMCPY || Opc == TargetOpcode::G_MEMMOVE ||
8067349cc55cSDimitry Andric           Opc == TargetOpcode::G_MEMSET) &&
8068349cc55cSDimitry Andric          "Expected memcpy like instruction");
8069349cc55cSDimitry Andric 
8070349cc55cSDimitry Andric   auto MMOIt = MI.memoperands_begin();
8071349cc55cSDimitry Andric   const MachineMemOperand *MemOp = *MMOIt;
8072349cc55cSDimitry Andric 
8073349cc55cSDimitry Andric   Align DstAlign = MemOp->getBaseAlign();
8074349cc55cSDimitry Andric   Align SrcAlign;
8075*06c3fb27SDimitry Andric   auto [Dst, Src, Len] = MI.getFirst3Regs();
8076349cc55cSDimitry Andric 
8077349cc55cSDimitry Andric   if (Opc != TargetOpcode::G_MEMSET) {
8078349cc55cSDimitry Andric     assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI");
8079349cc55cSDimitry Andric     MemOp = *(++MMOIt);
8080349cc55cSDimitry Andric     SrcAlign = MemOp->getBaseAlign();
8081349cc55cSDimitry Andric   }
8082349cc55cSDimitry Andric 
8083349cc55cSDimitry Andric   // See if this is a constant length copy
8084349cc55cSDimitry Andric   auto LenVRegAndVal = getIConstantVRegValWithLookThrough(Len, MRI);
8085349cc55cSDimitry Andric   if (!LenVRegAndVal)
8086349cc55cSDimitry Andric     return UnableToLegalize;
8087349cc55cSDimitry Andric   uint64_t KnownLen = LenVRegAndVal->Value.getZExtValue();
8088349cc55cSDimitry Andric 
8089349cc55cSDimitry Andric   if (KnownLen == 0) {
8090349cc55cSDimitry Andric     MI.eraseFromParent();
8091349cc55cSDimitry Andric     return Legalized;
8092349cc55cSDimitry Andric   }
8093349cc55cSDimitry Andric 
8094349cc55cSDimitry Andric   bool IsVolatile = MemOp->isVolatile();
8095349cc55cSDimitry Andric   if (Opc == TargetOpcode::G_MEMCPY_INLINE)
8096349cc55cSDimitry Andric     return lowerMemcpyInline(MI, Dst, Src, KnownLen, DstAlign, SrcAlign,
8097349cc55cSDimitry Andric                              IsVolatile);
8098349cc55cSDimitry Andric 
8099349cc55cSDimitry Andric   // Don't try to optimize volatile.
8100349cc55cSDimitry Andric   if (IsVolatile)
8101349cc55cSDimitry Andric     return UnableToLegalize;
8102349cc55cSDimitry Andric 
8103349cc55cSDimitry Andric   if (MaxLen && KnownLen > MaxLen)
8104349cc55cSDimitry Andric     return UnableToLegalize;
8105349cc55cSDimitry Andric 
8106349cc55cSDimitry Andric   if (Opc == TargetOpcode::G_MEMCPY) {
8107349cc55cSDimitry Andric     auto &MF = *MI.getParent()->getParent();
8108349cc55cSDimitry Andric     const auto &TLI = *MF.getSubtarget().getTargetLowering();
8109349cc55cSDimitry Andric     bool OptSize = shouldLowerMemFuncForSize(MF);
8110349cc55cSDimitry Andric     uint64_t Limit = TLI.getMaxStoresPerMemcpy(OptSize);
8111349cc55cSDimitry Andric     return lowerMemcpy(MI, Dst, Src, KnownLen, Limit, DstAlign, SrcAlign,
8112349cc55cSDimitry Andric                        IsVolatile);
8113349cc55cSDimitry Andric   }
8114349cc55cSDimitry Andric   if (Opc == TargetOpcode::G_MEMMOVE)
8115349cc55cSDimitry Andric     return lowerMemmove(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile);
8116349cc55cSDimitry Andric   if (Opc == TargetOpcode::G_MEMSET)
8117349cc55cSDimitry Andric     return lowerMemset(MI, Dst, Src, KnownLen, DstAlign, IsVolatile);
8118349cc55cSDimitry Andric   return UnableToLegalize;
8119349cc55cSDimitry Andric }
8120