xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp (revision 5678d1d98a348f315453555377ccb28821a2ffcd)
10b57cec5SDimitry Andric //===-- lib/CodeGen/GlobalISel/GICombinerHelper.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 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h"
95f757f3fSDimitry Andric #include "llvm/ADT/APFloat.h"
105f757f3fSDimitry Andric #include "llvm/ADT/STLExtras.h"
11fe6060f1SDimitry Andric #include "llvm/ADT/SetVector.h"
12fe6060f1SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
130b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
148bcb0991SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
15fe6060f1SDimitry Andric #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
16349cc55cSDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
175ffd83dbSDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
185ffd83dbSDimitry Andric #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/Utils.h"
2106c3fb27SDimitry Andric #include "llvm/CodeGen/LowLevelTypeUtils.h"
22fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
238bcb0991SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
25e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
2781ad6265SDimitry Andric #include "llvm/CodeGen/RegisterBankInfo.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
298bcb0991SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
30fe6060f1SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
31349cc55cSDimitry Andric #include "llvm/IR/DataLayout.h"
32bdd1243dSDimitry Andric #include "llvm/IR/InstrTypes.h"
33349cc55cSDimitry Andric #include "llvm/Support/Casting.h"
34349cc55cSDimitry Andric #include "llvm/Support/DivisionByConstantInfo.h"
355ffd83dbSDimitry Andric #include "llvm/Support/MathExtras.h"
3681ad6265SDimitry Andric #include "llvm/Target/TargetMachine.h"
37bdd1243dSDimitry Andric #include <cmath>
38bdd1243dSDimitry Andric #include <optional>
39fe6060f1SDimitry Andric #include <tuple>
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric #define DEBUG_TYPE "gi-combiner"
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric using namespace llvm;
445ffd83dbSDimitry Andric using namespace MIPatternMatch;
450b57cec5SDimitry Andric 
468bcb0991SDimitry Andric // Option to allow testing of the combiner while no targets know about indexed
478bcb0991SDimitry Andric // addressing.
488bcb0991SDimitry Andric static cl::opt<bool>
498bcb0991SDimitry Andric     ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
508bcb0991SDimitry Andric                        cl::desc("Force all indexed operations to be "
518bcb0991SDimitry Andric                                 "legal for the GlobalISel combiner"));
528bcb0991SDimitry Andric 
530b57cec5SDimitry Andric CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
54bdd1243dSDimitry Andric                                MachineIRBuilder &B, bool IsPreLegalize,
55bdd1243dSDimitry Andric                                GISelKnownBits *KB, MachineDominatorTree *MDT,
565ffd83dbSDimitry Andric                                const LegalizerInfo *LI)
57349cc55cSDimitry Andric     : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB),
58bdd1243dSDimitry Andric       MDT(MDT), IsPreLegalize(IsPreLegalize), LI(LI),
59bdd1243dSDimitry Andric       RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
60349cc55cSDimitry Andric       TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
618bcb0991SDimitry Andric   (void)this->KB;
628bcb0991SDimitry Andric }
630b57cec5SDimitry Andric 
64e8d8bef9SDimitry Andric const TargetLowering &CombinerHelper::getTargetLowering() const {
65e8d8bef9SDimitry Andric   return *Builder.getMF().getSubtarget().getTargetLowering();
66e8d8bef9SDimitry Andric }
67e8d8bef9SDimitry Andric 
68e8d8bef9SDimitry Andric /// \returns The little endian in-memory byte position of byte \p I in a
69e8d8bef9SDimitry Andric /// \p ByteWidth bytes wide type.
70e8d8bef9SDimitry Andric ///
71e8d8bef9SDimitry Andric /// E.g. Given a 4-byte type x, x[0] -> byte 0
72e8d8bef9SDimitry Andric static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
73e8d8bef9SDimitry Andric   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
74e8d8bef9SDimitry Andric   return I;
75e8d8bef9SDimitry Andric }
76e8d8bef9SDimitry Andric 
77349cc55cSDimitry Andric /// Determines the LogBase2 value for a non-null input value using the
78349cc55cSDimitry Andric /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
79349cc55cSDimitry Andric static Register buildLogBase2(Register V, MachineIRBuilder &MIB) {
80349cc55cSDimitry Andric   auto &MRI = *MIB.getMRI();
81349cc55cSDimitry Andric   LLT Ty = MRI.getType(V);
82349cc55cSDimitry Andric   auto Ctlz = MIB.buildCTLZ(Ty, V);
83349cc55cSDimitry Andric   auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
84349cc55cSDimitry Andric   return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
85349cc55cSDimitry Andric }
86349cc55cSDimitry Andric 
87e8d8bef9SDimitry Andric /// \returns The big endian in-memory byte position of byte \p I in a
88e8d8bef9SDimitry Andric /// \p ByteWidth bytes wide type.
89e8d8bef9SDimitry Andric ///
90e8d8bef9SDimitry Andric /// E.g. Given a 4-byte type x, x[0] -> byte 3
91e8d8bef9SDimitry Andric static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
92e8d8bef9SDimitry Andric   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
93e8d8bef9SDimitry Andric   return ByteWidth - I - 1;
94e8d8bef9SDimitry Andric }
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric /// Given a map from byte offsets in memory to indices in a load/store,
97e8d8bef9SDimitry Andric /// determine if that map corresponds to a little or big endian byte pattern.
98e8d8bef9SDimitry Andric ///
99e8d8bef9SDimitry Andric /// \param MemOffset2Idx maps memory offsets to address offsets.
100e8d8bef9SDimitry Andric /// \param LowestIdx is the lowest index in \p MemOffset2Idx.
101e8d8bef9SDimitry Andric ///
102bdd1243dSDimitry Andric /// \returns true if the map corresponds to a big endian byte pattern, false if
103bdd1243dSDimitry Andric /// it corresponds to a little endian byte pattern, and std::nullopt otherwise.
104e8d8bef9SDimitry Andric ///
105e8d8bef9SDimitry Andric /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
106e8d8bef9SDimitry Andric /// are as follows:
107e8d8bef9SDimitry Andric ///
108e8d8bef9SDimitry Andric /// AddrOffset   Little endian    Big endian
109e8d8bef9SDimitry Andric /// 0            0                3
110e8d8bef9SDimitry Andric /// 1            1                2
111e8d8bef9SDimitry Andric /// 2            2                1
112e8d8bef9SDimitry Andric /// 3            3                0
113bdd1243dSDimitry Andric static std::optional<bool>
114e8d8bef9SDimitry Andric isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
115e8d8bef9SDimitry Andric             int64_t LowestIdx) {
116e8d8bef9SDimitry Andric   // Need at least two byte positions to decide on endianness.
117e8d8bef9SDimitry Andric   unsigned Width = MemOffset2Idx.size();
118e8d8bef9SDimitry Andric   if (Width < 2)
119bdd1243dSDimitry Andric     return std::nullopt;
120e8d8bef9SDimitry Andric   bool BigEndian = true, LittleEndian = true;
121e8d8bef9SDimitry Andric   for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
122e8d8bef9SDimitry Andric     auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
123e8d8bef9SDimitry Andric     if (MemOffsetAndIdx == MemOffset2Idx.end())
124bdd1243dSDimitry Andric       return std::nullopt;
125e8d8bef9SDimitry Andric     const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
126e8d8bef9SDimitry Andric     assert(Idx >= 0 && "Expected non-negative byte offset?");
127e8d8bef9SDimitry Andric     LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
128e8d8bef9SDimitry Andric     BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
129e8d8bef9SDimitry Andric     if (!BigEndian && !LittleEndian)
130bdd1243dSDimitry Andric       return std::nullopt;
131e8d8bef9SDimitry Andric   }
132e8d8bef9SDimitry Andric 
133e8d8bef9SDimitry Andric   assert((BigEndian != LittleEndian) &&
134e8d8bef9SDimitry Andric          "Pattern cannot be both big and little endian!");
135e8d8bef9SDimitry Andric   return BigEndian;
136e8d8bef9SDimitry Andric }
137e8d8bef9SDimitry Andric 
138bdd1243dSDimitry Andric bool CombinerHelper::isPreLegalize() const { return IsPreLegalize; }
13981ad6265SDimitry Andric 
14081ad6265SDimitry Andric bool CombinerHelper::isLegal(const LegalityQuery &Query) const {
14181ad6265SDimitry Andric   assert(LI && "Must have LegalizerInfo to query isLegal!");
14281ad6265SDimitry Andric   return LI->getAction(Query).Action == LegalizeActions::Legal;
14381ad6265SDimitry Andric }
14481ad6265SDimitry Andric 
145e8d8bef9SDimitry Andric bool CombinerHelper::isLegalOrBeforeLegalizer(
146e8d8bef9SDimitry Andric     const LegalityQuery &Query) const {
14781ad6265SDimitry Andric   return isPreLegalize() || isLegal(Query);
14881ad6265SDimitry Andric }
14981ad6265SDimitry Andric 
15081ad6265SDimitry Andric bool CombinerHelper::isConstantLegalOrBeforeLegalizer(const LLT Ty) const {
15181ad6265SDimitry Andric   if (!Ty.isVector())
15281ad6265SDimitry Andric     return isLegalOrBeforeLegalizer({TargetOpcode::G_CONSTANT, {Ty}});
15381ad6265SDimitry Andric   // Vector constants are represented as a G_BUILD_VECTOR of scalar G_CONSTANTs.
15481ad6265SDimitry Andric   if (isPreLegalize())
15581ad6265SDimitry Andric     return true;
15681ad6265SDimitry Andric   LLT EltTy = Ty.getElementType();
15781ad6265SDimitry Andric   return isLegal({TargetOpcode::G_BUILD_VECTOR, {Ty, EltTy}}) &&
15881ad6265SDimitry Andric          isLegal({TargetOpcode::G_CONSTANT, {EltTy}});
159e8d8bef9SDimitry Andric }
160e8d8bef9SDimitry Andric 
1610b57cec5SDimitry Andric void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
1620b57cec5SDimitry Andric                                     Register ToReg) const {
1630b57cec5SDimitry Andric   Observer.changingAllUsesOfReg(MRI, FromReg);
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   if (MRI.constrainRegAttrs(ToReg, FromReg))
1660b57cec5SDimitry Andric     MRI.replaceRegWith(FromReg, ToReg);
1670b57cec5SDimitry Andric   else
1680b57cec5SDimitry Andric     Builder.buildCopy(ToReg, FromReg);
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   Observer.finishedChangingAllUsesOfReg();
1710b57cec5SDimitry Andric }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
1740b57cec5SDimitry Andric                                       MachineOperand &FromRegOp,
1750b57cec5SDimitry Andric                                       Register ToReg) const {
1760b57cec5SDimitry Andric   assert(FromRegOp.getParent() && "Expected an operand in an MI");
1770b57cec5SDimitry Andric   Observer.changingInstr(*FromRegOp.getParent());
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   FromRegOp.setReg(ToReg);
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   Observer.changedInstr(*FromRegOp.getParent());
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
184349cc55cSDimitry Andric void CombinerHelper::replaceOpcodeWith(MachineInstr &FromMI,
185349cc55cSDimitry Andric                                        unsigned ToOpcode) const {
186349cc55cSDimitry Andric   Observer.changingInstr(FromMI);
187349cc55cSDimitry Andric 
188349cc55cSDimitry Andric   FromMI.setDesc(Builder.getTII().get(ToOpcode));
189349cc55cSDimitry Andric 
190349cc55cSDimitry Andric   Observer.changedInstr(FromMI);
191349cc55cSDimitry Andric }
192349cc55cSDimitry Andric 
193349cc55cSDimitry Andric const RegisterBank *CombinerHelper::getRegBank(Register Reg) const {
194349cc55cSDimitry Andric   return RBI->getRegBank(Reg, MRI, *TRI);
195349cc55cSDimitry Andric }
196349cc55cSDimitry Andric 
197349cc55cSDimitry Andric void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) {
198349cc55cSDimitry Andric   if (RegBank)
199349cc55cSDimitry Andric     MRI.setRegBank(Reg, *RegBank);
200349cc55cSDimitry Andric }
201349cc55cSDimitry Andric 
2020b57cec5SDimitry Andric bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
2030b57cec5SDimitry Andric   if (matchCombineCopy(MI)) {
2040b57cec5SDimitry Andric     applyCombineCopy(MI);
2050b57cec5SDimitry Andric     return true;
2060b57cec5SDimitry Andric   }
2070b57cec5SDimitry Andric   return false;
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
2100b57cec5SDimitry Andric   if (MI.getOpcode() != TargetOpcode::COPY)
2110b57cec5SDimitry Andric     return false;
2128bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2138bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2145ffd83dbSDimitry Andric   return canReplaceReg(DstReg, SrcReg, MRI);
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
2178bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2188bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2190b57cec5SDimitry Andric   MI.eraseFromParent();
2200b57cec5SDimitry Andric   replaceRegWith(MRI, DstReg, SrcReg);
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric 
2238bcb0991SDimitry Andric bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
2248bcb0991SDimitry Andric   bool IsUndef = false;
2258bcb0991SDimitry Andric   SmallVector<Register, 4> Ops;
2268bcb0991SDimitry Andric   if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
2278bcb0991SDimitry Andric     applyCombineConcatVectors(MI, IsUndef, Ops);
2288bcb0991SDimitry Andric     return true;
2298bcb0991SDimitry Andric   }
2308bcb0991SDimitry Andric   return false;
2318bcb0991SDimitry Andric }
2328bcb0991SDimitry Andric 
2338bcb0991SDimitry Andric bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
2348bcb0991SDimitry Andric                                                SmallVectorImpl<Register> &Ops) {
2358bcb0991SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
2368bcb0991SDimitry Andric          "Invalid instruction");
2378bcb0991SDimitry Andric   IsUndef = true;
2388bcb0991SDimitry Andric   MachineInstr *Undef = nullptr;
2398bcb0991SDimitry Andric 
2408bcb0991SDimitry Andric   // Walk over all the operands of concat vectors and check if they are
2418bcb0991SDimitry Andric   // build_vector themselves or undef.
2428bcb0991SDimitry Andric   // Then collect their operands in Ops.
243480093f4SDimitry Andric   for (const MachineOperand &MO : MI.uses()) {
2448bcb0991SDimitry Andric     Register Reg = MO.getReg();
2458bcb0991SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
2468bcb0991SDimitry Andric     assert(Def && "Operand not defined");
2478bcb0991SDimitry Andric     switch (Def->getOpcode()) {
2488bcb0991SDimitry Andric     case TargetOpcode::G_BUILD_VECTOR:
2498bcb0991SDimitry Andric       IsUndef = false;
2508bcb0991SDimitry Andric       // Remember the operands of the build_vector to fold
2518bcb0991SDimitry Andric       // them into the yet-to-build flattened concat vectors.
252480093f4SDimitry Andric       for (const MachineOperand &BuildVecMO : Def->uses())
2538bcb0991SDimitry Andric         Ops.push_back(BuildVecMO.getReg());
2548bcb0991SDimitry Andric       break;
2558bcb0991SDimitry Andric     case TargetOpcode::G_IMPLICIT_DEF: {
2568bcb0991SDimitry Andric       LLT OpType = MRI.getType(Reg);
2578bcb0991SDimitry Andric       // Keep one undef value for all the undef operands.
2588bcb0991SDimitry Andric       if (!Undef) {
2598bcb0991SDimitry Andric         Builder.setInsertPt(*MI.getParent(), MI);
2608bcb0991SDimitry Andric         Undef = Builder.buildUndef(OpType.getScalarType());
2618bcb0991SDimitry Andric       }
2628bcb0991SDimitry Andric       assert(MRI.getType(Undef->getOperand(0).getReg()) ==
2638bcb0991SDimitry Andric                  OpType.getScalarType() &&
2648bcb0991SDimitry Andric              "All undefs should have the same type");
2658bcb0991SDimitry Andric       // Break the undef vector in as many scalar elements as needed
2668bcb0991SDimitry Andric       // for the flattening.
2678bcb0991SDimitry Andric       for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
2688bcb0991SDimitry Andric            EltIdx != EltEnd; ++EltIdx)
2698bcb0991SDimitry Andric         Ops.push_back(Undef->getOperand(0).getReg());
2708bcb0991SDimitry Andric       break;
2718bcb0991SDimitry Andric     }
2728bcb0991SDimitry Andric     default:
2738bcb0991SDimitry Andric       return false;
2748bcb0991SDimitry Andric     }
2758bcb0991SDimitry Andric   }
2768bcb0991SDimitry Andric   return true;
2778bcb0991SDimitry Andric }
2788bcb0991SDimitry Andric void CombinerHelper::applyCombineConcatVectors(
2798bcb0991SDimitry Andric     MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
2808bcb0991SDimitry Andric   // We determined that the concat_vectors can be flatten.
2818bcb0991SDimitry Andric   // Generate the flattened build_vector.
2828bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2838bcb0991SDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
2848bcb0991SDimitry Andric   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
2858bcb0991SDimitry Andric 
2868bcb0991SDimitry Andric   // Note: IsUndef is sort of redundant. We could have determine it by
2878bcb0991SDimitry Andric   // checking that at all Ops are undef.  Alternatively, we could have
2888bcb0991SDimitry Andric   // generate a build_vector of undefs and rely on another combine to
2898bcb0991SDimitry Andric   // clean that up.  For now, given we already gather this information
2908bcb0991SDimitry Andric   // in tryCombineConcatVectors, just save compile time and issue the
2918bcb0991SDimitry Andric   // right thing.
2928bcb0991SDimitry Andric   if (IsUndef)
2938bcb0991SDimitry Andric     Builder.buildUndef(NewDstReg);
2948bcb0991SDimitry Andric   else
2958bcb0991SDimitry Andric     Builder.buildBuildVector(NewDstReg, Ops);
2968bcb0991SDimitry Andric   MI.eraseFromParent();
2978bcb0991SDimitry Andric   replaceRegWith(MRI, DstReg, NewDstReg);
2988bcb0991SDimitry Andric }
2998bcb0991SDimitry Andric 
3008bcb0991SDimitry Andric bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
3018bcb0991SDimitry Andric   SmallVector<Register, 4> Ops;
3028bcb0991SDimitry Andric   if (matchCombineShuffleVector(MI, Ops)) {
3038bcb0991SDimitry Andric     applyCombineShuffleVector(MI, Ops);
3048bcb0991SDimitry Andric     return true;
3058bcb0991SDimitry Andric   }
3068bcb0991SDimitry Andric   return false;
3078bcb0991SDimitry Andric }
3088bcb0991SDimitry Andric 
3098bcb0991SDimitry Andric bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
3108bcb0991SDimitry Andric                                                SmallVectorImpl<Register> &Ops) {
3118bcb0991SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
3128bcb0991SDimitry Andric          "Invalid instruction kind");
3138bcb0991SDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
3148bcb0991SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
3158bcb0991SDimitry Andric   LLT SrcType = MRI.getType(Src1);
316480093f4SDimitry Andric   // As bizarre as it may look, shuffle vector can actually produce
317480093f4SDimitry Andric   // scalar! This is because at the IR level a <1 x ty> shuffle
318480093f4SDimitry Andric   // vector is perfectly valid.
319480093f4SDimitry Andric   unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
320480093f4SDimitry Andric   unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
3218bcb0991SDimitry Andric 
3228bcb0991SDimitry Andric   // If the resulting vector is smaller than the size of the source
3238bcb0991SDimitry Andric   // vectors being concatenated, we won't be able to replace the
3248bcb0991SDimitry Andric   // shuffle vector into a concat_vectors.
3258bcb0991SDimitry Andric   //
3268bcb0991SDimitry Andric   // Note: We may still be able to produce a concat_vectors fed by
3278bcb0991SDimitry Andric   //       extract_vector_elt and so on. It is less clear that would
3288bcb0991SDimitry Andric   //       be better though, so don't bother for now.
329480093f4SDimitry Andric   //
330480093f4SDimitry Andric   // If the destination is a scalar, the size of the sources doesn't
331480093f4SDimitry Andric   // matter. we will lower the shuffle to a plain copy. This will
332480093f4SDimitry Andric   // work only if the source and destination have the same size. But
333480093f4SDimitry Andric   // that's covered by the next condition.
334480093f4SDimitry Andric   //
335480093f4SDimitry Andric   // TODO: If the size between the source and destination don't match
336480093f4SDimitry Andric   //       we could still emit an extract vector element in that case.
337480093f4SDimitry Andric   if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
3388bcb0991SDimitry Andric     return false;
3398bcb0991SDimitry Andric 
3408bcb0991SDimitry Andric   // Check that the shuffle mask can be broken evenly between the
3418bcb0991SDimitry Andric   // different sources.
3428bcb0991SDimitry Andric   if (DstNumElts % SrcNumElts != 0)
3438bcb0991SDimitry Andric     return false;
3448bcb0991SDimitry Andric 
3458bcb0991SDimitry Andric   // Mask length is a multiple of the source vector length.
3468bcb0991SDimitry Andric   // Check if the shuffle is some kind of concatenation of the input
3478bcb0991SDimitry Andric   // vectors.
3488bcb0991SDimitry Andric   unsigned NumConcat = DstNumElts / SrcNumElts;
3498bcb0991SDimitry Andric   SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
350480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
3518bcb0991SDimitry Andric   for (unsigned i = 0; i != DstNumElts; ++i) {
3528bcb0991SDimitry Andric     int Idx = Mask[i];
3538bcb0991SDimitry Andric     // Undef value.
3548bcb0991SDimitry Andric     if (Idx < 0)
3558bcb0991SDimitry Andric       continue;
3568bcb0991SDimitry Andric     // Ensure the indices in each SrcType sized piece are sequential and that
3578bcb0991SDimitry Andric     // the same source is used for the whole piece.
3588bcb0991SDimitry Andric     if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3598bcb0991SDimitry Andric         (ConcatSrcs[i / SrcNumElts] >= 0 &&
3608bcb0991SDimitry Andric          ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
3618bcb0991SDimitry Andric       return false;
3628bcb0991SDimitry Andric     // Remember which source this index came from.
3638bcb0991SDimitry Andric     ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3648bcb0991SDimitry Andric   }
3658bcb0991SDimitry Andric 
3668bcb0991SDimitry Andric   // The shuffle is concatenating multiple vectors together.
3678bcb0991SDimitry Andric   // Collect the different operands for that.
3688bcb0991SDimitry Andric   Register UndefReg;
3698bcb0991SDimitry Andric   Register Src2 = MI.getOperand(2).getReg();
3708bcb0991SDimitry Andric   for (auto Src : ConcatSrcs) {
3718bcb0991SDimitry Andric     if (Src < 0) {
3728bcb0991SDimitry Andric       if (!UndefReg) {
3738bcb0991SDimitry Andric         Builder.setInsertPt(*MI.getParent(), MI);
3748bcb0991SDimitry Andric         UndefReg = Builder.buildUndef(SrcType).getReg(0);
3758bcb0991SDimitry Andric       }
3768bcb0991SDimitry Andric       Ops.push_back(UndefReg);
3778bcb0991SDimitry Andric     } else if (Src == 0)
3788bcb0991SDimitry Andric       Ops.push_back(Src1);
3798bcb0991SDimitry Andric     else
3808bcb0991SDimitry Andric       Ops.push_back(Src2);
3818bcb0991SDimitry Andric   }
3828bcb0991SDimitry Andric   return true;
3838bcb0991SDimitry Andric }
3848bcb0991SDimitry Andric 
3858bcb0991SDimitry Andric void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
3868bcb0991SDimitry Andric                                                const ArrayRef<Register> Ops) {
3878bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3888bcb0991SDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
3898bcb0991SDimitry Andric   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
3908bcb0991SDimitry Andric 
391480093f4SDimitry Andric   if (Ops.size() == 1)
392480093f4SDimitry Andric     Builder.buildCopy(NewDstReg, Ops[0]);
393480093f4SDimitry Andric   else
394bdd1243dSDimitry Andric     Builder.buildMergeLikeInstr(NewDstReg, Ops);
3958bcb0991SDimitry Andric 
3968bcb0991SDimitry Andric   MI.eraseFromParent();
3978bcb0991SDimitry Andric   replaceRegWith(MRI, DstReg, NewDstReg);
3988bcb0991SDimitry Andric }
3998bcb0991SDimitry Andric 
4005f757f3fSDimitry Andric bool CombinerHelper::matchShuffleToExtract(MachineInstr &MI) {
4015f757f3fSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
4025f757f3fSDimitry Andric          "Invalid instruction kind");
4035f757f3fSDimitry Andric 
4045f757f3fSDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
4055f757f3fSDimitry Andric   return Mask.size() == 1;
4065f757f3fSDimitry Andric }
4075f757f3fSDimitry Andric 
4085f757f3fSDimitry Andric void CombinerHelper::applyShuffleToExtract(MachineInstr &MI) {
4095f757f3fSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
4105f757f3fSDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
4115f757f3fSDimitry Andric 
4125f757f3fSDimitry Andric   int I = MI.getOperand(3).getShuffleMask()[0];
4135f757f3fSDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
4145f757f3fSDimitry Andric   LLT Src1Ty = MRI.getType(Src1);
4155f757f3fSDimitry Andric   int Src1NumElts = Src1Ty.isVector() ? Src1Ty.getNumElements() : 1;
4165f757f3fSDimitry Andric   Register SrcReg;
4175f757f3fSDimitry Andric   if (I >= Src1NumElts) {
4185f757f3fSDimitry Andric     SrcReg = MI.getOperand(2).getReg();
4195f757f3fSDimitry Andric     I -= Src1NumElts;
4205f757f3fSDimitry Andric   } else if (I >= 0)
4215f757f3fSDimitry Andric     SrcReg = Src1;
4225f757f3fSDimitry Andric 
4235f757f3fSDimitry Andric   if (I < 0)
4245f757f3fSDimitry Andric     Builder.buildUndef(DstReg);
4255f757f3fSDimitry Andric   else if (!MRI.getType(SrcReg).isVector())
4265f757f3fSDimitry Andric     Builder.buildCopy(DstReg, SrcReg);
4275f757f3fSDimitry Andric   else
4285f757f3fSDimitry Andric     Builder.buildExtractVectorElementConstant(DstReg, SrcReg, I);
4295f757f3fSDimitry Andric 
4305f757f3fSDimitry Andric   MI.eraseFromParent();
4315f757f3fSDimitry Andric }
4325f757f3fSDimitry Andric 
4330b57cec5SDimitry Andric namespace {
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric /// Select a preference between two uses. CurrentUse is the current preference
4360b57cec5SDimitry Andric /// while *ForCandidate is attributes of the candidate under consideration.
43706c3fb27SDimitry Andric PreferredTuple ChoosePreferredUse(MachineInstr &LoadMI,
43806c3fb27SDimitry Andric                                   PreferredTuple &CurrentUse,
4395ffd83dbSDimitry Andric                                   const LLT TyForCandidate,
4400b57cec5SDimitry Andric                                   unsigned OpcodeForCandidate,
4410b57cec5SDimitry Andric                                   MachineInstr *MIForCandidate) {
4420b57cec5SDimitry Andric   if (!CurrentUse.Ty.isValid()) {
4430b57cec5SDimitry Andric     if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
4440b57cec5SDimitry Andric         CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
4450b57cec5SDimitry Andric       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4460b57cec5SDimitry Andric     return CurrentUse;
4470b57cec5SDimitry Andric   }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   // We permit the extend to hoist through basic blocks but this is only
4500b57cec5SDimitry Andric   // sensible if the target has extending loads. If you end up lowering back
4510b57cec5SDimitry Andric   // into a load and extend during the legalizer then the end result is
4520b57cec5SDimitry Andric   // hoisting the extend up to the load.
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   // Prefer defined extensions to undefined extensions as these are more
4550b57cec5SDimitry Andric   // likely to reduce the number of instructions.
4560b57cec5SDimitry Andric   if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
4570b57cec5SDimitry Andric       CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
4580b57cec5SDimitry Andric     return CurrentUse;
4590b57cec5SDimitry Andric   else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
4600b57cec5SDimitry Andric            OpcodeForCandidate != TargetOpcode::G_ANYEXT)
4610b57cec5SDimitry Andric     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   // Prefer sign extensions to zero extensions as sign-extensions tend to be
46406c3fb27SDimitry Andric   // more expensive. Don't do this if the load is already a zero-extend load
46506c3fb27SDimitry Andric   // though, otherwise we'll rewrite a zero-extend load into a sign-extend
46606c3fb27SDimitry Andric   // later.
46706c3fb27SDimitry Andric   if (!isa<GZExtLoad>(LoadMI) && CurrentUse.Ty == TyForCandidate) {
4680b57cec5SDimitry Andric     if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
4690b57cec5SDimitry Andric         OpcodeForCandidate == TargetOpcode::G_ZEXT)
4700b57cec5SDimitry Andric       return CurrentUse;
4710b57cec5SDimitry Andric     else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
4720b57cec5SDimitry Andric              OpcodeForCandidate == TargetOpcode::G_SEXT)
4730b57cec5SDimitry Andric       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4740b57cec5SDimitry Andric   }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   // This is potentially target specific. We've chosen the largest type
4770b57cec5SDimitry Andric   // because G_TRUNC is usually free. One potential catch with this is that
4780b57cec5SDimitry Andric   // some targets have a reduced number of larger registers than smaller
4790b57cec5SDimitry Andric   // registers and this choice potentially increases the live-range for the
4800b57cec5SDimitry Andric   // larger value.
4810b57cec5SDimitry Andric   if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
4820b57cec5SDimitry Andric     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4830b57cec5SDimitry Andric   }
4840b57cec5SDimitry Andric   return CurrentUse;
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric /// Find a suitable place to insert some instructions and insert them. This
4880b57cec5SDimitry Andric /// function accounts for special cases like inserting before a PHI node.
4890b57cec5SDimitry Andric /// The current strategy for inserting before PHI's is to duplicate the
4900b57cec5SDimitry Andric /// instructions for each predecessor. However, while that's ok for G_TRUNC
4910b57cec5SDimitry Andric /// on most targets since it generally requires no code, other targets/cases may
4920b57cec5SDimitry Andric /// want to try harder to find a dominating block.
4930b57cec5SDimitry Andric static void InsertInsnsWithoutSideEffectsBeforeUse(
4940b57cec5SDimitry Andric     MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
4950b57cec5SDimitry Andric     std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
4960b57cec5SDimitry Andric                        MachineOperand &UseMO)>
4970b57cec5SDimitry Andric         Inserter) {
4980b57cec5SDimitry Andric   MachineInstr &UseMI = *UseMO.getParent();
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   MachineBasicBlock *InsertBB = UseMI.getParent();
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   // If the use is a PHI then we want the predecessor block instead.
5030b57cec5SDimitry Andric   if (UseMI.isPHI()) {
5040b57cec5SDimitry Andric     MachineOperand *PredBB = std::next(&UseMO);
5050b57cec5SDimitry Andric     InsertBB = PredBB->getMBB();
5060b57cec5SDimitry Andric   }
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // If the block is the same block as the def then we want to insert just after
5090b57cec5SDimitry Andric   // the def instead of at the start of the block.
5100b57cec5SDimitry Andric   if (InsertBB == DefMI.getParent()) {
5110b57cec5SDimitry Andric     MachineBasicBlock::iterator InsertPt = &DefMI;
5120b57cec5SDimitry Andric     Inserter(InsertBB, std::next(InsertPt), UseMO);
5130b57cec5SDimitry Andric     return;
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   // Otherwise we want the start of the BB
5170b57cec5SDimitry Andric   Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
5180b57cec5SDimitry Andric }
5190b57cec5SDimitry Andric } // end anonymous namespace
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
5220b57cec5SDimitry Andric   PreferredTuple Preferred;
5230b57cec5SDimitry Andric   if (matchCombineExtendingLoads(MI, Preferred)) {
5240b57cec5SDimitry Andric     applyCombineExtendingLoads(MI, Preferred);
5250b57cec5SDimitry Andric     return true;
5260b57cec5SDimitry Andric   }
5270b57cec5SDimitry Andric   return false;
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
530bdd1243dSDimitry Andric static unsigned getExtLoadOpcForExtend(unsigned ExtOpc) {
531bdd1243dSDimitry Andric   unsigned CandidateLoadOpc;
532bdd1243dSDimitry Andric   switch (ExtOpc) {
533bdd1243dSDimitry Andric   case TargetOpcode::G_ANYEXT:
534bdd1243dSDimitry Andric     CandidateLoadOpc = TargetOpcode::G_LOAD;
535bdd1243dSDimitry Andric     break;
536bdd1243dSDimitry Andric   case TargetOpcode::G_SEXT:
537bdd1243dSDimitry Andric     CandidateLoadOpc = TargetOpcode::G_SEXTLOAD;
538bdd1243dSDimitry Andric     break;
539bdd1243dSDimitry Andric   case TargetOpcode::G_ZEXT:
540bdd1243dSDimitry Andric     CandidateLoadOpc = TargetOpcode::G_ZEXTLOAD;
541bdd1243dSDimitry Andric     break;
542bdd1243dSDimitry Andric   default:
543bdd1243dSDimitry Andric     llvm_unreachable("Unexpected extend opc");
544bdd1243dSDimitry Andric   }
545bdd1243dSDimitry Andric   return CandidateLoadOpc;
546bdd1243dSDimitry Andric }
547bdd1243dSDimitry Andric 
5480b57cec5SDimitry Andric bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
5490b57cec5SDimitry Andric                                                 PreferredTuple &Preferred) {
5500b57cec5SDimitry Andric   // We match the loads and follow the uses to the extend instead of matching
5510b57cec5SDimitry Andric   // the extends and following the def to the load. This is because the load
5520b57cec5SDimitry Andric   // must remain in the same position for correctness (unless we also add code
5530b57cec5SDimitry Andric   // to find a safe place to sink it) whereas the extend is freely movable.
5540b57cec5SDimitry Andric   // It also prevents us from duplicating the load for the volatile case or just
5550b57cec5SDimitry Andric   // for performance.
556fe6060f1SDimitry Andric   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
557fe6060f1SDimitry Andric   if (!LoadMI)
5580b57cec5SDimitry Andric     return false;
5590b57cec5SDimitry Andric 
560fe6060f1SDimitry Andric   Register LoadReg = LoadMI->getDstReg();
5610b57cec5SDimitry Andric 
562fe6060f1SDimitry Andric   LLT LoadValueTy = MRI.getType(LoadReg);
5630b57cec5SDimitry Andric   if (!LoadValueTy.isScalar())
5640b57cec5SDimitry Andric     return false;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // Most architectures are going to legalize <s8 loads into at least a 1 byte
5670b57cec5SDimitry Andric   // load, and the MMOs can only describe memory accesses in multiples of bytes.
5680b57cec5SDimitry Andric   // If we try to perform extload combining on those, we can end up with
5690b57cec5SDimitry Andric   // %a(s8) = extload %ptr (load 1 byte from %ptr)
5700b57cec5SDimitry Andric   // ... which is an illegal extload instruction.
5710b57cec5SDimitry Andric   if (LoadValueTy.getSizeInBits() < 8)
5720b57cec5SDimitry Andric     return false;
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   // For non power-of-2 types, they will very likely be legalized into multiple
5750b57cec5SDimitry Andric   // loads. Don't bother trying to match them into extending loads.
57606c3fb27SDimitry Andric   if (!llvm::has_single_bit<uint32_t>(LoadValueTy.getSizeInBits()))
5770b57cec5SDimitry Andric     return false;
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   // Find the preferred type aside from the any-extends (unless it's the only
5800b57cec5SDimitry Andric   // one) and non-extending ops. We'll emit an extending load to that type and
5810b57cec5SDimitry Andric   // and emit a variant of (extend (trunc X)) for the others according to the
5820b57cec5SDimitry Andric   // relative type sizes. At the same time, pick an extend to use based on the
5830b57cec5SDimitry Andric   // extend involved in the chosen type.
584fe6060f1SDimitry Andric   unsigned PreferredOpcode =
585fe6060f1SDimitry Andric       isa<GLoad>(&MI)
5860b57cec5SDimitry Andric           ? TargetOpcode::G_ANYEXT
587fe6060f1SDimitry Andric           : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
5880b57cec5SDimitry Andric   Preferred = {LLT(), PreferredOpcode, nullptr};
589fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
5900b57cec5SDimitry Andric     if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
5910b57cec5SDimitry Andric         UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
5925ffd83dbSDimitry Andric         (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
593fe6060f1SDimitry Andric       const auto &MMO = LoadMI->getMMO();
594*5678d1d9SDimitry Andric       // Don't do anything for atomics.
595*5678d1d9SDimitry Andric       if (MMO.isAtomic())
596fe6060f1SDimitry Andric         continue;
5975ffd83dbSDimitry Andric       // Check for legality.
598bdd1243dSDimitry Andric       if (!isPreLegalize()) {
599349cc55cSDimitry Andric         LegalityQuery::MemDesc MMDesc(MMO);
600bdd1243dSDimitry Andric         unsigned CandidateLoadOpc = getExtLoadOpcForExtend(UseMI.getOpcode());
6015ffd83dbSDimitry Andric         LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
602fe6060f1SDimitry Andric         LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
603bdd1243dSDimitry Andric         if (LI->getAction({CandidateLoadOpc, {UseTy, SrcTy}, {MMDesc}})
604fe6060f1SDimitry Andric                 .Action != LegalizeActions::Legal)
6055ffd83dbSDimitry Andric           continue;
6065ffd83dbSDimitry Andric       }
60706c3fb27SDimitry Andric       Preferred = ChoosePreferredUse(MI, Preferred,
6080b57cec5SDimitry Andric                                      MRI.getType(UseMI.getOperand(0).getReg()),
6090b57cec5SDimitry Andric                                      UseMI.getOpcode(), &UseMI);
6100b57cec5SDimitry Andric     }
6110b57cec5SDimitry Andric   }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   // There were no extends
6140b57cec5SDimitry Andric   if (!Preferred.MI)
6150b57cec5SDimitry Andric     return false;
6160b57cec5SDimitry Andric   // It should be impossible to chose an extend without selecting a different
6170b57cec5SDimitry Andric   // type since by definition the result of an extend is larger.
6180b57cec5SDimitry Andric   assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
6210b57cec5SDimitry Andric   return true;
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
6250b57cec5SDimitry Andric                                                 PreferredTuple &Preferred) {
6260b57cec5SDimitry Andric   // Rewrite the load to the chosen extending load.
6270b57cec5SDimitry Andric   Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   // Inserter to insert a truncate back to the original type at a given point
6300b57cec5SDimitry Andric   // with some basic CSE to limit truncate duplication to one per BB.
6310b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
6320b57cec5SDimitry Andric   auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
6330b57cec5SDimitry Andric                            MachineBasicBlock::iterator InsertBefore,
6340b57cec5SDimitry Andric                            MachineOperand &UseMO) {
6350b57cec5SDimitry Andric     MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
6360b57cec5SDimitry Andric     if (PreviouslyEmitted) {
6370b57cec5SDimitry Andric       Observer.changingInstr(*UseMO.getParent());
6380b57cec5SDimitry Andric       UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
6390b57cec5SDimitry Andric       Observer.changedInstr(*UseMO.getParent());
6400b57cec5SDimitry Andric       return;
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric     Builder.setInsertPt(*InsertIntoBB, InsertBefore);
6440b57cec5SDimitry Andric     Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
6450b57cec5SDimitry Andric     MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
6460b57cec5SDimitry Andric     EmittedInsns[InsertIntoBB] = NewMI;
6470b57cec5SDimitry Andric     replaceRegOpWith(MRI, UseMO, NewDstReg);
6480b57cec5SDimitry Andric   };
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   Observer.changingInstr(MI);
651bdd1243dSDimitry Andric   unsigned LoadOpc = getExtLoadOpcForExtend(Preferred.ExtendOpcode);
652bdd1243dSDimitry Andric   MI.setDesc(Builder.getTII().get(LoadOpc));
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   // Rewrite all the uses to fix up the types.
6550b57cec5SDimitry Andric   auto &LoadValue = MI.getOperand(0);
6560b57cec5SDimitry Andric   SmallVector<MachineOperand *, 4> Uses;
6570b57cec5SDimitry Andric   for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
6580b57cec5SDimitry Andric     Uses.push_back(&UseMO);
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric   for (auto *UseMO : Uses) {
6610b57cec5SDimitry Andric     MachineInstr *UseMI = UseMO->getParent();
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric     // If the extend is compatible with the preferred extend then we should fix
6640b57cec5SDimitry Andric     // up the type and extend so that it uses the preferred use.
6650b57cec5SDimitry Andric     if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
6660b57cec5SDimitry Andric         UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
6678bcb0991SDimitry Andric       Register UseDstReg = UseMI->getOperand(0).getReg();
6680b57cec5SDimitry Andric       MachineOperand &UseSrcMO = UseMI->getOperand(1);
6695ffd83dbSDimitry Andric       const LLT UseDstTy = MRI.getType(UseDstReg);
6700b57cec5SDimitry Andric       if (UseDstReg != ChosenDstReg) {
6710b57cec5SDimitry Andric         if (Preferred.Ty == UseDstTy) {
6720b57cec5SDimitry Andric           // If the use has the same type as the preferred use, then merge
6730b57cec5SDimitry Andric           // the vregs and erase the extend. For example:
6740b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6750b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXT %1(s8)
6760b57cec5SDimitry Andric           //    %3:_(s32) = G_ANYEXT %1(s8)
6770b57cec5SDimitry Andric           //    ... = ... %3(s32)
6780b57cec5SDimitry Andric           // rewrites to:
6790b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXTLOAD ...
6800b57cec5SDimitry Andric           //    ... = ... %2(s32)
6810b57cec5SDimitry Andric           replaceRegWith(MRI, UseDstReg, ChosenDstReg);
6820b57cec5SDimitry Andric           Observer.erasingInstr(*UseMO->getParent());
6830b57cec5SDimitry Andric           UseMO->getParent()->eraseFromParent();
6840b57cec5SDimitry Andric         } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
6850b57cec5SDimitry Andric           // If the preferred size is smaller, then keep the extend but extend
6860b57cec5SDimitry Andric           // from the result of the extending load. For example:
6870b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6880b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXT %1(s8)
6890b57cec5SDimitry Andric           //    %3:_(s64) = G_ANYEXT %1(s8)
6900b57cec5SDimitry Andric           //    ... = ... %3(s64)
6910b57cec5SDimitry Andric           /// rewrites to:
6920b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXTLOAD ...
6930b57cec5SDimitry Andric           //    %3:_(s64) = G_ANYEXT %2:_(s32)
6940b57cec5SDimitry Andric           //    ... = ... %3(s64)
6950b57cec5SDimitry Andric           replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
6960b57cec5SDimitry Andric         } else {
6970b57cec5SDimitry Andric           // If the preferred size is large, then insert a truncate. For
6980b57cec5SDimitry Andric           // example:
6990b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
7000b57cec5SDimitry Andric           //    %2:_(s64) = G_SEXT %1(s8)
7010b57cec5SDimitry Andric           //    %3:_(s32) = G_ZEXT %1(s8)
7020b57cec5SDimitry Andric           //    ... = ... %3(s32)
7030b57cec5SDimitry Andric           /// rewrites to:
7040b57cec5SDimitry Andric           //    %2:_(s64) = G_SEXTLOAD ...
7050b57cec5SDimitry Andric           //    %4:_(s8) = G_TRUNC %2:_(s32)
7060b57cec5SDimitry Andric           //    %3:_(s64) = G_ZEXT %2:_(s8)
7070b57cec5SDimitry Andric           //    ... = ... %3(s64)
7080b57cec5SDimitry Andric           InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
7090b57cec5SDimitry Andric                                                  InsertTruncAt);
7100b57cec5SDimitry Andric         }
7110b57cec5SDimitry Andric         continue;
7120b57cec5SDimitry Andric       }
7130b57cec5SDimitry Andric       // The use is (one of) the uses of the preferred use we chose earlier.
7140b57cec5SDimitry Andric       // We're going to update the load to def this value later so just erase
7150b57cec5SDimitry Andric       // the old extend.
7160b57cec5SDimitry Andric       Observer.erasingInstr(*UseMO->getParent());
7170b57cec5SDimitry Andric       UseMO->getParent()->eraseFromParent();
7180b57cec5SDimitry Andric       continue;
7190b57cec5SDimitry Andric     }
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric     // The use isn't an extend. Truncate back to the type we originally loaded.
7220b57cec5SDimitry Andric     // This is free on many targets.
7230b57cec5SDimitry Andric     InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
7240b57cec5SDimitry Andric   }
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   MI.getOperand(0).setReg(ChosenDstReg);
7270b57cec5SDimitry Andric   Observer.changedInstr(MI);
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric 
730349cc55cSDimitry Andric bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI,
731349cc55cSDimitry Andric                                                  BuildFnTy &MatchInfo) {
732349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
733349cc55cSDimitry Andric 
734349cc55cSDimitry Andric   // If we have the following code:
735349cc55cSDimitry Andric   //  %mask = G_CONSTANT 255
736349cc55cSDimitry Andric   //  %ld   = G_LOAD %ptr, (load s16)
737349cc55cSDimitry Andric   //  %and  = G_AND %ld, %mask
738349cc55cSDimitry Andric   //
739349cc55cSDimitry Andric   // Try to fold it into
740349cc55cSDimitry Andric   //   %ld = G_ZEXTLOAD %ptr, (load s8)
741349cc55cSDimitry Andric 
742349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
743349cc55cSDimitry Andric   if (MRI.getType(Dst).isVector())
744349cc55cSDimitry Andric     return false;
745349cc55cSDimitry Andric 
746349cc55cSDimitry Andric   auto MaybeMask =
747349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
748349cc55cSDimitry Andric   if (!MaybeMask)
749349cc55cSDimitry Andric     return false;
750349cc55cSDimitry Andric 
751349cc55cSDimitry Andric   APInt MaskVal = MaybeMask->Value;
752349cc55cSDimitry Andric 
753349cc55cSDimitry Andric   if (!MaskVal.isMask())
754349cc55cSDimitry Andric     return false;
755349cc55cSDimitry Andric 
756349cc55cSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
757753f127fSDimitry Andric   // Don't use getOpcodeDef() here since intermediate instructions may have
758753f127fSDimitry Andric   // multiple users.
759753f127fSDimitry Andric   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(MRI.getVRegDef(SrcReg));
760753f127fSDimitry Andric   if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()))
761349cc55cSDimitry Andric     return false;
762349cc55cSDimitry Andric 
763349cc55cSDimitry Andric   Register LoadReg = LoadMI->getDstReg();
764753f127fSDimitry Andric   LLT RegTy = MRI.getType(LoadReg);
765349cc55cSDimitry Andric   Register PtrReg = LoadMI->getPointerReg();
766753f127fSDimitry Andric   unsigned RegSize = RegTy.getSizeInBits();
767349cc55cSDimitry Andric   uint64_t LoadSizeBits = LoadMI->getMemSizeInBits();
76806c3fb27SDimitry Andric   unsigned MaskSizeBits = MaskVal.countr_one();
769349cc55cSDimitry Andric 
770349cc55cSDimitry Andric   // The mask may not be larger than the in-memory type, as it might cover sign
771349cc55cSDimitry Andric   // extended bits
772349cc55cSDimitry Andric   if (MaskSizeBits > LoadSizeBits)
773349cc55cSDimitry Andric     return false;
774349cc55cSDimitry Andric 
775349cc55cSDimitry Andric   // If the mask covers the whole destination register, there's nothing to
776349cc55cSDimitry Andric   // extend
777753f127fSDimitry Andric   if (MaskSizeBits >= RegSize)
778349cc55cSDimitry Andric     return false;
779349cc55cSDimitry Andric 
780349cc55cSDimitry Andric   // Most targets cannot deal with loads of size < 8 and need to re-legalize to
781349cc55cSDimitry Andric   // at least byte loads. Avoid creating such loads here
782349cc55cSDimitry Andric   if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
783349cc55cSDimitry Andric     return false;
784349cc55cSDimitry Andric 
785349cc55cSDimitry Andric   const MachineMemOperand &MMO = LoadMI->getMMO();
786349cc55cSDimitry Andric   LegalityQuery::MemDesc MemDesc(MMO);
787753f127fSDimitry Andric 
788753f127fSDimitry Andric   // Don't modify the memory access size if this is atomic/volatile, but we can
789753f127fSDimitry Andric   // still adjust the opcode to indicate the high bit behavior.
790753f127fSDimitry Andric   if (LoadMI->isSimple())
791349cc55cSDimitry Andric     MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
792753f127fSDimitry Andric   else if (LoadSizeBits > MaskSizeBits || LoadSizeBits == RegSize)
793753f127fSDimitry Andric     return false;
794753f127fSDimitry Andric 
795753f127fSDimitry Andric   // TODO: Could check if it's legal with the reduced or original memory size.
796349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer(
797753f127fSDimitry Andric           {TargetOpcode::G_ZEXTLOAD, {RegTy, MRI.getType(PtrReg)}, {MemDesc}}))
798349cc55cSDimitry Andric     return false;
799349cc55cSDimitry Andric 
800349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
801349cc55cSDimitry Andric     B.setInstrAndDebugLoc(*LoadMI);
802349cc55cSDimitry Andric     auto &MF = B.getMF();
803349cc55cSDimitry Andric     auto PtrInfo = MMO.getPointerInfo();
804753f127fSDimitry Andric     auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MemDesc.MemoryTy);
805349cc55cSDimitry Andric     B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
806753f127fSDimitry Andric     LoadMI->eraseFromParent();
807349cc55cSDimitry Andric   };
808349cc55cSDimitry Andric   return true;
809349cc55cSDimitry Andric }
810349cc55cSDimitry Andric 
8115ffd83dbSDimitry Andric bool CombinerHelper::isPredecessor(const MachineInstr &DefMI,
8125ffd83dbSDimitry Andric                                    const MachineInstr &UseMI) {
8135ffd83dbSDimitry Andric   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
8145ffd83dbSDimitry Andric          "shouldn't consider debug uses");
8158bcb0991SDimitry Andric   assert(DefMI.getParent() == UseMI.getParent());
8168bcb0991SDimitry Andric   if (&DefMI == &UseMI)
817349cc55cSDimitry Andric     return true;
818e8d8bef9SDimitry Andric   const MachineBasicBlock &MBB = *DefMI.getParent();
819e8d8bef9SDimitry Andric   auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
820e8d8bef9SDimitry Andric     return &MI == &DefMI || &MI == &UseMI;
821e8d8bef9SDimitry Andric   });
822e8d8bef9SDimitry Andric   if (DefOrUse == MBB.end())
823e8d8bef9SDimitry Andric     llvm_unreachable("Block must contain both DefMI and UseMI!");
824e8d8bef9SDimitry Andric   return &*DefOrUse == &DefMI;
8258bcb0991SDimitry Andric }
8268bcb0991SDimitry Andric 
8275ffd83dbSDimitry Andric bool CombinerHelper::dominates(const MachineInstr &DefMI,
8285ffd83dbSDimitry Andric                                const MachineInstr &UseMI) {
8295ffd83dbSDimitry Andric   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
8305ffd83dbSDimitry Andric          "shouldn't consider debug uses");
8318bcb0991SDimitry Andric   if (MDT)
8328bcb0991SDimitry Andric     return MDT->dominates(&DefMI, &UseMI);
8338bcb0991SDimitry Andric   else if (DefMI.getParent() != UseMI.getParent())
8348bcb0991SDimitry Andric     return false;
8358bcb0991SDimitry Andric 
8368bcb0991SDimitry Andric   return isPredecessor(DefMI, UseMI);
8378bcb0991SDimitry Andric }
8388bcb0991SDimitry Andric 
839e8d8bef9SDimitry Andric bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) {
8405ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
8415ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
842e8d8bef9SDimitry Andric   Register LoadUser = SrcReg;
843e8d8bef9SDimitry Andric 
844e8d8bef9SDimitry Andric   if (MRI.getType(SrcReg).isVector())
845e8d8bef9SDimitry Andric     return false;
846e8d8bef9SDimitry Andric 
847e8d8bef9SDimitry Andric   Register TruncSrc;
848e8d8bef9SDimitry Andric   if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
849e8d8bef9SDimitry Andric     LoadUser = TruncSrc;
850e8d8bef9SDimitry Andric 
851e8d8bef9SDimitry Andric   uint64_t SizeInBits = MI.getOperand(2).getImm();
852e8d8bef9SDimitry Andric   // If the source is a G_SEXTLOAD from the same bit width, then we don't
853e8d8bef9SDimitry Andric   // need any extend at all, just a truncate.
854fe6060f1SDimitry Andric   if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
855e8d8bef9SDimitry Andric     // If truncating more than the original extended value, abort.
856fe6060f1SDimitry Andric     auto LoadSizeBits = LoadMI->getMemSizeInBits();
857fe6060f1SDimitry Andric     if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits)
858e8d8bef9SDimitry Andric       return false;
859fe6060f1SDimitry Andric     if (LoadSizeBits == SizeInBits)
860e8d8bef9SDimitry Andric       return true;
861e8d8bef9SDimitry Andric   }
862e8d8bef9SDimitry Andric   return false;
8635ffd83dbSDimitry Andric }
8645ffd83dbSDimitry Andric 
865fe6060f1SDimitry Andric void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) {
8665ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
867e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
868e8d8bef9SDimitry Andric   Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
869e8d8bef9SDimitry Andric   MI.eraseFromParent();
870e8d8bef9SDimitry Andric }
871e8d8bef9SDimitry Andric 
872e8d8bef9SDimitry Andric bool CombinerHelper::matchSextInRegOfLoad(
873e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
874e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
875e8d8bef9SDimitry Andric 
876753f127fSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
877753f127fSDimitry Andric   LLT RegTy = MRI.getType(DstReg);
878753f127fSDimitry Andric 
879e8d8bef9SDimitry Andric   // Only supports scalars for now.
880753f127fSDimitry Andric   if (RegTy.isVector())
881e8d8bef9SDimitry Andric     return false;
882e8d8bef9SDimitry Andric 
883e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
884fe6060f1SDimitry Andric   auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI);
885753f127fSDimitry Andric   if (!LoadDef || !MRI.hasOneNonDBGUse(DstReg))
886e8d8bef9SDimitry Andric     return false;
887e8d8bef9SDimitry Andric 
888753f127fSDimitry Andric   uint64_t MemBits = LoadDef->getMemSizeInBits();
889753f127fSDimitry Andric 
890e8d8bef9SDimitry Andric   // If the sign extend extends from a narrower width than the load's width,
891e8d8bef9SDimitry Andric   // then we can narrow the load width when we combine to a G_SEXTLOAD.
892e8d8bef9SDimitry Andric   // Avoid widening the load at all.
893753f127fSDimitry Andric   unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(), MemBits);
894e8d8bef9SDimitry Andric 
895e8d8bef9SDimitry Andric   // Don't generate G_SEXTLOADs with a < 1 byte width.
896e8d8bef9SDimitry Andric   if (NewSizeBits < 8)
897e8d8bef9SDimitry Andric     return false;
898e8d8bef9SDimitry Andric   // Don't bother creating a non-power-2 sextload, it will likely be broken up
899e8d8bef9SDimitry Andric   // anyway for most targets.
900e8d8bef9SDimitry Andric   if (!isPowerOf2_32(NewSizeBits))
901e8d8bef9SDimitry Andric     return false;
902349cc55cSDimitry Andric 
903349cc55cSDimitry Andric   const MachineMemOperand &MMO = LoadDef->getMMO();
904349cc55cSDimitry Andric   LegalityQuery::MemDesc MMDesc(MMO);
905753f127fSDimitry Andric 
906753f127fSDimitry Andric   // Don't modify the memory access size if this is atomic/volatile, but we can
907753f127fSDimitry Andric   // still adjust the opcode to indicate the high bit behavior.
908753f127fSDimitry Andric   if (LoadDef->isSimple())
909349cc55cSDimitry Andric     MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
910753f127fSDimitry Andric   else if (MemBits > NewSizeBits || MemBits == RegTy.getSizeInBits())
911753f127fSDimitry Andric     return false;
912753f127fSDimitry Andric 
913753f127fSDimitry Andric   // TODO: Could check if it's legal with the reduced or original memory size.
914349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD,
915349cc55cSDimitry Andric                                  {MRI.getType(LoadDef->getDstReg()),
916349cc55cSDimitry Andric                                   MRI.getType(LoadDef->getPointerReg())},
917349cc55cSDimitry Andric                                  {MMDesc}}))
918349cc55cSDimitry Andric     return false;
919349cc55cSDimitry Andric 
920fe6060f1SDimitry Andric   MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits);
921e8d8bef9SDimitry Andric   return true;
922e8d8bef9SDimitry Andric }
923e8d8bef9SDimitry Andric 
924fe6060f1SDimitry Andric void CombinerHelper::applySextInRegOfLoad(
925e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
926e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
927e8d8bef9SDimitry Andric   Register LoadReg;
928e8d8bef9SDimitry Andric   unsigned ScalarSizeBits;
929e8d8bef9SDimitry Andric   std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
930fe6060f1SDimitry Andric   GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
931e8d8bef9SDimitry Andric 
932e8d8bef9SDimitry Andric   // If we have the following:
933e8d8bef9SDimitry Andric   // %ld = G_LOAD %ptr, (load 2)
934e8d8bef9SDimitry Andric   // %ext = G_SEXT_INREG %ld, 8
935e8d8bef9SDimitry Andric   //    ==>
936e8d8bef9SDimitry Andric   // %ld = G_SEXTLOAD %ptr (load 1)
937e8d8bef9SDimitry Andric 
938fe6060f1SDimitry Andric   auto &MMO = LoadDef->getMMO();
939fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(*LoadDef);
940e8d8bef9SDimitry Andric   auto &MF = Builder.getMF();
941e8d8bef9SDimitry Andric   auto PtrInfo = MMO.getPointerInfo();
942e8d8bef9SDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
943e8d8bef9SDimitry Andric   Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
944fe6060f1SDimitry Andric                          LoadDef->getPointerReg(), *NewMMO);
9455ffd83dbSDimitry Andric   MI.eraseFromParent();
9465ffd83dbSDimitry Andric }
9475ffd83dbSDimitry Andric 
9485f757f3fSDimitry Andric static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
9495f757f3fSDimitry Andric   if (Ty.isVector())
9505f757f3fSDimitry Andric     return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
9515f757f3fSDimitry Andric                                 Ty.getNumElements());
9525f757f3fSDimitry Andric   return IntegerType::get(C, Ty.getSizeInBits());
9535f757f3fSDimitry Andric }
9548bcb0991SDimitry Andric 
9555f757f3fSDimitry Andric /// Return true if 'MI' is a load or a store that may be fold it's address
9565f757f3fSDimitry Andric /// operand into the load / store addressing mode.
9575f757f3fSDimitry Andric static bool canFoldInAddressingMode(GLoadStore *MI, const TargetLowering &TLI,
9585f757f3fSDimitry Andric                                     MachineRegisterInfo &MRI) {
9595f757f3fSDimitry Andric   TargetLowering::AddrMode AM;
9605f757f3fSDimitry Andric   auto *MF = MI->getMF();
9615f757f3fSDimitry Andric   auto *Addr = getOpcodeDef<GPtrAdd>(MI->getPointerReg(), MRI);
9625f757f3fSDimitry Andric   if (!Addr)
9638bcb0991SDimitry Andric     return false;
9648bcb0991SDimitry Andric 
9655f757f3fSDimitry Andric   AM.HasBaseReg = true;
9665f757f3fSDimitry Andric   if (auto CstOff = getIConstantVRegVal(Addr->getOffsetReg(), MRI))
9675f757f3fSDimitry Andric     AM.BaseOffs = CstOff->getSExtValue(); // [reg +/- imm]
9685f757f3fSDimitry Andric   else
9695f757f3fSDimitry Andric     AM.Scale = 1; // [reg +/- reg]
9705f757f3fSDimitry Andric 
9715f757f3fSDimitry Andric   return TLI.isLegalAddressingMode(
9725f757f3fSDimitry Andric       MF->getDataLayout(), AM,
9735f757f3fSDimitry Andric       getTypeForLLT(MI->getMMO().getMemoryType(),
9745f757f3fSDimitry Andric                     MF->getFunction().getContext()),
9755f757f3fSDimitry Andric       MI->getMMO().getAddrSpace());
9765f757f3fSDimitry Andric }
9775f757f3fSDimitry Andric 
9785f757f3fSDimitry Andric static unsigned getIndexedOpc(unsigned LdStOpc) {
9795f757f3fSDimitry Andric   switch (LdStOpc) {
9805f757f3fSDimitry Andric   case TargetOpcode::G_LOAD:
9815f757f3fSDimitry Andric     return TargetOpcode::G_INDEXED_LOAD;
9825f757f3fSDimitry Andric   case TargetOpcode::G_STORE:
9835f757f3fSDimitry Andric     return TargetOpcode::G_INDEXED_STORE;
9845f757f3fSDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
9855f757f3fSDimitry Andric     return TargetOpcode::G_INDEXED_ZEXTLOAD;
9865f757f3fSDimitry Andric   case TargetOpcode::G_SEXTLOAD:
9875f757f3fSDimitry Andric     return TargetOpcode::G_INDEXED_SEXTLOAD;
9885f757f3fSDimitry Andric   default:
9895f757f3fSDimitry Andric     llvm_unreachable("Unexpected opcode");
9905f757f3fSDimitry Andric   }
9915f757f3fSDimitry Andric }
9925f757f3fSDimitry Andric 
9935f757f3fSDimitry Andric bool CombinerHelper::isIndexedLoadStoreLegal(GLoadStore &LdSt) const {
9945f757f3fSDimitry Andric   // Check for legality.
9955f757f3fSDimitry Andric   LLT PtrTy = MRI.getType(LdSt.getPointerReg());
9965f757f3fSDimitry Andric   LLT Ty = MRI.getType(LdSt.getReg(0));
9975f757f3fSDimitry Andric   LLT MemTy = LdSt.getMMO().getMemoryType();
9985f757f3fSDimitry Andric   SmallVector<LegalityQuery::MemDesc, 2> MemDescrs(
9995f757f3fSDimitry Andric       {{MemTy, MemTy.getSizeInBits(), AtomicOrdering::NotAtomic}});
10005f757f3fSDimitry Andric   unsigned IndexedOpc = getIndexedOpc(LdSt.getOpcode());
10015f757f3fSDimitry Andric   SmallVector<LLT> OpTys;
10025f757f3fSDimitry Andric   if (IndexedOpc == TargetOpcode::G_INDEXED_STORE)
10035f757f3fSDimitry Andric     OpTys = {PtrTy, Ty, Ty};
10045f757f3fSDimitry Andric   else
10055f757f3fSDimitry Andric     OpTys = {Ty, PtrTy}; // For G_INDEXED_LOAD, G_INDEXED_[SZ]EXTLOAD
10065f757f3fSDimitry Andric 
10075f757f3fSDimitry Andric   LegalityQuery Q(IndexedOpc, OpTys, MemDescrs);
10085f757f3fSDimitry Andric   return isLegal(Q);
10095f757f3fSDimitry Andric }
10105f757f3fSDimitry Andric 
10115f757f3fSDimitry Andric static cl::opt<unsigned> PostIndexUseThreshold(
10125f757f3fSDimitry Andric     "post-index-use-threshold", cl::Hidden, cl::init(32),
10135f757f3fSDimitry Andric     cl::desc("Number of uses of a base pointer to check before it is no longer "
10145f757f3fSDimitry Andric              "considered for post-indexing."));
10155f757f3fSDimitry Andric 
10165f757f3fSDimitry Andric bool CombinerHelper::findPostIndexCandidate(GLoadStore &LdSt, Register &Addr,
10175f757f3fSDimitry Andric                                             Register &Base, Register &Offset,
10185f757f3fSDimitry Andric                                             bool &RematOffset) {
10195f757f3fSDimitry Andric   // We're looking for the following pattern, for either load or store:
10205f757f3fSDimitry Andric   // %baseptr:_(p0) = ...
10215f757f3fSDimitry Andric   // G_STORE %val(s64), %baseptr(p0)
10225f757f3fSDimitry Andric   // %offset:_(s64) = G_CONSTANT i64 -256
10235f757f3fSDimitry Andric   // %new_addr:_(p0) = G_PTR_ADD %baseptr, %offset(s64)
10245f757f3fSDimitry Andric   const auto &TLI = getTargetLowering();
10255f757f3fSDimitry Andric 
10265f757f3fSDimitry Andric   Register Ptr = LdSt.getPointerReg();
10275f757f3fSDimitry Andric   // If the store is the only use, don't bother.
10285f757f3fSDimitry Andric   if (MRI.hasOneNonDBGUse(Ptr))
10295f757f3fSDimitry Andric     return false;
10305f757f3fSDimitry Andric 
10315f757f3fSDimitry Andric   if (!isIndexedLoadStoreLegal(LdSt))
10325f757f3fSDimitry Andric     return false;
10335f757f3fSDimitry Andric 
10345f757f3fSDimitry Andric   if (getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Ptr, MRI))
10355f757f3fSDimitry Andric     return false;
10365f757f3fSDimitry Andric 
10375f757f3fSDimitry Andric   MachineInstr *StoredValDef = getDefIgnoringCopies(LdSt.getReg(0), MRI);
10385f757f3fSDimitry Andric   auto *PtrDef = MRI.getVRegDef(Ptr);
10395f757f3fSDimitry Andric 
10405f757f3fSDimitry Andric   unsigned NumUsesChecked = 0;
10415f757f3fSDimitry Andric   for (auto &Use : MRI.use_nodbg_instructions(Ptr)) {
10425f757f3fSDimitry Andric     if (++NumUsesChecked > PostIndexUseThreshold)
10435f757f3fSDimitry Andric       return false; // Try to avoid exploding compile time.
10445f757f3fSDimitry Andric 
10455f757f3fSDimitry Andric     auto *PtrAdd = dyn_cast<GPtrAdd>(&Use);
10465f757f3fSDimitry Andric     // The use itself might be dead. This can happen during combines if DCE
10475f757f3fSDimitry Andric     // hasn't had a chance to run yet. Don't allow it to form an indexed op.
10485f757f3fSDimitry Andric     if (!PtrAdd || MRI.use_nodbg_empty(PtrAdd->getReg(0)))
10498bcb0991SDimitry Andric       continue;
10508bcb0991SDimitry Andric 
10515f757f3fSDimitry Andric     // Check the user of this isn't the store, otherwise we'd be generate a
10525f757f3fSDimitry Andric     // indexed store defining its own use.
10535f757f3fSDimitry Andric     if (StoredValDef == &Use)
10548bcb0991SDimitry Andric       continue;
10555f757f3fSDimitry Andric 
10565f757f3fSDimitry Andric     Offset = PtrAdd->getOffsetReg();
10575f757f3fSDimitry Andric     if (!ForceLegalIndexing &&
10585f757f3fSDimitry Andric         !TLI.isIndexingLegal(LdSt, PtrAdd->getBaseReg(), Offset,
10595f757f3fSDimitry Andric                              /*IsPre*/ false, MRI))
10605f757f3fSDimitry Andric       continue;
10618bcb0991SDimitry Andric 
10628bcb0991SDimitry Andric     // Make sure the offset calculation is before the potentially indexed op.
10635f757f3fSDimitry Andric     MachineInstr *OffsetDef = MRI.getVRegDef(Offset);
10645f757f3fSDimitry Andric     RematOffset = false;
10655f757f3fSDimitry Andric     if (!dominates(*OffsetDef, LdSt)) {
10665f757f3fSDimitry Andric       // If the offset however is just a G_CONSTANT, we can always just
10675f757f3fSDimitry Andric       // rematerialize it where we need it.
10685f757f3fSDimitry Andric       if (OffsetDef->getOpcode() != TargetOpcode::G_CONSTANT)
10698bcb0991SDimitry Andric         continue;
10705f757f3fSDimitry Andric       RematOffset = true;
10718bcb0991SDimitry Andric     }
10728bcb0991SDimitry Andric 
10735f757f3fSDimitry Andric     for (auto &BasePtrUse : MRI.use_nodbg_instructions(PtrAdd->getBaseReg())) {
10745f757f3fSDimitry Andric       if (&BasePtrUse == PtrDef)
10758bcb0991SDimitry Andric         continue;
10765f757f3fSDimitry Andric 
10775f757f3fSDimitry Andric       // If the user is a later load/store that can be post-indexed, then don't
10785f757f3fSDimitry Andric       // combine this one.
10795f757f3fSDimitry Andric       auto *BasePtrLdSt = dyn_cast<GLoadStore>(&BasePtrUse);
10805f757f3fSDimitry Andric       if (BasePtrLdSt && BasePtrLdSt != &LdSt &&
10815f757f3fSDimitry Andric           dominates(LdSt, *BasePtrLdSt) &&
10825f757f3fSDimitry Andric           isIndexedLoadStoreLegal(*BasePtrLdSt))
10835f757f3fSDimitry Andric         return false;
10845f757f3fSDimitry Andric 
10855f757f3fSDimitry Andric       // Now we're looking for the key G_PTR_ADD instruction, which contains
10865f757f3fSDimitry Andric       // the offset add that we want to fold.
10875f757f3fSDimitry Andric       if (auto *BasePtrUseDef = dyn_cast<GPtrAdd>(&BasePtrUse)) {
10885f757f3fSDimitry Andric         Register PtrAddDefReg = BasePtrUseDef->getReg(0);
10895f757f3fSDimitry Andric         for (auto &BaseUseUse : MRI.use_nodbg_instructions(PtrAddDefReg)) {
10905f757f3fSDimitry Andric           // If the use is in a different block, then we may produce worse code
10915f757f3fSDimitry Andric           // due to the extra register pressure.
10925f757f3fSDimitry Andric           if (BaseUseUse.getParent() != LdSt.getParent())
10935f757f3fSDimitry Andric             return false;
10945f757f3fSDimitry Andric 
10955f757f3fSDimitry Andric           if (auto *UseUseLdSt = dyn_cast<GLoadStore>(&BaseUseUse))
10965f757f3fSDimitry Andric             if (canFoldInAddressingMode(UseUseLdSt, TLI, MRI))
10975f757f3fSDimitry Andric               return false;
10985f757f3fSDimitry Andric         }
10995f757f3fSDimitry Andric         if (!dominates(LdSt, BasePtrUse))
11005f757f3fSDimitry Andric           return false; // All use must be dominated by the load/store.
11015f757f3fSDimitry Andric       }
11028bcb0991SDimitry Andric     }
11038bcb0991SDimitry Andric 
11045f757f3fSDimitry Andric     Addr = PtrAdd->getReg(0);
11055f757f3fSDimitry Andric     Base = PtrAdd->getBaseReg();
11068bcb0991SDimitry Andric     return true;
11078bcb0991SDimitry Andric   }
11088bcb0991SDimitry Andric 
11098bcb0991SDimitry Andric   return false;
11108bcb0991SDimitry Andric }
11118bcb0991SDimitry Andric 
11125f757f3fSDimitry Andric bool CombinerHelper::findPreIndexCandidate(GLoadStore &LdSt, Register &Addr,
11138bcb0991SDimitry Andric                                            Register &Base, Register &Offset) {
11145f757f3fSDimitry Andric   auto &MF = *LdSt.getParent()->getParent();
11158bcb0991SDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
11168bcb0991SDimitry Andric 
11175f757f3fSDimitry Andric   Addr = LdSt.getPointerReg();
11185f757f3fSDimitry Andric   if (!mi_match(Addr, MRI, m_GPtrAdd(m_Reg(Base), m_Reg(Offset))) ||
11195f757f3fSDimitry Andric       MRI.hasOneNonDBGUse(Addr))
11208bcb0991SDimitry Andric     return false;
11218bcb0991SDimitry Andric 
11228bcb0991SDimitry Andric   if (!ForceLegalIndexing &&
11235f757f3fSDimitry Andric       !TLI.isIndexingLegal(LdSt, Base, Offset, /*IsPre*/ true, MRI))
11248bcb0991SDimitry Andric     return false;
11255f757f3fSDimitry Andric 
11265f757f3fSDimitry Andric   if (!isIndexedLoadStoreLegal(LdSt))
11275f757f3fSDimitry Andric     return false;
11288bcb0991SDimitry Andric 
11298bcb0991SDimitry Andric   MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
11305f757f3fSDimitry Andric   if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
11318bcb0991SDimitry Andric     return false;
11328bcb0991SDimitry Andric 
11335f757f3fSDimitry Andric   if (auto *St = dyn_cast<GStore>(&LdSt)) {
11348bcb0991SDimitry Andric     // Would require a copy.
11355f757f3fSDimitry Andric     if (Base == St->getValueReg())
11368bcb0991SDimitry Andric       return false;
11378bcb0991SDimitry Andric 
11388bcb0991SDimitry Andric     // We're expecting one use of Addr in MI, but it could also be the
11398bcb0991SDimitry Andric     // value stored, which isn't actually dominated by the instruction.
11405f757f3fSDimitry Andric     if (St->getValueReg() == Addr)
11418bcb0991SDimitry Andric       return false;
11428bcb0991SDimitry Andric   }
11435f757f3fSDimitry Andric 
11445f757f3fSDimitry Andric   // Avoid increasing cross-block register pressure.
11455f757f3fSDimitry Andric   for (auto &AddrUse : MRI.use_nodbg_instructions(Addr))
11465f757f3fSDimitry Andric     if (AddrUse.getParent() != LdSt.getParent())
11475f757f3fSDimitry Andric       return false;
11488bcb0991SDimitry Andric 
1149480093f4SDimitry Andric   // FIXME: check whether all uses of the base pointer are constant PtrAdds.
1150480093f4SDimitry Andric   // That might allow us to end base's liveness here by adjusting the constant.
11515f757f3fSDimitry Andric   bool RealUse = false;
11525f757f3fSDimitry Andric   for (auto &AddrUse : MRI.use_nodbg_instructions(Addr)) {
11535f757f3fSDimitry Andric     if (!dominates(LdSt, AddrUse))
11545f757f3fSDimitry Andric       return false; // All use must be dominated by the load/store.
11558bcb0991SDimitry Andric 
11565f757f3fSDimitry Andric     // If Ptr may be folded in addressing mode of other use, then it's
11575f757f3fSDimitry Andric     // not profitable to do this transformation.
11585f757f3fSDimitry Andric     if (auto *UseLdSt = dyn_cast<GLoadStore>(&AddrUse)) {
11595f757f3fSDimitry Andric       if (!canFoldInAddressingMode(UseLdSt, TLI, MRI))
11605f757f3fSDimitry Andric         RealUse = true;
11615f757f3fSDimitry Andric     } else {
11625f757f3fSDimitry Andric       RealUse = true;
11635f757f3fSDimitry Andric     }
11645f757f3fSDimitry Andric   }
11655f757f3fSDimitry Andric   return RealUse;
11665f757f3fSDimitry Andric }
11675f757f3fSDimitry Andric 
11685f757f3fSDimitry Andric bool CombinerHelper::matchCombineExtractedVectorLoad(MachineInstr &MI,
11695f757f3fSDimitry Andric                                                      BuildFnTy &MatchInfo) {
11705f757f3fSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
11715f757f3fSDimitry Andric 
11725f757f3fSDimitry Andric   // Check if there is a load that defines the vector being extracted from.
11735f757f3fSDimitry Andric   auto *LoadMI = getOpcodeDef<GLoad>(MI.getOperand(1).getReg(), MRI);
11745f757f3fSDimitry Andric   if (!LoadMI)
11758bcb0991SDimitry Andric     return false;
11765f757f3fSDimitry Andric 
11775f757f3fSDimitry Andric   Register Vector = MI.getOperand(1).getReg();
11785f757f3fSDimitry Andric   LLT VecEltTy = MRI.getType(Vector).getElementType();
11795f757f3fSDimitry Andric 
11805f757f3fSDimitry Andric   assert(MRI.getType(MI.getOperand(0).getReg()) == VecEltTy);
11815f757f3fSDimitry Andric 
11825f757f3fSDimitry Andric   // Checking whether we should reduce the load width.
11835f757f3fSDimitry Andric   if (!MRI.hasOneNonDBGUse(Vector))
11845f757f3fSDimitry Andric     return false;
11855f757f3fSDimitry Andric 
11865f757f3fSDimitry Andric   // Check if the defining load is simple.
11875f757f3fSDimitry Andric   if (!LoadMI->isSimple())
11885f757f3fSDimitry Andric     return false;
11895f757f3fSDimitry Andric 
11905f757f3fSDimitry Andric   // If the vector element type is not a multiple of a byte then we are unable
11915f757f3fSDimitry Andric   // to correctly compute an address to load only the extracted element as a
11925f757f3fSDimitry Andric   // scalar.
11935f757f3fSDimitry Andric   if (!VecEltTy.isByteSized())
11945f757f3fSDimitry Andric     return false;
11955f757f3fSDimitry Andric 
11965f757f3fSDimitry Andric   // Check if the new load that we are going to create is legal
11975f757f3fSDimitry Andric   // if we are in the post-legalization phase.
11985f757f3fSDimitry Andric   MachineMemOperand MMO = LoadMI->getMMO();
11995f757f3fSDimitry Andric   Align Alignment = MMO.getAlign();
12005f757f3fSDimitry Andric   MachinePointerInfo PtrInfo;
12015f757f3fSDimitry Andric   uint64_t Offset;
12025f757f3fSDimitry Andric 
12035f757f3fSDimitry Andric   // Finding the appropriate PtrInfo if offset is a known constant.
12045f757f3fSDimitry Andric   // This is required to create the memory operand for the narrowed load.
12055f757f3fSDimitry Andric   // This machine memory operand object helps us infer about legality
12065f757f3fSDimitry Andric   // before we proceed to combine the instruction.
12075f757f3fSDimitry Andric   if (auto CVal = getIConstantVRegVal(Vector, MRI)) {
12085f757f3fSDimitry Andric     int Elt = CVal->getZExtValue();
12095f757f3fSDimitry Andric     // FIXME: should be (ABI size)*Elt.
12105f757f3fSDimitry Andric     Offset = VecEltTy.getSizeInBits() * Elt / 8;
12115f757f3fSDimitry Andric     PtrInfo = MMO.getPointerInfo().getWithOffset(Offset);
12125f757f3fSDimitry Andric   } else {
12135f757f3fSDimitry Andric     // Discard the pointer info except the address space because the memory
12145f757f3fSDimitry Andric     // operand can't represent this new access since the offset is variable.
12155f757f3fSDimitry Andric     Offset = VecEltTy.getSizeInBits() / 8;
12165f757f3fSDimitry Andric     PtrInfo = MachinePointerInfo(MMO.getPointerInfo().getAddrSpace());
12178bcb0991SDimitry Andric   }
12185f757f3fSDimitry Andric 
12195f757f3fSDimitry Andric   Alignment = commonAlignment(Alignment, Offset);
12205f757f3fSDimitry Andric 
12215f757f3fSDimitry Andric   Register VecPtr = LoadMI->getPointerReg();
12225f757f3fSDimitry Andric   LLT PtrTy = MRI.getType(VecPtr);
12235f757f3fSDimitry Andric 
12245f757f3fSDimitry Andric   MachineFunction &MF = *MI.getMF();
12255f757f3fSDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, VecEltTy);
12265f757f3fSDimitry Andric 
12275f757f3fSDimitry Andric   LegalityQuery::MemDesc MMDesc(*NewMMO);
12285f757f3fSDimitry Andric 
12295f757f3fSDimitry Andric   LegalityQuery Q = {TargetOpcode::G_LOAD, {VecEltTy, PtrTy}, {MMDesc}};
12305f757f3fSDimitry Andric 
12315f757f3fSDimitry Andric   if (!isLegalOrBeforeLegalizer(Q))
12325f757f3fSDimitry Andric     return false;
12335f757f3fSDimitry Andric 
12345f757f3fSDimitry Andric   // Load must be allowed and fast on the target.
12355f757f3fSDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
12365f757f3fSDimitry Andric   auto &DL = MF.getDataLayout();
12375f757f3fSDimitry Andric   unsigned Fast = 0;
12385f757f3fSDimitry Andric   if (!getTargetLowering().allowsMemoryAccess(C, DL, VecEltTy, *NewMMO,
12395f757f3fSDimitry Andric                                               &Fast) ||
12405f757f3fSDimitry Andric       !Fast)
12415f757f3fSDimitry Andric     return false;
12425f757f3fSDimitry Andric 
12435f757f3fSDimitry Andric   Register Result = MI.getOperand(0).getReg();
12445f757f3fSDimitry Andric   Register Index = MI.getOperand(2).getReg();
12455f757f3fSDimitry Andric 
12465f757f3fSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
12475f757f3fSDimitry Andric     GISelObserverWrapper DummyObserver;
12485f757f3fSDimitry Andric     LegalizerHelper Helper(B.getMF(), DummyObserver, B);
12495f757f3fSDimitry Andric     //// Get pointer to the vector element.
12505f757f3fSDimitry Andric     Register finalPtr = Helper.getVectorElementPointer(
12515f757f3fSDimitry Andric         LoadMI->getPointerReg(), MRI.getType(LoadMI->getOperand(0).getReg()),
12525f757f3fSDimitry Andric         Index);
12535f757f3fSDimitry Andric     // New G_LOAD instruction.
12545f757f3fSDimitry Andric     B.buildLoad(Result, finalPtr, PtrInfo, Alignment);
12555f757f3fSDimitry Andric     // Remove original GLOAD instruction.
12565f757f3fSDimitry Andric     LoadMI->eraseFromParent();
12575f757f3fSDimitry Andric   };
12588bcb0991SDimitry Andric 
12598bcb0991SDimitry Andric   return true;
12608bcb0991SDimitry Andric }
12618bcb0991SDimitry Andric 
12625f757f3fSDimitry Andric bool CombinerHelper::matchCombineIndexedLoadStore(
12635f757f3fSDimitry Andric     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
12645f757f3fSDimitry Andric   auto &LdSt = cast<GLoadStore>(MI);
1265480093f4SDimitry Andric 
12665f757f3fSDimitry Andric   if (LdSt.isAtomic())
12678bcb0991SDimitry Andric     return false;
12688bcb0991SDimitry Andric 
12695f757f3fSDimitry Andric   MatchInfo.IsPre = findPreIndexCandidate(LdSt, MatchInfo.Addr, MatchInfo.Base,
1270480093f4SDimitry Andric                                           MatchInfo.Offset);
1271480093f4SDimitry Andric   if (!MatchInfo.IsPre &&
12725f757f3fSDimitry Andric       !findPostIndexCandidate(LdSt, MatchInfo.Addr, MatchInfo.Base,
12735f757f3fSDimitry Andric                               MatchInfo.Offset, MatchInfo.RematOffset))
12748bcb0991SDimitry Andric     return false;
12758bcb0991SDimitry Andric 
1276480093f4SDimitry Andric   return true;
1277480093f4SDimitry Andric }
12788bcb0991SDimitry Andric 
1279480093f4SDimitry Andric void CombinerHelper::applyCombineIndexedLoadStore(
1280480093f4SDimitry Andric     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1281480093f4SDimitry Andric   MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
12825f757f3fSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1283480093f4SDimitry Andric   unsigned Opcode = MI.getOpcode();
1284480093f4SDimitry Andric   bool IsStore = Opcode == TargetOpcode::G_STORE;
12855f757f3fSDimitry Andric   unsigned NewOpcode = getIndexedOpc(Opcode);
12865f757f3fSDimitry Andric 
12875f757f3fSDimitry Andric   // If the offset constant didn't happen to dominate the load/store, we can
12885f757f3fSDimitry Andric   // just clone it as needed.
12895f757f3fSDimitry Andric   if (MatchInfo.RematOffset) {
12905f757f3fSDimitry Andric     auto *OldCst = MRI.getVRegDef(MatchInfo.Offset);
12915f757f3fSDimitry Andric     auto NewCst = Builder.buildConstant(MRI.getType(MatchInfo.Offset),
12925f757f3fSDimitry Andric                                         *OldCst->getOperand(1).getCImm());
12935f757f3fSDimitry Andric     MatchInfo.Offset = NewCst.getReg(0);
12948bcb0991SDimitry Andric   }
12958bcb0991SDimitry Andric 
12965f757f3fSDimitry Andric   auto MIB = Builder.buildInstr(NewOpcode);
12978bcb0991SDimitry Andric   if (IsStore) {
1298480093f4SDimitry Andric     MIB.addDef(MatchInfo.Addr);
12998bcb0991SDimitry Andric     MIB.addUse(MI.getOperand(0).getReg());
13008bcb0991SDimitry Andric   } else {
13018bcb0991SDimitry Andric     MIB.addDef(MI.getOperand(0).getReg());
1302480093f4SDimitry Andric     MIB.addDef(MatchInfo.Addr);
13038bcb0991SDimitry Andric   }
13048bcb0991SDimitry Andric 
1305480093f4SDimitry Andric   MIB.addUse(MatchInfo.Base);
1306480093f4SDimitry Andric   MIB.addUse(MatchInfo.Offset);
1307480093f4SDimitry Andric   MIB.addImm(MatchInfo.IsPre);
13085f757f3fSDimitry Andric   MIB->cloneMemRefs(*MI.getMF(), MI);
13098bcb0991SDimitry Andric   MI.eraseFromParent();
13108bcb0991SDimitry Andric   AddrDef.eraseFromParent();
13118bcb0991SDimitry Andric 
13128bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "    Combinined to indexed operation");
13138bcb0991SDimitry Andric }
13148bcb0991SDimitry Andric 
1315fe6060f1SDimitry Andric bool CombinerHelper::matchCombineDivRem(MachineInstr &MI,
1316fe6060f1SDimitry Andric                                         MachineInstr *&OtherMI) {
1317fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
1318fe6060f1SDimitry Andric   bool IsDiv, IsSigned;
1319fe6060f1SDimitry Andric 
1320fe6060f1SDimitry Andric   switch (Opcode) {
1321fe6060f1SDimitry Andric   default:
1322fe6060f1SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1323fe6060f1SDimitry Andric   case TargetOpcode::G_SDIV:
1324fe6060f1SDimitry Andric   case TargetOpcode::G_UDIV: {
1325fe6060f1SDimitry Andric     IsDiv = true;
1326fe6060f1SDimitry Andric     IsSigned = Opcode == TargetOpcode::G_SDIV;
1327fe6060f1SDimitry Andric     break;
1328fe6060f1SDimitry Andric   }
1329fe6060f1SDimitry Andric   case TargetOpcode::G_SREM:
1330fe6060f1SDimitry Andric   case TargetOpcode::G_UREM: {
1331fe6060f1SDimitry Andric     IsDiv = false;
1332fe6060f1SDimitry Andric     IsSigned = Opcode == TargetOpcode::G_SREM;
1333fe6060f1SDimitry Andric     break;
1334fe6060f1SDimitry Andric   }
1335fe6060f1SDimitry Andric   }
1336fe6060f1SDimitry Andric 
1337fe6060f1SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
1338fe6060f1SDimitry Andric   unsigned DivOpcode, RemOpcode, DivremOpcode;
1339fe6060f1SDimitry Andric   if (IsSigned) {
1340fe6060f1SDimitry Andric     DivOpcode = TargetOpcode::G_SDIV;
1341fe6060f1SDimitry Andric     RemOpcode = TargetOpcode::G_SREM;
1342fe6060f1SDimitry Andric     DivremOpcode = TargetOpcode::G_SDIVREM;
1343fe6060f1SDimitry Andric   } else {
1344fe6060f1SDimitry Andric     DivOpcode = TargetOpcode::G_UDIV;
1345fe6060f1SDimitry Andric     RemOpcode = TargetOpcode::G_UREM;
1346fe6060f1SDimitry Andric     DivremOpcode = TargetOpcode::G_UDIVREM;
1347fe6060f1SDimitry Andric   }
1348fe6060f1SDimitry Andric 
1349fe6060f1SDimitry Andric   if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
13508bcb0991SDimitry Andric     return false;
13518bcb0991SDimitry Andric 
1352fe6060f1SDimitry Andric   // Combine:
1353fe6060f1SDimitry Andric   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1354fe6060f1SDimitry Andric   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1355fe6060f1SDimitry Andric   // into:
1356fe6060f1SDimitry Andric   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1357fe6060f1SDimitry Andric 
1358fe6060f1SDimitry Andric   // Combine:
1359fe6060f1SDimitry Andric   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1360fe6060f1SDimitry Andric   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1361fe6060f1SDimitry Andric   // into:
1362fe6060f1SDimitry Andric   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1363fe6060f1SDimitry Andric 
1364fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
1365fe6060f1SDimitry Andric     if (MI.getParent() == UseMI.getParent() &&
1366fe6060f1SDimitry Andric         ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
1367fe6060f1SDimitry Andric          (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
1368972a253aSDimitry Andric         matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2)) &&
1369972a253aSDimitry Andric         matchEqualDefs(MI.getOperand(1), UseMI.getOperand(1))) {
1370fe6060f1SDimitry Andric       OtherMI = &UseMI;
1371fe6060f1SDimitry Andric       return true;
1372fe6060f1SDimitry Andric     }
1373fe6060f1SDimitry Andric   }
1374fe6060f1SDimitry Andric 
1375fe6060f1SDimitry Andric   return false;
1376fe6060f1SDimitry Andric }
1377fe6060f1SDimitry Andric 
1378fe6060f1SDimitry Andric void CombinerHelper::applyCombineDivRem(MachineInstr &MI,
1379fe6060f1SDimitry Andric                                         MachineInstr *&OtherMI) {
1380fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
1381fe6060f1SDimitry Andric   assert(OtherMI && "OtherMI shouldn't be empty.");
1382fe6060f1SDimitry Andric 
1383fe6060f1SDimitry Andric   Register DestDivReg, DestRemReg;
1384fe6060f1SDimitry Andric   if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
1385fe6060f1SDimitry Andric     DestDivReg = MI.getOperand(0).getReg();
1386fe6060f1SDimitry Andric     DestRemReg = OtherMI->getOperand(0).getReg();
1387fe6060f1SDimitry Andric   } else {
1388fe6060f1SDimitry Andric     DestDivReg = OtherMI->getOperand(0).getReg();
1389fe6060f1SDimitry Andric     DestRemReg = MI.getOperand(0).getReg();
1390fe6060f1SDimitry Andric   }
1391fe6060f1SDimitry Andric 
1392fe6060f1SDimitry Andric   bool IsSigned =
1393fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
1394fe6060f1SDimitry Andric 
1395fe6060f1SDimitry Andric   // Check which instruction is first in the block so we don't break def-use
139606c3fb27SDimitry Andric   // deps by "moving" the instruction incorrectly. Also keep track of which
139706c3fb27SDimitry Andric   // instruction is first so we pick it's operands, avoiding use-before-def
139806c3fb27SDimitry Andric   // bugs.
139906c3fb27SDimitry Andric   MachineInstr *FirstInst;
140006c3fb27SDimitry Andric   if (dominates(MI, *OtherMI)) {
1401fe6060f1SDimitry Andric     Builder.setInstrAndDebugLoc(MI);
140206c3fb27SDimitry Andric     FirstInst = &MI;
140306c3fb27SDimitry Andric   } else {
1404fe6060f1SDimitry Andric     Builder.setInstrAndDebugLoc(*OtherMI);
140506c3fb27SDimitry Andric     FirstInst = OtherMI;
140606c3fb27SDimitry Andric   }
1407fe6060f1SDimitry Andric 
1408fe6060f1SDimitry Andric   Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
1409fe6060f1SDimitry Andric                               : TargetOpcode::G_UDIVREM,
1410fe6060f1SDimitry Andric                      {DestDivReg, DestRemReg},
141106c3fb27SDimitry Andric                      { FirstInst->getOperand(1), FirstInst->getOperand(2) });
1412fe6060f1SDimitry Andric   MI.eraseFromParent();
1413fe6060f1SDimitry Andric   OtherMI->eraseFromParent();
1414fe6060f1SDimitry Andric }
1415fe6060f1SDimitry Andric 
1416fe6060f1SDimitry Andric bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI,
1417fe6060f1SDimitry Andric                                                    MachineInstr *&BrCond) {
1418fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BR);
1419fe6060f1SDimitry Andric 
14200b57cec5SDimitry Andric   // Try to match the following:
14210b57cec5SDimitry Andric   // bb1:
14220b57cec5SDimitry Andric   //   G_BRCOND %c1, %bb2
14230b57cec5SDimitry Andric   //   G_BR %bb3
14240b57cec5SDimitry Andric   // bb2:
14250b57cec5SDimitry Andric   // ...
14260b57cec5SDimitry Andric   // bb3:
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric   // The above pattern does not have a fall through to the successor bb2, always
14290b57cec5SDimitry Andric   // resulting in a branch no matter which path is taken. Here we try to find
14300b57cec5SDimitry Andric   // and replace that pattern with conditional branch to bb3 and otherwise
1431e8d8bef9SDimitry Andric   // fallthrough to bb2. This is generally better for branch predictors.
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
14340b57cec5SDimitry Andric   MachineBasicBlock::iterator BrIt(MI);
14350b57cec5SDimitry Andric   if (BrIt == MBB->begin())
14360b57cec5SDimitry Andric     return false;
14370b57cec5SDimitry Andric   assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
14380b57cec5SDimitry Andric 
1439fe6060f1SDimitry Andric   BrCond = &*std::prev(BrIt);
14400b57cec5SDimitry Andric   if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
14410b57cec5SDimitry Andric     return false;
14420b57cec5SDimitry Andric 
1443d409305fSDimitry Andric   // Check that the next block is the conditional branch target. Also make sure
1444d409305fSDimitry Andric   // that it isn't the same as the G_BR's target (otherwise, this will loop.)
1445d409305fSDimitry Andric   MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
1446d409305fSDimitry Andric   return BrCondTarget != MI.getOperand(0).getMBB() &&
1447d409305fSDimitry Andric          MBB->isLayoutSuccessor(BrCondTarget);
14480b57cec5SDimitry Andric }
14490b57cec5SDimitry Andric 
1450fe6060f1SDimitry Andric void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI,
1451fe6060f1SDimitry Andric                                                    MachineInstr *&BrCond) {
14520b57cec5SDimitry Andric   MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
1453e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(*BrCond);
1454e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
1455e8d8bef9SDimitry Andric   // FIXME: Does int/fp matter for this? If so, we might need to restrict
1456e8d8bef9SDimitry Andric   // this to i1 only since we might not know for sure what kind of
1457e8d8bef9SDimitry Andric   // compare generated the condition value.
1458e8d8bef9SDimitry Andric   auto True = Builder.buildConstant(
1459e8d8bef9SDimitry Andric       Ty, getICmpTrueVal(getTargetLowering(), false, false));
1460e8d8bef9SDimitry Andric   auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
14610b57cec5SDimitry Andric 
1462e8d8bef9SDimitry Andric   auto *FallthroughBB = BrCond->getOperand(1).getMBB();
1463e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
1464e8d8bef9SDimitry Andric   MI.getOperand(0).setMBB(FallthroughBB);
1465e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
14660b57cec5SDimitry Andric 
1467e8d8bef9SDimitry Andric   // Change the conditional branch to use the inverted condition and
1468e8d8bef9SDimitry Andric   // new target block.
14690b57cec5SDimitry Andric   Observer.changingInstr(*BrCond);
1470e8d8bef9SDimitry Andric   BrCond->getOperand(0).setReg(Xor.getReg(0));
14710b57cec5SDimitry Andric   BrCond->getOperand(1).setMBB(BrTarget);
14720b57cec5SDimitry Andric   Observer.changedInstr(*BrCond);
14738bcb0991SDimitry Andric }
14748bcb0991SDimitry Andric 
14758bcb0991SDimitry Andric 
1476fe6060f1SDimitry Andric bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) {
1477349cc55cSDimitry Andric   MachineIRBuilder HelperBuilder(MI);
1478349cc55cSDimitry Andric   GISelObserverWrapper DummyObserver;
1479349cc55cSDimitry Andric   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1480349cc55cSDimitry Andric   return Helper.lowerMemcpyInline(MI) ==
1481349cc55cSDimitry Andric          LegalizerHelper::LegalizeResult::Legalized;
14828bcb0991SDimitry Andric }
14838bcb0991SDimitry Andric 
14848bcb0991SDimitry Andric bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
1485349cc55cSDimitry Andric   MachineIRBuilder HelperBuilder(MI);
1486349cc55cSDimitry Andric   GISelObserverWrapper DummyObserver;
1487349cc55cSDimitry Andric   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1488349cc55cSDimitry Andric   return Helper.lowerMemCpyFamily(MI, MaxLen) ==
1489349cc55cSDimitry Andric          LegalizerHelper::LegalizeResult::Legalized;
14908bcb0991SDimitry Andric }
14918bcb0991SDimitry Andric 
149206c3fb27SDimitry Andric static APFloat constantFoldFpUnary(const MachineInstr &MI,
149306c3fb27SDimitry Andric                                    const MachineRegisterInfo &MRI,
149406c3fb27SDimitry Andric                                    const APFloat &Val) {
149506c3fb27SDimitry Andric   APFloat Result(Val);
149606c3fb27SDimitry Andric   switch (MI.getOpcode()) {
1497e8d8bef9SDimitry Andric   default:
1498e8d8bef9SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1499e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
150006c3fb27SDimitry Andric     Result.changeSign();
150106c3fb27SDimitry Andric     return Result;
1502e8d8bef9SDimitry Andric   }
1503e8d8bef9SDimitry Andric   case TargetOpcode::G_FABS: {
150406c3fb27SDimitry Andric     Result.clearSign();
150506c3fb27SDimitry Andric     return Result;
1506e8d8bef9SDimitry Andric   }
150706c3fb27SDimitry Andric   case TargetOpcode::G_FPTRUNC: {
150806c3fb27SDimitry Andric     bool Unused;
150906c3fb27SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
151006c3fb27SDimitry Andric     Result.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven,
151106c3fb27SDimitry Andric                    &Unused);
151206c3fb27SDimitry Andric     return Result;
151306c3fb27SDimitry Andric   }
1514e8d8bef9SDimitry Andric   case TargetOpcode::G_FSQRT: {
1515e8d8bef9SDimitry Andric     bool Unused;
151606c3fb27SDimitry Andric     Result.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
151706c3fb27SDimitry Andric                    &Unused);
151806c3fb27SDimitry Andric     Result = APFloat(sqrt(Result.convertToDouble()));
1519e8d8bef9SDimitry Andric     break;
1520e8d8bef9SDimitry Andric   }
1521e8d8bef9SDimitry Andric   case TargetOpcode::G_FLOG2: {
1522e8d8bef9SDimitry Andric     bool Unused;
152306c3fb27SDimitry Andric     Result.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
152406c3fb27SDimitry Andric                    &Unused);
152506c3fb27SDimitry Andric     Result = APFloat(log2(Result.convertToDouble()));
1526e8d8bef9SDimitry Andric     break;
1527e8d8bef9SDimitry Andric   }
1528e8d8bef9SDimitry Andric   }
1529e8d8bef9SDimitry Andric   // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise,
153006c3fb27SDimitry Andric   // `buildFConstant` will assert on size mismatch. Only `G_FSQRT`, and
153106c3fb27SDimitry Andric   // `G_FLOG2` reach here.
1532e8d8bef9SDimitry Andric   bool Unused;
153306c3fb27SDimitry Andric   Result.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &Unused);
153406c3fb27SDimitry Andric   return Result;
1535e8d8bef9SDimitry Andric }
1536e8d8bef9SDimitry Andric 
153706c3fb27SDimitry Andric void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
153806c3fb27SDimitry Andric                                                      const ConstantFP *Cst) {
1539e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
154006c3fb27SDimitry Andric   APFloat Folded = constantFoldFpUnary(MI, MRI, Cst->getValue());
154106c3fb27SDimitry Andric   const ConstantFP *NewCst = ConstantFP::get(Builder.getContext(), Folded);
154206c3fb27SDimitry Andric   Builder.buildFConstant(MI.getOperand(0), *NewCst);
1543e8d8bef9SDimitry Andric   MI.eraseFromParent();
1544e8d8bef9SDimitry Andric }
1545e8d8bef9SDimitry Andric 
1546480093f4SDimitry Andric bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
1547480093f4SDimitry Andric                                            PtrAddChain &MatchInfo) {
1548480093f4SDimitry Andric   // We're trying to match the following pattern:
1549480093f4SDimitry Andric   //   %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1550480093f4SDimitry Andric   //   %root = G_PTR_ADD %t1, G_CONSTANT imm2
1551480093f4SDimitry Andric   // -->
1552480093f4SDimitry Andric   //   %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1553480093f4SDimitry Andric 
1554480093f4SDimitry Andric   if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1555480093f4SDimitry Andric     return false;
1556480093f4SDimitry Andric 
1557480093f4SDimitry Andric   Register Add2 = MI.getOperand(1).getReg();
1558480093f4SDimitry Andric   Register Imm1 = MI.getOperand(2).getReg();
1559349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1560480093f4SDimitry Andric   if (!MaybeImmVal)
1561480093f4SDimitry Andric     return false;
1562480093f4SDimitry Andric 
1563349cc55cSDimitry Andric   MachineInstr *Add2Def = MRI.getVRegDef(Add2);
1564480093f4SDimitry Andric   if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
1565480093f4SDimitry Andric     return false;
1566480093f4SDimitry Andric 
1567480093f4SDimitry Andric   Register Base = Add2Def->getOperand(1).getReg();
1568480093f4SDimitry Andric   Register Imm2 = Add2Def->getOperand(2).getReg();
1569349cc55cSDimitry Andric   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1570480093f4SDimitry Andric   if (!MaybeImm2Val)
1571480093f4SDimitry Andric     return false;
1572480093f4SDimitry Andric 
1573349cc55cSDimitry Andric   // Check if the new combined immediate forms an illegal addressing mode.
1574349cc55cSDimitry Andric   // Do not combine if it was legal before but would get illegal.
1575349cc55cSDimitry Andric   // To do so, we need to find a load/store user of the pointer to get
1576349cc55cSDimitry Andric   // the access type.
1577349cc55cSDimitry Andric   Type *AccessTy = nullptr;
1578349cc55cSDimitry Andric   auto &MF = *MI.getMF();
1579349cc55cSDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
1580349cc55cSDimitry Andric     if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
1581349cc55cSDimitry Andric       AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
1582349cc55cSDimitry Andric                                MF.getFunction().getContext());
1583349cc55cSDimitry Andric       break;
1584349cc55cSDimitry Andric     }
1585349cc55cSDimitry Andric   }
1586349cc55cSDimitry Andric   TargetLoweringBase::AddrMode AMNew;
1587349cc55cSDimitry Andric   APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
1588349cc55cSDimitry Andric   AMNew.BaseOffs = CombinedImm.getSExtValue();
1589349cc55cSDimitry Andric   if (AccessTy) {
1590349cc55cSDimitry Andric     AMNew.HasBaseReg = true;
1591349cc55cSDimitry Andric     TargetLoweringBase::AddrMode AMOld;
15925f757f3fSDimitry Andric     AMOld.BaseOffs = MaybeImmVal->Value.getSExtValue();
1593349cc55cSDimitry Andric     AMOld.HasBaseReg = true;
1594349cc55cSDimitry Andric     unsigned AS = MRI.getType(Add2).getAddressSpace();
1595349cc55cSDimitry Andric     const auto &TLI = *MF.getSubtarget().getTargetLowering();
1596349cc55cSDimitry Andric     if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
1597349cc55cSDimitry Andric         !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
1598349cc55cSDimitry Andric       return false;
1599349cc55cSDimitry Andric   }
1600349cc55cSDimitry Andric 
1601480093f4SDimitry Andric   // Pass the combined immediate to the apply function.
1602349cc55cSDimitry Andric   MatchInfo.Imm = AMNew.BaseOffs;
1603480093f4SDimitry Andric   MatchInfo.Base = Base;
1604349cc55cSDimitry Andric   MatchInfo.Bank = getRegBank(Imm2);
1605480093f4SDimitry Andric   return true;
1606480093f4SDimitry Andric }
1607480093f4SDimitry Andric 
1608fe6060f1SDimitry Andric void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
1609480093f4SDimitry Andric                                            PtrAddChain &MatchInfo) {
1610480093f4SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1611480093f4SDimitry Andric   MachineIRBuilder MIB(MI);
1612480093f4SDimitry Andric   LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1613480093f4SDimitry Andric   auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1614349cc55cSDimitry Andric   setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
1615480093f4SDimitry Andric   Observer.changingInstr(MI);
1616480093f4SDimitry Andric   MI.getOperand(1).setReg(MatchInfo.Base);
1617480093f4SDimitry Andric   MI.getOperand(2).setReg(NewOffset.getReg(0));
1618480093f4SDimitry Andric   Observer.changedInstr(MI);
1619480093f4SDimitry Andric }
1620480093f4SDimitry Andric 
1621e8d8bef9SDimitry Andric bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI,
1622e8d8bef9SDimitry Andric                                           RegisterImmPair &MatchInfo) {
1623e8d8bef9SDimitry Andric   // We're trying to match the following pattern with any of
1624e8d8bef9SDimitry Andric   // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
1625e8d8bef9SDimitry Andric   //   %t1 = SHIFT %base, G_CONSTANT imm1
1626e8d8bef9SDimitry Andric   //   %root = SHIFT %t1, G_CONSTANT imm2
1627e8d8bef9SDimitry Andric   // -->
1628e8d8bef9SDimitry Andric   //   %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
1629e8d8bef9SDimitry Andric 
1630e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1631e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1632e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1633e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_USHLSAT) &&
1634e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1635e8d8bef9SDimitry Andric 
1636e8d8bef9SDimitry Andric   Register Shl2 = MI.getOperand(1).getReg();
1637e8d8bef9SDimitry Andric   Register Imm1 = MI.getOperand(2).getReg();
1638349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1639e8d8bef9SDimitry Andric   if (!MaybeImmVal)
1640e8d8bef9SDimitry Andric     return false;
1641e8d8bef9SDimitry Andric 
1642e8d8bef9SDimitry Andric   MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2);
1643e8d8bef9SDimitry Andric   if (Shl2Def->getOpcode() != Opcode)
1644e8d8bef9SDimitry Andric     return false;
1645e8d8bef9SDimitry Andric 
1646e8d8bef9SDimitry Andric   Register Base = Shl2Def->getOperand(1).getReg();
1647e8d8bef9SDimitry Andric   Register Imm2 = Shl2Def->getOperand(2).getReg();
1648349cc55cSDimitry Andric   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1649e8d8bef9SDimitry Andric   if (!MaybeImm2Val)
1650e8d8bef9SDimitry Andric     return false;
1651e8d8bef9SDimitry Andric 
1652e8d8bef9SDimitry Andric   // Pass the combined immediate to the apply function.
1653e8d8bef9SDimitry Andric   MatchInfo.Imm =
16545f757f3fSDimitry Andric       (MaybeImmVal->Value.getZExtValue() + MaybeImm2Val->Value).getZExtValue();
1655e8d8bef9SDimitry Andric   MatchInfo.Reg = Base;
1656e8d8bef9SDimitry Andric 
1657e8d8bef9SDimitry Andric   // There is no simple replacement for a saturating unsigned left shift that
1658e8d8bef9SDimitry Andric   // exceeds the scalar size.
1659e8d8bef9SDimitry Andric   if (Opcode == TargetOpcode::G_USHLSAT &&
1660e8d8bef9SDimitry Andric       MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
1661e8d8bef9SDimitry Andric     return false;
1662e8d8bef9SDimitry Andric 
1663e8d8bef9SDimitry Andric   return true;
1664e8d8bef9SDimitry Andric }
1665e8d8bef9SDimitry Andric 
1666fe6060f1SDimitry Andric void CombinerHelper::applyShiftImmedChain(MachineInstr &MI,
1667e8d8bef9SDimitry Andric                                           RegisterImmPair &MatchInfo) {
1668e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1669e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1670e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1671e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_USHLSAT) &&
1672e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1673e8d8bef9SDimitry Andric 
1674e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1675e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1676e8d8bef9SDimitry Andric   unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
1677e8d8bef9SDimitry Andric   auto Imm = MatchInfo.Imm;
1678e8d8bef9SDimitry Andric 
1679e8d8bef9SDimitry Andric   if (Imm >= ScalarSizeInBits) {
1680e8d8bef9SDimitry Andric     // Any logical shift that exceeds scalar size will produce zero.
1681e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
1682e8d8bef9SDimitry Andric       Builder.buildConstant(MI.getOperand(0), 0);
1683e8d8bef9SDimitry Andric       MI.eraseFromParent();
1684fe6060f1SDimitry Andric       return;
1685e8d8bef9SDimitry Andric     }
1686e8d8bef9SDimitry Andric     // Arithmetic shift and saturating signed left shift have no effect beyond
1687e8d8bef9SDimitry Andric     // scalar size.
1688e8d8bef9SDimitry Andric     Imm = ScalarSizeInBits - 1;
1689e8d8bef9SDimitry Andric   }
1690e8d8bef9SDimitry Andric 
1691e8d8bef9SDimitry Andric   LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
1692e8d8bef9SDimitry Andric   Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
1693e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
1694e8d8bef9SDimitry Andric   MI.getOperand(1).setReg(MatchInfo.Reg);
1695e8d8bef9SDimitry Andric   MI.getOperand(2).setReg(NewImm);
1696e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
1697e8d8bef9SDimitry Andric }
1698e8d8bef9SDimitry Andric 
1699e8d8bef9SDimitry Andric bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI,
1700e8d8bef9SDimitry Andric                                               ShiftOfShiftedLogic &MatchInfo) {
1701e8d8bef9SDimitry Andric   // We're trying to match the following pattern with any of
1702e8d8bef9SDimitry Andric   // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination
1703e8d8bef9SDimitry Andric   // with any of G_AND/G_OR/G_XOR logic instructions.
1704e8d8bef9SDimitry Andric   //   %t1 = SHIFT %X, G_CONSTANT C0
1705e8d8bef9SDimitry Andric   //   %t2 = LOGIC %t1, %Y
1706e8d8bef9SDimitry Andric   //   %root = SHIFT %t2, G_CONSTANT C1
1707e8d8bef9SDimitry Andric   // -->
1708e8d8bef9SDimitry Andric   //   %t3 = SHIFT %X, G_CONSTANT (C0+C1)
1709e8d8bef9SDimitry Andric   //   %t4 = SHIFT %Y, G_CONSTANT C1
1710e8d8bef9SDimitry Andric   //   %root = LOGIC %t3, %t4
1711e8d8bef9SDimitry Andric   unsigned ShiftOpcode = MI.getOpcode();
1712e8d8bef9SDimitry Andric   assert((ShiftOpcode == TargetOpcode::G_SHL ||
1713e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_ASHR ||
1714e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_LSHR ||
1715e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_USHLSAT ||
1716e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_SSHLSAT) &&
1717e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1718e8d8bef9SDimitry Andric 
1719e8d8bef9SDimitry Andric   // Match a one-use bitwise logic op.
1720e8d8bef9SDimitry Andric   Register LogicDest = MI.getOperand(1).getReg();
1721e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(LogicDest))
1722e8d8bef9SDimitry Andric     return false;
1723e8d8bef9SDimitry Andric 
1724e8d8bef9SDimitry Andric   MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest);
1725e8d8bef9SDimitry Andric   unsigned LogicOpcode = LogicMI->getOpcode();
1726e8d8bef9SDimitry Andric   if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
1727e8d8bef9SDimitry Andric       LogicOpcode != TargetOpcode::G_XOR)
1728e8d8bef9SDimitry Andric     return false;
1729e8d8bef9SDimitry Andric 
1730e8d8bef9SDimitry Andric   // Find a matching one-use shift by constant.
1731e8d8bef9SDimitry Andric   const Register C1 = MI.getOperand(2).getReg();
1732349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
17335f757f3fSDimitry Andric   if (!MaybeImmVal || MaybeImmVal->Value == 0)
1734e8d8bef9SDimitry Andric     return false;
1735e8d8bef9SDimitry Andric 
1736e8d8bef9SDimitry Andric   const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
1737e8d8bef9SDimitry Andric 
1738e8d8bef9SDimitry Andric   auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
1739e8d8bef9SDimitry Andric     // Shift should match previous one and should be a one-use.
1740e8d8bef9SDimitry Andric     if (MI->getOpcode() != ShiftOpcode ||
1741e8d8bef9SDimitry Andric         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1742e8d8bef9SDimitry Andric       return false;
1743e8d8bef9SDimitry Andric 
1744e8d8bef9SDimitry Andric     // Must be a constant.
1745e8d8bef9SDimitry Andric     auto MaybeImmVal =
1746349cc55cSDimitry Andric         getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1747e8d8bef9SDimitry Andric     if (!MaybeImmVal)
1748e8d8bef9SDimitry Andric       return false;
1749e8d8bef9SDimitry Andric 
1750e8d8bef9SDimitry Andric     ShiftVal = MaybeImmVal->Value.getSExtValue();
1751e8d8bef9SDimitry Andric     return true;
1752e8d8bef9SDimitry Andric   };
1753e8d8bef9SDimitry Andric 
1754e8d8bef9SDimitry Andric   // Logic ops are commutative, so check each operand for a match.
1755e8d8bef9SDimitry Andric   Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
1756e8d8bef9SDimitry Andric   MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1);
1757e8d8bef9SDimitry Andric   Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
1758e8d8bef9SDimitry Andric   MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2);
1759e8d8bef9SDimitry Andric   uint64_t C0Val;
1760e8d8bef9SDimitry Andric 
1761e8d8bef9SDimitry Andric   if (matchFirstShift(LogicMIOp1, C0Val)) {
1762e8d8bef9SDimitry Andric     MatchInfo.LogicNonShiftReg = LogicMIReg2;
1763e8d8bef9SDimitry Andric     MatchInfo.Shift2 = LogicMIOp1;
1764e8d8bef9SDimitry Andric   } else if (matchFirstShift(LogicMIOp2, C0Val)) {
1765e8d8bef9SDimitry Andric     MatchInfo.LogicNonShiftReg = LogicMIReg1;
1766e8d8bef9SDimitry Andric     MatchInfo.Shift2 = LogicMIOp2;
1767e8d8bef9SDimitry Andric   } else
1768e8d8bef9SDimitry Andric     return false;
1769e8d8bef9SDimitry Andric 
1770e8d8bef9SDimitry Andric   MatchInfo.ValSum = C0Val + C1Val;
1771e8d8bef9SDimitry Andric 
1772e8d8bef9SDimitry Andric   // The fold is not valid if the sum of the shift values exceeds bitwidth.
1773e8d8bef9SDimitry Andric   if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
1774e8d8bef9SDimitry Andric     return false;
1775e8d8bef9SDimitry Andric 
1776e8d8bef9SDimitry Andric   MatchInfo.Logic = LogicMI;
1777e8d8bef9SDimitry Andric   return true;
1778e8d8bef9SDimitry Andric }
1779e8d8bef9SDimitry Andric 
1780fe6060f1SDimitry Andric void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI,
1781e8d8bef9SDimitry Andric                                               ShiftOfShiftedLogic &MatchInfo) {
1782e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1783e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1784e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT ||
1785e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_SSHLSAT) &&
1786e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1787e8d8bef9SDimitry Andric 
1788e8d8bef9SDimitry Andric   LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
1789e8d8bef9SDimitry Andric   LLT DestType = MRI.getType(MI.getOperand(0).getReg());
1790e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1791e8d8bef9SDimitry Andric 
1792e8d8bef9SDimitry Andric   Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
1793e8d8bef9SDimitry Andric 
1794e8d8bef9SDimitry Andric   Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
1795e8d8bef9SDimitry Andric   Register Shift1 =
1796e8d8bef9SDimitry Andric       Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
1797e8d8bef9SDimitry Andric 
1798bdd1243dSDimitry Andric   // If LogicNonShiftReg is the same to Shift1Base, and shift1 const is the same
1799bdd1243dSDimitry Andric   // to MatchInfo.Shift2 const, CSEMIRBuilder will reuse the old shift1 when
1800bdd1243dSDimitry Andric   // build shift2. So, if we erase MatchInfo.Shift2 at the end, actually we
1801bdd1243dSDimitry Andric   // remove old shift1. And it will cause crash later. So erase it earlier to
1802bdd1243dSDimitry Andric   // avoid the crash.
1803bdd1243dSDimitry Andric   MatchInfo.Shift2->eraseFromParent();
1804bdd1243dSDimitry Andric 
1805e8d8bef9SDimitry Andric   Register Shift2Const = MI.getOperand(2).getReg();
1806e8d8bef9SDimitry Andric   Register Shift2 = Builder
1807e8d8bef9SDimitry Andric                         .buildInstr(Opcode, {DestType},
1808e8d8bef9SDimitry Andric                                     {MatchInfo.LogicNonShiftReg, Shift2Const})
1809e8d8bef9SDimitry Andric                         .getReg(0);
1810e8d8bef9SDimitry Andric 
1811e8d8bef9SDimitry Andric   Register Dest = MI.getOperand(0).getReg();
1812e8d8bef9SDimitry Andric   Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
1813e8d8bef9SDimitry Andric 
1814bdd1243dSDimitry Andric   // This was one use so it's safe to remove it.
18150eae32dcSDimitry Andric   MatchInfo.Logic->eraseFromParent();
1816e8d8bef9SDimitry Andric 
1817e8d8bef9SDimitry Andric   MI.eraseFromParent();
1818e8d8bef9SDimitry Andric }
1819e8d8bef9SDimitry Andric 
182006c3fb27SDimitry Andric bool CombinerHelper::matchCommuteShift(MachineInstr &MI, BuildFnTy &MatchInfo) {
182106c3fb27SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHL && "Expected G_SHL");
182206c3fb27SDimitry Andric   // Combine (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
182306c3fb27SDimitry Andric   // Combine (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
182406c3fb27SDimitry Andric   auto &Shl = cast<GenericMachineInstr>(MI);
182506c3fb27SDimitry Andric   Register DstReg = Shl.getReg(0);
182606c3fb27SDimitry Andric   Register SrcReg = Shl.getReg(1);
182706c3fb27SDimitry Andric   Register ShiftReg = Shl.getReg(2);
182806c3fb27SDimitry Andric   Register X, C1;
182906c3fb27SDimitry Andric 
183006c3fb27SDimitry Andric   if (!getTargetLowering().isDesirableToCommuteWithShift(MI, !isPreLegalize()))
183106c3fb27SDimitry Andric     return false;
183206c3fb27SDimitry Andric 
183306c3fb27SDimitry Andric   if (!mi_match(SrcReg, MRI,
183406c3fb27SDimitry Andric                 m_OneNonDBGUse(m_any_of(m_GAdd(m_Reg(X), m_Reg(C1)),
183506c3fb27SDimitry Andric                                         m_GOr(m_Reg(X), m_Reg(C1))))))
183606c3fb27SDimitry Andric     return false;
183706c3fb27SDimitry Andric 
183806c3fb27SDimitry Andric   APInt C1Val, C2Val;
183906c3fb27SDimitry Andric   if (!mi_match(C1, MRI, m_ICstOrSplat(C1Val)) ||
184006c3fb27SDimitry Andric       !mi_match(ShiftReg, MRI, m_ICstOrSplat(C2Val)))
184106c3fb27SDimitry Andric     return false;
184206c3fb27SDimitry Andric 
184306c3fb27SDimitry Andric   auto *SrcDef = MRI.getVRegDef(SrcReg);
184406c3fb27SDimitry Andric   assert((SrcDef->getOpcode() == TargetOpcode::G_ADD ||
184506c3fb27SDimitry Andric           SrcDef->getOpcode() == TargetOpcode::G_OR) && "Unexpected op");
184606c3fb27SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
184706c3fb27SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
184806c3fb27SDimitry Andric     auto S1 = B.buildShl(SrcTy, X, ShiftReg);
184906c3fb27SDimitry Andric     auto S2 = B.buildShl(SrcTy, C1, ShiftReg);
185006c3fb27SDimitry Andric     B.buildInstr(SrcDef->getOpcode(), {DstReg}, {S1, S2});
185106c3fb27SDimitry Andric   };
185206c3fb27SDimitry Andric   return true;
185306c3fb27SDimitry Andric }
185406c3fb27SDimitry Andric 
18555ffd83dbSDimitry Andric bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
18565ffd83dbSDimitry Andric                                           unsigned &ShiftVal) {
18575ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
18585ffd83dbSDimitry Andric   auto MaybeImmVal =
1859349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1860e8d8bef9SDimitry Andric   if (!MaybeImmVal)
18615ffd83dbSDimitry Andric     return false;
1862e8d8bef9SDimitry Andric 
1863e8d8bef9SDimitry Andric   ShiftVal = MaybeImmVal->Value.exactLogBase2();
1864e8d8bef9SDimitry Andric   return (static_cast<int32_t>(ShiftVal) != -1);
18655ffd83dbSDimitry Andric }
18665ffd83dbSDimitry Andric 
1867fe6060f1SDimitry Andric void CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
18685ffd83dbSDimitry Andric                                           unsigned &ShiftVal) {
18695ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
18705ffd83dbSDimitry Andric   MachineIRBuilder MIB(MI);
18715ffd83dbSDimitry Andric   LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
18725ffd83dbSDimitry Andric   auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
18735ffd83dbSDimitry Andric   Observer.changingInstr(MI);
18745ffd83dbSDimitry Andric   MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
18755ffd83dbSDimitry Andric   MI.getOperand(2).setReg(ShiftCst.getReg(0));
18765ffd83dbSDimitry Andric   Observer.changedInstr(MI);
18775ffd83dbSDimitry Andric }
18785ffd83dbSDimitry Andric 
1879e8d8bef9SDimitry Andric // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
1880e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI,
1881e8d8bef9SDimitry Andric                                              RegisterImmPair &MatchData) {
1882e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHL && KB);
18835f757f3fSDimitry Andric   if (!getTargetLowering().isDesirableToPullExtFromShl(MI))
18845f757f3fSDimitry Andric     return false;
1885e8d8bef9SDimitry Andric 
1886e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
1887e8d8bef9SDimitry Andric 
1888e8d8bef9SDimitry Andric   Register ExtSrc;
1889e8d8bef9SDimitry Andric   if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
1890e8d8bef9SDimitry Andric       !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
1891e8d8bef9SDimitry Andric       !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
1892e8d8bef9SDimitry Andric     return false;
1893e8d8bef9SDimitry Andric 
1894e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
189506c3fb27SDimitry Andric   MachineInstr *MIShiftAmt = MRI.getVRegDef(RHS);
189606c3fb27SDimitry Andric   auto MaybeShiftAmtVal = isConstantOrConstantSplatVector(*MIShiftAmt, MRI);
1897e8d8bef9SDimitry Andric   if (!MaybeShiftAmtVal)
1898e8d8bef9SDimitry Andric     return false;
1899e8d8bef9SDimitry Andric 
1900e8d8bef9SDimitry Andric   if (LI) {
1901e8d8bef9SDimitry Andric     LLT SrcTy = MRI.getType(ExtSrc);
1902e8d8bef9SDimitry Andric 
1903e8d8bef9SDimitry Andric     // We only really care about the legality with the shifted value. We can
1904e8d8bef9SDimitry Andric     // pick any type the constant shift amount, so ask the target what to
1905e8d8bef9SDimitry Andric     // use. Otherwise we would have to guess and hope it is reported as legal.
1906e8d8bef9SDimitry Andric     LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
1907e8d8bef9SDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
1908e8d8bef9SDimitry Andric       return false;
1909e8d8bef9SDimitry Andric   }
1910e8d8bef9SDimitry Andric 
191106c3fb27SDimitry Andric   int64_t ShiftAmt = MaybeShiftAmtVal->getSExtValue();
1912e8d8bef9SDimitry Andric   MatchData.Reg = ExtSrc;
1913e8d8bef9SDimitry Andric   MatchData.Imm = ShiftAmt;
1914e8d8bef9SDimitry Andric 
191506c3fb27SDimitry Andric   unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countl_one();
191606c3fb27SDimitry Andric   unsigned SrcTySize = MRI.getType(ExtSrc).getScalarSizeInBits();
191706c3fb27SDimitry Andric   return MinLeadingZeros >= ShiftAmt && ShiftAmt < SrcTySize;
1918e8d8bef9SDimitry Andric }
1919e8d8bef9SDimitry Andric 
1920fe6060f1SDimitry Andric void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI,
1921e8d8bef9SDimitry Andric                                              const RegisterImmPair &MatchData) {
1922e8d8bef9SDimitry Andric   Register ExtSrcReg = MatchData.Reg;
1923e8d8bef9SDimitry Andric   int64_t ShiftAmtVal = MatchData.Imm;
1924e8d8bef9SDimitry Andric 
1925e8d8bef9SDimitry Andric   LLT ExtSrcTy = MRI.getType(ExtSrcReg);
1926e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1927e8d8bef9SDimitry Andric   auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
1928e8d8bef9SDimitry Andric   auto NarrowShift =
1929e8d8bef9SDimitry Andric       Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
1930e8d8bef9SDimitry Andric   Builder.buildZExt(MI.getOperand(0), NarrowShift);
1931e8d8bef9SDimitry Andric   MI.eraseFromParent();
1932fe6060f1SDimitry Andric }
1933fe6060f1SDimitry Andric 
1934fe6060f1SDimitry Andric bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI,
1935fe6060f1SDimitry Andric                                               Register &MatchInfo) {
1936fe6060f1SDimitry Andric   GMerge &Merge = cast<GMerge>(MI);
1937fe6060f1SDimitry Andric   SmallVector<Register, 16> MergedValues;
1938fe6060f1SDimitry Andric   for (unsigned I = 0; I < Merge.getNumSources(); ++I)
1939fe6060f1SDimitry Andric     MergedValues.emplace_back(Merge.getSourceReg(I));
1940fe6060f1SDimitry Andric 
1941fe6060f1SDimitry Andric   auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI);
1942fe6060f1SDimitry Andric   if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources())
1943fe6060f1SDimitry Andric     return false;
1944fe6060f1SDimitry Andric 
1945fe6060f1SDimitry Andric   for (unsigned I = 0; I < MergedValues.size(); ++I)
1946fe6060f1SDimitry Andric     if (MergedValues[I] != Unmerge->getReg(I))
1947fe6060f1SDimitry Andric       return false;
1948fe6060f1SDimitry Andric 
1949fe6060f1SDimitry Andric   MatchInfo = Unmerge->getSourceReg();
1950e8d8bef9SDimitry Andric   return true;
1951e8d8bef9SDimitry Andric }
1952e8d8bef9SDimitry Andric 
1953e8d8bef9SDimitry Andric static Register peekThroughBitcast(Register Reg,
1954e8d8bef9SDimitry Andric                                    const MachineRegisterInfo &MRI) {
1955e8d8bef9SDimitry Andric   while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
1956e8d8bef9SDimitry Andric     ;
1957e8d8bef9SDimitry Andric 
1958e8d8bef9SDimitry Andric   return Reg;
1959e8d8bef9SDimitry Andric }
1960e8d8bef9SDimitry Andric 
1961e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeMergeToPlainValues(
1962e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1963e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1964e8d8bef9SDimitry Andric          "Expected an unmerge");
1965349cc55cSDimitry Andric   auto &Unmerge = cast<GUnmerge>(MI);
1966349cc55cSDimitry Andric   Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
1967e8d8bef9SDimitry Andric 
1968bdd1243dSDimitry Andric   auto *SrcInstr = getOpcodeDef<GMergeLikeInstr>(SrcReg, MRI);
1969349cc55cSDimitry Andric   if (!SrcInstr)
1970e8d8bef9SDimitry Andric     return false;
1971e8d8bef9SDimitry Andric 
1972e8d8bef9SDimitry Andric   // Check the source type of the merge.
1973349cc55cSDimitry Andric   LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
1974349cc55cSDimitry Andric   LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
1975e8d8bef9SDimitry Andric   bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
1976e8d8bef9SDimitry Andric   if (SrcMergeTy != Dst0Ty && !SameSize)
1977e8d8bef9SDimitry Andric     return false;
1978e8d8bef9SDimitry Andric   // They are the same now (modulo a bitcast).
1979e8d8bef9SDimitry Andric   // We can collect all the src registers.
1980349cc55cSDimitry Andric   for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
1981349cc55cSDimitry Andric     Operands.push_back(SrcInstr->getSourceReg(Idx));
1982e8d8bef9SDimitry Andric   return true;
1983e8d8bef9SDimitry Andric }
1984e8d8bef9SDimitry Andric 
1985fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeMergeToPlainValues(
1986e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1987e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1988e8d8bef9SDimitry Andric          "Expected an unmerge");
1989e8d8bef9SDimitry Andric   assert((MI.getNumOperands() - 1 == Operands.size()) &&
1990e8d8bef9SDimitry Andric          "Not enough operands to replace all defs");
1991e8d8bef9SDimitry Andric   unsigned NumElems = MI.getNumOperands() - 1;
1992e8d8bef9SDimitry Andric 
1993e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(Operands[0]);
1994e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
1995e8d8bef9SDimitry Andric   bool CanReuseInputDirectly = DstTy == SrcTy;
1996e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1997e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1998e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(Idx).getReg();
1999e8d8bef9SDimitry Andric     Register SrcReg = Operands[Idx];
200006c3fb27SDimitry Andric 
200106c3fb27SDimitry Andric     // This combine may run after RegBankSelect, so we need to be aware of
200206c3fb27SDimitry Andric     // register banks.
200306c3fb27SDimitry Andric     const auto &DstCB = MRI.getRegClassOrRegBank(DstReg);
200406c3fb27SDimitry Andric     if (!DstCB.isNull() && DstCB != MRI.getRegClassOrRegBank(SrcReg)) {
200506c3fb27SDimitry Andric       SrcReg = Builder.buildCopy(MRI.getType(SrcReg), SrcReg).getReg(0);
200606c3fb27SDimitry Andric       MRI.setRegClassOrRegBank(SrcReg, DstCB);
200706c3fb27SDimitry Andric     }
200806c3fb27SDimitry Andric 
2009e8d8bef9SDimitry Andric     if (CanReuseInputDirectly)
2010e8d8bef9SDimitry Andric       replaceRegWith(MRI, DstReg, SrcReg);
2011e8d8bef9SDimitry Andric     else
2012e8d8bef9SDimitry Andric       Builder.buildCast(DstReg, SrcReg);
2013e8d8bef9SDimitry Andric   }
2014e8d8bef9SDimitry Andric   MI.eraseFromParent();
2015e8d8bef9SDimitry Andric }
2016e8d8bef9SDimitry Andric 
2017e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI,
2018e8d8bef9SDimitry Andric                                                  SmallVectorImpl<APInt> &Csts) {
2019e8d8bef9SDimitry Andric   unsigned SrcIdx = MI.getNumOperands() - 1;
2020e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(SrcIdx).getReg();
2021e8d8bef9SDimitry Andric   MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg);
2022e8d8bef9SDimitry Andric   if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT &&
2023e8d8bef9SDimitry Andric       SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT)
2024e8d8bef9SDimitry Andric     return false;
2025e8d8bef9SDimitry Andric   // Break down the big constant in smaller ones.
2026e8d8bef9SDimitry Andric   const MachineOperand &CstVal = SrcInstr->getOperand(1);
2027e8d8bef9SDimitry Andric   APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT
2028e8d8bef9SDimitry Andric                   ? CstVal.getCImm()->getValue()
2029e8d8bef9SDimitry Andric                   : CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
2030e8d8bef9SDimitry Andric 
2031e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
2032e8d8bef9SDimitry Andric   unsigned ShiftAmt = Dst0Ty.getSizeInBits();
2033e8d8bef9SDimitry Andric   // Unmerge a constant.
2034e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
2035e8d8bef9SDimitry Andric     Csts.emplace_back(Val.trunc(ShiftAmt));
2036e8d8bef9SDimitry Andric     Val = Val.lshr(ShiftAmt);
2037e8d8bef9SDimitry Andric   }
2038e8d8bef9SDimitry Andric 
2039e8d8bef9SDimitry Andric   return true;
2040e8d8bef9SDimitry Andric }
2041e8d8bef9SDimitry Andric 
2042fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI,
2043e8d8bef9SDimitry Andric                                                  SmallVectorImpl<APInt> &Csts) {
2044e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2045e8d8bef9SDimitry Andric          "Expected an unmerge");
2046e8d8bef9SDimitry Andric   assert((MI.getNumOperands() - 1 == Csts.size()) &&
2047e8d8bef9SDimitry Andric          "Not enough operands to replace all defs");
2048e8d8bef9SDimitry Andric   unsigned NumElems = MI.getNumOperands() - 1;
2049e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2050e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
2051e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(Idx).getReg();
2052e8d8bef9SDimitry Andric     Builder.buildConstant(DstReg, Csts[Idx]);
2053e8d8bef9SDimitry Andric   }
2054e8d8bef9SDimitry Andric 
2055e8d8bef9SDimitry Andric   MI.eraseFromParent();
2056e8d8bef9SDimitry Andric }
2057e8d8bef9SDimitry Andric 
205804eeddc0SDimitry Andric bool CombinerHelper::matchCombineUnmergeUndef(
205904eeddc0SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
206004eeddc0SDimitry Andric   unsigned SrcIdx = MI.getNumOperands() - 1;
206104eeddc0SDimitry Andric   Register SrcReg = MI.getOperand(SrcIdx).getReg();
206204eeddc0SDimitry Andric   MatchInfo = [&MI](MachineIRBuilder &B) {
206304eeddc0SDimitry Andric     unsigned NumElems = MI.getNumOperands() - 1;
206404eeddc0SDimitry Andric     for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
206504eeddc0SDimitry Andric       Register DstReg = MI.getOperand(Idx).getReg();
206604eeddc0SDimitry Andric       B.buildUndef(DstReg);
206704eeddc0SDimitry Andric     }
206804eeddc0SDimitry Andric   };
206904eeddc0SDimitry Andric   return isa<GImplicitDef>(MRI.getVRegDef(SrcReg));
207004eeddc0SDimitry Andric }
207104eeddc0SDimitry Andric 
2072e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
2073e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2074e8d8bef9SDimitry Andric          "Expected an unmerge");
2075e8d8bef9SDimitry Andric   // Check that all the lanes are dead except the first one.
2076e8d8bef9SDimitry Andric   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
2077e8d8bef9SDimitry Andric     if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
2078e8d8bef9SDimitry Andric       return false;
2079e8d8bef9SDimitry Andric   }
2080e8d8bef9SDimitry Andric   return true;
2081e8d8bef9SDimitry Andric }
2082e8d8bef9SDimitry Andric 
2083fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
2084e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2085e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
2086e8d8bef9SDimitry Andric   // Truncating a vector is going to truncate every single lane,
2087e8d8bef9SDimitry Andric   // whereas we want the full lowbits.
2088e8d8bef9SDimitry Andric   // Do the operation on a scalar instead.
2089e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2090e8d8bef9SDimitry Andric   if (SrcTy.isVector())
2091e8d8bef9SDimitry Andric     SrcReg =
2092e8d8bef9SDimitry Andric         Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0);
2093e8d8bef9SDimitry Andric 
2094e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
2095e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
2096e8d8bef9SDimitry Andric   if (Dst0Ty.isVector()) {
2097e8d8bef9SDimitry Andric     auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg);
2098e8d8bef9SDimitry Andric     Builder.buildCast(Dst0Reg, MIB);
2099e8d8bef9SDimitry Andric   } else
2100e8d8bef9SDimitry Andric     Builder.buildTrunc(Dst0Reg, SrcReg);
2101e8d8bef9SDimitry Andric   MI.eraseFromParent();
2102e8d8bef9SDimitry Andric }
2103e8d8bef9SDimitry Andric 
2104e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) {
2105e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2106e8d8bef9SDimitry Andric          "Expected an unmerge");
2107e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
2108e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
2109e8d8bef9SDimitry Andric   // G_ZEXT on vector applies to each lane, so it will
2110e8d8bef9SDimitry Andric   // affect all destinations. Therefore we won't be able
2111e8d8bef9SDimitry Andric   // to simplify the unmerge to just the first definition.
2112e8d8bef9SDimitry Andric   if (Dst0Ty.isVector())
2113e8d8bef9SDimitry Andric     return false;
2114e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
2115e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2116e8d8bef9SDimitry Andric   if (SrcTy.isVector())
2117e8d8bef9SDimitry Andric     return false;
2118e8d8bef9SDimitry Andric 
2119e8d8bef9SDimitry Andric   Register ZExtSrcReg;
2120e8d8bef9SDimitry Andric   if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
2121e8d8bef9SDimitry Andric     return false;
2122e8d8bef9SDimitry Andric 
2123e8d8bef9SDimitry Andric   // Finally we can replace the first definition with
2124e8d8bef9SDimitry Andric   // a zext of the source if the definition is big enough to hold
2125e8d8bef9SDimitry Andric   // all of ZExtSrc bits.
2126e8d8bef9SDimitry Andric   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
2127e8d8bef9SDimitry Andric   return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
2128e8d8bef9SDimitry Andric }
2129e8d8bef9SDimitry Andric 
2130fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) {
2131e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2132e8d8bef9SDimitry Andric          "Expected an unmerge");
2133e8d8bef9SDimitry Andric 
2134e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
2135e8d8bef9SDimitry Andric 
2136e8d8bef9SDimitry Andric   MachineInstr *ZExtInstr =
2137e8d8bef9SDimitry Andric       MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg());
2138e8d8bef9SDimitry Andric   assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT &&
2139e8d8bef9SDimitry Andric          "Expecting a G_ZEXT");
2140e8d8bef9SDimitry Andric 
2141e8d8bef9SDimitry Andric   Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg();
2142e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
2143e8d8bef9SDimitry Andric   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
2144e8d8bef9SDimitry Andric 
2145e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2146e8d8bef9SDimitry Andric 
2147e8d8bef9SDimitry Andric   if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
2148e8d8bef9SDimitry Andric     Builder.buildZExt(Dst0Reg, ZExtSrcReg);
2149e8d8bef9SDimitry Andric   } else {
2150e8d8bef9SDimitry Andric     assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
2151e8d8bef9SDimitry Andric            "ZExt src doesn't fit in destination");
2152e8d8bef9SDimitry Andric     replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
2153e8d8bef9SDimitry Andric   }
2154e8d8bef9SDimitry Andric 
2155e8d8bef9SDimitry Andric   Register ZeroReg;
2156e8d8bef9SDimitry Andric   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
2157e8d8bef9SDimitry Andric     if (!ZeroReg)
2158e8d8bef9SDimitry Andric       ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
2159e8d8bef9SDimitry Andric     replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
2160e8d8bef9SDimitry Andric   }
2161e8d8bef9SDimitry Andric   MI.eraseFromParent();
2162e8d8bef9SDimitry Andric }
2163e8d8bef9SDimitry Andric 
21645ffd83dbSDimitry Andric bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
21655ffd83dbSDimitry Andric                                                 unsigned TargetShiftSize,
21665ffd83dbSDimitry Andric                                                 unsigned &ShiftVal) {
21675ffd83dbSDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SHL ||
21685ffd83dbSDimitry Andric           MI.getOpcode() == TargetOpcode::G_LSHR ||
21695ffd83dbSDimitry Andric           MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
21705ffd83dbSDimitry Andric 
21715ffd83dbSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
21725ffd83dbSDimitry Andric   if (Ty.isVector()) // TODO:
21735ffd83dbSDimitry Andric     return false;
21745ffd83dbSDimitry Andric 
21755ffd83dbSDimitry Andric   // Don't narrow further than the requested size.
21765ffd83dbSDimitry Andric   unsigned Size = Ty.getSizeInBits();
21775ffd83dbSDimitry Andric   if (Size <= TargetShiftSize)
21785ffd83dbSDimitry Andric     return false;
21795ffd83dbSDimitry Andric 
21805ffd83dbSDimitry Andric   auto MaybeImmVal =
2181349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
21825ffd83dbSDimitry Andric   if (!MaybeImmVal)
21835ffd83dbSDimitry Andric     return false;
21845ffd83dbSDimitry Andric 
2185e8d8bef9SDimitry Andric   ShiftVal = MaybeImmVal->Value.getSExtValue();
21865ffd83dbSDimitry Andric   return ShiftVal >= Size / 2 && ShiftVal < Size;
21875ffd83dbSDimitry Andric }
21885ffd83dbSDimitry Andric 
2189fe6060f1SDimitry Andric void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
21905ffd83dbSDimitry Andric                                                 const unsigned &ShiftVal) {
21915ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
21925ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
21935ffd83dbSDimitry Andric   LLT Ty = MRI.getType(SrcReg);
21945ffd83dbSDimitry Andric   unsigned Size = Ty.getSizeInBits();
21955ffd83dbSDimitry Andric   unsigned HalfSize = Size / 2;
21965ffd83dbSDimitry Andric   assert(ShiftVal >= HalfSize);
21975ffd83dbSDimitry Andric 
21985ffd83dbSDimitry Andric   LLT HalfTy = LLT::scalar(HalfSize);
21995ffd83dbSDimitry Andric 
22005ffd83dbSDimitry Andric   Builder.setInstr(MI);
22015ffd83dbSDimitry Andric   auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
22025ffd83dbSDimitry Andric   unsigned NarrowShiftAmt = ShiftVal - HalfSize;
22035ffd83dbSDimitry Andric 
22045ffd83dbSDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_LSHR) {
22055ffd83dbSDimitry Andric     Register Narrowed = Unmerge.getReg(1);
22065ffd83dbSDimitry Andric 
22075ffd83dbSDimitry Andric     //  dst = G_LSHR s64:x, C for C >= 32
22085ffd83dbSDimitry Andric     // =>
22095ffd83dbSDimitry Andric     //   lo, hi = G_UNMERGE_VALUES x
22105ffd83dbSDimitry Andric     //   dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
22115ffd83dbSDimitry Andric 
22125ffd83dbSDimitry Andric     if (NarrowShiftAmt != 0) {
22135ffd83dbSDimitry Andric       Narrowed = Builder.buildLShr(HalfTy, Narrowed,
22145ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
22155ffd83dbSDimitry Andric     }
22165ffd83dbSDimitry Andric 
22175ffd83dbSDimitry Andric     auto Zero = Builder.buildConstant(HalfTy, 0);
2218bdd1243dSDimitry Andric     Builder.buildMergeLikeInstr(DstReg, {Narrowed, Zero});
22195ffd83dbSDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
22205ffd83dbSDimitry Andric     Register Narrowed = Unmerge.getReg(0);
22215ffd83dbSDimitry Andric     //  dst = G_SHL s64:x, C for C >= 32
22225ffd83dbSDimitry Andric     // =>
22235ffd83dbSDimitry Andric     //   lo, hi = G_UNMERGE_VALUES x
22245ffd83dbSDimitry Andric     //   dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
22255ffd83dbSDimitry Andric     if (NarrowShiftAmt != 0) {
22265ffd83dbSDimitry Andric       Narrowed = Builder.buildShl(HalfTy, Narrowed,
22275ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
22285ffd83dbSDimitry Andric     }
22295ffd83dbSDimitry Andric 
22305ffd83dbSDimitry Andric     auto Zero = Builder.buildConstant(HalfTy, 0);
2231bdd1243dSDimitry Andric     Builder.buildMergeLikeInstr(DstReg, {Zero, Narrowed});
22325ffd83dbSDimitry Andric   } else {
22335ffd83dbSDimitry Andric     assert(MI.getOpcode() == TargetOpcode::G_ASHR);
22345ffd83dbSDimitry Andric     auto Hi = Builder.buildAShr(
22355ffd83dbSDimitry Andric       HalfTy, Unmerge.getReg(1),
22365ffd83dbSDimitry Andric       Builder.buildConstant(HalfTy, HalfSize - 1));
22375ffd83dbSDimitry Andric 
22385ffd83dbSDimitry Andric     if (ShiftVal == HalfSize) {
22395ffd83dbSDimitry Andric       // (G_ASHR i64:x, 32) ->
22405ffd83dbSDimitry Andric       //   G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
2241bdd1243dSDimitry Andric       Builder.buildMergeLikeInstr(DstReg, {Unmerge.getReg(1), Hi});
22425ffd83dbSDimitry Andric     } else if (ShiftVal == Size - 1) {
22435ffd83dbSDimitry Andric       // Don't need a second shift.
22445ffd83dbSDimitry Andric       // (G_ASHR i64:x, 63) ->
22455ffd83dbSDimitry Andric       //   %narrowed = (G_ASHR hi_32(x), 31)
22465ffd83dbSDimitry Andric       //   G_MERGE_VALUES %narrowed, %narrowed
2247bdd1243dSDimitry Andric       Builder.buildMergeLikeInstr(DstReg, {Hi, Hi});
22485ffd83dbSDimitry Andric     } else {
22495ffd83dbSDimitry Andric       auto Lo = Builder.buildAShr(
22505ffd83dbSDimitry Andric         HalfTy, Unmerge.getReg(1),
22515ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
22525ffd83dbSDimitry Andric 
22535ffd83dbSDimitry Andric       // (G_ASHR i64:x, C) ->, for C >= 32
22545ffd83dbSDimitry Andric       //   G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
2255bdd1243dSDimitry Andric       Builder.buildMergeLikeInstr(DstReg, {Lo, Hi});
22565ffd83dbSDimitry Andric     }
22575ffd83dbSDimitry Andric   }
22585ffd83dbSDimitry Andric 
22595ffd83dbSDimitry Andric   MI.eraseFromParent();
22605ffd83dbSDimitry Andric }
22615ffd83dbSDimitry Andric 
22625ffd83dbSDimitry Andric bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
22635ffd83dbSDimitry Andric                                               unsigned TargetShiftAmount) {
22645ffd83dbSDimitry Andric   unsigned ShiftAmt;
22655ffd83dbSDimitry Andric   if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
22665ffd83dbSDimitry Andric     applyCombineShiftToUnmerge(MI, ShiftAmt);
22675ffd83dbSDimitry Andric     return true;
22685ffd83dbSDimitry Andric   }
22695ffd83dbSDimitry Andric 
22705ffd83dbSDimitry Andric   return false;
22715ffd83dbSDimitry Andric }
22725ffd83dbSDimitry Andric 
2273e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
2274e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
2275e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2276e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2277e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2278e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI,
2279e8d8bef9SDimitry Andric                   m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg))));
2280e8d8bef9SDimitry Andric }
2281e8d8bef9SDimitry Andric 
2282fe6060f1SDimitry Andric void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
2283e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
2284e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2285e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2286e8d8bef9SDimitry Andric   Builder.buildCopy(DstReg, Reg);
2287e8d8bef9SDimitry Andric   MI.eraseFromParent();
2288e8d8bef9SDimitry Andric }
2289e8d8bef9SDimitry Andric 
2290fe6060f1SDimitry Andric void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2291e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2292e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2293e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2294e8d8bef9SDimitry Andric   Builder.buildZExtOrTrunc(DstReg, Reg);
2295e8d8bef9SDimitry Andric   MI.eraseFromParent();
2296e8d8bef9SDimitry Andric }
2297e8d8bef9SDimitry Andric 
2298e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineAddP2IToPtrAdd(
2299e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2300e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ADD);
2301e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2302e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2303e8d8bef9SDimitry Andric   LLT IntTy = MRI.getType(LHS);
2304e8d8bef9SDimitry Andric 
2305e8d8bef9SDimitry Andric   // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the
2306e8d8bef9SDimitry Andric   // instruction.
2307e8d8bef9SDimitry Andric   PtrReg.second = false;
2308e8d8bef9SDimitry Andric   for (Register SrcReg : {LHS, RHS}) {
2309e8d8bef9SDimitry Andric     if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) {
2310e8d8bef9SDimitry Andric       // Don't handle cases where the integer is implicitly converted to the
2311e8d8bef9SDimitry Andric       // pointer width.
2312e8d8bef9SDimitry Andric       LLT PtrTy = MRI.getType(PtrReg.first);
2313e8d8bef9SDimitry Andric       if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits())
2314e8d8bef9SDimitry Andric         return true;
2315e8d8bef9SDimitry Andric     }
2316e8d8bef9SDimitry Andric 
2317e8d8bef9SDimitry Andric     PtrReg.second = true;
2318e8d8bef9SDimitry Andric   }
2319e8d8bef9SDimitry Andric 
2320e8d8bef9SDimitry Andric   return false;
2321e8d8bef9SDimitry Andric }
2322e8d8bef9SDimitry Andric 
2323fe6060f1SDimitry Andric void CombinerHelper::applyCombineAddP2IToPtrAdd(
2324e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2325e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2326e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2327e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2328e8d8bef9SDimitry Andric 
2329e8d8bef9SDimitry Andric   const bool DoCommute = PtrReg.second;
2330e8d8bef9SDimitry Andric   if (DoCommute)
2331e8d8bef9SDimitry Andric     std::swap(LHS, RHS);
2332e8d8bef9SDimitry Andric   LHS = PtrReg.first;
2333e8d8bef9SDimitry Andric 
2334e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(LHS);
2335e8d8bef9SDimitry Andric 
2336e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2337e8d8bef9SDimitry Andric   auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS);
2338e8d8bef9SDimitry Andric   Builder.buildPtrToInt(Dst, PtrAdd);
2339e8d8bef9SDimitry Andric   MI.eraseFromParent();
2340e8d8bef9SDimitry Andric }
2341e8d8bef9SDimitry Andric 
2342e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI,
234304eeddc0SDimitry Andric                                                   APInt &NewCst) {
2344349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
2345349cc55cSDimitry Andric   Register LHS = PtrAdd.getBaseReg();
2346349cc55cSDimitry Andric   Register RHS = PtrAdd.getOffsetReg();
2347e8d8bef9SDimitry Andric   MachineRegisterInfo &MRI = Builder.getMF().getRegInfo();
2348e8d8bef9SDimitry Andric 
234904eeddc0SDimitry Andric   if (auto RHSCst = getIConstantVRegVal(RHS, MRI)) {
235004eeddc0SDimitry Andric     APInt Cst;
2351e8d8bef9SDimitry Andric     if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) {
235204eeddc0SDimitry Andric       auto DstTy = MRI.getType(PtrAdd.getReg(0));
235304eeddc0SDimitry Andric       // G_INTTOPTR uses zero-extension
235404eeddc0SDimitry Andric       NewCst = Cst.zextOrTrunc(DstTy.getSizeInBits());
235504eeddc0SDimitry Andric       NewCst += RHSCst->sextOrTrunc(DstTy.getSizeInBits());
2356e8d8bef9SDimitry Andric       return true;
2357e8d8bef9SDimitry Andric     }
2358e8d8bef9SDimitry Andric   }
2359e8d8bef9SDimitry Andric 
2360e8d8bef9SDimitry Andric   return false;
2361e8d8bef9SDimitry Andric }
2362e8d8bef9SDimitry Andric 
2363fe6060f1SDimitry Andric void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI,
236404eeddc0SDimitry Andric                                                   APInt &NewCst) {
2365349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
2366349cc55cSDimitry Andric   Register Dst = PtrAdd.getReg(0);
2367e8d8bef9SDimitry Andric 
2368e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2369e8d8bef9SDimitry Andric   Builder.buildConstant(Dst, NewCst);
2370349cc55cSDimitry Andric   PtrAdd.eraseFromParent();
2371e8d8bef9SDimitry Andric }
2372e8d8bef9SDimitry Andric 
2373e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) {
2374e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
2375e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2376e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
23777a6dacacSDimitry Andric   Register OriginalSrcReg = getSrcRegIgnoringCopies(SrcReg, MRI);
23787a6dacacSDimitry Andric   if (OriginalSrcReg.isValid())
23797a6dacacSDimitry Andric     SrcReg = OriginalSrcReg;
2380e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2381e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI,
2382e8d8bef9SDimitry Andric                   m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))));
2383e8d8bef9SDimitry Andric }
2384e8d8bef9SDimitry Andric 
2385fe6060f1SDimitry Andric bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
2386fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2387e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2388fe6060f1SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2389fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2390fe6060f1SDimitry Andric   if (mi_match(SrcReg, MRI,
2391fe6060f1SDimitry Andric                m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
2392fe6060f1SDimitry Andric     unsigned DstSize = DstTy.getScalarSizeInBits();
2393fe6060f1SDimitry Andric     unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2394fe6060f1SDimitry Andric     return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2395fe6060f1SDimitry Andric   }
2396fe6060f1SDimitry Andric   return false;
2397e8d8bef9SDimitry Andric }
2398e8d8bef9SDimitry Andric 
2399e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineExtOfExt(
2400e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2401e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2402e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_SEXT ||
2403e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2404e8d8bef9SDimitry Andric          "Expected a G_[ASZ]EXT");
2405e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
24067a6dacacSDimitry Andric   Register OriginalSrcReg = getSrcRegIgnoringCopies(SrcReg, MRI);
24077a6dacacSDimitry Andric   if (OriginalSrcReg.isValid())
24087a6dacacSDimitry Andric     SrcReg = OriginalSrcReg;
2409e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2410e8d8bef9SDimitry Andric   // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
2411e8d8bef9SDimitry Andric   unsigned Opc = MI.getOpcode();
2412e8d8bef9SDimitry Andric   unsigned SrcOpc = SrcMI->getOpcode();
2413e8d8bef9SDimitry Andric   if (Opc == SrcOpc ||
2414e8d8bef9SDimitry Andric       (Opc == TargetOpcode::G_ANYEXT &&
2415e8d8bef9SDimitry Andric        (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
2416e8d8bef9SDimitry Andric       (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
2417e8d8bef9SDimitry Andric     MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
2418e8d8bef9SDimitry Andric     return true;
2419e8d8bef9SDimitry Andric   }
2420e8d8bef9SDimitry Andric   return false;
2421e8d8bef9SDimitry Andric }
2422e8d8bef9SDimitry Andric 
2423fe6060f1SDimitry Andric void CombinerHelper::applyCombineExtOfExt(
2424e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2425e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2426e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_SEXT ||
2427e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2428e8d8bef9SDimitry Andric          "Expected a G_[ASZ]EXT");
2429e8d8bef9SDimitry Andric 
2430e8d8bef9SDimitry Andric   Register Reg = std::get<0>(MatchInfo);
2431e8d8bef9SDimitry Andric   unsigned SrcExtOp = std::get<1>(MatchInfo);
2432e8d8bef9SDimitry Andric 
2433e8d8bef9SDimitry Andric   // Combine exts with the same opcode.
2434e8d8bef9SDimitry Andric   if (MI.getOpcode() == SrcExtOp) {
2435e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2436e8d8bef9SDimitry Andric     MI.getOperand(1).setReg(Reg);
2437e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2438fe6060f1SDimitry Andric     return;
2439e8d8bef9SDimitry Andric   }
2440e8d8bef9SDimitry Andric 
2441e8d8bef9SDimitry Andric   // Combine:
2442e8d8bef9SDimitry Andric   // - anyext([sz]ext x) to [sz]ext x
2443e8d8bef9SDimitry Andric   // - sext(zext x) to zext x
2444e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2445e8d8bef9SDimitry Andric       (MI.getOpcode() == TargetOpcode::G_SEXT &&
2446e8d8bef9SDimitry Andric        SrcExtOp == TargetOpcode::G_ZEXT)) {
2447e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
2448e8d8bef9SDimitry Andric     Builder.setInstrAndDebugLoc(MI);
2449e8d8bef9SDimitry Andric     Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
2450e8d8bef9SDimitry Andric     MI.eraseFromParent();
2451fe6060f1SDimitry Andric   }
2452e8d8bef9SDimitry Andric }
2453e8d8bef9SDimitry Andric 
2454e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineTruncOfExt(
2455e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2456e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2457e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2458e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2459e8d8bef9SDimitry Andric   unsigned SrcOpc = SrcMI->getOpcode();
2460e8d8bef9SDimitry Andric   if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
2461e8d8bef9SDimitry Andric       SrcOpc == TargetOpcode::G_ZEXT) {
2462e8d8bef9SDimitry Andric     MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
2463e8d8bef9SDimitry Andric     return true;
2464e8d8bef9SDimitry Andric   }
2465e8d8bef9SDimitry Andric   return false;
2466e8d8bef9SDimitry Andric }
2467e8d8bef9SDimitry Andric 
2468fe6060f1SDimitry Andric void CombinerHelper::applyCombineTruncOfExt(
2469e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2470e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2471e8d8bef9SDimitry Andric   Register SrcReg = MatchInfo.first;
2472e8d8bef9SDimitry Andric   unsigned SrcExtOp = MatchInfo.second;
2473e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2474e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2475e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2476e8d8bef9SDimitry Andric   if (SrcTy == DstTy) {
2477e8d8bef9SDimitry Andric     MI.eraseFromParent();
2478e8d8bef9SDimitry Andric     replaceRegWith(MRI, DstReg, SrcReg);
2479fe6060f1SDimitry Andric     return;
2480e8d8bef9SDimitry Andric   }
2481e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2482e8d8bef9SDimitry Andric   if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
2483e8d8bef9SDimitry Andric     Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
2484e8d8bef9SDimitry Andric   else
2485e8d8bef9SDimitry Andric     Builder.buildTrunc(DstReg, SrcReg);
2486e8d8bef9SDimitry Andric   MI.eraseFromParent();
2487e8d8bef9SDimitry Andric }
2488e8d8bef9SDimitry Andric 
2489bdd1243dSDimitry Andric static LLT getMidVTForTruncRightShiftCombine(LLT ShiftTy, LLT TruncTy) {
2490bdd1243dSDimitry Andric   const unsigned ShiftSize = ShiftTy.getScalarSizeInBits();
2491bdd1243dSDimitry Andric   const unsigned TruncSize = TruncTy.getScalarSizeInBits();
2492bdd1243dSDimitry Andric 
2493bdd1243dSDimitry Andric   // ShiftTy > 32 > TruncTy -> 32
2494bdd1243dSDimitry Andric   if (ShiftSize > 32 && TruncSize < 32)
2495bdd1243dSDimitry Andric     return ShiftTy.changeElementSize(32);
2496bdd1243dSDimitry Andric 
2497bdd1243dSDimitry Andric   // TODO: We could also reduce to 16 bits, but that's more target-dependent.
2498bdd1243dSDimitry Andric   //  Some targets like it, some don't, some only like it under certain
2499bdd1243dSDimitry Andric   //  conditions/processor versions, etc.
2500bdd1243dSDimitry Andric   //  A TL hook might be needed for this.
2501bdd1243dSDimitry Andric 
2502bdd1243dSDimitry Andric   // Don't combine
2503bdd1243dSDimitry Andric   return ShiftTy;
2504bdd1243dSDimitry Andric }
2505bdd1243dSDimitry Andric 
2506bdd1243dSDimitry Andric bool CombinerHelper::matchCombineTruncOfShift(
2507bdd1243dSDimitry Andric     MachineInstr &MI, std::pair<MachineInstr *, LLT> &MatchInfo) {
2508e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2509e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2510e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2511e8d8bef9SDimitry Andric 
2512bdd1243dSDimitry Andric   if (!MRI.hasOneNonDBGUse(SrcReg))
2513bdd1243dSDimitry Andric     return false;
2514bdd1243dSDimitry Andric 
2515bdd1243dSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2516bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2517bdd1243dSDimitry Andric 
2518bdd1243dSDimitry Andric   MachineInstr *SrcMI = getDefIgnoringCopies(SrcReg, MRI);
2519bdd1243dSDimitry Andric   const auto &TL = getTargetLowering();
2520bdd1243dSDimitry Andric 
2521bdd1243dSDimitry Andric   LLT NewShiftTy;
2522bdd1243dSDimitry Andric   switch (SrcMI->getOpcode()) {
2523bdd1243dSDimitry Andric   default:
2524bdd1243dSDimitry Andric     return false;
2525bdd1243dSDimitry Andric   case TargetOpcode::G_SHL: {
2526bdd1243dSDimitry Andric     NewShiftTy = DstTy;
2527bdd1243dSDimitry Andric 
2528bdd1243dSDimitry Andric     // Make sure new shift amount is legal.
2529bdd1243dSDimitry Andric     KnownBits Known = KB->getKnownBits(SrcMI->getOperand(2).getReg());
2530bdd1243dSDimitry Andric     if (Known.getMaxValue().uge(NewShiftTy.getScalarSizeInBits()))
2531bdd1243dSDimitry Andric       return false;
2532bdd1243dSDimitry Andric     break;
2533bdd1243dSDimitry Andric   }
2534bdd1243dSDimitry Andric   case TargetOpcode::G_LSHR:
2535bdd1243dSDimitry Andric   case TargetOpcode::G_ASHR: {
2536bdd1243dSDimitry Andric     // For right shifts, we conservatively do not do the transform if the TRUNC
2537bdd1243dSDimitry Andric     // has any STORE users. The reason is that if we change the type of the
2538bdd1243dSDimitry Andric     // shift, we may break the truncstore combine.
2539bdd1243dSDimitry Andric     //
2540bdd1243dSDimitry Andric     // TODO: Fix truncstore combine to handle (trunc(lshr (trunc x), k)).
2541bdd1243dSDimitry Andric     for (auto &User : MRI.use_instructions(DstReg))
2542bdd1243dSDimitry Andric       if (User.getOpcode() == TargetOpcode::G_STORE)
2543bdd1243dSDimitry Andric         return false;
2544bdd1243dSDimitry Andric 
2545bdd1243dSDimitry Andric     NewShiftTy = getMidVTForTruncRightShiftCombine(SrcTy, DstTy);
2546bdd1243dSDimitry Andric     if (NewShiftTy == SrcTy)
2547bdd1243dSDimitry Andric       return false;
2548bdd1243dSDimitry Andric 
2549bdd1243dSDimitry Andric     // Make sure we won't lose information by truncating the high bits.
2550bdd1243dSDimitry Andric     KnownBits Known = KB->getKnownBits(SrcMI->getOperand(2).getReg());
2551bdd1243dSDimitry Andric     if (Known.getMaxValue().ugt(NewShiftTy.getScalarSizeInBits() -
2552bdd1243dSDimitry Andric                                 DstTy.getScalarSizeInBits()))
2553bdd1243dSDimitry Andric       return false;
2554bdd1243dSDimitry Andric     break;
2555bdd1243dSDimitry Andric   }
2556bdd1243dSDimitry Andric   }
2557bdd1243dSDimitry Andric 
2558bdd1243dSDimitry Andric   if (!isLegalOrBeforeLegalizer(
2559bdd1243dSDimitry Andric           {SrcMI->getOpcode(),
2560bdd1243dSDimitry Andric            {NewShiftTy, TL.getPreferredShiftAmountTy(NewShiftTy)}}))
2561bdd1243dSDimitry Andric     return false;
2562bdd1243dSDimitry Andric 
2563bdd1243dSDimitry Andric   MatchInfo = std::make_pair(SrcMI, NewShiftTy);
2564e8d8bef9SDimitry Andric   return true;
2565e8d8bef9SDimitry Andric }
2566e8d8bef9SDimitry Andric 
2567bdd1243dSDimitry Andric void CombinerHelper::applyCombineTruncOfShift(
2568bdd1243dSDimitry Andric     MachineInstr &MI, std::pair<MachineInstr *, LLT> &MatchInfo) {
2569e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2570bdd1243dSDimitry Andric 
2571bdd1243dSDimitry Andric   MachineInstr *ShiftMI = MatchInfo.first;
2572bdd1243dSDimitry Andric   LLT NewShiftTy = MatchInfo.second;
2573bdd1243dSDimitry Andric 
2574bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2575bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(Dst);
2576bdd1243dSDimitry Andric 
2577bdd1243dSDimitry Andric   Register ShiftAmt = ShiftMI->getOperand(2).getReg();
2578bdd1243dSDimitry Andric   Register ShiftSrc = ShiftMI->getOperand(1).getReg();
2579bdd1243dSDimitry Andric   ShiftSrc = Builder.buildTrunc(NewShiftTy, ShiftSrc).getReg(0);
2580bdd1243dSDimitry Andric 
2581bdd1243dSDimitry Andric   Register NewShift =
2582bdd1243dSDimitry Andric       Builder
2583bdd1243dSDimitry Andric           .buildInstr(ShiftMI->getOpcode(), {NewShiftTy}, {ShiftSrc, ShiftAmt})
2584bdd1243dSDimitry Andric           .getReg(0);
2585bdd1243dSDimitry Andric 
2586bdd1243dSDimitry Andric   if (NewShiftTy == DstTy)
2587bdd1243dSDimitry Andric     replaceRegWith(MRI, Dst, NewShift);
2588bdd1243dSDimitry Andric   else
2589bdd1243dSDimitry Andric     Builder.buildTrunc(Dst, NewShift);
2590bdd1243dSDimitry Andric 
2591bdd1243dSDimitry Andric   eraseInst(MI);
2592e8d8bef9SDimitry Andric }
2593e8d8bef9SDimitry Andric 
25945ffd83dbSDimitry Andric bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
25955ffd83dbSDimitry Andric   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
25965ffd83dbSDimitry Andric     return MO.isReg() &&
25975ffd83dbSDimitry Andric            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
25985ffd83dbSDimitry Andric   });
25995ffd83dbSDimitry Andric }
26005ffd83dbSDimitry Andric 
26015ffd83dbSDimitry Andric bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
26025ffd83dbSDimitry Andric   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
26035ffd83dbSDimitry Andric     return !MO.isReg() ||
26045ffd83dbSDimitry Andric            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
26055ffd83dbSDimitry Andric   });
26065ffd83dbSDimitry Andric }
26075ffd83dbSDimitry Andric 
26085ffd83dbSDimitry Andric bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
26095ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
26105ffd83dbSDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
26115ffd83dbSDimitry Andric   return all_of(Mask, [](int Elt) { return Elt < 0; });
26125ffd83dbSDimitry Andric }
26135ffd83dbSDimitry Andric 
26145ffd83dbSDimitry Andric bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
26155ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_STORE);
26165ffd83dbSDimitry Andric   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
26175ffd83dbSDimitry Andric                       MRI);
26185ffd83dbSDimitry Andric }
26195ffd83dbSDimitry Andric 
2620e8d8bef9SDimitry Andric bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
2621e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2622e8d8bef9SDimitry Andric   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
2623e8d8bef9SDimitry Andric                       MRI);
2624e8d8bef9SDimitry Andric }
2625e8d8bef9SDimitry Andric 
2626bdd1243dSDimitry Andric bool CombinerHelper::matchInsertExtractVecEltOutOfBounds(MachineInstr &MI) {
2627bdd1243dSDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT ||
2628bdd1243dSDimitry Andric           MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT) &&
2629bdd1243dSDimitry Andric          "Expected an insert/extract element op");
2630bdd1243dSDimitry Andric   LLT VecTy = MRI.getType(MI.getOperand(1).getReg());
2631bdd1243dSDimitry Andric   unsigned IdxIdx =
2632bdd1243dSDimitry Andric       MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
2633bdd1243dSDimitry Andric   auto Idx = getIConstantVRegVal(MI.getOperand(IdxIdx).getReg(), MRI);
2634bdd1243dSDimitry Andric   if (!Idx)
2635bdd1243dSDimitry Andric     return false;
2636bdd1243dSDimitry Andric   return Idx->getZExtValue() >= VecTy.getNumElements();
2637bdd1243dSDimitry Andric }
2638bdd1243dSDimitry Andric 
2639e8d8bef9SDimitry Andric bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
2640349cc55cSDimitry Andric   GSelect &SelMI = cast<GSelect>(MI);
2641349cc55cSDimitry Andric   auto Cst =
2642349cc55cSDimitry Andric       isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI);
2643349cc55cSDimitry Andric   if (!Cst)
2644e8d8bef9SDimitry Andric     return false;
2645349cc55cSDimitry Andric   OpIdx = Cst->isZero() ? 3 : 2;
2646349cc55cSDimitry Andric   return true;
2647e8d8bef9SDimitry Andric }
2648e8d8bef9SDimitry Andric 
264906c3fb27SDimitry Andric void CombinerHelper::eraseInst(MachineInstr &MI) { MI.eraseFromParent(); }
26505ffd83dbSDimitry Andric 
26515ffd83dbSDimitry Andric bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
26525ffd83dbSDimitry Andric                                     const MachineOperand &MOP2) {
26535ffd83dbSDimitry Andric   if (!MOP1.isReg() || !MOP2.isReg())
26545ffd83dbSDimitry Andric     return false;
2655349cc55cSDimitry Andric   auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
2656349cc55cSDimitry Andric   if (!InstAndDef1)
26575ffd83dbSDimitry Andric     return false;
2658349cc55cSDimitry Andric   auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
2659349cc55cSDimitry Andric   if (!InstAndDef2)
26605ffd83dbSDimitry Andric     return false;
2661349cc55cSDimitry Andric   MachineInstr *I1 = InstAndDef1->MI;
2662349cc55cSDimitry Andric   MachineInstr *I2 = InstAndDef2->MI;
26635ffd83dbSDimitry Andric 
26645ffd83dbSDimitry Andric   // Handle a case like this:
26655ffd83dbSDimitry Andric   //
26665ffd83dbSDimitry Andric   // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
26675ffd83dbSDimitry Andric   //
26685ffd83dbSDimitry Andric   // Even though %0 and %1 are produced by the same instruction they are not
26695ffd83dbSDimitry Andric   // the same values.
26705ffd83dbSDimitry Andric   if (I1 == I2)
26715ffd83dbSDimitry Andric     return MOP1.getReg() == MOP2.getReg();
26725ffd83dbSDimitry Andric 
26735ffd83dbSDimitry Andric   // If we have an instruction which loads or stores, we can't guarantee that
26745ffd83dbSDimitry Andric   // it is identical.
26755ffd83dbSDimitry Andric   //
26765ffd83dbSDimitry Andric   // For example, we may have
26775ffd83dbSDimitry Andric   //
26785ffd83dbSDimitry Andric   // %x1 = G_LOAD %addr (load N from @somewhere)
26795ffd83dbSDimitry Andric   // ...
26805ffd83dbSDimitry Andric   // call @foo
26815ffd83dbSDimitry Andric   // ...
26825ffd83dbSDimitry Andric   // %x2 = G_LOAD %addr (load N from @somewhere)
26835ffd83dbSDimitry Andric   // ...
26845ffd83dbSDimitry Andric   // %or = G_OR %x1, %x2
26855ffd83dbSDimitry Andric   //
26865ffd83dbSDimitry Andric   // It's possible that @foo will modify whatever lives at the address we're
26875ffd83dbSDimitry Andric   // loading from. To be safe, let's just assume that all loads and stores
26885ffd83dbSDimitry Andric   // are different (unless we have something which is guaranteed to not
26895ffd83dbSDimitry Andric   // change.)
2690fcaf7f86SDimitry Andric   if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad())
26915ffd83dbSDimitry Andric     return false;
26925ffd83dbSDimitry Andric 
269381ad6265SDimitry Andric   // If both instructions are loads or stores, they are equal only if both
269481ad6265SDimitry Andric   // are dereferenceable invariant loads with the same number of bits.
269581ad6265SDimitry Andric   if (I1->mayLoadOrStore() && I2->mayLoadOrStore()) {
269681ad6265SDimitry Andric     GLoadStore *LS1 = dyn_cast<GLoadStore>(I1);
269781ad6265SDimitry Andric     GLoadStore *LS2 = dyn_cast<GLoadStore>(I2);
269881ad6265SDimitry Andric     if (!LS1 || !LS2)
269981ad6265SDimitry Andric       return false;
270081ad6265SDimitry Andric 
2701fcaf7f86SDimitry Andric     if (!I2->isDereferenceableInvariantLoad() ||
270281ad6265SDimitry Andric         (LS1->getMemSizeInBits() != LS2->getMemSizeInBits()))
270381ad6265SDimitry Andric       return false;
270481ad6265SDimitry Andric   }
270581ad6265SDimitry Andric 
27065ffd83dbSDimitry Andric   // Check for physical registers on the instructions first to avoid cases
27075ffd83dbSDimitry Andric   // like this:
27085ffd83dbSDimitry Andric   //
27095ffd83dbSDimitry Andric   // %a = COPY $physreg
27105ffd83dbSDimitry Andric   // ...
27115ffd83dbSDimitry Andric   // SOMETHING implicit-def $physreg
27125ffd83dbSDimitry Andric   // ...
27135ffd83dbSDimitry Andric   // %b = COPY $physreg
27145ffd83dbSDimitry Andric   //
27155ffd83dbSDimitry Andric   // These copies are not equivalent.
27165ffd83dbSDimitry Andric   if (any_of(I1->uses(), [](const MachineOperand &MO) {
27175ffd83dbSDimitry Andric         return MO.isReg() && MO.getReg().isPhysical();
27185ffd83dbSDimitry Andric       })) {
27195ffd83dbSDimitry Andric     // Check if we have a case like this:
27205ffd83dbSDimitry Andric     //
27215ffd83dbSDimitry Andric     // %a = COPY $physreg
27225ffd83dbSDimitry Andric     // %b = COPY %a
27235ffd83dbSDimitry Andric     //
27245ffd83dbSDimitry Andric     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
27255ffd83dbSDimitry Andric     // From that, we know that they must have the same value, since they must
27265ffd83dbSDimitry Andric     // have come from the same COPY.
27275ffd83dbSDimitry Andric     return I1->isIdenticalTo(*I2);
27285ffd83dbSDimitry Andric   }
27295ffd83dbSDimitry Andric 
27305ffd83dbSDimitry Andric   // We don't have any physical registers, so we don't necessarily need the
27315ffd83dbSDimitry Andric   // same vreg defs.
27325ffd83dbSDimitry Andric   //
27335ffd83dbSDimitry Andric   // On the off-chance that there's some target instruction feeding into the
27345ffd83dbSDimitry Andric   // instruction, let's use produceSameValue instead of isIdenticalTo.
2735349cc55cSDimitry Andric   if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
2736349cc55cSDimitry Andric     // Handle instructions with multiple defs that produce same values. Values
2737349cc55cSDimitry Andric     // are same for operands with same index.
2738349cc55cSDimitry Andric     // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2739349cc55cSDimitry Andric     // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2740349cc55cSDimitry Andric     // I1 and I2 are different instructions but produce same values,
2741349cc55cSDimitry Andric     // %1 and %6 are same, %1 and %7 are not the same value.
2742349cc55cSDimitry Andric     return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) ==
2743349cc55cSDimitry Andric            I2->findRegisterDefOperandIdx(InstAndDef2->Reg);
2744349cc55cSDimitry Andric   }
2745349cc55cSDimitry Andric   return false;
27465ffd83dbSDimitry Andric }
27475ffd83dbSDimitry Andric 
27485ffd83dbSDimitry Andric bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
27495ffd83dbSDimitry Andric   if (!MOP.isReg())
27505ffd83dbSDimitry Andric     return false;
2751349cc55cSDimitry Andric   auto *MI = MRI.getVRegDef(MOP.getReg());
2752349cc55cSDimitry Andric   auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI);
275381ad6265SDimitry Andric   return MaybeCst && MaybeCst->getBitWidth() <= 64 &&
2754349cc55cSDimitry Andric          MaybeCst->getSExtValue() == C;
27555ffd83dbSDimitry Andric }
27565ffd83dbSDimitry Andric 
27575f757f3fSDimitry Andric bool CombinerHelper::matchConstantFPOp(const MachineOperand &MOP, double C) {
27585f757f3fSDimitry Andric   if (!MOP.isReg())
27595f757f3fSDimitry Andric     return false;
27605f757f3fSDimitry Andric   std::optional<FPValueAndVReg> MaybeCst;
27615f757f3fSDimitry Andric   if (!mi_match(MOP.getReg(), MRI, m_GFCstOrSplat(MaybeCst)))
27625f757f3fSDimitry Andric     return false;
27635f757f3fSDimitry Andric 
27645f757f3fSDimitry Andric   return MaybeCst->Value.isExactlyValue(C);
27655f757f3fSDimitry Andric }
27665f757f3fSDimitry Andric 
276706c3fb27SDimitry Andric void CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
27685ffd83dbSDimitry Andric                                                      unsigned OpIdx) {
27695ffd83dbSDimitry Andric   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
27705ffd83dbSDimitry Andric   Register OldReg = MI.getOperand(0).getReg();
27715ffd83dbSDimitry Andric   Register Replacement = MI.getOperand(OpIdx).getReg();
27725ffd83dbSDimitry Andric   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
27735ffd83dbSDimitry Andric   MI.eraseFromParent();
27745ffd83dbSDimitry Andric   replaceRegWith(MRI, OldReg, Replacement);
27755ffd83dbSDimitry Andric }
27765ffd83dbSDimitry Andric 
277706c3fb27SDimitry Andric void CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
2778e8d8bef9SDimitry Andric                                                  Register Replacement) {
2779e8d8bef9SDimitry Andric   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2780e8d8bef9SDimitry Andric   Register OldReg = MI.getOperand(0).getReg();
2781e8d8bef9SDimitry Andric   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2782e8d8bef9SDimitry Andric   MI.eraseFromParent();
2783e8d8bef9SDimitry Andric   replaceRegWith(MRI, OldReg, Replacement);
2784e8d8bef9SDimitry Andric }
2785e8d8bef9SDimitry Andric 
27865f757f3fSDimitry Andric bool CombinerHelper::matchConstantLargerBitWidth(MachineInstr &MI,
27875f757f3fSDimitry Andric                                                  unsigned ConstIdx) {
27885f757f3fSDimitry Andric   Register ConstReg = MI.getOperand(ConstIdx).getReg();
27895f757f3fSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
27905f757f3fSDimitry Andric 
27915f757f3fSDimitry Andric   // Get the shift amount
27925f757f3fSDimitry Andric   auto VRegAndVal = getIConstantVRegValWithLookThrough(ConstReg, MRI);
27935f757f3fSDimitry Andric   if (!VRegAndVal)
27945f757f3fSDimitry Andric     return false;
27955f757f3fSDimitry Andric 
27965f757f3fSDimitry Andric   // Return true of shift amount >= Bitwidth
27975f757f3fSDimitry Andric   return (VRegAndVal->Value.uge(DstTy.getSizeInBits()));
27985f757f3fSDimitry Andric }
27995f757f3fSDimitry Andric 
28005f757f3fSDimitry Andric void CombinerHelper::applyFunnelShiftConstantModulo(MachineInstr &MI) {
28015f757f3fSDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_FSHL ||
28025f757f3fSDimitry Andric           MI.getOpcode() == TargetOpcode::G_FSHR) &&
28035f757f3fSDimitry Andric          "This is not a funnel shift operation");
28045f757f3fSDimitry Andric 
28055f757f3fSDimitry Andric   Register ConstReg = MI.getOperand(3).getReg();
28065f757f3fSDimitry Andric   LLT ConstTy = MRI.getType(ConstReg);
28075f757f3fSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
28085f757f3fSDimitry Andric 
28095f757f3fSDimitry Andric   auto VRegAndVal = getIConstantVRegValWithLookThrough(ConstReg, MRI);
28105f757f3fSDimitry Andric   assert((VRegAndVal) && "Value is not a constant");
28115f757f3fSDimitry Andric 
28125f757f3fSDimitry Andric   // Calculate the new Shift Amount = Old Shift Amount % BitWidth
28135f757f3fSDimitry Andric   APInt NewConst = VRegAndVal->Value.urem(
28145f757f3fSDimitry Andric       APInt(ConstTy.getSizeInBits(), DstTy.getScalarSizeInBits()));
28155f757f3fSDimitry Andric 
28165f757f3fSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
28175f757f3fSDimitry Andric   auto NewConstInstr = Builder.buildConstant(ConstTy, NewConst.getZExtValue());
28185f757f3fSDimitry Andric   Builder.buildInstr(
28195f757f3fSDimitry Andric       MI.getOpcode(), {MI.getOperand(0)},
28205f757f3fSDimitry Andric       {MI.getOperand(1), MI.getOperand(2), NewConstInstr.getReg(0)});
28215f757f3fSDimitry Andric 
28225f757f3fSDimitry Andric   MI.eraseFromParent();
28235f757f3fSDimitry Andric }
28245f757f3fSDimitry Andric 
28255ffd83dbSDimitry Andric bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
28265ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
28275ffd83dbSDimitry Andric   // Match (cond ? x : x)
28285ffd83dbSDimitry Andric   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
28295ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
28305ffd83dbSDimitry Andric                        MRI);
28315ffd83dbSDimitry Andric }
28325ffd83dbSDimitry Andric 
28335ffd83dbSDimitry Andric bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
28345ffd83dbSDimitry Andric   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
28355ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
28365ffd83dbSDimitry Andric                        MRI);
28375ffd83dbSDimitry Andric }
28385ffd83dbSDimitry Andric 
28395ffd83dbSDimitry Andric bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
28405ffd83dbSDimitry Andric   return matchConstantOp(MI.getOperand(OpIdx), 0) &&
28415ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
28425ffd83dbSDimitry Andric                        MRI);
28435ffd83dbSDimitry Andric }
28445ffd83dbSDimitry Andric 
2845e8d8bef9SDimitry Andric bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
2846e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
2847e8d8bef9SDimitry Andric   return MO.isReg() &&
2848e8d8bef9SDimitry Andric          getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2849e8d8bef9SDimitry Andric }
2850e8d8bef9SDimitry Andric 
2851e8d8bef9SDimitry Andric bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
2852e8d8bef9SDimitry Andric                                                         unsigned OpIdx) {
2853e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
2854e8d8bef9SDimitry Andric   return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
2855e8d8bef9SDimitry Andric }
2856e8d8bef9SDimitry Andric 
285706c3fb27SDimitry Andric void CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
28585ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
28595ffd83dbSDimitry Andric   Builder.setInstr(MI);
28605ffd83dbSDimitry Andric   Builder.buildFConstant(MI.getOperand(0), C);
28615ffd83dbSDimitry Andric   MI.eraseFromParent();
28625ffd83dbSDimitry Andric }
28635ffd83dbSDimitry Andric 
286406c3fb27SDimitry Andric void CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
28655ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
28665ffd83dbSDimitry Andric   Builder.setInstr(MI);
28675ffd83dbSDimitry Andric   Builder.buildConstant(MI.getOperand(0), C);
28685ffd83dbSDimitry Andric   MI.eraseFromParent();
28695ffd83dbSDimitry Andric }
28705ffd83dbSDimitry Andric 
287106c3fb27SDimitry Andric void CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) {
2872fe6060f1SDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2873fe6060f1SDimitry Andric   Builder.setInstr(MI);
2874fe6060f1SDimitry Andric   Builder.buildConstant(MI.getOperand(0), C);
2875fe6060f1SDimitry Andric   MI.eraseFromParent();
2876fe6060f1SDimitry Andric }
2877fe6060f1SDimitry Andric 
28785f757f3fSDimitry Andric void CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, ConstantFP *CFP) {
28795f757f3fSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
28805f757f3fSDimitry Andric   Builder.setInstr(MI);
28815f757f3fSDimitry Andric   Builder.buildFConstant(MI.getOperand(0), CFP->getValueAPF());
28825f757f3fSDimitry Andric   MI.eraseFromParent();
28835f757f3fSDimitry Andric }
28845f757f3fSDimitry Andric 
288506c3fb27SDimitry Andric void CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
28865ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
28875ffd83dbSDimitry Andric   Builder.setInstr(MI);
28885ffd83dbSDimitry Andric   Builder.buildUndef(MI.getOperand(0));
28895ffd83dbSDimitry Andric   MI.eraseFromParent();
28905ffd83dbSDimitry Andric }
28915ffd83dbSDimitry Andric 
28925ffd83dbSDimitry Andric bool CombinerHelper::matchSimplifyAddToSub(
28935ffd83dbSDimitry Andric     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
28945ffd83dbSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
28955ffd83dbSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
28965ffd83dbSDimitry Andric   Register &NewLHS = std::get<0>(MatchInfo);
28975ffd83dbSDimitry Andric   Register &NewRHS = std::get<1>(MatchInfo);
28985ffd83dbSDimitry Andric 
28995ffd83dbSDimitry Andric   // Helper lambda to check for opportunities for
29005ffd83dbSDimitry Andric   // ((0-A) + B) -> B - A
29015ffd83dbSDimitry Andric   // (A + (0-B)) -> A - B
29025ffd83dbSDimitry Andric   auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
2903e8d8bef9SDimitry Andric     if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
29045ffd83dbSDimitry Andric       return false;
29055ffd83dbSDimitry Andric     NewLHS = MaybeNewLHS;
29065ffd83dbSDimitry Andric     return true;
29075ffd83dbSDimitry Andric   };
29085ffd83dbSDimitry Andric 
29095ffd83dbSDimitry Andric   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
29105ffd83dbSDimitry Andric }
29115ffd83dbSDimitry Andric 
2912e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineInsertVecElts(
2913e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2914e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2915e8d8bef9SDimitry Andric          "Invalid opcode");
2916e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2917e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2918e8d8bef9SDimitry Andric   assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2919e8d8bef9SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
2920e8d8bef9SDimitry Andric   // If this MI is part of a sequence of insert_vec_elts, then
2921e8d8bef9SDimitry Andric   // don't do the combine in the middle of the sequence.
2922e8d8bef9SDimitry Andric   if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
2923e8d8bef9SDimitry Andric                                    TargetOpcode::G_INSERT_VECTOR_ELT)
2924e8d8bef9SDimitry Andric     return false;
2925e8d8bef9SDimitry Andric   MachineInstr *CurrInst = &MI;
2926e8d8bef9SDimitry Andric   MachineInstr *TmpInst;
2927e8d8bef9SDimitry Andric   int64_t IntImm;
2928e8d8bef9SDimitry Andric   Register TmpReg;
2929e8d8bef9SDimitry Andric   MatchInfo.resize(NumElts);
2930e8d8bef9SDimitry Andric   while (mi_match(
2931e8d8bef9SDimitry Andric       CurrInst->getOperand(0).getReg(), MRI,
2932e8d8bef9SDimitry Andric       m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2933bdd1243dSDimitry Andric     if (IntImm >= NumElts || IntImm < 0)
2934e8d8bef9SDimitry Andric       return false;
2935e8d8bef9SDimitry Andric     if (!MatchInfo[IntImm])
2936e8d8bef9SDimitry Andric       MatchInfo[IntImm] = TmpReg;
2937e8d8bef9SDimitry Andric     CurrInst = TmpInst;
2938e8d8bef9SDimitry Andric   }
2939e8d8bef9SDimitry Andric   // Variable index.
2940e8d8bef9SDimitry Andric   if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2941e8d8bef9SDimitry Andric     return false;
2942e8d8bef9SDimitry Andric   if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2943e8d8bef9SDimitry Andric     for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2944e8d8bef9SDimitry Andric       if (!MatchInfo[I - 1].isValid())
2945e8d8bef9SDimitry Andric         MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2946e8d8bef9SDimitry Andric     }
2947e8d8bef9SDimitry Andric     return true;
2948e8d8bef9SDimitry Andric   }
2949e8d8bef9SDimitry Andric   // If we didn't end in a G_IMPLICIT_DEF, bail out.
2950e8d8bef9SDimitry Andric   return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
2951e8d8bef9SDimitry Andric }
2952e8d8bef9SDimitry Andric 
2953fe6060f1SDimitry Andric void CombinerHelper::applyCombineInsertVecElts(
2954e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2955e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2956e8d8bef9SDimitry Andric   Register UndefReg;
2957e8d8bef9SDimitry Andric   auto GetUndef = [&]() {
2958e8d8bef9SDimitry Andric     if (UndefReg)
2959e8d8bef9SDimitry Andric       return UndefReg;
2960e8d8bef9SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2961e8d8bef9SDimitry Andric     UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
2962e8d8bef9SDimitry Andric     return UndefReg;
2963e8d8bef9SDimitry Andric   };
2964e8d8bef9SDimitry Andric   for (unsigned I = 0; I < MatchInfo.size(); ++I) {
2965e8d8bef9SDimitry Andric     if (!MatchInfo[I])
2966e8d8bef9SDimitry Andric       MatchInfo[I] = GetUndef();
2967e8d8bef9SDimitry Andric   }
2968e8d8bef9SDimitry Andric   Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
2969e8d8bef9SDimitry Andric   MI.eraseFromParent();
2970e8d8bef9SDimitry Andric }
2971e8d8bef9SDimitry Andric 
2972fe6060f1SDimitry Andric void CombinerHelper::applySimplifyAddToSub(
29735ffd83dbSDimitry Andric     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
29745ffd83dbSDimitry Andric   Builder.setInstr(MI);
29755ffd83dbSDimitry Andric   Register SubLHS, SubRHS;
29765ffd83dbSDimitry Andric   std::tie(SubLHS, SubRHS) = MatchInfo;
29775ffd83dbSDimitry Andric   Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
29785ffd83dbSDimitry Andric   MI.eraseFromParent();
29795ffd83dbSDimitry Andric }
29805ffd83dbSDimitry Andric 
2981e8d8bef9SDimitry Andric bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
2982e8d8bef9SDimitry Andric     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2983e8d8bef9SDimitry Andric   // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
2984e8d8bef9SDimitry Andric   //
2985e8d8bef9SDimitry Andric   // Creates the new hand + logic instruction (but does not insert them.)
2986e8d8bef9SDimitry Andric   //
2987e8d8bef9SDimitry Andric   // On success, MatchInfo is populated with the new instructions. These are
2988e8d8bef9SDimitry Andric   // inserted in applyHoistLogicOpWithSameOpcodeHands.
2989e8d8bef9SDimitry Andric   unsigned LogicOpcode = MI.getOpcode();
2990e8d8bef9SDimitry Andric   assert(LogicOpcode == TargetOpcode::G_AND ||
2991e8d8bef9SDimitry Andric          LogicOpcode == TargetOpcode::G_OR ||
2992e8d8bef9SDimitry Andric          LogicOpcode == TargetOpcode::G_XOR);
2993e8d8bef9SDimitry Andric   MachineIRBuilder MIB(MI);
2994e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2995e8d8bef9SDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
2996e8d8bef9SDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
2997e8d8bef9SDimitry Andric 
2998e8d8bef9SDimitry Andric   // Don't recompute anything.
2999e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
3000e8d8bef9SDimitry Andric     return false;
3001e8d8bef9SDimitry Andric 
3002e8d8bef9SDimitry Andric   // Make sure we have (hand x, ...), (hand y, ...)
3003e8d8bef9SDimitry Andric   MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
3004e8d8bef9SDimitry Andric   MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
3005e8d8bef9SDimitry Andric   if (!LeftHandInst || !RightHandInst)
3006e8d8bef9SDimitry Andric     return false;
3007e8d8bef9SDimitry Andric   unsigned HandOpcode = LeftHandInst->getOpcode();
3008e8d8bef9SDimitry Andric   if (HandOpcode != RightHandInst->getOpcode())
3009e8d8bef9SDimitry Andric     return false;
3010e8d8bef9SDimitry Andric   if (!LeftHandInst->getOperand(1).isReg() ||
3011e8d8bef9SDimitry Andric       !RightHandInst->getOperand(1).isReg())
3012e8d8bef9SDimitry Andric     return false;
3013e8d8bef9SDimitry Andric 
3014e8d8bef9SDimitry Andric   // Make sure the types match up, and if we're doing this post-legalization,
3015e8d8bef9SDimitry Andric   // we end up with legal types.
3016e8d8bef9SDimitry Andric   Register X = LeftHandInst->getOperand(1).getReg();
3017e8d8bef9SDimitry Andric   Register Y = RightHandInst->getOperand(1).getReg();
3018e8d8bef9SDimitry Andric   LLT XTy = MRI.getType(X);
3019e8d8bef9SDimitry Andric   LLT YTy = MRI.getType(Y);
302006c3fb27SDimitry Andric   if (!XTy.isValid() || XTy != YTy)
3021e8d8bef9SDimitry Andric     return false;
3022e8d8bef9SDimitry Andric 
3023e8d8bef9SDimitry Andric   // Optional extra source register.
3024e8d8bef9SDimitry Andric   Register ExtraHandOpSrcReg;
3025e8d8bef9SDimitry Andric   switch (HandOpcode) {
3026e8d8bef9SDimitry Andric   default:
3027e8d8bef9SDimitry Andric     return false;
3028e8d8bef9SDimitry Andric   case TargetOpcode::G_ANYEXT:
3029e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXT:
3030e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXT: {
3031e8d8bef9SDimitry Andric     // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
3032e8d8bef9SDimitry Andric     break;
3033e8d8bef9SDimitry Andric   }
3034e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
3035e8d8bef9SDimitry Andric   case TargetOpcode::G_ASHR:
3036e8d8bef9SDimitry Andric   case TargetOpcode::G_LSHR:
3037e8d8bef9SDimitry Andric   case TargetOpcode::G_SHL: {
3038e8d8bef9SDimitry Andric     // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
3039e8d8bef9SDimitry Andric     MachineOperand &ZOp = LeftHandInst->getOperand(2);
3040e8d8bef9SDimitry Andric     if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
3041e8d8bef9SDimitry Andric       return false;
3042e8d8bef9SDimitry Andric     ExtraHandOpSrcReg = ZOp.getReg();
3043e8d8bef9SDimitry Andric     break;
3044e8d8bef9SDimitry Andric   }
3045e8d8bef9SDimitry Andric   }
3046e8d8bef9SDimitry Andric 
304706c3fb27SDimitry Andric   if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
304806c3fb27SDimitry Andric     return false;
304906c3fb27SDimitry Andric 
3050e8d8bef9SDimitry Andric   // Record the steps to build the new instructions.
3051e8d8bef9SDimitry Andric   //
3052e8d8bef9SDimitry Andric   // Steps to build (logic x, y)
3053e8d8bef9SDimitry Andric   auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
3054e8d8bef9SDimitry Andric   OperandBuildSteps LogicBuildSteps = {
3055e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
3056e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
3057e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
3058e8d8bef9SDimitry Andric   InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
3059e8d8bef9SDimitry Andric 
3060e8d8bef9SDimitry Andric   // Steps to build hand (logic x, y), ...z
3061e8d8bef9SDimitry Andric   OperandBuildSteps HandBuildSteps = {
3062e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
3063e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
3064e8d8bef9SDimitry Andric   if (ExtraHandOpSrcReg.isValid())
3065e8d8bef9SDimitry Andric     HandBuildSteps.push_back(
3066e8d8bef9SDimitry Andric         [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
3067e8d8bef9SDimitry Andric   InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
3068e8d8bef9SDimitry Andric 
3069e8d8bef9SDimitry Andric   MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
3070e8d8bef9SDimitry Andric   return true;
3071e8d8bef9SDimitry Andric }
3072e8d8bef9SDimitry Andric 
3073fe6060f1SDimitry Andric void CombinerHelper::applyBuildInstructionSteps(
3074e8d8bef9SDimitry Andric     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
3075e8d8bef9SDimitry Andric   assert(MatchInfo.InstrsToBuild.size() &&
3076e8d8bef9SDimitry Andric          "Expected at least one instr to build?");
3077e8d8bef9SDimitry Andric   Builder.setInstr(MI);
3078e8d8bef9SDimitry Andric   for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
3079e8d8bef9SDimitry Andric     assert(InstrToBuild.Opcode && "Expected a valid opcode?");
3080e8d8bef9SDimitry Andric     assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
3081e8d8bef9SDimitry Andric     MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
3082e8d8bef9SDimitry Andric     for (auto &OperandFn : InstrToBuild.OperandFns)
3083e8d8bef9SDimitry Andric       OperandFn(Instr);
3084e8d8bef9SDimitry Andric   }
3085e8d8bef9SDimitry Andric   MI.eraseFromParent();
3086e8d8bef9SDimitry Andric }
3087e8d8bef9SDimitry Andric 
3088e8d8bef9SDimitry Andric bool CombinerHelper::matchAshrShlToSextInreg(
3089e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
3090e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
3091e8d8bef9SDimitry Andric   int64_t ShlCst, AshrCst;
3092e8d8bef9SDimitry Andric   Register Src;
3093e8d8bef9SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
3094bdd1243dSDimitry Andric                 m_GAShr(m_GShl(m_Reg(Src), m_ICstOrSplat(ShlCst)),
3095bdd1243dSDimitry Andric                         m_ICstOrSplat(AshrCst))))
3096e8d8bef9SDimitry Andric     return false;
3097e8d8bef9SDimitry Andric   if (ShlCst != AshrCst)
3098e8d8bef9SDimitry Andric     return false;
3099e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer(
3100e8d8bef9SDimitry Andric           {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
3101e8d8bef9SDimitry Andric     return false;
3102e8d8bef9SDimitry Andric   MatchInfo = std::make_tuple(Src, ShlCst);
3103e8d8bef9SDimitry Andric   return true;
3104e8d8bef9SDimitry Andric }
3105fe6060f1SDimitry Andric 
3106fe6060f1SDimitry Andric void CombinerHelper::applyAshShlToSextInreg(
3107e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
3108e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
3109e8d8bef9SDimitry Andric   Register Src;
3110e8d8bef9SDimitry Andric   int64_t ShiftAmt;
3111e8d8bef9SDimitry Andric   std::tie(Src, ShiftAmt) = MatchInfo;
3112e8d8bef9SDimitry Andric   unsigned Size = MRI.getType(Src).getScalarSizeInBits();
3113e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3114e8d8bef9SDimitry Andric   Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
3115e8d8bef9SDimitry Andric   MI.eraseFromParent();
3116fe6060f1SDimitry Andric }
3117fe6060f1SDimitry Andric 
3118fe6060f1SDimitry Andric /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
3119fe6060f1SDimitry Andric bool CombinerHelper::matchOverlappingAnd(
3120fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3121fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
3122fe6060f1SDimitry Andric 
3123fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
3124fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
3125fe6060f1SDimitry Andric 
3126fe6060f1SDimitry Andric   Register R;
3127fe6060f1SDimitry Andric   int64_t C1;
3128fe6060f1SDimitry Andric   int64_t C2;
3129fe6060f1SDimitry Andric   if (!mi_match(
3130fe6060f1SDimitry Andric           Dst, MRI,
3131fe6060f1SDimitry Andric           m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
3132fe6060f1SDimitry Andric     return false;
3133fe6060f1SDimitry Andric 
3134fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
3135fe6060f1SDimitry Andric     if (C1 & C2) {
3136fe6060f1SDimitry Andric       B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
3137fe6060f1SDimitry Andric       return;
3138fe6060f1SDimitry Andric     }
3139fe6060f1SDimitry Andric     auto Zero = B.buildConstant(Ty, 0);
3140fe6060f1SDimitry Andric     replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
3141fe6060f1SDimitry Andric   };
3142e8d8bef9SDimitry Andric   return true;
3143e8d8bef9SDimitry Andric }
3144e8d8bef9SDimitry Andric 
3145e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
3146e8d8bef9SDimitry Andric                                        Register &Replacement) {
3147e8d8bef9SDimitry Andric   // Given
3148e8d8bef9SDimitry Andric   //
3149e8d8bef9SDimitry Andric   // %y:_(sN) = G_SOMETHING
3150e8d8bef9SDimitry Andric   // %x:_(sN) = G_SOMETHING
3151e8d8bef9SDimitry Andric   // %res:_(sN) = G_AND %x, %y
3152e8d8bef9SDimitry Andric   //
3153e8d8bef9SDimitry Andric   // Eliminate the G_AND when it is known that x & y == x or x & y == y.
3154e8d8bef9SDimitry Andric   //
3155e8d8bef9SDimitry Andric   // Patterns like this can appear as a result of legalization. E.g.
3156e8d8bef9SDimitry Andric   //
3157e8d8bef9SDimitry Andric   // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
3158e8d8bef9SDimitry Andric   // %one:_(s32) = G_CONSTANT i32 1
3159e8d8bef9SDimitry Andric   // %and:_(s32) = G_AND %cmp, %one
3160e8d8bef9SDimitry Andric   //
3161e8d8bef9SDimitry Andric   // In this case, G_ICMP only produces a single bit, so x & 1 == x.
3162e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
3163e8d8bef9SDimitry Andric   if (!KB)
3164e8d8bef9SDimitry Andric     return false;
3165e8d8bef9SDimitry Andric 
3166e8d8bef9SDimitry Andric   Register AndDst = MI.getOperand(0).getReg();
3167e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
3168e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
3169e8d8bef9SDimitry Andric   KnownBits LHSBits = KB->getKnownBits(LHS);
3170e8d8bef9SDimitry Andric   KnownBits RHSBits = KB->getKnownBits(RHS);
3171e8d8bef9SDimitry Andric 
3172e8d8bef9SDimitry Andric   // Check that x & Mask == x.
3173e8d8bef9SDimitry Andric   // x & 1 == x, always
3174e8d8bef9SDimitry Andric   // x & 0 == x, only if x is also 0
3175e8d8bef9SDimitry Andric   // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
3176e8d8bef9SDimitry Andric   //
3177e8d8bef9SDimitry Andric   // Check if we can replace AndDst with the LHS of the G_AND
3178e8d8bef9SDimitry Andric   if (canReplaceReg(AndDst, LHS, MRI) &&
3179349cc55cSDimitry Andric       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
3180e8d8bef9SDimitry Andric     Replacement = LHS;
3181e8d8bef9SDimitry Andric     return true;
3182e8d8bef9SDimitry Andric   }
3183e8d8bef9SDimitry Andric 
3184e8d8bef9SDimitry Andric   // Check if we can replace AndDst with the RHS of the G_AND
3185e8d8bef9SDimitry Andric   if (canReplaceReg(AndDst, RHS, MRI) &&
3186349cc55cSDimitry Andric       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
3187e8d8bef9SDimitry Andric     Replacement = RHS;
3188e8d8bef9SDimitry Andric     return true;
3189e8d8bef9SDimitry Andric   }
3190e8d8bef9SDimitry Andric 
3191e8d8bef9SDimitry Andric   return false;
3192e8d8bef9SDimitry Andric }
3193e8d8bef9SDimitry Andric 
3194e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
3195e8d8bef9SDimitry Andric   // Given
3196e8d8bef9SDimitry Andric   //
3197e8d8bef9SDimitry Andric   // %y:_(sN) = G_SOMETHING
3198e8d8bef9SDimitry Andric   // %x:_(sN) = G_SOMETHING
3199e8d8bef9SDimitry Andric   // %res:_(sN) = G_OR %x, %y
3200e8d8bef9SDimitry Andric   //
3201e8d8bef9SDimitry Andric   // Eliminate the G_OR when it is known that x | y == x or x | y == y.
3202e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
3203e8d8bef9SDimitry Andric   if (!KB)
3204e8d8bef9SDimitry Andric     return false;
3205e8d8bef9SDimitry Andric 
3206e8d8bef9SDimitry Andric   Register OrDst = MI.getOperand(0).getReg();
3207e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
3208e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
3209e8d8bef9SDimitry Andric   KnownBits LHSBits = KB->getKnownBits(LHS);
3210e8d8bef9SDimitry Andric   KnownBits RHSBits = KB->getKnownBits(RHS);
3211e8d8bef9SDimitry Andric 
3212e8d8bef9SDimitry Andric   // Check that x | Mask == x.
3213e8d8bef9SDimitry Andric   // x | 0 == x, always
3214e8d8bef9SDimitry Andric   // x | 1 == x, only if x is also 1
3215e8d8bef9SDimitry Andric   // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
3216e8d8bef9SDimitry Andric   //
3217e8d8bef9SDimitry Andric   // Check if we can replace OrDst with the LHS of the G_OR
3218e8d8bef9SDimitry Andric   if (canReplaceReg(OrDst, LHS, MRI) &&
3219349cc55cSDimitry Andric       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
3220e8d8bef9SDimitry Andric     Replacement = LHS;
3221e8d8bef9SDimitry Andric     return true;
3222e8d8bef9SDimitry Andric   }
3223e8d8bef9SDimitry Andric 
3224e8d8bef9SDimitry Andric   // Check if we can replace OrDst with the RHS of the G_OR
3225e8d8bef9SDimitry Andric   if (canReplaceReg(OrDst, RHS, MRI) &&
3226349cc55cSDimitry Andric       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
3227e8d8bef9SDimitry Andric     Replacement = RHS;
3228e8d8bef9SDimitry Andric     return true;
3229e8d8bef9SDimitry Andric   }
3230e8d8bef9SDimitry Andric 
3231e8d8bef9SDimitry Andric   return false;
3232e8d8bef9SDimitry Andric }
3233e8d8bef9SDimitry Andric 
3234e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
3235e8d8bef9SDimitry Andric   // If the input is already sign extended, just drop the extension.
3236e8d8bef9SDimitry Andric   Register Src = MI.getOperand(1).getReg();
3237e8d8bef9SDimitry Andric   unsigned ExtBits = MI.getOperand(2).getImm();
3238e8d8bef9SDimitry Andric   unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
3239e8d8bef9SDimitry Andric   return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
3240e8d8bef9SDimitry Andric }
3241e8d8bef9SDimitry Andric 
3242e8d8bef9SDimitry Andric static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
3243e8d8bef9SDimitry Andric                              int64_t Cst, bool IsVector, bool IsFP) {
3244e8d8bef9SDimitry Andric   // For i1, Cst will always be -1 regardless of boolean contents.
3245e8d8bef9SDimitry Andric   return (ScalarSizeBits == 1 && Cst == -1) ||
3246e8d8bef9SDimitry Andric          isConstTrueVal(TLI, Cst, IsVector, IsFP);
3247e8d8bef9SDimitry Andric }
3248e8d8bef9SDimitry Andric 
3249e8d8bef9SDimitry Andric bool CombinerHelper::matchNotCmp(MachineInstr &MI,
3250e8d8bef9SDimitry Andric                                  SmallVectorImpl<Register> &RegsToNegate) {
3251e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3252e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3253e8d8bef9SDimitry Andric   const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
3254e8d8bef9SDimitry Andric   Register XorSrc;
3255e8d8bef9SDimitry Andric   Register CstReg;
3256e8d8bef9SDimitry Andric   // We match xor(src, true) here.
3257e8d8bef9SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
3258e8d8bef9SDimitry Andric                 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
3259e8d8bef9SDimitry Andric     return false;
3260e8d8bef9SDimitry Andric 
3261e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(XorSrc))
3262e8d8bef9SDimitry Andric     return false;
3263e8d8bef9SDimitry Andric 
3264e8d8bef9SDimitry Andric   // Check that XorSrc is the root of a tree of comparisons combined with ANDs
3265e8d8bef9SDimitry Andric   // and ORs. The suffix of RegsToNegate starting from index I is used a work
3266e8d8bef9SDimitry Andric   // list of tree nodes to visit.
3267e8d8bef9SDimitry Andric   RegsToNegate.push_back(XorSrc);
3268e8d8bef9SDimitry Andric   // Remember whether the comparisons are all integer or all floating point.
3269e8d8bef9SDimitry Andric   bool IsInt = false;
3270e8d8bef9SDimitry Andric   bool IsFP = false;
3271e8d8bef9SDimitry Andric   for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
3272e8d8bef9SDimitry Andric     Register Reg = RegsToNegate[I];
3273e8d8bef9SDimitry Andric     if (!MRI.hasOneNonDBGUse(Reg))
3274e8d8bef9SDimitry Andric       return false;
3275e8d8bef9SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
3276e8d8bef9SDimitry Andric     switch (Def->getOpcode()) {
3277e8d8bef9SDimitry Andric     default:
3278e8d8bef9SDimitry Andric       // Don't match if the tree contains anything other than ANDs, ORs and
3279e8d8bef9SDimitry Andric       // comparisons.
3280e8d8bef9SDimitry Andric       return false;
3281e8d8bef9SDimitry Andric     case TargetOpcode::G_ICMP:
3282e8d8bef9SDimitry Andric       if (IsFP)
3283e8d8bef9SDimitry Andric         return false;
3284e8d8bef9SDimitry Andric       IsInt = true;
3285e8d8bef9SDimitry Andric       // When we apply the combine we will invert the predicate.
3286e8d8bef9SDimitry Andric       break;
3287e8d8bef9SDimitry Andric     case TargetOpcode::G_FCMP:
3288e8d8bef9SDimitry Andric       if (IsInt)
3289e8d8bef9SDimitry Andric         return false;
3290e8d8bef9SDimitry Andric       IsFP = true;
3291e8d8bef9SDimitry Andric       // When we apply the combine we will invert the predicate.
3292e8d8bef9SDimitry Andric       break;
3293e8d8bef9SDimitry Andric     case TargetOpcode::G_AND:
3294e8d8bef9SDimitry Andric     case TargetOpcode::G_OR:
3295e8d8bef9SDimitry Andric       // Implement De Morgan's laws:
3296e8d8bef9SDimitry Andric       // ~(x & y) -> ~x | ~y
3297e8d8bef9SDimitry Andric       // ~(x | y) -> ~x & ~y
3298e8d8bef9SDimitry Andric       // When we apply the combine we will change the opcode and recursively
3299e8d8bef9SDimitry Andric       // negate the operands.
3300e8d8bef9SDimitry Andric       RegsToNegate.push_back(Def->getOperand(1).getReg());
3301e8d8bef9SDimitry Andric       RegsToNegate.push_back(Def->getOperand(2).getReg());
3302e8d8bef9SDimitry Andric       break;
3303e8d8bef9SDimitry Andric     }
3304e8d8bef9SDimitry Andric   }
3305e8d8bef9SDimitry Andric 
3306e8d8bef9SDimitry Andric   // Now we know whether the comparisons are integer or floating point, check
3307e8d8bef9SDimitry Andric   // the constant in the xor.
3308e8d8bef9SDimitry Andric   int64_t Cst;
3309e8d8bef9SDimitry Andric   if (Ty.isVector()) {
3310e8d8bef9SDimitry Andric     MachineInstr *CstDef = MRI.getVRegDef(CstReg);
331181ad6265SDimitry Andric     auto MaybeCst = getIConstantSplatSExtVal(*CstDef, MRI);
3312e8d8bef9SDimitry Andric     if (!MaybeCst)
3313e8d8bef9SDimitry Andric       return false;
3314e8d8bef9SDimitry Andric     if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
3315e8d8bef9SDimitry Andric       return false;
3316e8d8bef9SDimitry Andric   } else {
3317e8d8bef9SDimitry Andric     if (!mi_match(CstReg, MRI, m_ICst(Cst)))
3318e8d8bef9SDimitry Andric       return false;
3319e8d8bef9SDimitry Andric     if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
3320e8d8bef9SDimitry Andric       return false;
3321e8d8bef9SDimitry Andric   }
3322e8d8bef9SDimitry Andric 
3323e8d8bef9SDimitry Andric   return true;
3324e8d8bef9SDimitry Andric }
3325e8d8bef9SDimitry Andric 
3326fe6060f1SDimitry Andric void CombinerHelper::applyNotCmp(MachineInstr &MI,
3327e8d8bef9SDimitry Andric                                  SmallVectorImpl<Register> &RegsToNegate) {
3328e8d8bef9SDimitry Andric   for (Register Reg : RegsToNegate) {
3329e8d8bef9SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
3330e8d8bef9SDimitry Andric     Observer.changingInstr(*Def);
3331e8d8bef9SDimitry Andric     // For each comparison, invert the opcode. For each AND and OR, change the
3332e8d8bef9SDimitry Andric     // opcode.
3333e8d8bef9SDimitry Andric     switch (Def->getOpcode()) {
3334e8d8bef9SDimitry Andric     default:
3335e8d8bef9SDimitry Andric       llvm_unreachable("Unexpected opcode");
3336e8d8bef9SDimitry Andric     case TargetOpcode::G_ICMP:
3337e8d8bef9SDimitry Andric     case TargetOpcode::G_FCMP: {
3338e8d8bef9SDimitry Andric       MachineOperand &PredOp = Def->getOperand(1);
3339e8d8bef9SDimitry Andric       CmpInst::Predicate NewP = CmpInst::getInversePredicate(
3340e8d8bef9SDimitry Andric           (CmpInst::Predicate)PredOp.getPredicate());
3341e8d8bef9SDimitry Andric       PredOp.setPredicate(NewP);
3342e8d8bef9SDimitry Andric       break;
3343e8d8bef9SDimitry Andric     }
3344e8d8bef9SDimitry Andric     case TargetOpcode::G_AND:
3345e8d8bef9SDimitry Andric       Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
3346e8d8bef9SDimitry Andric       break;
3347e8d8bef9SDimitry Andric     case TargetOpcode::G_OR:
3348e8d8bef9SDimitry Andric       Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3349e8d8bef9SDimitry Andric       break;
3350e8d8bef9SDimitry Andric     }
3351e8d8bef9SDimitry Andric     Observer.changedInstr(*Def);
3352e8d8bef9SDimitry Andric   }
3353e8d8bef9SDimitry Andric 
3354e8d8bef9SDimitry Andric   replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
3355e8d8bef9SDimitry Andric   MI.eraseFromParent();
3356e8d8bef9SDimitry Andric }
3357e8d8bef9SDimitry Andric 
3358e8d8bef9SDimitry Andric bool CombinerHelper::matchXorOfAndWithSameReg(
3359e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3360e8d8bef9SDimitry Andric   // Match (xor (and x, y), y) (or any of its commuted cases)
3361e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3362e8d8bef9SDimitry Andric   Register &X = MatchInfo.first;
3363e8d8bef9SDimitry Andric   Register &Y = MatchInfo.second;
3364e8d8bef9SDimitry Andric   Register AndReg = MI.getOperand(1).getReg();
3365e8d8bef9SDimitry Andric   Register SharedReg = MI.getOperand(2).getReg();
3366e8d8bef9SDimitry Andric 
3367e8d8bef9SDimitry Andric   // Find a G_AND on either side of the G_XOR.
3368e8d8bef9SDimitry Andric   // Look for one of
3369e8d8bef9SDimitry Andric   //
3370e8d8bef9SDimitry Andric   // (xor (and x, y), SharedReg)
3371e8d8bef9SDimitry Andric   // (xor SharedReg, (and x, y))
3372e8d8bef9SDimitry Andric   if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3373e8d8bef9SDimitry Andric     std::swap(AndReg, SharedReg);
3374e8d8bef9SDimitry Andric     if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3375e8d8bef9SDimitry Andric       return false;
3376e8d8bef9SDimitry Andric   }
3377e8d8bef9SDimitry Andric 
3378e8d8bef9SDimitry Andric   // Only do this if we'll eliminate the G_AND.
3379e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(AndReg))
3380e8d8bef9SDimitry Andric     return false;
3381e8d8bef9SDimitry Andric 
3382e8d8bef9SDimitry Andric   // We can combine if SharedReg is the same as either the LHS or RHS of the
3383e8d8bef9SDimitry Andric   // G_AND.
3384e8d8bef9SDimitry Andric   if (Y != SharedReg)
3385e8d8bef9SDimitry Andric     std::swap(X, Y);
3386e8d8bef9SDimitry Andric   return Y == SharedReg;
3387e8d8bef9SDimitry Andric }
3388e8d8bef9SDimitry Andric 
3389fe6060f1SDimitry Andric void CombinerHelper::applyXorOfAndWithSameReg(
3390e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3391e8d8bef9SDimitry Andric   // Fold (xor (and x, y), y) -> (and (not x), y)
3392e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3393e8d8bef9SDimitry Andric   Register X, Y;
3394e8d8bef9SDimitry Andric   std::tie(X, Y) = MatchInfo;
3395e8d8bef9SDimitry Andric   auto Not = Builder.buildNot(MRI.getType(X), X);
3396e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
3397e8d8bef9SDimitry Andric   MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3398e8d8bef9SDimitry Andric   MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3399e8d8bef9SDimitry Andric   MI.getOperand(2).setReg(Y);
3400e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
3401e8d8bef9SDimitry Andric }
3402e8d8bef9SDimitry Andric 
3403e8d8bef9SDimitry Andric bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
3404349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
3405349cc55cSDimitry Andric   Register DstReg = PtrAdd.getReg(0);
3406e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(DstReg);
3407e8d8bef9SDimitry Andric   const DataLayout &DL = Builder.getMF().getDataLayout();
3408e8d8bef9SDimitry Andric 
3409e8d8bef9SDimitry Andric   if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3410e8d8bef9SDimitry Andric     return false;
3411e8d8bef9SDimitry Andric 
3412e8d8bef9SDimitry Andric   if (Ty.isPointer()) {
3413349cc55cSDimitry Andric     auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI);
3414e8d8bef9SDimitry Andric     return ConstVal && *ConstVal == 0;
3415e8d8bef9SDimitry Andric   }
3416e8d8bef9SDimitry Andric 
3417e8d8bef9SDimitry Andric   assert(Ty.isVector() && "Expecting a vector type");
3418349cc55cSDimitry Andric   const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg());
3419e8d8bef9SDimitry Andric   return isBuildVectorAllZeros(*VecMI, MRI);
3420e8d8bef9SDimitry Andric }
3421e8d8bef9SDimitry Andric 
3422fe6060f1SDimitry Andric void CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
3423349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
3424349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(PtrAdd);
3425349cc55cSDimitry Andric   Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg());
3426349cc55cSDimitry Andric   PtrAdd.eraseFromParent();
3427e8d8bef9SDimitry Andric }
3428e8d8bef9SDimitry Andric 
3429e8d8bef9SDimitry Andric /// The second source operand is known to be a power of 2.
3430fe6060f1SDimitry Andric void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
3431e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3432e8d8bef9SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
3433e8d8bef9SDimitry Andric   Register Pow2Src1 = MI.getOperand(2).getReg();
3434e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(DstReg);
3435e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3436e8d8bef9SDimitry Andric 
3437e8d8bef9SDimitry Andric   // Fold (urem x, pow2) -> (and x, pow2-1)
3438e8d8bef9SDimitry Andric   auto NegOne = Builder.buildConstant(Ty, -1);
3439e8d8bef9SDimitry Andric   auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3440e8d8bef9SDimitry Andric   Builder.buildAnd(DstReg, Src0, Add);
3441e8d8bef9SDimitry Andric   MI.eraseFromParent();
3442e8d8bef9SDimitry Andric }
3443e8d8bef9SDimitry Andric 
344481ad6265SDimitry Andric bool CombinerHelper::matchFoldBinOpIntoSelect(MachineInstr &MI,
344581ad6265SDimitry Andric                                               unsigned &SelectOpNo) {
344681ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
344781ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
344881ad6265SDimitry Andric 
344981ad6265SDimitry Andric   Register OtherOperandReg = RHS;
345081ad6265SDimitry Andric   SelectOpNo = 1;
345181ad6265SDimitry Andric   MachineInstr *Select = MRI.getVRegDef(LHS);
345281ad6265SDimitry Andric 
345381ad6265SDimitry Andric   // Don't do this unless the old select is going away. We want to eliminate the
345481ad6265SDimitry Andric   // binary operator, not replace a binop with a select.
345581ad6265SDimitry Andric   if (Select->getOpcode() != TargetOpcode::G_SELECT ||
345681ad6265SDimitry Andric       !MRI.hasOneNonDBGUse(LHS)) {
345781ad6265SDimitry Andric     OtherOperandReg = LHS;
345881ad6265SDimitry Andric     SelectOpNo = 2;
345981ad6265SDimitry Andric     Select = MRI.getVRegDef(RHS);
346081ad6265SDimitry Andric     if (Select->getOpcode() != TargetOpcode::G_SELECT ||
346181ad6265SDimitry Andric         !MRI.hasOneNonDBGUse(RHS))
346281ad6265SDimitry Andric       return false;
346381ad6265SDimitry Andric   }
346481ad6265SDimitry Andric 
346581ad6265SDimitry Andric   MachineInstr *SelectLHS = MRI.getVRegDef(Select->getOperand(2).getReg());
346681ad6265SDimitry Andric   MachineInstr *SelectRHS = MRI.getVRegDef(Select->getOperand(3).getReg());
346781ad6265SDimitry Andric 
346881ad6265SDimitry Andric   if (!isConstantOrConstantVector(*SelectLHS, MRI,
346981ad6265SDimitry Andric                                   /*AllowFP*/ true,
347081ad6265SDimitry Andric                                   /*AllowOpaqueConstants*/ false))
347181ad6265SDimitry Andric     return false;
347281ad6265SDimitry Andric   if (!isConstantOrConstantVector(*SelectRHS, MRI,
347381ad6265SDimitry Andric                                   /*AllowFP*/ true,
347481ad6265SDimitry Andric                                   /*AllowOpaqueConstants*/ false))
347581ad6265SDimitry Andric     return false;
347681ad6265SDimitry Andric 
347781ad6265SDimitry Andric   unsigned BinOpcode = MI.getOpcode();
347881ad6265SDimitry Andric 
34795f757f3fSDimitry Andric   // We know that one of the operands is a select of constants. Now verify that
348081ad6265SDimitry Andric   // the other binary operator operand is either a constant, or we can handle a
348181ad6265SDimitry Andric   // variable.
348281ad6265SDimitry Andric   bool CanFoldNonConst =
348381ad6265SDimitry Andric       (BinOpcode == TargetOpcode::G_AND || BinOpcode == TargetOpcode::G_OR) &&
348481ad6265SDimitry Andric       (isNullOrNullSplat(*SelectLHS, MRI) ||
348581ad6265SDimitry Andric        isAllOnesOrAllOnesSplat(*SelectLHS, MRI)) &&
348681ad6265SDimitry Andric       (isNullOrNullSplat(*SelectRHS, MRI) ||
348781ad6265SDimitry Andric        isAllOnesOrAllOnesSplat(*SelectRHS, MRI));
348881ad6265SDimitry Andric   if (CanFoldNonConst)
348981ad6265SDimitry Andric     return true;
349081ad6265SDimitry Andric 
349181ad6265SDimitry Andric   return isConstantOrConstantVector(*MRI.getVRegDef(OtherOperandReg), MRI,
349281ad6265SDimitry Andric                                     /*AllowFP*/ true,
349381ad6265SDimitry Andric                                     /*AllowOpaqueConstants*/ false);
349481ad6265SDimitry Andric }
349581ad6265SDimitry Andric 
349681ad6265SDimitry Andric /// \p SelectOperand is the operand in binary operator \p MI that is the select
349781ad6265SDimitry Andric /// to fold.
349806c3fb27SDimitry Andric void CombinerHelper::applyFoldBinOpIntoSelect(MachineInstr &MI,
349981ad6265SDimitry Andric                                               const unsigned &SelectOperand) {
350081ad6265SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
350181ad6265SDimitry Andric 
350281ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
350381ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
350481ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
350581ad6265SDimitry Andric   MachineInstr *Select = MRI.getVRegDef(MI.getOperand(SelectOperand).getReg());
350681ad6265SDimitry Andric 
350781ad6265SDimitry Andric   Register SelectCond = Select->getOperand(1).getReg();
350881ad6265SDimitry Andric   Register SelectTrue = Select->getOperand(2).getReg();
350981ad6265SDimitry Andric   Register SelectFalse = Select->getOperand(3).getReg();
351081ad6265SDimitry Andric 
351181ad6265SDimitry Andric   LLT Ty = MRI.getType(Dst);
351281ad6265SDimitry Andric   unsigned BinOpcode = MI.getOpcode();
351381ad6265SDimitry Andric 
351481ad6265SDimitry Andric   Register FoldTrue, FoldFalse;
351581ad6265SDimitry Andric 
351681ad6265SDimitry Andric   // We have a select-of-constants followed by a binary operator with a
351781ad6265SDimitry Andric   // constant. Eliminate the binop by pulling the constant math into the select.
351881ad6265SDimitry Andric   // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
351981ad6265SDimitry Andric   if (SelectOperand == 1) {
352081ad6265SDimitry Andric     // TODO: SelectionDAG verifies this actually constant folds before
352181ad6265SDimitry Andric     // committing to the combine.
352281ad6265SDimitry Andric 
352381ad6265SDimitry Andric     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {SelectTrue, RHS}).getReg(0);
352481ad6265SDimitry Andric     FoldFalse =
352581ad6265SDimitry Andric         Builder.buildInstr(BinOpcode, {Ty}, {SelectFalse, RHS}).getReg(0);
352681ad6265SDimitry Andric   } else {
352781ad6265SDimitry Andric     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectTrue}).getReg(0);
352881ad6265SDimitry Andric     FoldFalse =
352981ad6265SDimitry Andric         Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectFalse}).getReg(0);
353081ad6265SDimitry Andric   }
353181ad6265SDimitry Andric 
353281ad6265SDimitry Andric   Builder.buildSelect(Dst, SelectCond, FoldTrue, FoldFalse, MI.getFlags());
353381ad6265SDimitry Andric   MI.eraseFromParent();
353481ad6265SDimitry Andric }
353581ad6265SDimitry Andric 
3536bdd1243dSDimitry Andric std::optional<SmallVector<Register, 8>>
3537e8d8bef9SDimitry Andric CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3538e8d8bef9SDimitry Andric   assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3539e8d8bef9SDimitry Andric   // We want to detect if Root is part of a tree which represents a bunch
3540e8d8bef9SDimitry Andric   // of loads being merged into a larger load. We'll try to recognize patterns
3541e8d8bef9SDimitry Andric   // like, for example:
3542e8d8bef9SDimitry Andric   //
3543e8d8bef9SDimitry Andric   //  Reg   Reg
3544e8d8bef9SDimitry Andric   //   \    /
3545e8d8bef9SDimitry Andric   //    OR_1   Reg
3546e8d8bef9SDimitry Andric   //     \    /
3547e8d8bef9SDimitry Andric   //      OR_2
3548e8d8bef9SDimitry Andric   //        \     Reg
3549e8d8bef9SDimitry Andric   //         .. /
3550e8d8bef9SDimitry Andric   //        Root
3551e8d8bef9SDimitry Andric   //
3552e8d8bef9SDimitry Andric   //  Reg   Reg   Reg   Reg
3553e8d8bef9SDimitry Andric   //     \ /       \   /
3554e8d8bef9SDimitry Andric   //     OR_1      OR_2
3555e8d8bef9SDimitry Andric   //       \       /
3556e8d8bef9SDimitry Andric   //        \    /
3557e8d8bef9SDimitry Andric   //         ...
3558e8d8bef9SDimitry Andric   //         Root
3559e8d8bef9SDimitry Andric   //
3560e8d8bef9SDimitry Andric   // Each "Reg" may have been produced by a load + some arithmetic. This
3561e8d8bef9SDimitry Andric   // function will save each of them.
3562e8d8bef9SDimitry Andric   SmallVector<Register, 8> RegsToVisit;
3563e8d8bef9SDimitry Andric   SmallVector<const MachineInstr *, 7> Ors = {Root};
3564e8d8bef9SDimitry Andric 
3565e8d8bef9SDimitry Andric   // In the "worst" case, we're dealing with a load for each byte. So, there
3566e8d8bef9SDimitry Andric   // are at most #bytes - 1 ORs.
3567e8d8bef9SDimitry Andric   const unsigned MaxIter =
3568e8d8bef9SDimitry Andric       MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3569e8d8bef9SDimitry Andric   for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3570e8d8bef9SDimitry Andric     if (Ors.empty())
3571e8d8bef9SDimitry Andric       break;
3572e8d8bef9SDimitry Andric     const MachineInstr *Curr = Ors.pop_back_val();
3573e8d8bef9SDimitry Andric     Register OrLHS = Curr->getOperand(1).getReg();
3574e8d8bef9SDimitry Andric     Register OrRHS = Curr->getOperand(2).getReg();
3575e8d8bef9SDimitry Andric 
3576e8d8bef9SDimitry Andric     // In the combine, we want to elimate the entire tree.
3577e8d8bef9SDimitry Andric     if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3578bdd1243dSDimitry Andric       return std::nullopt;
3579e8d8bef9SDimitry Andric 
3580e8d8bef9SDimitry Andric     // If it's a G_OR, save it and continue to walk. If it's not, then it's
3581e8d8bef9SDimitry Andric     // something that may be a load + arithmetic.
3582e8d8bef9SDimitry Andric     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3583e8d8bef9SDimitry Andric       Ors.push_back(Or);
3584e8d8bef9SDimitry Andric     else
3585e8d8bef9SDimitry Andric       RegsToVisit.push_back(OrLHS);
3586e8d8bef9SDimitry Andric     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3587e8d8bef9SDimitry Andric       Ors.push_back(Or);
3588e8d8bef9SDimitry Andric     else
3589e8d8bef9SDimitry Andric       RegsToVisit.push_back(OrRHS);
3590e8d8bef9SDimitry Andric   }
3591e8d8bef9SDimitry Andric 
3592e8d8bef9SDimitry Andric   // We're going to try and merge each register into a wider power-of-2 type,
3593e8d8bef9SDimitry Andric   // so we ought to have an even number of registers.
3594e8d8bef9SDimitry Andric   if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3595bdd1243dSDimitry Andric     return std::nullopt;
3596e8d8bef9SDimitry Andric   return RegsToVisit;
3597e8d8bef9SDimitry Andric }
3598e8d8bef9SDimitry Andric 
3599e8d8bef9SDimitry Andric /// Helper function for findLoadOffsetsForLoadOrCombine.
3600e8d8bef9SDimitry Andric ///
3601e8d8bef9SDimitry Andric /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3602e8d8bef9SDimitry Andric /// and then moving that value into a specific byte offset.
3603e8d8bef9SDimitry Andric ///
3604e8d8bef9SDimitry Andric /// e.g. x[i] << 24
3605e8d8bef9SDimitry Andric ///
3606e8d8bef9SDimitry Andric /// \returns The load instruction and the byte offset it is moved into.
3607bdd1243dSDimitry Andric static std::optional<std::pair<GZExtLoad *, int64_t>>
3608e8d8bef9SDimitry Andric matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3609e8d8bef9SDimitry Andric                          const MachineRegisterInfo &MRI) {
3610e8d8bef9SDimitry Andric   assert(MRI.hasOneNonDBGUse(Reg) &&
3611e8d8bef9SDimitry Andric          "Expected Reg to only have one non-debug use?");
3612e8d8bef9SDimitry Andric   Register MaybeLoad;
3613e8d8bef9SDimitry Andric   int64_t Shift;
3614e8d8bef9SDimitry Andric   if (!mi_match(Reg, MRI,
3615e8d8bef9SDimitry Andric                 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3616e8d8bef9SDimitry Andric     Shift = 0;
3617e8d8bef9SDimitry Andric     MaybeLoad = Reg;
3618e8d8bef9SDimitry Andric   }
3619e8d8bef9SDimitry Andric 
3620e8d8bef9SDimitry Andric   if (Shift % MemSizeInBits != 0)
3621bdd1243dSDimitry Andric     return std::nullopt;
3622e8d8bef9SDimitry Andric 
3623e8d8bef9SDimitry Andric   // TODO: Handle other types of loads.
3624fe6060f1SDimitry Andric   auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
3625e8d8bef9SDimitry Andric   if (!Load)
3626bdd1243dSDimitry Andric     return std::nullopt;
3627e8d8bef9SDimitry Andric 
3628fe6060f1SDimitry Andric   if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
3629bdd1243dSDimitry Andric     return std::nullopt;
3630e8d8bef9SDimitry Andric 
3631e8d8bef9SDimitry Andric   return std::make_pair(Load, Shift / MemSizeInBits);
3632e8d8bef9SDimitry Andric }
3633e8d8bef9SDimitry Andric 
3634bdd1243dSDimitry Andric std::optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
3635e8d8bef9SDimitry Andric CombinerHelper::findLoadOffsetsForLoadOrCombine(
3636e8d8bef9SDimitry Andric     SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
3637e8d8bef9SDimitry Andric     const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
3638e8d8bef9SDimitry Andric 
3639e8d8bef9SDimitry Andric   // Each load found for the pattern. There should be one for each RegsToVisit.
3640e8d8bef9SDimitry Andric   SmallSetVector<const MachineInstr *, 8> Loads;
3641e8d8bef9SDimitry Andric 
3642e8d8bef9SDimitry Andric   // The lowest index used in any load. (The lowest "i" for each x[i].)
3643e8d8bef9SDimitry Andric   int64_t LowestIdx = INT64_MAX;
3644e8d8bef9SDimitry Andric 
3645e8d8bef9SDimitry Andric   // The load which uses the lowest index.
3646fe6060f1SDimitry Andric   GZExtLoad *LowestIdxLoad = nullptr;
3647e8d8bef9SDimitry Andric 
3648e8d8bef9SDimitry Andric   // Keeps track of the load indices we see. We shouldn't see any indices twice.
3649e8d8bef9SDimitry Andric   SmallSet<int64_t, 8> SeenIdx;
3650e8d8bef9SDimitry Andric 
3651e8d8bef9SDimitry Andric   // Ensure each load is in the same MBB.
3652e8d8bef9SDimitry Andric   // TODO: Support multiple MachineBasicBlocks.
3653e8d8bef9SDimitry Andric   MachineBasicBlock *MBB = nullptr;
3654e8d8bef9SDimitry Andric   const MachineMemOperand *MMO = nullptr;
3655e8d8bef9SDimitry Andric 
3656e8d8bef9SDimitry Andric   // Earliest instruction-order load in the pattern.
3657fe6060f1SDimitry Andric   GZExtLoad *EarliestLoad = nullptr;
3658e8d8bef9SDimitry Andric 
3659e8d8bef9SDimitry Andric   // Latest instruction-order load in the pattern.
3660fe6060f1SDimitry Andric   GZExtLoad *LatestLoad = nullptr;
3661e8d8bef9SDimitry Andric 
3662e8d8bef9SDimitry Andric   // Base pointer which every load should share.
3663e8d8bef9SDimitry Andric   Register BasePtr;
3664e8d8bef9SDimitry Andric 
3665e8d8bef9SDimitry Andric   // We want to find a load for each register. Each load should have some
3666e8d8bef9SDimitry Andric   // appropriate bit twiddling arithmetic. During this loop, we will also keep
3667e8d8bef9SDimitry Andric   // track of the load which uses the lowest index. Later, we will check if we
3668e8d8bef9SDimitry Andric   // can use its pointer in the final, combined load.
3669e8d8bef9SDimitry Andric   for (auto Reg : RegsToVisit) {
3670e8d8bef9SDimitry Andric     // Find the load, and find the position that it will end up in (e.g. a
3671e8d8bef9SDimitry Andric     // shifted) value.
3672e8d8bef9SDimitry Andric     auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3673e8d8bef9SDimitry Andric     if (!LoadAndPos)
3674bdd1243dSDimitry Andric       return std::nullopt;
3675fe6060f1SDimitry Andric     GZExtLoad *Load;
3676e8d8bef9SDimitry Andric     int64_t DstPos;
3677e8d8bef9SDimitry Andric     std::tie(Load, DstPos) = *LoadAndPos;
3678e8d8bef9SDimitry Andric 
3679e8d8bef9SDimitry Andric     // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
3680e8d8bef9SDimitry Andric     // it is difficult to check for stores/calls/etc between loads.
3681e8d8bef9SDimitry Andric     MachineBasicBlock *LoadMBB = Load->getParent();
3682e8d8bef9SDimitry Andric     if (!MBB)
3683e8d8bef9SDimitry Andric       MBB = LoadMBB;
3684e8d8bef9SDimitry Andric     if (LoadMBB != MBB)
3685bdd1243dSDimitry Andric       return std::nullopt;
3686e8d8bef9SDimitry Andric 
3687e8d8bef9SDimitry Andric     // Make sure that the MachineMemOperands of every seen load are compatible.
3688fe6060f1SDimitry Andric     auto &LoadMMO = Load->getMMO();
3689e8d8bef9SDimitry Andric     if (!MMO)
3690fe6060f1SDimitry Andric       MMO = &LoadMMO;
3691fe6060f1SDimitry Andric     if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
3692bdd1243dSDimitry Andric       return std::nullopt;
3693e8d8bef9SDimitry Andric 
3694e8d8bef9SDimitry Andric     // Find out what the base pointer and index for the load is.
3695e8d8bef9SDimitry Andric     Register LoadPtr;
3696e8d8bef9SDimitry Andric     int64_t Idx;
3697e8d8bef9SDimitry Andric     if (!mi_match(Load->getOperand(1).getReg(), MRI,
3698e8d8bef9SDimitry Andric                   m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
3699e8d8bef9SDimitry Andric       LoadPtr = Load->getOperand(1).getReg();
3700e8d8bef9SDimitry Andric       Idx = 0;
3701e8d8bef9SDimitry Andric     }
3702e8d8bef9SDimitry Andric 
3703e8d8bef9SDimitry Andric     // Don't combine things like a[i], a[i] -> a bigger load.
3704e8d8bef9SDimitry Andric     if (!SeenIdx.insert(Idx).second)
3705bdd1243dSDimitry Andric       return std::nullopt;
3706e8d8bef9SDimitry Andric 
3707e8d8bef9SDimitry Andric     // Every load must share the same base pointer; don't combine things like:
3708e8d8bef9SDimitry Andric     //
3709e8d8bef9SDimitry Andric     // a[i], b[i + 1] -> a bigger load.
3710e8d8bef9SDimitry Andric     if (!BasePtr.isValid())
3711e8d8bef9SDimitry Andric       BasePtr = LoadPtr;
3712e8d8bef9SDimitry Andric     if (BasePtr != LoadPtr)
3713bdd1243dSDimitry Andric       return std::nullopt;
3714e8d8bef9SDimitry Andric 
3715e8d8bef9SDimitry Andric     if (Idx < LowestIdx) {
3716e8d8bef9SDimitry Andric       LowestIdx = Idx;
3717e8d8bef9SDimitry Andric       LowestIdxLoad = Load;
3718e8d8bef9SDimitry Andric     }
3719e8d8bef9SDimitry Andric 
3720e8d8bef9SDimitry Andric     // Keep track of the byte offset that this load ends up at. If we have seen
3721e8d8bef9SDimitry Andric     // the byte offset, then stop here. We do not want to combine:
3722e8d8bef9SDimitry Andric     //
3723e8d8bef9SDimitry Andric     // a[i] << 16, a[i + k] << 16 -> a bigger load.
3724e8d8bef9SDimitry Andric     if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
3725bdd1243dSDimitry Andric       return std::nullopt;
3726e8d8bef9SDimitry Andric     Loads.insert(Load);
3727e8d8bef9SDimitry Andric 
3728e8d8bef9SDimitry Andric     // Keep track of the position of the earliest/latest loads in the pattern.
3729e8d8bef9SDimitry Andric     // We will check that there are no load fold barriers between them later
3730e8d8bef9SDimitry Andric     // on.
3731e8d8bef9SDimitry Andric     //
3732e8d8bef9SDimitry Andric     // FIXME: Is there a better way to check for load fold barriers?
3733e8d8bef9SDimitry Andric     if (!EarliestLoad || dominates(*Load, *EarliestLoad))
3734e8d8bef9SDimitry Andric       EarliestLoad = Load;
3735e8d8bef9SDimitry Andric     if (!LatestLoad || dominates(*LatestLoad, *Load))
3736e8d8bef9SDimitry Andric       LatestLoad = Load;
3737e8d8bef9SDimitry Andric   }
3738e8d8bef9SDimitry Andric 
3739e8d8bef9SDimitry Andric   // We found a load for each register. Let's check if each load satisfies the
3740e8d8bef9SDimitry Andric   // pattern.
3741e8d8bef9SDimitry Andric   assert(Loads.size() == RegsToVisit.size() &&
3742e8d8bef9SDimitry Andric          "Expected to find a load for each register?");
3743e8d8bef9SDimitry Andric   assert(EarliestLoad != LatestLoad && EarliestLoad &&
3744e8d8bef9SDimitry Andric          LatestLoad && "Expected at least two loads?");
3745e8d8bef9SDimitry Andric 
3746e8d8bef9SDimitry Andric   // Check if there are any stores, calls, etc. between any of the loads. If
3747e8d8bef9SDimitry Andric   // there are, then we can't safely perform the combine.
3748e8d8bef9SDimitry Andric   //
3749e8d8bef9SDimitry Andric   // MaxIter is chosen based off the (worst case) number of iterations it
3750e8d8bef9SDimitry Andric   // typically takes to succeed in the LLVM test suite plus some padding.
3751e8d8bef9SDimitry Andric   //
3752e8d8bef9SDimitry Andric   // FIXME: Is there a better way to check for load fold barriers?
3753e8d8bef9SDimitry Andric   const unsigned MaxIter = 20;
3754e8d8bef9SDimitry Andric   unsigned Iter = 0;
3755e8d8bef9SDimitry Andric   for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
3756e8d8bef9SDimitry Andric                                                  LatestLoad->getIterator())) {
3757e8d8bef9SDimitry Andric     if (Loads.count(&MI))
3758e8d8bef9SDimitry Andric       continue;
3759e8d8bef9SDimitry Andric     if (MI.isLoadFoldBarrier())
3760bdd1243dSDimitry Andric       return std::nullopt;
3761e8d8bef9SDimitry Andric     if (Iter++ == MaxIter)
3762bdd1243dSDimitry Andric       return std::nullopt;
3763e8d8bef9SDimitry Andric   }
3764e8d8bef9SDimitry Andric 
3765fe6060f1SDimitry Andric   return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
3766e8d8bef9SDimitry Andric }
3767e8d8bef9SDimitry Andric 
3768e8d8bef9SDimitry Andric bool CombinerHelper::matchLoadOrCombine(
3769e8d8bef9SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3770e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
3771e8d8bef9SDimitry Andric   MachineFunction &MF = *MI.getMF();
3772e8d8bef9SDimitry Andric   // Assuming a little-endian target, transform:
3773e8d8bef9SDimitry Andric   //  s8 *a = ...
3774e8d8bef9SDimitry Andric   //  s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
3775e8d8bef9SDimitry Andric   // =>
3776e8d8bef9SDimitry Andric   //  s32 val = *((i32)a)
3777e8d8bef9SDimitry Andric   //
3778e8d8bef9SDimitry Andric   //  s8 *a = ...
3779e8d8bef9SDimitry Andric   //  s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
3780e8d8bef9SDimitry Andric   // =>
3781e8d8bef9SDimitry Andric   //  s32 val = BSWAP(*((s32)a))
3782e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
3783e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
3784e8d8bef9SDimitry Andric   if (Ty.isVector())
3785e8d8bef9SDimitry Andric     return false;
3786e8d8bef9SDimitry Andric 
3787e8d8bef9SDimitry Andric   // We need to combine at least two loads into this type. Since the smallest
3788e8d8bef9SDimitry Andric   // possible load is into a byte, we need at least a 16-bit wide type.
3789e8d8bef9SDimitry Andric   const unsigned WideMemSizeInBits = Ty.getSizeInBits();
3790e8d8bef9SDimitry Andric   if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
3791e8d8bef9SDimitry Andric     return false;
3792e8d8bef9SDimitry Andric 
3793e8d8bef9SDimitry Andric   // Match a collection of non-OR instructions in the pattern.
3794e8d8bef9SDimitry Andric   auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
3795e8d8bef9SDimitry Andric   if (!RegsToVisit)
3796e8d8bef9SDimitry Andric     return false;
3797e8d8bef9SDimitry Andric 
3798e8d8bef9SDimitry Andric   // We have a collection of non-OR instructions. Figure out how wide each of
3799e8d8bef9SDimitry Andric   // the small loads should be based off of the number of potential loads we
3800e8d8bef9SDimitry Andric   // found.
3801e8d8bef9SDimitry Andric   const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
3802e8d8bef9SDimitry Andric   if (NarrowMemSizeInBits % 8 != 0)
3803e8d8bef9SDimitry Andric     return false;
3804e8d8bef9SDimitry Andric 
3805e8d8bef9SDimitry Andric   // Check if each register feeding into each OR is a load from the same
3806e8d8bef9SDimitry Andric   // base pointer + some arithmetic.
3807e8d8bef9SDimitry Andric   //
3808e8d8bef9SDimitry Andric   // e.g. a[0], a[1] << 8, a[2] << 16, etc.
3809e8d8bef9SDimitry Andric   //
3810e8d8bef9SDimitry Andric   // Also verify that each of these ends up putting a[i] into the same memory
3811e8d8bef9SDimitry Andric   // offset as a load into a wide type would.
3812e8d8bef9SDimitry Andric   SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
3813fe6060f1SDimitry Andric   GZExtLoad *LowestIdxLoad, *LatestLoad;
3814e8d8bef9SDimitry Andric   int64_t LowestIdx;
3815e8d8bef9SDimitry Andric   auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
3816e8d8bef9SDimitry Andric       MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
3817e8d8bef9SDimitry Andric   if (!MaybeLoadInfo)
3818e8d8bef9SDimitry Andric     return false;
3819fe6060f1SDimitry Andric   std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
3820e8d8bef9SDimitry Andric 
3821e8d8bef9SDimitry Andric   // We have a bunch of loads being OR'd together. Using the addresses + offsets
3822e8d8bef9SDimitry Andric   // we found before, check if this corresponds to a big or little endian byte
3823e8d8bef9SDimitry Andric   // pattern. If it does, then we can represent it using a load + possibly a
3824e8d8bef9SDimitry Andric   // BSWAP.
3825e8d8bef9SDimitry Andric   bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
3826bdd1243dSDimitry Andric   std::optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
382781ad6265SDimitry Andric   if (!IsBigEndian)
3828e8d8bef9SDimitry Andric     return false;
3829e8d8bef9SDimitry Andric   bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
3830e8d8bef9SDimitry Andric   if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
3831e8d8bef9SDimitry Andric     return false;
3832e8d8bef9SDimitry Andric 
3833e8d8bef9SDimitry Andric   // Make sure that the load from the lowest index produces offset 0 in the
3834e8d8bef9SDimitry Andric   // final value.
3835e8d8bef9SDimitry Andric   //
3836e8d8bef9SDimitry Andric   // This ensures that we won't combine something like this:
3837e8d8bef9SDimitry Andric   //
3838e8d8bef9SDimitry Andric   // load x[i] -> byte 2
3839e8d8bef9SDimitry Andric   // load x[i+1] -> byte 0 ---> wide_load x[i]
3840e8d8bef9SDimitry Andric   // load x[i+2] -> byte 1
3841e8d8bef9SDimitry Andric   const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
3842e8d8bef9SDimitry Andric   const unsigned ZeroByteOffset =
3843e8d8bef9SDimitry Andric       *IsBigEndian
3844e8d8bef9SDimitry Andric           ? bigEndianByteAt(NumLoadsInTy, 0)
3845e8d8bef9SDimitry Andric           : littleEndianByteAt(NumLoadsInTy, 0);
3846e8d8bef9SDimitry Andric   auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
3847e8d8bef9SDimitry Andric   if (ZeroOffsetIdx == MemOffset2Idx.end() ||
3848e8d8bef9SDimitry Andric       ZeroOffsetIdx->second != LowestIdx)
3849e8d8bef9SDimitry Andric     return false;
3850e8d8bef9SDimitry Andric 
3851e8d8bef9SDimitry Andric   // We wil reuse the pointer from the load which ends up at byte offset 0. It
3852e8d8bef9SDimitry Andric   // may not use index 0.
3853fe6060f1SDimitry Andric   Register Ptr = LowestIdxLoad->getPointerReg();
3854fe6060f1SDimitry Andric   const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
3855349cc55cSDimitry Andric   LegalityQuery::MemDesc MMDesc(MMO);
3856fe6060f1SDimitry Andric   MMDesc.MemoryTy = Ty;
3857e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer(
3858e8d8bef9SDimitry Andric           {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
3859e8d8bef9SDimitry Andric     return false;
3860e8d8bef9SDimitry Andric   auto PtrInfo = MMO.getPointerInfo();
3861e8d8bef9SDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
3862e8d8bef9SDimitry Andric 
3863e8d8bef9SDimitry Andric   // Load must be allowed and fast on the target.
3864e8d8bef9SDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
3865e8d8bef9SDimitry Andric   auto &DL = MF.getDataLayout();
3866bdd1243dSDimitry Andric   unsigned Fast = 0;
3867e8d8bef9SDimitry Andric   if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
3868e8d8bef9SDimitry Andric       !Fast)
3869e8d8bef9SDimitry Andric     return false;
3870e8d8bef9SDimitry Andric 
3871e8d8bef9SDimitry Andric   MatchInfo = [=](MachineIRBuilder &MIB) {
3872fe6060f1SDimitry Andric     MIB.setInstrAndDebugLoc(*LatestLoad);
3873e8d8bef9SDimitry Andric     Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
3874e8d8bef9SDimitry Andric     MIB.buildLoad(LoadDst, Ptr, *NewMMO);
3875e8d8bef9SDimitry Andric     if (NeedsBSwap)
3876e8d8bef9SDimitry Andric       MIB.buildBSwap(Dst, LoadDst);
3877e8d8bef9SDimitry Andric   };
3878e8d8bef9SDimitry Andric   return true;
3879e8d8bef9SDimitry Andric }
3880e8d8bef9SDimitry Andric 
3881fe6060f1SDimitry Andric bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
3882fe6060f1SDimitry Andric                                             MachineInstr *&ExtMI) {
38837a6dacacSDimitry Andric   auto &PHI = cast<GPhi>(MI);
38847a6dacacSDimitry Andric   Register DstReg = PHI.getReg(0);
3885fe6060f1SDimitry Andric 
3886fe6060f1SDimitry Andric   // TODO: Extending a vector may be expensive, don't do this until heuristics
3887fe6060f1SDimitry Andric   // are better.
3888fe6060f1SDimitry Andric   if (MRI.getType(DstReg).isVector())
3889fe6060f1SDimitry Andric     return false;
3890fe6060f1SDimitry Andric 
3891fe6060f1SDimitry Andric   // Try to match a phi, whose only use is an extend.
3892fe6060f1SDimitry Andric   if (!MRI.hasOneNonDBGUse(DstReg))
3893fe6060f1SDimitry Andric     return false;
3894fe6060f1SDimitry Andric   ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
3895fe6060f1SDimitry Andric   switch (ExtMI->getOpcode()) {
3896fe6060f1SDimitry Andric   case TargetOpcode::G_ANYEXT:
3897fe6060f1SDimitry Andric     return true; // G_ANYEXT is usually free.
3898fe6060f1SDimitry Andric   case TargetOpcode::G_ZEXT:
3899fe6060f1SDimitry Andric   case TargetOpcode::G_SEXT:
3900fe6060f1SDimitry Andric     break;
3901fe6060f1SDimitry Andric   default:
3902fe6060f1SDimitry Andric     return false;
3903fe6060f1SDimitry Andric   }
3904fe6060f1SDimitry Andric 
3905fe6060f1SDimitry Andric   // If the target is likely to fold this extend away, don't propagate.
3906fe6060f1SDimitry Andric   if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
3907fe6060f1SDimitry Andric     return false;
3908fe6060f1SDimitry Andric 
3909fe6060f1SDimitry Andric   // We don't want to propagate the extends unless there's a good chance that
3910fe6060f1SDimitry Andric   // they'll be optimized in some way.
3911fe6060f1SDimitry Andric   // Collect the unique incoming values.
3912fe6060f1SDimitry Andric   SmallPtrSet<MachineInstr *, 4> InSrcs;
39137a6dacacSDimitry Andric   for (unsigned I = 0; I < PHI.getNumIncomingValues(); ++I) {
39147a6dacacSDimitry Andric     auto *DefMI = getDefIgnoringCopies(PHI.getIncomingValue(I), MRI);
3915fe6060f1SDimitry Andric     switch (DefMI->getOpcode()) {
3916fe6060f1SDimitry Andric     case TargetOpcode::G_LOAD:
3917fe6060f1SDimitry Andric     case TargetOpcode::G_TRUNC:
3918fe6060f1SDimitry Andric     case TargetOpcode::G_SEXT:
3919fe6060f1SDimitry Andric     case TargetOpcode::G_ZEXT:
3920fe6060f1SDimitry Andric     case TargetOpcode::G_ANYEXT:
3921fe6060f1SDimitry Andric     case TargetOpcode::G_CONSTANT:
39227a6dacacSDimitry Andric       InSrcs.insert(DefMI);
3923fe6060f1SDimitry Andric       // Don't try to propagate if there are too many places to create new
3924fe6060f1SDimitry Andric       // extends, chances are it'll increase code size.
3925fe6060f1SDimitry Andric       if (InSrcs.size() > 2)
3926fe6060f1SDimitry Andric         return false;
3927fe6060f1SDimitry Andric       break;
3928fe6060f1SDimitry Andric     default:
3929fe6060f1SDimitry Andric       return false;
3930fe6060f1SDimitry Andric     }
3931fe6060f1SDimitry Andric   }
3932fe6060f1SDimitry Andric   return true;
3933fe6060f1SDimitry Andric }
3934fe6060f1SDimitry Andric 
3935fe6060f1SDimitry Andric void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
3936fe6060f1SDimitry Andric                                             MachineInstr *&ExtMI) {
39377a6dacacSDimitry Andric   auto &PHI = cast<GPhi>(MI);
3938fe6060f1SDimitry Andric   Register DstReg = ExtMI->getOperand(0).getReg();
3939fe6060f1SDimitry Andric   LLT ExtTy = MRI.getType(DstReg);
3940fe6060f1SDimitry Andric 
3941fe6060f1SDimitry Andric   // Propagate the extension into the block of each incoming reg's block.
3942fe6060f1SDimitry Andric   // Use a SetVector here because PHIs can have duplicate edges, and we want
3943fe6060f1SDimitry Andric   // deterministic iteration order.
3944fe6060f1SDimitry Andric   SmallSetVector<MachineInstr *, 8> SrcMIs;
3945fe6060f1SDimitry Andric   SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
39467a6dacacSDimitry Andric   for (unsigned I = 0; I < PHI.getNumIncomingValues(); ++I) {
39477a6dacacSDimitry Andric     auto SrcReg = PHI.getIncomingValue(I);
39487a6dacacSDimitry Andric     auto *SrcMI = MRI.getVRegDef(SrcReg);
3949fe6060f1SDimitry Andric     if (!SrcMIs.insert(SrcMI))
3950fe6060f1SDimitry Andric       continue;
3951fe6060f1SDimitry Andric 
3952fe6060f1SDimitry Andric     // Build an extend after each src inst.
3953fe6060f1SDimitry Andric     auto *MBB = SrcMI->getParent();
3954fe6060f1SDimitry Andric     MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
3955fe6060f1SDimitry Andric     if (InsertPt != MBB->end() && InsertPt->isPHI())
3956fe6060f1SDimitry Andric       InsertPt = MBB->getFirstNonPHI();
3957fe6060f1SDimitry Andric 
3958fe6060f1SDimitry Andric     Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
3959fe6060f1SDimitry Andric     Builder.setDebugLoc(MI.getDebugLoc());
39607a6dacacSDimitry Andric     auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy, SrcReg);
3961fe6060f1SDimitry Andric     OldToNewSrcMap[SrcMI] = NewExt;
3962fe6060f1SDimitry Andric   }
3963fe6060f1SDimitry Andric 
3964fe6060f1SDimitry Andric   // Create a new phi with the extended inputs.
3965fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3966fe6060f1SDimitry Andric   auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
3967fe6060f1SDimitry Andric   NewPhi.addDef(DstReg);
39684824e7fdSDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
3969fe6060f1SDimitry Andric     if (!MO.isReg()) {
3970fe6060f1SDimitry Andric       NewPhi.addMBB(MO.getMBB());
3971fe6060f1SDimitry Andric       continue;
3972fe6060f1SDimitry Andric     }
3973fe6060f1SDimitry Andric     auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
3974fe6060f1SDimitry Andric     NewPhi.addUse(NewSrc->getOperand(0).getReg());
3975fe6060f1SDimitry Andric   }
3976fe6060f1SDimitry Andric   Builder.insertInstr(NewPhi);
3977fe6060f1SDimitry Andric   ExtMI->eraseFromParent();
3978fe6060f1SDimitry Andric }
3979fe6060f1SDimitry Andric 
3980fe6060f1SDimitry Andric bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI,
3981fe6060f1SDimitry Andric                                                 Register &Reg) {
3982fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
3983fe6060f1SDimitry Andric   // If we have a constant index, look for a G_BUILD_VECTOR source
3984fe6060f1SDimitry Andric   // and find the source register that the index maps to.
3985fe6060f1SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
3986fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(SrcVec);
3987fe6060f1SDimitry Andric 
3988349cc55cSDimitry Andric   auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
3989fe6060f1SDimitry Andric   if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
3990fe6060f1SDimitry Andric     return false;
3991fe6060f1SDimitry Andric 
3992fe6060f1SDimitry Andric   unsigned VecIdx = Cst->Value.getZExtValue();
3993bdd1243dSDimitry Andric 
3994bdd1243dSDimitry Andric   // Check if we have a build_vector or build_vector_trunc with an optional
3995bdd1243dSDimitry Andric   // trunc in front.
3996bdd1243dSDimitry Andric   MachineInstr *SrcVecMI = MRI.getVRegDef(SrcVec);
3997bdd1243dSDimitry Andric   if (SrcVecMI->getOpcode() == TargetOpcode::G_TRUNC) {
3998bdd1243dSDimitry Andric     SrcVecMI = MRI.getVRegDef(SrcVecMI->getOperand(1).getReg());
3999fe6060f1SDimitry Andric   }
4000fe6060f1SDimitry Andric 
4001bdd1243dSDimitry Andric   if (SrcVecMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR &&
4002bdd1243dSDimitry Andric       SrcVecMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR_TRUNC)
4003bdd1243dSDimitry Andric     return false;
4004bdd1243dSDimitry Andric 
4005fe6060f1SDimitry Andric   EVT Ty(getMVTForLLT(SrcTy));
4006fe6060f1SDimitry Andric   if (!MRI.hasOneNonDBGUse(SrcVec) &&
4007fe6060f1SDimitry Andric       !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
4008fe6060f1SDimitry Andric     return false;
4009fe6060f1SDimitry Andric 
4010bdd1243dSDimitry Andric   Reg = SrcVecMI->getOperand(VecIdx + 1).getReg();
4011fe6060f1SDimitry Andric   return true;
4012fe6060f1SDimitry Andric }
4013fe6060f1SDimitry Andric 
4014fe6060f1SDimitry Andric void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI,
4015fe6060f1SDimitry Andric                                                 Register &Reg) {
4016fe6060f1SDimitry Andric   // Check the type of the register, since it may have come from a
4017fe6060f1SDimitry Andric   // G_BUILD_VECTOR_TRUNC.
4018fe6060f1SDimitry Andric   LLT ScalarTy = MRI.getType(Reg);
4019fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
4020fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
4021fe6060f1SDimitry Andric 
4022fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4023fe6060f1SDimitry Andric   if (ScalarTy != DstTy) {
4024fe6060f1SDimitry Andric     assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
4025fe6060f1SDimitry Andric     Builder.buildTrunc(DstReg, Reg);
4026fe6060f1SDimitry Andric     MI.eraseFromParent();
4027fe6060f1SDimitry Andric     return;
4028fe6060f1SDimitry Andric   }
4029fe6060f1SDimitry Andric   replaceSingleDefInstWithReg(MI, Reg);
4030fe6060f1SDimitry Andric }
4031fe6060f1SDimitry Andric 
4032fe6060f1SDimitry Andric bool CombinerHelper::matchExtractAllEltsFromBuildVector(
4033fe6060f1SDimitry Andric     MachineInstr &MI,
4034fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
4035fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4036fe6060f1SDimitry Andric   // This combine tries to find build_vector's which have every source element
4037fe6060f1SDimitry Andric   // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
4038fe6060f1SDimitry Andric   // the masked load scalarization is run late in the pipeline. There's already
4039fe6060f1SDimitry Andric   // a combine for a similar pattern starting from the extract, but that
4040fe6060f1SDimitry Andric   // doesn't attempt to do it if there are multiple uses of the build_vector,
4041fe6060f1SDimitry Andric   // which in this case is true. Starting the combine from the build_vector
4042fe6060f1SDimitry Andric   // feels more natural than trying to find sibling nodes of extracts.
4043fe6060f1SDimitry Andric   // E.g.
4044fe6060f1SDimitry Andric   //  %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
4045fe6060f1SDimitry Andric   //  %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
4046fe6060f1SDimitry Andric   //  %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
4047fe6060f1SDimitry Andric   //  %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
4048fe6060f1SDimitry Andric   //  %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
4049fe6060f1SDimitry Andric   // ==>
4050fe6060f1SDimitry Andric   // replace ext{1,2,3,4} with %s{1,2,3,4}
4051fe6060f1SDimitry Andric 
4052fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
4053fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
4054fe6060f1SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
4055fe6060f1SDimitry Andric 
4056fe6060f1SDimitry Andric   SmallBitVector ExtractedElts(NumElts);
40574824e7fdSDimitry Andric   for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
4058fe6060f1SDimitry Andric     if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
4059fe6060f1SDimitry Andric       return false;
4060349cc55cSDimitry Andric     auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
4061fe6060f1SDimitry Andric     if (!Cst)
4062fe6060f1SDimitry Andric       return false;
406381ad6265SDimitry Andric     unsigned Idx = Cst->getZExtValue();
4064fe6060f1SDimitry Andric     if (Idx >= NumElts)
4065fe6060f1SDimitry Andric       return false; // Out of range.
4066fe6060f1SDimitry Andric     ExtractedElts.set(Idx);
4067fe6060f1SDimitry Andric     SrcDstPairs.emplace_back(
4068fe6060f1SDimitry Andric         std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
4069fe6060f1SDimitry Andric   }
4070fe6060f1SDimitry Andric   // Match if every element was extracted.
4071fe6060f1SDimitry Andric   return ExtractedElts.all();
4072fe6060f1SDimitry Andric }
4073fe6060f1SDimitry Andric 
4074fe6060f1SDimitry Andric void CombinerHelper::applyExtractAllEltsFromBuildVector(
4075fe6060f1SDimitry Andric     MachineInstr &MI,
4076fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
4077fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4078fe6060f1SDimitry Andric   for (auto &Pair : SrcDstPairs) {
4079fe6060f1SDimitry Andric     auto *ExtMI = Pair.second;
4080fe6060f1SDimitry Andric     replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
4081fe6060f1SDimitry Andric     ExtMI->eraseFromParent();
4082fe6060f1SDimitry Andric   }
4083fe6060f1SDimitry Andric   MI.eraseFromParent();
4084fe6060f1SDimitry Andric }
4085fe6060f1SDimitry Andric 
4086fe6060f1SDimitry Andric void CombinerHelper::applyBuildFn(
4087e8d8bef9SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4088e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4089e8d8bef9SDimitry Andric   MatchInfo(Builder);
4090e8d8bef9SDimitry Andric   MI.eraseFromParent();
4091fe6060f1SDimitry Andric }
4092fe6060f1SDimitry Andric 
4093fe6060f1SDimitry Andric void CombinerHelper::applyBuildFnNoErase(
4094fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4095fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4096fe6060f1SDimitry Andric   MatchInfo(Builder);
4097fe6060f1SDimitry Andric }
4098fe6060f1SDimitry Andric 
40994824e7fdSDimitry Andric bool CombinerHelper::matchOrShiftToFunnelShift(MachineInstr &MI,
41004824e7fdSDimitry Andric                                                BuildFnTy &MatchInfo) {
41014824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
41024824e7fdSDimitry Andric 
41034824e7fdSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
41044824e7fdSDimitry Andric   LLT Ty = MRI.getType(Dst);
41054824e7fdSDimitry Andric   unsigned BitWidth = Ty.getScalarSizeInBits();
41064824e7fdSDimitry Andric 
410704eeddc0SDimitry Andric   Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
41084824e7fdSDimitry Andric   unsigned FshOpc = 0;
41094824e7fdSDimitry Andric 
411004eeddc0SDimitry Andric   // Match (or (shl ...), (lshr ...)).
411104eeddc0SDimitry Andric   if (!mi_match(Dst, MRI,
41124824e7fdSDimitry Andric                 // m_GOr() handles the commuted version as well.
41134824e7fdSDimitry Andric                 m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
411404eeddc0SDimitry Andric                       m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
411504eeddc0SDimitry Andric     return false;
411604eeddc0SDimitry Andric 
411704eeddc0SDimitry Andric   // Given constants C0 and C1 such that C0 + C1 is bit-width:
411804eeddc0SDimitry Andric   // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
411904eeddc0SDimitry Andric   int64_t CstShlAmt, CstLShrAmt;
412081ad6265SDimitry Andric   if (mi_match(ShlAmt, MRI, m_ICstOrSplat(CstShlAmt)) &&
412181ad6265SDimitry Andric       mi_match(LShrAmt, MRI, m_ICstOrSplat(CstLShrAmt)) &&
412204eeddc0SDimitry Andric       CstShlAmt + CstLShrAmt == BitWidth) {
412304eeddc0SDimitry Andric     FshOpc = TargetOpcode::G_FSHR;
412404eeddc0SDimitry Andric     Amt = LShrAmt;
412504eeddc0SDimitry Andric 
412604eeddc0SDimitry Andric   } else if (mi_match(LShrAmt, MRI,
412704eeddc0SDimitry Andric                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
412804eeddc0SDimitry Andric              ShlAmt == Amt) {
412904eeddc0SDimitry Andric     // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
41304824e7fdSDimitry Andric     FshOpc = TargetOpcode::G_FSHL;
41314824e7fdSDimitry Andric 
413204eeddc0SDimitry Andric   } else if (mi_match(ShlAmt, MRI,
413304eeddc0SDimitry Andric                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
413404eeddc0SDimitry Andric              LShrAmt == Amt) {
413504eeddc0SDimitry Andric     // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
41364824e7fdSDimitry Andric     FshOpc = TargetOpcode::G_FSHR;
41374824e7fdSDimitry Andric 
41384824e7fdSDimitry Andric   } else {
41394824e7fdSDimitry Andric     return false;
41404824e7fdSDimitry Andric   }
41414824e7fdSDimitry Andric 
414204eeddc0SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
41434824e7fdSDimitry Andric   if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}))
41444824e7fdSDimitry Andric     return false;
41454824e7fdSDimitry Andric 
41464824e7fdSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
414704eeddc0SDimitry Andric     B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
41484824e7fdSDimitry Andric   };
41494824e7fdSDimitry Andric   return true;
41504824e7fdSDimitry Andric }
41514824e7fdSDimitry Andric 
4152fe6060f1SDimitry Andric /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate.
4153fe6060f1SDimitry Andric bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) {
4154fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
4155fe6060f1SDimitry Andric   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
4156fe6060f1SDimitry Andric   Register X = MI.getOperand(1).getReg();
4157fe6060f1SDimitry Andric   Register Y = MI.getOperand(2).getReg();
4158fe6060f1SDimitry Andric   if (X != Y)
4159fe6060f1SDimitry Andric     return false;
4160fe6060f1SDimitry Andric   unsigned RotateOpc =
4161fe6060f1SDimitry Andric       Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR;
4162fe6060f1SDimitry Andric   return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}});
4163fe6060f1SDimitry Andric }
4164fe6060f1SDimitry Andric 
4165fe6060f1SDimitry Andric void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) {
4166fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
4167fe6060f1SDimitry Andric   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
4168fe6060f1SDimitry Andric   bool IsFSHL = Opc == TargetOpcode::G_FSHL;
4169fe6060f1SDimitry Andric   Observer.changingInstr(MI);
4170fe6060f1SDimitry Andric   MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL
4171fe6060f1SDimitry Andric                                          : TargetOpcode::G_ROTR));
417281ad6265SDimitry Andric   MI.removeOperand(2);
4173fe6060f1SDimitry Andric   Observer.changedInstr(MI);
4174fe6060f1SDimitry Andric }
4175fe6060f1SDimitry Andric 
4176fe6060f1SDimitry Andric // Fold (rot x, c) -> (rot x, c % BitSize)
4177fe6060f1SDimitry Andric bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) {
4178fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4179fe6060f1SDimitry Andric          MI.getOpcode() == TargetOpcode::G_ROTR);
4180fe6060f1SDimitry Andric   unsigned Bitsize =
4181fe6060f1SDimitry Andric       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4182fe6060f1SDimitry Andric   Register AmtReg = MI.getOperand(2).getReg();
4183fe6060f1SDimitry Andric   bool OutOfRange = false;
4184fe6060f1SDimitry Andric   auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
4185fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(C))
4186fe6060f1SDimitry Andric       OutOfRange |= CI->getValue().uge(Bitsize);
4187fe6060f1SDimitry Andric     return true;
4188fe6060f1SDimitry Andric   };
4189fe6060f1SDimitry Andric   return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
4190fe6060f1SDimitry Andric }
4191fe6060f1SDimitry Andric 
4192fe6060f1SDimitry Andric void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) {
4193fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4194fe6060f1SDimitry Andric          MI.getOpcode() == TargetOpcode::G_ROTR);
4195fe6060f1SDimitry Andric   unsigned Bitsize =
4196fe6060f1SDimitry Andric       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4197fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4198fe6060f1SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
4199fe6060f1SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
4200fe6060f1SDimitry Andric   auto Bits = Builder.buildConstant(AmtTy, Bitsize);
4201fe6060f1SDimitry Andric   Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
4202fe6060f1SDimitry Andric   Observer.changingInstr(MI);
4203fe6060f1SDimitry Andric   MI.getOperand(2).setReg(Amt);
4204fe6060f1SDimitry Andric   Observer.changedInstr(MI);
4205fe6060f1SDimitry Andric }
4206fe6060f1SDimitry Andric 
4207fe6060f1SDimitry Andric bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI,
4208fe6060f1SDimitry Andric                                                    int64_t &MatchInfo) {
4209fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4210fe6060f1SDimitry Andric   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4211fe6060f1SDimitry Andric   auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg());
4212fe6060f1SDimitry Andric   auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg());
4213bdd1243dSDimitry Andric   std::optional<bool> KnownVal;
4214fe6060f1SDimitry Andric   switch (Pred) {
4215fe6060f1SDimitry Andric   default:
4216fe6060f1SDimitry Andric     llvm_unreachable("Unexpected G_ICMP predicate?");
4217fe6060f1SDimitry Andric   case CmpInst::ICMP_EQ:
4218fe6060f1SDimitry Andric     KnownVal = KnownBits::eq(KnownLHS, KnownRHS);
4219fe6060f1SDimitry Andric     break;
4220fe6060f1SDimitry Andric   case CmpInst::ICMP_NE:
4221fe6060f1SDimitry Andric     KnownVal = KnownBits::ne(KnownLHS, KnownRHS);
4222fe6060f1SDimitry Andric     break;
4223fe6060f1SDimitry Andric   case CmpInst::ICMP_SGE:
4224fe6060f1SDimitry Andric     KnownVal = KnownBits::sge(KnownLHS, KnownRHS);
4225fe6060f1SDimitry Andric     break;
4226fe6060f1SDimitry Andric   case CmpInst::ICMP_SGT:
4227fe6060f1SDimitry Andric     KnownVal = KnownBits::sgt(KnownLHS, KnownRHS);
4228fe6060f1SDimitry Andric     break;
4229fe6060f1SDimitry Andric   case CmpInst::ICMP_SLE:
4230fe6060f1SDimitry Andric     KnownVal = KnownBits::sle(KnownLHS, KnownRHS);
4231fe6060f1SDimitry Andric     break;
4232fe6060f1SDimitry Andric   case CmpInst::ICMP_SLT:
4233fe6060f1SDimitry Andric     KnownVal = KnownBits::slt(KnownLHS, KnownRHS);
4234fe6060f1SDimitry Andric     break;
4235fe6060f1SDimitry Andric   case CmpInst::ICMP_UGE:
4236fe6060f1SDimitry Andric     KnownVal = KnownBits::uge(KnownLHS, KnownRHS);
4237fe6060f1SDimitry Andric     break;
4238fe6060f1SDimitry Andric   case CmpInst::ICMP_UGT:
4239fe6060f1SDimitry Andric     KnownVal = KnownBits::ugt(KnownLHS, KnownRHS);
4240fe6060f1SDimitry Andric     break;
4241fe6060f1SDimitry Andric   case CmpInst::ICMP_ULE:
4242fe6060f1SDimitry Andric     KnownVal = KnownBits::ule(KnownLHS, KnownRHS);
4243fe6060f1SDimitry Andric     break;
4244fe6060f1SDimitry Andric   case CmpInst::ICMP_ULT:
4245fe6060f1SDimitry Andric     KnownVal = KnownBits::ult(KnownLHS, KnownRHS);
4246fe6060f1SDimitry Andric     break;
4247fe6060f1SDimitry Andric   }
4248fe6060f1SDimitry Andric   if (!KnownVal)
4249fe6060f1SDimitry Andric     return false;
4250fe6060f1SDimitry Andric   MatchInfo =
4251fe6060f1SDimitry Andric       *KnownVal
4252fe6060f1SDimitry Andric           ? getICmpTrueVal(getTargetLowering(),
4253fe6060f1SDimitry Andric                            /*IsVector = */
4254fe6060f1SDimitry Andric                            MRI.getType(MI.getOperand(0).getReg()).isVector(),
4255fe6060f1SDimitry Andric                            /* IsFP = */ false)
4256fe6060f1SDimitry Andric           : 0;
4257fe6060f1SDimitry Andric   return true;
4258fe6060f1SDimitry Andric }
4259fe6060f1SDimitry Andric 
4260349cc55cSDimitry Andric bool CombinerHelper::matchICmpToLHSKnownBits(
4261349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4262349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4263349cc55cSDimitry Andric   // Given:
4264349cc55cSDimitry Andric   //
4265349cc55cSDimitry Andric   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4266349cc55cSDimitry Andric   // %cmp = G_ICMP ne %x, 0
4267349cc55cSDimitry Andric   //
4268349cc55cSDimitry Andric   // Or:
4269349cc55cSDimitry Andric   //
4270349cc55cSDimitry Andric   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4271349cc55cSDimitry Andric   // %cmp = G_ICMP eq %x, 1
4272349cc55cSDimitry Andric   //
4273349cc55cSDimitry Andric   // We can replace %cmp with %x assuming true is 1 on the target.
4274349cc55cSDimitry Andric   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4275349cc55cSDimitry Andric   if (!CmpInst::isEquality(Pred))
4276349cc55cSDimitry Andric     return false;
4277349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4278349cc55cSDimitry Andric   LLT DstTy = MRI.getType(Dst);
4279349cc55cSDimitry Andric   if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(),
4280349cc55cSDimitry Andric                      /* IsFP = */ false) != 1)
4281349cc55cSDimitry Andric     return false;
4282349cc55cSDimitry Andric   int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
4283349cc55cSDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
4284349cc55cSDimitry Andric     return false;
4285349cc55cSDimitry Andric   Register LHS = MI.getOperand(2).getReg();
4286349cc55cSDimitry Andric   auto KnownLHS = KB->getKnownBits(LHS);
4287349cc55cSDimitry Andric   if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
4288349cc55cSDimitry Andric     return false;
4289349cc55cSDimitry Andric   // Make sure replacing Dst with the LHS is a legal operation.
4290349cc55cSDimitry Andric   LLT LHSTy = MRI.getType(LHS);
4291349cc55cSDimitry Andric   unsigned LHSSize = LHSTy.getSizeInBits();
4292349cc55cSDimitry Andric   unsigned DstSize = DstTy.getSizeInBits();
4293349cc55cSDimitry Andric   unsigned Op = TargetOpcode::COPY;
4294349cc55cSDimitry Andric   if (DstSize != LHSSize)
4295349cc55cSDimitry Andric     Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
4296349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
4297349cc55cSDimitry Andric     return false;
4298349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
4299349cc55cSDimitry Andric   return true;
4300349cc55cSDimitry Andric }
4301349cc55cSDimitry Andric 
4302349cc55cSDimitry Andric // Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
4303349cc55cSDimitry Andric bool CombinerHelper::matchAndOrDisjointMask(
4304349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4305349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4306349cc55cSDimitry Andric 
4307349cc55cSDimitry Andric   // Ignore vector types to simplify matching the two constants.
4308349cc55cSDimitry Andric   // TODO: do this for vectors and scalars via a demanded bits analysis.
4309349cc55cSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
4310349cc55cSDimitry Andric   if (Ty.isVector())
4311349cc55cSDimitry Andric     return false;
4312349cc55cSDimitry Andric 
4313349cc55cSDimitry Andric   Register Src;
431481ad6265SDimitry Andric   Register AndMaskReg;
431581ad6265SDimitry Andric   int64_t AndMaskBits;
431681ad6265SDimitry Andric   int64_t OrMaskBits;
4317349cc55cSDimitry Andric   if (!mi_match(MI, MRI,
431881ad6265SDimitry Andric                 m_GAnd(m_GOr(m_Reg(Src), m_ICst(OrMaskBits)),
431981ad6265SDimitry Andric                        m_all_of(m_ICst(AndMaskBits), m_Reg(AndMaskReg)))))
4320349cc55cSDimitry Andric     return false;
4321349cc55cSDimitry Andric 
432281ad6265SDimitry Andric   // Check if OrMask could turn on any bits in Src.
432381ad6265SDimitry Andric   if (AndMaskBits & OrMaskBits)
4324349cc55cSDimitry Andric     return false;
4325349cc55cSDimitry Andric 
4326349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4327349cc55cSDimitry Andric     Observer.changingInstr(MI);
432881ad6265SDimitry Andric     // Canonicalize the result to have the constant on the RHS.
432981ad6265SDimitry Andric     if (MI.getOperand(1).getReg() == AndMaskReg)
433081ad6265SDimitry Andric       MI.getOperand(2).setReg(AndMaskReg);
4331349cc55cSDimitry Andric     MI.getOperand(1).setReg(Src);
4332349cc55cSDimitry Andric     Observer.changedInstr(MI);
4333349cc55cSDimitry Andric   };
4334349cc55cSDimitry Andric   return true;
4335349cc55cSDimitry Andric }
4336349cc55cSDimitry Andric 
4337fe6060f1SDimitry Andric /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
4338fe6060f1SDimitry Andric bool CombinerHelper::matchBitfieldExtractFromSExtInReg(
4339fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4340fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
4341fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4342fe6060f1SDimitry Andric   Register Src = MI.getOperand(1).getReg();
4343fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Src);
4344fe6060f1SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4345fe6060f1SDimitry Andric   if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
4346fe6060f1SDimitry Andric     return false;
4347fe6060f1SDimitry Andric   int64_t Width = MI.getOperand(2).getImm();
4348fe6060f1SDimitry Andric   Register ShiftSrc;
4349fe6060f1SDimitry Andric   int64_t ShiftImm;
4350fe6060f1SDimitry Andric   if (!mi_match(
4351fe6060f1SDimitry Andric           Src, MRI,
4352fe6060f1SDimitry Andric           m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
4353fe6060f1SDimitry Andric                                   m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
4354fe6060f1SDimitry Andric     return false;
4355fe6060f1SDimitry Andric   if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
4356fe6060f1SDimitry Andric     return false;
4357fe6060f1SDimitry Andric 
4358fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4359fe6060f1SDimitry Andric     auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
4360fe6060f1SDimitry Andric     auto Cst2 = B.buildConstant(ExtractTy, Width);
4361fe6060f1SDimitry Andric     B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
4362fe6060f1SDimitry Andric   };
4363fe6060f1SDimitry Andric   return true;
4364fe6060f1SDimitry Andric }
4365fe6060f1SDimitry Andric 
4366fe6060f1SDimitry Andric /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
4367fe6060f1SDimitry Andric bool CombinerHelper::matchBitfieldExtractFromAnd(
4368fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4369fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4370fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4371fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
437204eeddc0SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
43735f757f3fSDimitry Andric   if (LI && !LI->isLegalOrCustom({TargetOpcode::G_UBFX, {Ty, ExtractTy}}))
4374fe6060f1SDimitry Andric     return false;
4375fe6060f1SDimitry Andric 
4376fe6060f1SDimitry Andric   int64_t AndImm, LSBImm;
4377fe6060f1SDimitry Andric   Register ShiftSrc;
4378fe6060f1SDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4379fe6060f1SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
4380fe6060f1SDimitry Andric                 m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
4381fe6060f1SDimitry Andric                        m_ICst(AndImm))))
4382fe6060f1SDimitry Andric     return false;
4383fe6060f1SDimitry Andric 
4384fe6060f1SDimitry Andric   // The mask is a mask of the low bits iff imm & (imm+1) == 0.
4385fe6060f1SDimitry Andric   auto MaybeMask = static_cast<uint64_t>(AndImm);
4386fe6060f1SDimitry Andric   if (MaybeMask & (MaybeMask + 1))
4387fe6060f1SDimitry Andric     return false;
4388fe6060f1SDimitry Andric 
4389fe6060f1SDimitry Andric   // LSB must fit within the register.
4390fe6060f1SDimitry Andric   if (static_cast<uint64_t>(LSBImm) >= Size)
4391fe6060f1SDimitry Andric     return false;
4392fe6060f1SDimitry Andric 
439306c3fb27SDimitry Andric   uint64_t Width = APInt(Size, AndImm).countr_one();
4394fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4395fe6060f1SDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
4396fe6060f1SDimitry Andric     auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
4397fe6060f1SDimitry Andric     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
4398fe6060f1SDimitry Andric   };
4399fe6060f1SDimitry Andric   return true;
4400fe6060f1SDimitry Andric }
4401fe6060f1SDimitry Andric 
4402349cc55cSDimitry Andric bool CombinerHelper::matchBitfieldExtractFromShr(
4403349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4404349cc55cSDimitry Andric   const unsigned Opcode = MI.getOpcode();
4405349cc55cSDimitry Andric   assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
4406349cc55cSDimitry Andric 
4407349cc55cSDimitry Andric   const Register Dst = MI.getOperand(0).getReg();
4408349cc55cSDimitry Andric 
4409349cc55cSDimitry Andric   const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
4410349cc55cSDimitry Andric                                   ? TargetOpcode::G_SBFX
4411349cc55cSDimitry Andric                                   : TargetOpcode::G_UBFX;
4412349cc55cSDimitry Andric 
4413349cc55cSDimitry Andric   // Check if the type we would use for the extract is legal
4414349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4415349cc55cSDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4416349cc55cSDimitry Andric   if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
4417349cc55cSDimitry Andric     return false;
4418349cc55cSDimitry Andric 
4419349cc55cSDimitry Andric   Register ShlSrc;
4420349cc55cSDimitry Andric   int64_t ShrAmt;
4421349cc55cSDimitry Andric   int64_t ShlAmt;
4422349cc55cSDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4423349cc55cSDimitry Andric 
4424349cc55cSDimitry Andric   // Try to match shr (shl x, c1), c2
4425349cc55cSDimitry Andric   if (!mi_match(Dst, MRI,
4426349cc55cSDimitry Andric                 m_BinOp(Opcode,
4427349cc55cSDimitry Andric                         m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
4428349cc55cSDimitry Andric                         m_ICst(ShrAmt))))
4429349cc55cSDimitry Andric     return false;
4430349cc55cSDimitry Andric 
4431349cc55cSDimitry Andric   // Make sure that the shift sizes can fit a bitfield extract
4432349cc55cSDimitry Andric   if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
4433349cc55cSDimitry Andric     return false;
4434349cc55cSDimitry Andric 
4435349cc55cSDimitry Andric   // Skip this combine if the G_SEXT_INREG combine could handle it
4436349cc55cSDimitry Andric   if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
4437349cc55cSDimitry Andric     return false;
4438349cc55cSDimitry Andric 
4439349cc55cSDimitry Andric   // Calculate start position and width of the extract
4440349cc55cSDimitry Andric   const int64_t Pos = ShrAmt - ShlAmt;
4441349cc55cSDimitry Andric   const int64_t Width = Size - ShrAmt;
4442349cc55cSDimitry Andric 
4443349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4444349cc55cSDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
4445349cc55cSDimitry Andric     auto PosCst = B.buildConstant(ExtractTy, Pos);
4446349cc55cSDimitry Andric     B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
4447349cc55cSDimitry Andric   };
4448349cc55cSDimitry Andric   return true;
4449349cc55cSDimitry Andric }
4450349cc55cSDimitry Andric 
4451349cc55cSDimitry Andric bool CombinerHelper::matchBitfieldExtractFromShrAnd(
4452349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4453349cc55cSDimitry Andric   const unsigned Opcode = MI.getOpcode();
4454349cc55cSDimitry Andric   assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
4455349cc55cSDimitry Andric 
4456349cc55cSDimitry Andric   const Register Dst = MI.getOperand(0).getReg();
4457349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
445804eeddc0SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
44595f757f3fSDimitry Andric   if (LI && !LI->isLegalOrCustom({TargetOpcode::G_UBFX, {Ty, ExtractTy}}))
4460349cc55cSDimitry Andric     return false;
4461349cc55cSDimitry Andric 
4462349cc55cSDimitry Andric   // Try to match shr (and x, c1), c2
4463349cc55cSDimitry Andric   Register AndSrc;
4464349cc55cSDimitry Andric   int64_t ShrAmt;
4465349cc55cSDimitry Andric   int64_t SMask;
4466349cc55cSDimitry Andric   if (!mi_match(Dst, MRI,
4467349cc55cSDimitry Andric                 m_BinOp(Opcode,
4468349cc55cSDimitry Andric                         m_OneNonDBGUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
4469349cc55cSDimitry Andric                         m_ICst(ShrAmt))))
4470349cc55cSDimitry Andric     return false;
4471349cc55cSDimitry Andric 
4472349cc55cSDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4473349cc55cSDimitry Andric   if (ShrAmt < 0 || ShrAmt >= Size)
4474349cc55cSDimitry Andric     return false;
4475349cc55cSDimitry Andric 
447681ad6265SDimitry Andric   // If the shift subsumes the mask, emit the 0 directly.
447781ad6265SDimitry Andric   if (0 == (SMask >> ShrAmt)) {
447881ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
447981ad6265SDimitry Andric       B.buildConstant(Dst, 0);
448081ad6265SDimitry Andric     };
448181ad6265SDimitry Andric     return true;
448281ad6265SDimitry Andric   }
448381ad6265SDimitry Andric 
4484349cc55cSDimitry Andric   // Check that ubfx can do the extraction, with no holes in the mask.
4485349cc55cSDimitry Andric   uint64_t UMask = SMask;
4486349cc55cSDimitry Andric   UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
4487349cc55cSDimitry Andric   UMask &= maskTrailingOnes<uint64_t>(Size);
4488349cc55cSDimitry Andric   if (!isMask_64(UMask))
4489349cc55cSDimitry Andric     return false;
4490349cc55cSDimitry Andric 
4491349cc55cSDimitry Andric   // Calculate start position and width of the extract.
4492349cc55cSDimitry Andric   const int64_t Pos = ShrAmt;
449306c3fb27SDimitry Andric   const int64_t Width = llvm::countr_one(UMask) - ShrAmt;
4494349cc55cSDimitry Andric 
4495349cc55cSDimitry Andric   // It's preferable to keep the shift, rather than form G_SBFX.
4496349cc55cSDimitry Andric   // TODO: remove the G_AND via demanded bits analysis.
4497349cc55cSDimitry Andric   if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
4498349cc55cSDimitry Andric     return false;
4499349cc55cSDimitry Andric 
4500349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
450104eeddc0SDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
450204eeddc0SDimitry Andric     auto PosCst = B.buildConstant(ExtractTy, Pos);
4503349cc55cSDimitry Andric     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
4504349cc55cSDimitry Andric   };
4505349cc55cSDimitry Andric   return true;
4506349cc55cSDimitry Andric }
4507349cc55cSDimitry Andric 
4508fe6060f1SDimitry Andric bool CombinerHelper::reassociationCanBreakAddressingModePattern(
45095f757f3fSDimitry Andric     MachineInstr &MI) {
45105f757f3fSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
4511fe6060f1SDimitry Andric 
45125f757f3fSDimitry Andric   Register Src1Reg = PtrAdd.getBaseReg();
45135f757f3fSDimitry Andric   auto *Src1Def = getOpcodeDef<GPtrAdd>(Src1Reg, MRI);
4514fe6060f1SDimitry Andric   if (!Src1Def)
4515fe6060f1SDimitry Andric     return false;
4516fe6060f1SDimitry Andric 
45175f757f3fSDimitry Andric   Register Src2Reg = PtrAdd.getOffsetReg();
4518fe6060f1SDimitry Andric 
4519fe6060f1SDimitry Andric   if (MRI.hasOneNonDBGUse(Src1Reg))
4520fe6060f1SDimitry Andric     return false;
4521fe6060f1SDimitry Andric 
45225f757f3fSDimitry Andric   auto C1 = getIConstantVRegVal(Src1Def->getOffsetReg(), MRI);
4523fe6060f1SDimitry Andric   if (!C1)
4524fe6060f1SDimitry Andric     return false;
4525349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4526fe6060f1SDimitry Andric   if (!C2)
4527fe6060f1SDimitry Andric     return false;
4528fe6060f1SDimitry Andric 
4529fe6060f1SDimitry Andric   const APInt &C1APIntVal = *C1;
4530fe6060f1SDimitry Andric   const APInt &C2APIntVal = *C2;
4531fe6060f1SDimitry Andric   const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
4532fe6060f1SDimitry Andric 
45335f757f3fSDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(PtrAdd.getReg(0))) {
4534fe6060f1SDimitry Andric     // This combine may end up running before ptrtoint/inttoptr combines
4535fe6060f1SDimitry Andric     // manage to eliminate redundant conversions, so try to look through them.
4536fe6060f1SDimitry Andric     MachineInstr *ConvUseMI = &UseMI;
4537fe6060f1SDimitry Andric     unsigned ConvUseOpc = ConvUseMI->getOpcode();
4538fe6060f1SDimitry Andric     while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
4539fe6060f1SDimitry Andric            ConvUseOpc == TargetOpcode::G_PTRTOINT) {
4540fe6060f1SDimitry Andric       Register DefReg = ConvUseMI->getOperand(0).getReg();
4541fe6060f1SDimitry Andric       if (!MRI.hasOneNonDBGUse(DefReg))
4542fe6060f1SDimitry Andric         break;
4543fe6060f1SDimitry Andric       ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
4544fe6060f1SDimitry Andric       ConvUseOpc = ConvUseMI->getOpcode();
4545fe6060f1SDimitry Andric     }
45465f757f3fSDimitry Andric     auto *LdStMI = dyn_cast<GLoadStore>(ConvUseMI);
45475f757f3fSDimitry Andric     if (!LdStMI)
4548fe6060f1SDimitry Andric       continue;
4549fe6060f1SDimitry Andric     // Is x[offset2] already not a legal addressing mode? If so then
4550fe6060f1SDimitry Andric     // reassociating the constants breaks nothing (we test offset2 because
4551fe6060f1SDimitry Andric     // that's the one we hope to fold into the load or store).
4552fe6060f1SDimitry Andric     TargetLoweringBase::AddrMode AM;
4553fe6060f1SDimitry Andric     AM.HasBaseReg = true;
4554fe6060f1SDimitry Andric     AM.BaseOffs = C2APIntVal.getSExtValue();
45555f757f3fSDimitry Andric     unsigned AS = MRI.getType(LdStMI->getPointerReg()).getAddressSpace();
45565f757f3fSDimitry Andric     Type *AccessTy = getTypeForLLT(LdStMI->getMMO().getMemoryType(),
4557fe6060f1SDimitry Andric                                    PtrAdd.getMF()->getFunction().getContext());
4558fe6060f1SDimitry Andric     const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
4559fe6060f1SDimitry Andric     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4560fe6060f1SDimitry Andric                                    AccessTy, AS))
4561fe6060f1SDimitry Andric       continue;
4562fe6060f1SDimitry Andric 
4563fe6060f1SDimitry Andric     // Would x[offset1+offset2] still be a legal addressing mode?
4564fe6060f1SDimitry Andric     AM.BaseOffs = CombinedValue;
4565fe6060f1SDimitry Andric     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4566fe6060f1SDimitry Andric                                    AccessTy, AS))
4567fe6060f1SDimitry Andric       return true;
4568fe6060f1SDimitry Andric   }
4569fe6060f1SDimitry Andric 
4570fe6060f1SDimitry Andric   return false;
4571fe6060f1SDimitry Andric }
4572fe6060f1SDimitry Andric 
4573349cc55cSDimitry Andric bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI,
4574349cc55cSDimitry Andric                                                   MachineInstr *RHS,
4575349cc55cSDimitry Andric                                                   BuildFnTy &MatchInfo) {
4576fe6060f1SDimitry Andric   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4577fe6060f1SDimitry Andric   Register Src1Reg = MI.getOperand(1).getReg();
4578fe6060f1SDimitry Andric   if (RHS->getOpcode() != TargetOpcode::G_ADD)
4579fe6060f1SDimitry Andric     return false;
4580349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
4581fe6060f1SDimitry Andric   if (!C2)
4582fe6060f1SDimitry Andric     return false;
4583fe6060f1SDimitry Andric 
4584fe6060f1SDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4585fe6060f1SDimitry Andric     LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
4586fe6060f1SDimitry Andric 
4587fe6060f1SDimitry Andric     auto NewBase =
4588fe6060f1SDimitry Andric         Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg());
4589fe6060f1SDimitry Andric     Observer.changingInstr(MI);
4590fe6060f1SDimitry Andric     MI.getOperand(1).setReg(NewBase.getReg(0));
4591fe6060f1SDimitry Andric     MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
4592fe6060f1SDimitry Andric     Observer.changedInstr(MI);
4593fe6060f1SDimitry Andric   };
4594349cc55cSDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4595349cc55cSDimitry Andric }
4596349cc55cSDimitry Andric 
4597349cc55cSDimitry Andric bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI,
4598349cc55cSDimitry Andric                                                   MachineInstr *LHS,
4599349cc55cSDimitry Andric                                                   MachineInstr *RHS,
4600349cc55cSDimitry Andric                                                   BuildFnTy &MatchInfo) {
4601349cc55cSDimitry Andric   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
4602349cc55cSDimitry Andric   // if and only if (G_PTR_ADD X, C) has one use.
4603349cc55cSDimitry Andric   Register LHSBase;
4604bdd1243dSDimitry Andric   std::optional<ValueAndVReg> LHSCstOff;
4605349cc55cSDimitry Andric   if (!mi_match(MI.getBaseReg(), MRI,
4606349cc55cSDimitry Andric                 m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
4607349cc55cSDimitry Andric     return false;
4608349cc55cSDimitry Andric 
4609349cc55cSDimitry Andric   auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
4610349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4611349cc55cSDimitry Andric     // When we change LHSPtrAdd's offset register we might cause it to use a reg
4612349cc55cSDimitry Andric     // before its def. Sink the instruction so the outer PTR_ADD to ensure this
4613349cc55cSDimitry Andric     // doesn't happen.
4614349cc55cSDimitry Andric     LHSPtrAdd->moveBefore(&MI);
4615349cc55cSDimitry Andric     Register RHSReg = MI.getOffsetReg();
4616bdd1243dSDimitry Andric     // set VReg will cause type mismatch if it comes from extend/trunc
4617bdd1243dSDimitry Andric     auto NewCst = B.buildConstant(MRI.getType(RHSReg), LHSCstOff->Value);
4618349cc55cSDimitry Andric     Observer.changingInstr(MI);
4619bdd1243dSDimitry Andric     MI.getOperand(2).setReg(NewCst.getReg(0));
4620349cc55cSDimitry Andric     Observer.changedInstr(MI);
4621349cc55cSDimitry Andric     Observer.changingInstr(*LHSPtrAdd);
4622349cc55cSDimitry Andric     LHSPtrAdd->getOperand(2).setReg(RHSReg);
4623349cc55cSDimitry Andric     Observer.changedInstr(*LHSPtrAdd);
4624349cc55cSDimitry Andric   };
4625349cc55cSDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4626349cc55cSDimitry Andric }
4627349cc55cSDimitry Andric 
4628349cc55cSDimitry Andric bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI,
4629349cc55cSDimitry Andric                                                         MachineInstr *LHS,
4630349cc55cSDimitry Andric                                                         MachineInstr *RHS,
4631349cc55cSDimitry Andric                                                         BuildFnTy &MatchInfo) {
4632349cc55cSDimitry Andric   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4633349cc55cSDimitry Andric   auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
4634349cc55cSDimitry Andric   if (!LHSPtrAdd)
4635349cc55cSDimitry Andric     return false;
4636349cc55cSDimitry Andric 
4637349cc55cSDimitry Andric   Register Src2Reg = MI.getOperand(2).getReg();
4638349cc55cSDimitry Andric   Register LHSSrc1 = LHSPtrAdd->getBaseReg();
4639349cc55cSDimitry Andric   Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
4640349cc55cSDimitry Andric   auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
4641fe6060f1SDimitry Andric   if (!C1)
4642fe6060f1SDimitry Andric     return false;
4643349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4644fe6060f1SDimitry Andric   if (!C2)
4645fe6060f1SDimitry Andric     return false;
4646fe6060f1SDimitry Andric 
4647fe6060f1SDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4648fe6060f1SDimitry Andric     auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
4649fe6060f1SDimitry Andric     Observer.changingInstr(MI);
4650fe6060f1SDimitry Andric     MI.getOperand(1).setReg(LHSSrc1);
4651fe6060f1SDimitry Andric     MI.getOperand(2).setReg(NewCst.getReg(0));
4652fe6060f1SDimitry Andric     Observer.changedInstr(MI);
4653fe6060f1SDimitry Andric   };
4654fe6060f1SDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4655fe6060f1SDimitry Andric }
4656fe6060f1SDimitry Andric 
4657349cc55cSDimitry Andric bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI,
4658349cc55cSDimitry Andric                                         BuildFnTy &MatchInfo) {
4659349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
4660349cc55cSDimitry Andric   // We're trying to match a few pointer computation patterns here for
4661349cc55cSDimitry Andric   // re-association opportunities.
4662349cc55cSDimitry Andric   // 1) Isolating a constant operand to be on the RHS, e.g.:
4663349cc55cSDimitry Andric   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4664349cc55cSDimitry Andric   //
4665349cc55cSDimitry Andric   // 2) Folding two constants in each sub-tree as long as such folding
4666349cc55cSDimitry Andric   // doesn't break a legal addressing mode.
4667349cc55cSDimitry Andric   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4668349cc55cSDimitry Andric   //
4669349cc55cSDimitry Andric   // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
4670349cc55cSDimitry Andric   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
4671349cc55cSDimitry Andric   // iif (G_PTR_ADD X, C) has one use.
4672349cc55cSDimitry Andric   MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg());
4673349cc55cSDimitry Andric   MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg());
4674349cc55cSDimitry Andric 
4675349cc55cSDimitry Andric   // Try to match example 2.
4676349cc55cSDimitry Andric   if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
4677349cc55cSDimitry Andric     return true;
4678349cc55cSDimitry Andric 
4679349cc55cSDimitry Andric   // Try to match example 3.
4680349cc55cSDimitry Andric   if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
4681349cc55cSDimitry Andric     return true;
4682349cc55cSDimitry Andric 
4683349cc55cSDimitry Andric   // Try to match example 1.
4684349cc55cSDimitry Andric   if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
4685349cc55cSDimitry Andric     return true;
4686349cc55cSDimitry Andric 
4687349cc55cSDimitry Andric   return false;
4688349cc55cSDimitry Andric }
468906c3fb27SDimitry Andric bool CombinerHelper::tryReassocBinOp(unsigned Opc, Register DstReg,
469006c3fb27SDimitry Andric                                      Register OpLHS, Register OpRHS,
469106c3fb27SDimitry Andric                                      BuildFnTy &MatchInfo) {
469206c3fb27SDimitry Andric   LLT OpRHSTy = MRI.getType(OpRHS);
469306c3fb27SDimitry Andric   MachineInstr *OpLHSDef = MRI.getVRegDef(OpLHS);
469406c3fb27SDimitry Andric 
469506c3fb27SDimitry Andric   if (OpLHSDef->getOpcode() != Opc)
469606c3fb27SDimitry Andric     return false;
469706c3fb27SDimitry Andric 
469806c3fb27SDimitry Andric   MachineInstr *OpRHSDef = MRI.getVRegDef(OpRHS);
469906c3fb27SDimitry Andric   Register OpLHSLHS = OpLHSDef->getOperand(1).getReg();
470006c3fb27SDimitry Andric   Register OpLHSRHS = OpLHSDef->getOperand(2).getReg();
470106c3fb27SDimitry Andric 
470206c3fb27SDimitry Andric   // If the inner op is (X op C), pull the constant out so it can be folded with
470306c3fb27SDimitry Andric   // other constants in the expression tree. Folding is not guaranteed so we
470406c3fb27SDimitry Andric   // might have (C1 op C2). In that case do not pull a constant out because it
470506c3fb27SDimitry Andric   // won't help and can lead to infinite loops.
470606c3fb27SDimitry Andric   if (isConstantOrConstantSplatVector(*MRI.getVRegDef(OpLHSRHS), MRI) &&
470706c3fb27SDimitry Andric       !isConstantOrConstantSplatVector(*MRI.getVRegDef(OpLHSLHS), MRI)) {
470806c3fb27SDimitry Andric     if (isConstantOrConstantSplatVector(*OpRHSDef, MRI)) {
470906c3fb27SDimitry Andric       // (Opc (Opc X, C1), C2) -> (Opc X, (Opc C1, C2))
471006c3fb27SDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
471106c3fb27SDimitry Andric         auto NewCst = B.buildInstr(Opc, {OpRHSTy}, {OpLHSRHS, OpRHS});
471206c3fb27SDimitry Andric         B.buildInstr(Opc, {DstReg}, {OpLHSLHS, NewCst});
471306c3fb27SDimitry Andric       };
471406c3fb27SDimitry Andric       return true;
471506c3fb27SDimitry Andric     }
471606c3fb27SDimitry Andric     if (getTargetLowering().isReassocProfitable(MRI, OpLHS, OpRHS)) {
471706c3fb27SDimitry Andric       // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
471806c3fb27SDimitry Andric       //              iff (op x, c1) has one use
471906c3fb27SDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
472006c3fb27SDimitry Andric         auto NewLHSLHS = B.buildInstr(Opc, {OpRHSTy}, {OpLHSLHS, OpRHS});
472106c3fb27SDimitry Andric         B.buildInstr(Opc, {DstReg}, {NewLHSLHS, OpLHSRHS});
472206c3fb27SDimitry Andric       };
472306c3fb27SDimitry Andric       return true;
472406c3fb27SDimitry Andric     }
472506c3fb27SDimitry Andric   }
472606c3fb27SDimitry Andric 
472706c3fb27SDimitry Andric   return false;
472806c3fb27SDimitry Andric }
472906c3fb27SDimitry Andric 
473006c3fb27SDimitry Andric bool CombinerHelper::matchReassocCommBinOp(MachineInstr &MI,
473106c3fb27SDimitry Andric                                            BuildFnTy &MatchInfo) {
473206c3fb27SDimitry Andric   // We don't check if the reassociation will break a legal addressing mode
473306c3fb27SDimitry Andric   // here since pointer arithmetic is handled by G_PTR_ADD.
473406c3fb27SDimitry Andric   unsigned Opc = MI.getOpcode();
473506c3fb27SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
473606c3fb27SDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
473706c3fb27SDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
473806c3fb27SDimitry Andric 
473906c3fb27SDimitry Andric   if (tryReassocBinOp(Opc, DstReg, LHSReg, RHSReg, MatchInfo))
474006c3fb27SDimitry Andric     return true;
474106c3fb27SDimitry Andric   if (tryReassocBinOp(Opc, DstReg, RHSReg, LHSReg, MatchInfo))
474206c3fb27SDimitry Andric     return true;
474306c3fb27SDimitry Andric   return false;
474406c3fb27SDimitry Andric }
4745349cc55cSDimitry Andric 
47465f757f3fSDimitry Andric bool CombinerHelper::matchConstantFoldCastOp(MachineInstr &MI, APInt &MatchInfo) {
47475f757f3fSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
47485f757f3fSDimitry Andric   Register SrcOp = MI.getOperand(1).getReg();
47495f757f3fSDimitry Andric 
47505f757f3fSDimitry Andric   if (auto MaybeCst = ConstantFoldCastOp(MI.getOpcode(), DstTy, SrcOp, MRI)) {
47515f757f3fSDimitry Andric     MatchInfo = *MaybeCst;
47525f757f3fSDimitry Andric     return true;
47535f757f3fSDimitry Andric   }
47545f757f3fSDimitry Andric 
47555f757f3fSDimitry Andric   return false;
47565f757f3fSDimitry Andric }
47575f757f3fSDimitry Andric 
47585f757f3fSDimitry Andric bool CombinerHelper::matchConstantFoldBinOp(MachineInstr &MI, APInt &MatchInfo) {
4759fe6060f1SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
4760fe6060f1SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
4761fe6060f1SDimitry Andric   auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
4762fe6060f1SDimitry Andric   if (!MaybeCst)
4763fe6060f1SDimitry Andric     return false;
4764fe6060f1SDimitry Andric   MatchInfo = *MaybeCst;
4765e8d8bef9SDimitry Andric   return true;
4766e8d8bef9SDimitry Andric }
4767e8d8bef9SDimitry Andric 
47685f757f3fSDimitry Andric bool CombinerHelper::matchConstantFoldFPBinOp(MachineInstr &MI, ConstantFP* &MatchInfo) {
47695f757f3fSDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
47705f757f3fSDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
47715f757f3fSDimitry Andric   auto MaybeCst = ConstantFoldFPBinOp(MI.getOpcode(), Op1, Op2, MRI);
47725f757f3fSDimitry Andric   if (!MaybeCst)
47735f757f3fSDimitry Andric     return false;
47745f757f3fSDimitry Andric   MatchInfo =
47755f757f3fSDimitry Andric       ConstantFP::get(MI.getMF()->getFunction().getContext(), *MaybeCst);
47765f757f3fSDimitry Andric   return true;
47775f757f3fSDimitry Andric }
47785f757f3fSDimitry Andric 
47795f757f3fSDimitry Andric bool CombinerHelper::matchConstantFoldFMA(MachineInstr &MI,
47805f757f3fSDimitry Andric                                           ConstantFP *&MatchInfo) {
47815f757f3fSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FMA ||
47825f757f3fSDimitry Andric          MI.getOpcode() == TargetOpcode::G_FMAD);
47835f757f3fSDimitry Andric   auto [_, Op1, Op2, Op3] = MI.getFirst4Regs();
47845f757f3fSDimitry Andric 
47855f757f3fSDimitry Andric   const ConstantFP *Op3Cst = getConstantFPVRegVal(Op3, MRI);
47865f757f3fSDimitry Andric   if (!Op3Cst)
47875f757f3fSDimitry Andric     return false;
47885f757f3fSDimitry Andric 
47895f757f3fSDimitry Andric   const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
47905f757f3fSDimitry Andric   if (!Op2Cst)
47915f757f3fSDimitry Andric     return false;
47925f757f3fSDimitry Andric 
47935f757f3fSDimitry Andric   const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
47945f757f3fSDimitry Andric   if (!Op1Cst)
47955f757f3fSDimitry Andric     return false;
47965f757f3fSDimitry Andric 
47975f757f3fSDimitry Andric   APFloat Op1F = Op1Cst->getValueAPF();
47985f757f3fSDimitry Andric   Op1F.fusedMultiplyAdd(Op2Cst->getValueAPF(), Op3Cst->getValueAPF(),
47995f757f3fSDimitry Andric                         APFloat::rmNearestTiesToEven);
48005f757f3fSDimitry Andric   MatchInfo = ConstantFP::get(MI.getMF()->getFunction().getContext(), Op1F);
48015f757f3fSDimitry Andric   return true;
48025f757f3fSDimitry Andric }
48035f757f3fSDimitry Andric 
4804349cc55cSDimitry Andric bool CombinerHelper::matchNarrowBinopFeedingAnd(
4805349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4806349cc55cSDimitry Andric   // Look for a binop feeding into an AND with a mask:
4807349cc55cSDimitry Andric   //
4808349cc55cSDimitry Andric   // %add = G_ADD %lhs, %rhs
4809349cc55cSDimitry Andric   // %and = G_AND %add, 000...11111111
4810349cc55cSDimitry Andric   //
4811349cc55cSDimitry Andric   // Check if it's possible to perform the binop at a narrower width and zext
4812349cc55cSDimitry Andric   // back to the original width like so:
4813349cc55cSDimitry Andric   //
4814349cc55cSDimitry Andric   // %narrow_lhs = G_TRUNC %lhs
4815349cc55cSDimitry Andric   // %narrow_rhs = G_TRUNC %rhs
4816349cc55cSDimitry Andric   // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
4817349cc55cSDimitry Andric   // %new_add = G_ZEXT %narrow_add
4818349cc55cSDimitry Andric   // %and = G_AND %new_add, 000...11111111
4819349cc55cSDimitry Andric   //
4820349cc55cSDimitry Andric   // This can allow later combines to eliminate the G_AND if it turns out
4821349cc55cSDimitry Andric   // that the mask is irrelevant.
4822349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4823349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4824349cc55cSDimitry Andric   Register AndLHS = MI.getOperand(1).getReg();
4825349cc55cSDimitry Andric   Register AndRHS = MI.getOperand(2).getReg();
4826349cc55cSDimitry Andric   LLT WideTy = MRI.getType(Dst);
4827349cc55cSDimitry Andric 
4828349cc55cSDimitry Andric   // If the potential binop has more than one use, then it's possible that one
4829349cc55cSDimitry Andric   // of those uses will need its full width.
4830349cc55cSDimitry Andric   if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
4831349cc55cSDimitry Andric     return false;
4832349cc55cSDimitry Andric 
4833349cc55cSDimitry Andric   // Check if the LHS feeding the AND is impacted by the high bits that we're
4834349cc55cSDimitry Andric   // masking out.
4835349cc55cSDimitry Andric   //
4836349cc55cSDimitry Andric   // e.g. for 64-bit x, y:
4837349cc55cSDimitry Andric   //
4838349cc55cSDimitry Andric   // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
4839349cc55cSDimitry Andric   MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
4840349cc55cSDimitry Andric   if (!LHSInst)
4841349cc55cSDimitry Andric     return false;
4842349cc55cSDimitry Andric   unsigned LHSOpc = LHSInst->getOpcode();
4843349cc55cSDimitry Andric   switch (LHSOpc) {
4844349cc55cSDimitry Andric   default:
4845349cc55cSDimitry Andric     return false;
4846349cc55cSDimitry Andric   case TargetOpcode::G_ADD:
4847349cc55cSDimitry Andric   case TargetOpcode::G_SUB:
4848349cc55cSDimitry Andric   case TargetOpcode::G_MUL:
4849349cc55cSDimitry Andric   case TargetOpcode::G_AND:
4850349cc55cSDimitry Andric   case TargetOpcode::G_OR:
4851349cc55cSDimitry Andric   case TargetOpcode::G_XOR:
4852349cc55cSDimitry Andric     break;
4853349cc55cSDimitry Andric   }
4854349cc55cSDimitry Andric 
4855349cc55cSDimitry Andric   // Find the mask on the RHS.
4856349cc55cSDimitry Andric   auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
4857349cc55cSDimitry Andric   if (!Cst)
4858349cc55cSDimitry Andric     return false;
4859349cc55cSDimitry Andric   auto Mask = Cst->Value;
4860349cc55cSDimitry Andric   if (!Mask.isMask())
4861349cc55cSDimitry Andric     return false;
4862349cc55cSDimitry Andric 
4863349cc55cSDimitry Andric   // No point in combining if there's nothing to truncate.
486406c3fb27SDimitry Andric   unsigned NarrowWidth = Mask.countr_one();
4865349cc55cSDimitry Andric   if (NarrowWidth == WideTy.getSizeInBits())
4866349cc55cSDimitry Andric     return false;
4867349cc55cSDimitry Andric   LLT NarrowTy = LLT::scalar(NarrowWidth);
4868349cc55cSDimitry Andric 
4869349cc55cSDimitry Andric   // Check if adding the zext + truncates could be harmful.
4870349cc55cSDimitry Andric   auto &MF = *MI.getMF();
4871349cc55cSDimitry Andric   const auto &TLI = getTargetLowering();
4872349cc55cSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
4873349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
4874349cc55cSDimitry Andric   if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) ||
4875349cc55cSDimitry Andric       !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx))
4876349cc55cSDimitry Andric     return false;
4877349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
4878349cc55cSDimitry Andric       !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
4879349cc55cSDimitry Andric     return false;
4880349cc55cSDimitry Andric   Register BinOpLHS = LHSInst->getOperand(1).getReg();
4881349cc55cSDimitry Andric   Register BinOpRHS = LHSInst->getOperand(2).getReg();
4882349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4883349cc55cSDimitry Andric     auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
4884349cc55cSDimitry Andric     auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
4885349cc55cSDimitry Andric     auto NarrowBinOp =
4886349cc55cSDimitry Andric         Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
4887349cc55cSDimitry Andric     auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
4888349cc55cSDimitry Andric     Observer.changingInstr(MI);
4889349cc55cSDimitry Andric     MI.getOperand(1).setReg(Ext.getReg(0));
4890349cc55cSDimitry Andric     Observer.changedInstr(MI);
4891349cc55cSDimitry Andric   };
4892349cc55cSDimitry Andric   return true;
4893349cc55cSDimitry Andric }
4894349cc55cSDimitry Andric 
4895349cc55cSDimitry Andric bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) {
4896349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
4897349cc55cSDimitry Andric   assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO);
48984824e7fdSDimitry Andric 
48994824e7fdSDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(2)))
4900349cc55cSDimitry Andric     return false;
4901349cc55cSDimitry Andric 
4902349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4903349cc55cSDimitry Andric     Observer.changingInstr(MI);
4904349cc55cSDimitry Andric     unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO
4905349cc55cSDimitry Andric                                                    : TargetOpcode::G_SADDO;
4906349cc55cSDimitry Andric     MI.setDesc(Builder.getTII().get(NewOpc));
4907349cc55cSDimitry Andric     MI.getOperand(3).setReg(MI.getOperand(2).getReg());
4908349cc55cSDimitry Andric     Observer.changedInstr(MI);
4909349cc55cSDimitry Andric   };
4910349cc55cSDimitry Andric   return true;
4911349cc55cSDimitry Andric }
4912349cc55cSDimitry Andric 
491381ad6265SDimitry Andric bool CombinerHelper::matchMulOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
491481ad6265SDimitry Andric   // (G_*MULO x, 0) -> 0 + no carry out
491581ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UMULO ||
491681ad6265SDimitry Andric          MI.getOpcode() == TargetOpcode::G_SMULO);
491781ad6265SDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
491881ad6265SDimitry Andric     return false;
491981ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
492081ad6265SDimitry Andric   Register Carry = MI.getOperand(1).getReg();
492181ad6265SDimitry Andric   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Dst)) ||
492281ad6265SDimitry Andric       !isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
492381ad6265SDimitry Andric     return false;
492481ad6265SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
492581ad6265SDimitry Andric     B.buildConstant(Dst, 0);
492681ad6265SDimitry Andric     B.buildConstant(Carry, 0);
492781ad6265SDimitry Andric   };
492881ad6265SDimitry Andric   return true;
492981ad6265SDimitry Andric }
493081ad6265SDimitry Andric 
493181ad6265SDimitry Andric bool CombinerHelper::matchAddOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
493281ad6265SDimitry Andric   // (G_*ADDO x, 0) -> x + no carry out
493381ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UADDO ||
493481ad6265SDimitry Andric          MI.getOpcode() == TargetOpcode::G_SADDO);
493581ad6265SDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
493681ad6265SDimitry Andric     return false;
493781ad6265SDimitry Andric   Register Carry = MI.getOperand(1).getReg();
493881ad6265SDimitry Andric   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
493981ad6265SDimitry Andric     return false;
494081ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
494181ad6265SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
494281ad6265SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
494381ad6265SDimitry Andric     B.buildCopy(Dst, LHS);
494481ad6265SDimitry Andric     B.buildConstant(Carry, 0);
494581ad6265SDimitry Andric   };
494681ad6265SDimitry Andric   return true;
494781ad6265SDimitry Andric }
494881ad6265SDimitry Andric 
4949bdd1243dSDimitry Andric bool CombinerHelper::matchAddEToAddO(MachineInstr &MI, BuildFnTy &MatchInfo) {
4950bdd1243dSDimitry Andric   // (G_*ADDE x, y, 0) -> (G_*ADDO x, y)
4951bdd1243dSDimitry Andric   // (G_*SUBE x, y, 0) -> (G_*SUBO x, y)
4952bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UADDE ||
4953bdd1243dSDimitry Andric          MI.getOpcode() == TargetOpcode::G_SADDE ||
4954bdd1243dSDimitry Andric          MI.getOpcode() == TargetOpcode::G_USUBE ||
4955bdd1243dSDimitry Andric          MI.getOpcode() == TargetOpcode::G_SSUBE);
4956bdd1243dSDimitry Andric   if (!mi_match(MI.getOperand(4).getReg(), MRI, m_SpecificICstOrSplat(0)))
4957bdd1243dSDimitry Andric     return false;
4958bdd1243dSDimitry Andric   MatchInfo = [&](MachineIRBuilder &B) {
4959bdd1243dSDimitry Andric     unsigned NewOpcode;
4960bdd1243dSDimitry Andric     switch (MI.getOpcode()) {
4961bdd1243dSDimitry Andric     case TargetOpcode::G_UADDE:
4962bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_UADDO;
4963bdd1243dSDimitry Andric       break;
4964bdd1243dSDimitry Andric     case TargetOpcode::G_SADDE:
4965bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_SADDO;
4966bdd1243dSDimitry Andric       break;
4967bdd1243dSDimitry Andric     case TargetOpcode::G_USUBE:
4968bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_USUBO;
4969bdd1243dSDimitry Andric       break;
4970bdd1243dSDimitry Andric     case TargetOpcode::G_SSUBE:
4971bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_SSUBO;
4972bdd1243dSDimitry Andric       break;
4973bdd1243dSDimitry Andric     }
4974bdd1243dSDimitry Andric     Observer.changingInstr(MI);
4975bdd1243dSDimitry Andric     MI.setDesc(B.getTII().get(NewOpcode));
4976bdd1243dSDimitry Andric     MI.removeOperand(4);
4977bdd1243dSDimitry Andric     Observer.changedInstr(MI);
4978bdd1243dSDimitry Andric   };
4979bdd1243dSDimitry Andric   return true;
4980bdd1243dSDimitry Andric }
4981bdd1243dSDimitry Andric 
4982bdd1243dSDimitry Andric bool CombinerHelper::matchSubAddSameReg(MachineInstr &MI,
4983bdd1243dSDimitry Andric                                         BuildFnTy &MatchInfo) {
4984bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SUB);
4985bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4986bdd1243dSDimitry Andric   // (x + y) - z -> x (if y == z)
4987bdd1243dSDimitry Andric   // (x + y) - z -> y (if x == z)
4988bdd1243dSDimitry Andric   Register X, Y, Z;
4989bdd1243dSDimitry Andric   if (mi_match(Dst, MRI, m_GSub(m_GAdd(m_Reg(X), m_Reg(Y)), m_Reg(Z)))) {
4990bdd1243dSDimitry Andric     Register ReplaceReg;
4991bdd1243dSDimitry Andric     int64_t CstX, CstY;
4992bdd1243dSDimitry Andric     if (Y == Z || (mi_match(Y, MRI, m_ICstOrSplat(CstY)) &&
4993bdd1243dSDimitry Andric                    mi_match(Z, MRI, m_SpecificICstOrSplat(CstY))))
4994bdd1243dSDimitry Andric       ReplaceReg = X;
4995bdd1243dSDimitry Andric     else if (X == Z || (mi_match(X, MRI, m_ICstOrSplat(CstX)) &&
4996bdd1243dSDimitry Andric                         mi_match(Z, MRI, m_SpecificICstOrSplat(CstX))))
4997bdd1243dSDimitry Andric       ReplaceReg = Y;
4998bdd1243dSDimitry Andric     if (ReplaceReg) {
4999bdd1243dSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) { B.buildCopy(Dst, ReplaceReg); };
5000bdd1243dSDimitry Andric       return true;
5001bdd1243dSDimitry Andric     }
5002bdd1243dSDimitry Andric   }
5003bdd1243dSDimitry Andric 
5004bdd1243dSDimitry Andric   // x - (y + z) -> 0 - y (if x == z)
5005bdd1243dSDimitry Andric   // x - (y + z) -> 0 - z (if x == y)
5006bdd1243dSDimitry Andric   if (mi_match(Dst, MRI, m_GSub(m_Reg(X), m_GAdd(m_Reg(Y), m_Reg(Z))))) {
5007bdd1243dSDimitry Andric     Register ReplaceReg;
5008bdd1243dSDimitry Andric     int64_t CstX;
5009bdd1243dSDimitry Andric     if (X == Z || (mi_match(X, MRI, m_ICstOrSplat(CstX)) &&
5010bdd1243dSDimitry Andric                    mi_match(Z, MRI, m_SpecificICstOrSplat(CstX))))
5011bdd1243dSDimitry Andric       ReplaceReg = Y;
5012bdd1243dSDimitry Andric     else if (X == Y || (mi_match(X, MRI, m_ICstOrSplat(CstX)) &&
5013bdd1243dSDimitry Andric                         mi_match(Y, MRI, m_SpecificICstOrSplat(CstX))))
5014bdd1243dSDimitry Andric       ReplaceReg = Z;
5015bdd1243dSDimitry Andric     if (ReplaceReg) {
5016bdd1243dSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
5017bdd1243dSDimitry Andric         auto Zero = B.buildConstant(MRI.getType(Dst), 0);
5018bdd1243dSDimitry Andric         B.buildSub(Dst, Zero, ReplaceReg);
5019bdd1243dSDimitry Andric       };
5020bdd1243dSDimitry Andric       return true;
5021bdd1243dSDimitry Andric     }
5022bdd1243dSDimitry Andric   }
5023bdd1243dSDimitry Andric   return false;
5024bdd1243dSDimitry Andric }
5025bdd1243dSDimitry Andric 
5026349cc55cSDimitry Andric MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) {
5027349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
5028349cc55cSDimitry Andric   auto &UDiv = cast<GenericMachineInstr>(MI);
5029349cc55cSDimitry Andric   Register Dst = UDiv.getReg(0);
5030349cc55cSDimitry Andric   Register LHS = UDiv.getReg(1);
5031349cc55cSDimitry Andric   Register RHS = UDiv.getReg(2);
5032349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
5033349cc55cSDimitry Andric   LLT ScalarTy = Ty.getScalarType();
5034349cc55cSDimitry Andric   const unsigned EltBits = ScalarTy.getScalarSizeInBits();
5035349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
5036349cc55cSDimitry Andric   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
5037349cc55cSDimitry Andric   auto &MIB = Builder;
5038349cc55cSDimitry Andric   MIB.setInstrAndDebugLoc(MI);
5039349cc55cSDimitry Andric 
5040349cc55cSDimitry Andric   bool UseNPQ = false;
5041349cc55cSDimitry Andric   SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5042349cc55cSDimitry Andric 
5043349cc55cSDimitry Andric   auto BuildUDIVPattern = [&](const Constant *C) {
5044349cc55cSDimitry Andric     auto *CI = cast<ConstantInt>(C);
5045349cc55cSDimitry Andric     const APInt &Divisor = CI->getValue();
5046bdd1243dSDimitry Andric 
5047bdd1243dSDimitry Andric     bool SelNPQ = false;
5048bdd1243dSDimitry Andric     APInt Magic(Divisor.getBitWidth(), 0);
5049349cc55cSDimitry Andric     unsigned PreShift = 0, PostShift = 0;
5050349cc55cSDimitry Andric 
5051bdd1243dSDimitry Andric     // Magic algorithm doesn't work for division by 1. We need to emit a select
5052bdd1243dSDimitry Andric     // at the end.
5053bdd1243dSDimitry Andric     // TODO: Use undef values for divisor of 1.
505406c3fb27SDimitry Andric     if (!Divisor.isOne()) {
5055bdd1243dSDimitry Andric       UnsignedDivisionByConstantInfo magics =
5056bdd1243dSDimitry Andric           UnsignedDivisionByConstantInfo::get(Divisor);
5057349cc55cSDimitry Andric 
5058bdd1243dSDimitry Andric       Magic = std::move(magics.Magic);
5059bdd1243dSDimitry Andric 
5060bdd1243dSDimitry Andric       assert(magics.PreShift < Divisor.getBitWidth() &&
5061349cc55cSDimitry Andric              "We shouldn't generate an undefined shift!");
5062bdd1243dSDimitry Andric       assert(magics.PostShift < Divisor.getBitWidth() &&
5063bdd1243dSDimitry Andric              "We shouldn't generate an undefined shift!");
5064bdd1243dSDimitry Andric       assert((!magics.IsAdd || magics.PreShift == 0) && "Unexpected pre-shift");
5065bdd1243dSDimitry Andric       PreShift = magics.PreShift;
5066bdd1243dSDimitry Andric       PostShift = magics.PostShift;
5067bdd1243dSDimitry Andric       SelNPQ = magics.IsAdd;
5068349cc55cSDimitry Andric     }
5069349cc55cSDimitry Andric 
5070349cc55cSDimitry Andric     PreShifts.push_back(
5071349cc55cSDimitry Andric         MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
5072bdd1243dSDimitry Andric     MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
5073349cc55cSDimitry Andric     NPQFactors.push_back(
5074349cc55cSDimitry Andric         MIB.buildConstant(ScalarTy,
5075349cc55cSDimitry Andric                           SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5076349cc55cSDimitry Andric                                  : APInt::getZero(EltBits))
5077349cc55cSDimitry Andric             .getReg(0));
5078349cc55cSDimitry Andric     PostShifts.push_back(
5079349cc55cSDimitry Andric         MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
5080349cc55cSDimitry Andric     UseNPQ |= SelNPQ;
5081349cc55cSDimitry Andric     return true;
5082349cc55cSDimitry Andric   };
5083349cc55cSDimitry Andric 
5084349cc55cSDimitry Andric   // Collect the shifts/magic values from each element.
5085349cc55cSDimitry Andric   bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
5086349cc55cSDimitry Andric   (void)Matched;
5087349cc55cSDimitry Andric   assert(Matched && "Expected unary predicate match to succeed");
5088349cc55cSDimitry Andric 
5089349cc55cSDimitry Andric   Register PreShift, PostShift, MagicFactor, NPQFactor;
5090349cc55cSDimitry Andric   auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
5091349cc55cSDimitry Andric   if (RHSDef) {
5092349cc55cSDimitry Andric     PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
5093349cc55cSDimitry Andric     MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
5094349cc55cSDimitry Andric     NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
5095349cc55cSDimitry Andric     PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
5096349cc55cSDimitry Andric   } else {
5097349cc55cSDimitry Andric     assert(MRI.getType(RHS).isScalar() &&
5098349cc55cSDimitry Andric            "Non-build_vector operation should have been a scalar");
5099349cc55cSDimitry Andric     PreShift = PreShifts[0];
5100349cc55cSDimitry Andric     MagicFactor = MagicFactors[0];
5101349cc55cSDimitry Andric     PostShift = PostShifts[0];
5102349cc55cSDimitry Andric   }
5103349cc55cSDimitry Andric 
5104349cc55cSDimitry Andric   Register Q = LHS;
5105349cc55cSDimitry Andric   Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
5106349cc55cSDimitry Andric 
5107349cc55cSDimitry Andric   // Multiply the numerator (operand 0) by the magic value.
5108349cc55cSDimitry Andric   Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
5109349cc55cSDimitry Andric 
5110349cc55cSDimitry Andric   if (UseNPQ) {
5111349cc55cSDimitry Andric     Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
5112349cc55cSDimitry Andric 
5113349cc55cSDimitry Andric     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5114349cc55cSDimitry Andric     // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
5115349cc55cSDimitry Andric     if (Ty.isVector())
5116349cc55cSDimitry Andric       NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
5117349cc55cSDimitry Andric     else
5118349cc55cSDimitry Andric       NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
5119349cc55cSDimitry Andric 
5120349cc55cSDimitry Andric     Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
5121349cc55cSDimitry Andric   }
5122349cc55cSDimitry Andric 
5123349cc55cSDimitry Andric   Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
5124349cc55cSDimitry Andric   auto One = MIB.buildConstant(Ty, 1);
5125349cc55cSDimitry Andric   auto IsOne = MIB.buildICmp(
5126349cc55cSDimitry Andric       CmpInst::Predicate::ICMP_EQ,
5127349cc55cSDimitry Andric       Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One);
5128349cc55cSDimitry Andric   return MIB.buildSelect(Ty, IsOne, LHS, Q);
5129349cc55cSDimitry Andric }
5130349cc55cSDimitry Andric 
5131349cc55cSDimitry Andric bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
5132349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
5133349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5134349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5135349cc55cSDimitry Andric   LLT DstTy = MRI.getType(Dst);
5136349cc55cSDimitry Andric   auto *RHSDef = MRI.getVRegDef(RHS);
5137349cc55cSDimitry Andric   if (!isConstantOrConstantVector(*RHSDef, MRI))
5138349cc55cSDimitry Andric     return false;
5139349cc55cSDimitry Andric 
5140349cc55cSDimitry Andric   auto &MF = *MI.getMF();
5141349cc55cSDimitry Andric   AttributeList Attr = MF.getFunction().getAttributes();
5142349cc55cSDimitry Andric   const auto &TLI = getTargetLowering();
5143349cc55cSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
5144349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
5145349cc55cSDimitry Andric   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
5146349cc55cSDimitry Andric     return false;
5147349cc55cSDimitry Andric 
5148349cc55cSDimitry Andric   // Don't do this for minsize because the instruction sequence is usually
5149349cc55cSDimitry Andric   // larger.
5150349cc55cSDimitry Andric   if (MF.getFunction().hasMinSize())
5151349cc55cSDimitry Andric     return false;
5152349cc55cSDimitry Andric 
5153349cc55cSDimitry Andric   // Don't do this if the types are not going to be legal.
5154349cc55cSDimitry Andric   if (LI) {
5155349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
5156349cc55cSDimitry Andric       return false;
5157349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
5158349cc55cSDimitry Andric       return false;
5159349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer(
5160349cc55cSDimitry Andric             {TargetOpcode::G_ICMP,
5161349cc55cSDimitry Andric              {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
5162349cc55cSDimitry Andric               DstTy}}))
5163349cc55cSDimitry Andric       return false;
5164349cc55cSDimitry Andric   }
5165349cc55cSDimitry Andric 
5166349cc55cSDimitry Andric   auto CheckEltValue = [&](const Constant *C) {
5167349cc55cSDimitry Andric     if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
5168349cc55cSDimitry Andric       return !CI->isZero();
5169349cc55cSDimitry Andric     return false;
5170349cc55cSDimitry Andric   };
5171349cc55cSDimitry Andric   return matchUnaryPredicate(MRI, RHS, CheckEltValue);
5172349cc55cSDimitry Andric }
5173349cc55cSDimitry Andric 
5174349cc55cSDimitry Andric void CombinerHelper::applyUDivByConst(MachineInstr &MI) {
5175349cc55cSDimitry Andric   auto *NewMI = buildUDivUsingMul(MI);
5176349cc55cSDimitry Andric   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
5177349cc55cSDimitry Andric }
5178349cc55cSDimitry Andric 
5179bdd1243dSDimitry Andric bool CombinerHelper::matchSDivByConst(MachineInstr &MI) {
5180bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
5181bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5182bdd1243dSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5183bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(Dst);
5184bdd1243dSDimitry Andric 
5185bdd1243dSDimitry Andric   auto &MF = *MI.getMF();
5186bdd1243dSDimitry Andric   AttributeList Attr = MF.getFunction().getAttributes();
5187bdd1243dSDimitry Andric   const auto &TLI = getTargetLowering();
5188bdd1243dSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
5189bdd1243dSDimitry Andric   auto &DL = MF.getDataLayout();
5190bdd1243dSDimitry Andric   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
5191bdd1243dSDimitry Andric     return false;
5192bdd1243dSDimitry Andric 
5193bdd1243dSDimitry Andric   // Don't do this for minsize because the instruction sequence is usually
5194bdd1243dSDimitry Andric   // larger.
5195bdd1243dSDimitry Andric   if (MF.getFunction().hasMinSize())
5196bdd1243dSDimitry Andric     return false;
5197bdd1243dSDimitry Andric 
5198bdd1243dSDimitry Andric   // If the sdiv has an 'exact' flag we can use a simpler lowering.
5199bdd1243dSDimitry Andric   if (MI.getFlag(MachineInstr::MIFlag::IsExact)) {
5200bdd1243dSDimitry Andric     return matchUnaryPredicate(
5201bdd1243dSDimitry Andric         MRI, RHS, [](const Constant *C) { return C && !C->isZeroValue(); });
5202bdd1243dSDimitry Andric   }
5203bdd1243dSDimitry Andric 
5204bdd1243dSDimitry Andric   // Don't support the general case for now.
5205bdd1243dSDimitry Andric   return false;
5206bdd1243dSDimitry Andric }
5207bdd1243dSDimitry Andric 
5208bdd1243dSDimitry Andric void CombinerHelper::applySDivByConst(MachineInstr &MI) {
5209bdd1243dSDimitry Andric   auto *NewMI = buildSDivUsingMul(MI);
5210bdd1243dSDimitry Andric   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
5211bdd1243dSDimitry Andric }
5212bdd1243dSDimitry Andric 
5213bdd1243dSDimitry Andric MachineInstr *CombinerHelper::buildSDivUsingMul(MachineInstr &MI) {
5214bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
5215bdd1243dSDimitry Andric   auto &SDiv = cast<GenericMachineInstr>(MI);
5216bdd1243dSDimitry Andric   Register Dst = SDiv.getReg(0);
5217bdd1243dSDimitry Andric   Register LHS = SDiv.getReg(1);
5218bdd1243dSDimitry Andric   Register RHS = SDiv.getReg(2);
5219bdd1243dSDimitry Andric   LLT Ty = MRI.getType(Dst);
5220bdd1243dSDimitry Andric   LLT ScalarTy = Ty.getScalarType();
5221bdd1243dSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
5222bdd1243dSDimitry Andric   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
5223bdd1243dSDimitry Andric   auto &MIB = Builder;
5224bdd1243dSDimitry Andric   MIB.setInstrAndDebugLoc(MI);
5225bdd1243dSDimitry Andric 
5226bdd1243dSDimitry Andric   bool UseSRA = false;
5227bdd1243dSDimitry Andric   SmallVector<Register, 16> Shifts, Factors;
5228bdd1243dSDimitry Andric 
5229bdd1243dSDimitry Andric   auto *RHSDef = cast<GenericMachineInstr>(getDefIgnoringCopies(RHS, MRI));
5230bdd1243dSDimitry Andric   bool IsSplat = getIConstantSplatVal(*RHSDef, MRI).has_value();
5231bdd1243dSDimitry Andric 
5232bdd1243dSDimitry Andric   auto BuildSDIVPattern = [&](const Constant *C) {
5233bdd1243dSDimitry Andric     // Don't recompute inverses for each splat element.
5234bdd1243dSDimitry Andric     if (IsSplat && !Factors.empty()) {
5235bdd1243dSDimitry Andric       Shifts.push_back(Shifts[0]);
5236bdd1243dSDimitry Andric       Factors.push_back(Factors[0]);
5237bdd1243dSDimitry Andric       return true;
5238bdd1243dSDimitry Andric     }
5239bdd1243dSDimitry Andric 
5240bdd1243dSDimitry Andric     auto *CI = cast<ConstantInt>(C);
5241bdd1243dSDimitry Andric     APInt Divisor = CI->getValue();
524206c3fb27SDimitry Andric     unsigned Shift = Divisor.countr_zero();
5243bdd1243dSDimitry Andric     if (Shift) {
5244bdd1243dSDimitry Andric       Divisor.ashrInPlace(Shift);
5245bdd1243dSDimitry Andric       UseSRA = true;
5246bdd1243dSDimitry Andric     }
5247bdd1243dSDimitry Andric 
5248bdd1243dSDimitry Andric     // Calculate the multiplicative inverse modulo BW.
5249bdd1243dSDimitry Andric     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5250bdd1243dSDimitry Andric     unsigned W = Divisor.getBitWidth();
5251bdd1243dSDimitry Andric     APInt Factor = Divisor.zext(W + 1)
5252bdd1243dSDimitry Andric                        .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5253bdd1243dSDimitry Andric                        .trunc(W);
5254bdd1243dSDimitry Andric     Shifts.push_back(MIB.buildConstant(ScalarShiftAmtTy, Shift).getReg(0));
5255bdd1243dSDimitry Andric     Factors.push_back(MIB.buildConstant(ScalarTy, Factor).getReg(0));
5256bdd1243dSDimitry Andric     return true;
5257bdd1243dSDimitry Andric   };
5258bdd1243dSDimitry Andric 
5259bdd1243dSDimitry Andric   // Collect all magic values from the build vector.
5260bdd1243dSDimitry Andric   bool Matched = matchUnaryPredicate(MRI, RHS, BuildSDIVPattern);
5261bdd1243dSDimitry Andric   (void)Matched;
5262bdd1243dSDimitry Andric   assert(Matched && "Expected unary predicate match to succeed");
5263bdd1243dSDimitry Andric 
5264bdd1243dSDimitry Andric   Register Shift, Factor;
5265bdd1243dSDimitry Andric   if (Ty.isVector()) {
5266bdd1243dSDimitry Andric     Shift = MIB.buildBuildVector(ShiftAmtTy, Shifts).getReg(0);
5267bdd1243dSDimitry Andric     Factor = MIB.buildBuildVector(Ty, Factors).getReg(0);
5268bdd1243dSDimitry Andric   } else {
5269bdd1243dSDimitry Andric     Shift = Shifts[0];
5270bdd1243dSDimitry Andric     Factor = Factors[0];
5271bdd1243dSDimitry Andric   }
5272bdd1243dSDimitry Andric 
5273bdd1243dSDimitry Andric   Register Res = LHS;
5274bdd1243dSDimitry Andric 
5275bdd1243dSDimitry Andric   if (UseSRA)
5276bdd1243dSDimitry Andric     Res = MIB.buildAShr(Ty, Res, Shift, MachineInstr::IsExact).getReg(0);
5277bdd1243dSDimitry Andric 
5278bdd1243dSDimitry Andric   return MIB.buildMul(Ty, Res, Factor);
5279bdd1243dSDimitry Andric }
5280bdd1243dSDimitry Andric 
5281349cc55cSDimitry Andric bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) {
5282349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UMULH);
5283349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5284349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5285349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
5286349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
5287349cc55cSDimitry Andric   auto MatchPow2ExceptOne = [&](const Constant *C) {
5288349cc55cSDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(C))
5289349cc55cSDimitry Andric       return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
5290349cc55cSDimitry Andric     return false;
5291349cc55cSDimitry Andric   };
5292349cc55cSDimitry Andric   if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
5293349cc55cSDimitry Andric     return false;
5294349cc55cSDimitry Andric   return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}});
5295349cc55cSDimitry Andric }
5296349cc55cSDimitry Andric 
5297349cc55cSDimitry Andric void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) {
5298349cc55cSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5299349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5300349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5301349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
5302349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
5303349cc55cSDimitry Andric   unsigned NumEltBits = Ty.getScalarSizeInBits();
5304349cc55cSDimitry Andric 
5305349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
5306349cc55cSDimitry Andric   auto LogBase2 = buildLogBase2(RHS, Builder);
5307349cc55cSDimitry Andric   auto ShiftAmt =
5308349cc55cSDimitry Andric       Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
5309349cc55cSDimitry Andric   auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
5310349cc55cSDimitry Andric   Builder.buildLShr(Dst, LHS, Trunc);
5311349cc55cSDimitry Andric   MI.eraseFromParent();
5312349cc55cSDimitry Andric }
5313349cc55cSDimitry Andric 
5314349cc55cSDimitry Andric bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI,
5315349cc55cSDimitry Andric                                                BuildFnTy &MatchInfo) {
5316349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
5317349cc55cSDimitry Andric   assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB ||
5318349cc55cSDimitry Andric          Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
5319349cc55cSDimitry Andric          Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA);
5320349cc55cSDimitry Andric 
5321349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5322349cc55cSDimitry Andric   Register X = MI.getOperand(1).getReg();
5323349cc55cSDimitry Andric   Register Y = MI.getOperand(2).getReg();
5324349cc55cSDimitry Andric   LLT Type = MRI.getType(Dst);
5325349cc55cSDimitry Andric 
5326349cc55cSDimitry Andric   // fold (fadd x, fneg(y)) -> (fsub x, y)
5327349cc55cSDimitry Andric   // fold (fadd fneg(y), x) -> (fsub x, y)
5328349cc55cSDimitry Andric   // G_ADD is commutative so both cases are checked by m_GFAdd
5329349cc55cSDimitry Andric   if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
5330349cc55cSDimitry Andric       isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) {
5331349cc55cSDimitry Andric     Opc = TargetOpcode::G_FSUB;
5332349cc55cSDimitry Andric   }
5333349cc55cSDimitry Andric   /// fold (fsub x, fneg(y)) -> (fadd x, y)
5334349cc55cSDimitry Andric   else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
5335349cc55cSDimitry Andric            isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) {
5336349cc55cSDimitry Andric     Opc = TargetOpcode::G_FADD;
5337349cc55cSDimitry Andric   }
5338349cc55cSDimitry Andric   // fold (fmul fneg(x), fneg(y)) -> (fmul x, y)
5339349cc55cSDimitry Andric   // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y)
5340349cc55cSDimitry Andric   // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z)
5341349cc55cSDimitry Andric   // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z)
5342349cc55cSDimitry Andric   else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
5343349cc55cSDimitry Andric             Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) &&
5344349cc55cSDimitry Andric            mi_match(X, MRI, m_GFNeg(m_Reg(X))) &&
5345349cc55cSDimitry Andric            mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) {
5346349cc55cSDimitry Andric     // no opcode change
5347349cc55cSDimitry Andric   } else
5348349cc55cSDimitry Andric     return false;
5349349cc55cSDimitry Andric 
5350349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
5351349cc55cSDimitry Andric     Observer.changingInstr(MI);
5352349cc55cSDimitry Andric     MI.setDesc(B.getTII().get(Opc));
5353349cc55cSDimitry Andric     MI.getOperand(1).setReg(X);
5354349cc55cSDimitry Andric     MI.getOperand(2).setReg(Y);
5355349cc55cSDimitry Andric     Observer.changedInstr(MI);
5356349cc55cSDimitry Andric   };
5357349cc55cSDimitry Andric   return true;
5358349cc55cSDimitry Andric }
5359349cc55cSDimitry Andric 
5360bdd1243dSDimitry Andric bool CombinerHelper::matchFsubToFneg(MachineInstr &MI, Register &MatchInfo) {
5361bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5362bdd1243dSDimitry Andric 
5363bdd1243dSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5364bdd1243dSDimitry Andric   MatchInfo = MI.getOperand(2).getReg();
5365bdd1243dSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
5366bdd1243dSDimitry Andric 
5367bdd1243dSDimitry Andric   const auto LHSCst = Ty.isVector()
5368bdd1243dSDimitry Andric                           ? getFConstantSplat(LHS, MRI, /* allowUndef */ true)
5369bdd1243dSDimitry Andric                           : getFConstantVRegValWithLookThrough(LHS, MRI);
5370bdd1243dSDimitry Andric   if (!LHSCst)
5371bdd1243dSDimitry Andric     return false;
5372bdd1243dSDimitry Andric 
5373bdd1243dSDimitry Andric   // -0.0 is always allowed
5374bdd1243dSDimitry Andric   if (LHSCst->Value.isNegZero())
5375bdd1243dSDimitry Andric     return true;
5376bdd1243dSDimitry Andric 
5377bdd1243dSDimitry Andric   // +0.0 is only allowed if nsz is set.
5378bdd1243dSDimitry Andric   if (LHSCst->Value.isPosZero())
5379bdd1243dSDimitry Andric     return MI.getFlag(MachineInstr::FmNsz);
5380bdd1243dSDimitry Andric 
5381bdd1243dSDimitry Andric   return false;
5382bdd1243dSDimitry Andric }
5383bdd1243dSDimitry Andric 
5384bdd1243dSDimitry Andric void CombinerHelper::applyFsubToFneg(MachineInstr &MI, Register &MatchInfo) {
5385bdd1243dSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
5386bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5387bdd1243dSDimitry Andric   Builder.buildFNeg(
5388bdd1243dSDimitry Andric       Dst, Builder.buildFCanonicalize(MRI.getType(Dst), MatchInfo).getReg(0));
5389bdd1243dSDimitry Andric   eraseInst(MI);
5390bdd1243dSDimitry Andric }
5391bdd1243dSDimitry Andric 
53924824e7fdSDimitry Andric /// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
53934824e7fdSDimitry Andric /// due to global flags or MachineInstr flags.
53944824e7fdSDimitry Andric static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
53954824e7fdSDimitry Andric   if (MI.getOpcode() != TargetOpcode::G_FMUL)
53964824e7fdSDimitry Andric     return false;
53974824e7fdSDimitry Andric   return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
53984824e7fdSDimitry Andric }
53994824e7fdSDimitry Andric 
54004824e7fdSDimitry Andric static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
54014824e7fdSDimitry Andric                         const MachineRegisterInfo &MRI) {
54024824e7fdSDimitry Andric   return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
54034824e7fdSDimitry Andric                        MRI.use_instr_nodbg_end()) >
54044824e7fdSDimitry Andric          std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
54054824e7fdSDimitry Andric                        MRI.use_instr_nodbg_end());
54064824e7fdSDimitry Andric }
54074824e7fdSDimitry Andric 
54084824e7fdSDimitry Andric bool CombinerHelper::canCombineFMadOrFMA(MachineInstr &MI,
54094824e7fdSDimitry Andric                                          bool &AllowFusionGlobally,
54104824e7fdSDimitry Andric                                          bool &HasFMAD, bool &Aggressive,
54114824e7fdSDimitry Andric                                          bool CanReassociate) {
54124824e7fdSDimitry Andric 
54134824e7fdSDimitry Andric   auto *MF = MI.getMF();
54144824e7fdSDimitry Andric   const auto &TLI = *MF->getSubtarget().getTargetLowering();
54154824e7fdSDimitry Andric   const TargetOptions &Options = MF->getTarget().Options;
54164824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
54174824e7fdSDimitry Andric 
54184824e7fdSDimitry Andric   if (CanReassociate &&
54194824e7fdSDimitry Andric       !(Options.UnsafeFPMath || MI.getFlag(MachineInstr::MIFlag::FmReassoc)))
54204824e7fdSDimitry Andric     return false;
54214824e7fdSDimitry Andric 
54224824e7fdSDimitry Andric   // Floating-point multiply-add with intermediate rounding.
5423bdd1243dSDimitry Andric   HasFMAD = (!isPreLegalize() && TLI.isFMADLegal(MI, DstType));
54244824e7fdSDimitry Andric   // Floating-point multiply-add without intermediate rounding.
54254824e7fdSDimitry Andric   bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
54264824e7fdSDimitry Andric                 isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
54274824e7fdSDimitry Andric   // No valid opcode, do not combine.
54284824e7fdSDimitry Andric   if (!HasFMAD && !HasFMA)
54294824e7fdSDimitry Andric     return false;
54304824e7fdSDimitry Andric 
54314824e7fdSDimitry Andric   AllowFusionGlobally = Options.AllowFPOpFusion == FPOpFusion::Fast ||
54324824e7fdSDimitry Andric                         Options.UnsafeFPMath || HasFMAD;
54334824e7fdSDimitry Andric   // If the addition is not contractable, do not combine.
54344824e7fdSDimitry Andric   if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
54354824e7fdSDimitry Andric     return false;
54364824e7fdSDimitry Andric 
54374824e7fdSDimitry Andric   Aggressive = TLI.enableAggressiveFMAFusion(DstType);
54384824e7fdSDimitry Andric   return true;
54394824e7fdSDimitry Andric }
54404824e7fdSDimitry Andric 
54414824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFMulToFMadOrFMA(
54424824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
54434824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
54444824e7fdSDimitry Andric 
54454824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
54464824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
54474824e7fdSDimitry Andric     return false;
54484824e7fdSDimitry Andric 
544904eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
545004eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
545104eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
545204eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
54534824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
54544824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
54554824e7fdSDimitry Andric 
54564824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
54574824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
545804eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
545904eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
546004eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
54614824e7fdSDimitry Andric       std::swap(LHS, RHS);
54624824e7fdSDimitry Andric   }
54634824e7fdSDimitry Andric 
54644824e7fdSDimitry Andric   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
546504eeddc0SDimitry Andric   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
546604eeddc0SDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
54674824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
54684824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
546904eeddc0SDimitry Andric                    {LHS.MI->getOperand(1).getReg(),
547004eeddc0SDimitry Andric                     LHS.MI->getOperand(2).getReg(), RHS.Reg});
54714824e7fdSDimitry Andric     };
54724824e7fdSDimitry Andric     return true;
54734824e7fdSDimitry Andric   }
54744824e7fdSDimitry Andric 
54754824e7fdSDimitry Andric   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
547604eeddc0SDimitry Andric   if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
547704eeddc0SDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
54784824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
54794824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
548004eeddc0SDimitry Andric                    {RHS.MI->getOperand(1).getReg(),
548104eeddc0SDimitry Andric                     RHS.MI->getOperand(2).getReg(), LHS.Reg});
54824824e7fdSDimitry Andric     };
54834824e7fdSDimitry Andric     return true;
54844824e7fdSDimitry Andric   }
54854824e7fdSDimitry Andric 
54864824e7fdSDimitry Andric   return false;
54874824e7fdSDimitry Andric }
54884824e7fdSDimitry Andric 
54894824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA(
54904824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
54914824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
54924824e7fdSDimitry Andric 
54934824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
54944824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
54954824e7fdSDimitry Andric     return false;
54964824e7fdSDimitry Andric 
54974824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
549804eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
549904eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
550004eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
550104eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
55024824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
55034824e7fdSDimitry Andric 
55044824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
55054824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
55064824e7fdSDimitry Andric 
55074824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
55084824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
550904eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
551004eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
551104eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
55124824e7fdSDimitry Andric       std::swap(LHS, RHS);
55134824e7fdSDimitry Andric   }
55144824e7fdSDimitry Andric 
55154824e7fdSDimitry Andric   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
55164824e7fdSDimitry Andric   MachineInstr *FpExtSrc;
551704eeddc0SDimitry Andric   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
55184824e7fdSDimitry Andric       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
55194824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
55204824e7fdSDimitry Andric                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
55214824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55224824e7fdSDimitry Andric       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
55234824e7fdSDimitry Andric       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
552404eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
552504eeddc0SDimitry Andric                    {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg});
55264824e7fdSDimitry Andric     };
55274824e7fdSDimitry Andric     return true;
55284824e7fdSDimitry Andric   }
55294824e7fdSDimitry Andric 
55304824e7fdSDimitry Andric   // fold (fadd z, (fpext (fmul x, y))) -> (fma (fpext x), (fpext y), z)
55314824e7fdSDimitry Andric   // Note: Commutes FADD operands.
553204eeddc0SDimitry Andric   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
55334824e7fdSDimitry Andric       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
55344824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
55354824e7fdSDimitry Andric                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
55364824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55374824e7fdSDimitry Andric       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
55384824e7fdSDimitry Andric       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
553904eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
554004eeddc0SDimitry Andric                    {FpExtX.getReg(0), FpExtY.getReg(0), LHS.Reg});
55414824e7fdSDimitry Andric     };
55424824e7fdSDimitry Andric     return true;
55434824e7fdSDimitry Andric   }
55444824e7fdSDimitry Andric 
55454824e7fdSDimitry Andric   return false;
55464824e7fdSDimitry Andric }
55474824e7fdSDimitry Andric 
55484824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA(
55494824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
55504824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
55514824e7fdSDimitry Andric 
55524824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
55534824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
55544824e7fdSDimitry Andric     return false;
55554824e7fdSDimitry Andric 
555604eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
555704eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
555804eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
555904eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
55604824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
55614824e7fdSDimitry Andric 
55624824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
55634824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
55644824e7fdSDimitry Andric 
55654824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
55664824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
556704eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
556804eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
556904eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
55704824e7fdSDimitry Andric       std::swap(LHS, RHS);
55714824e7fdSDimitry Andric   }
55724824e7fdSDimitry Andric 
55734824e7fdSDimitry Andric   MachineInstr *FMA = nullptr;
55744824e7fdSDimitry Andric   Register Z;
55754824e7fdSDimitry Andric   // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
557604eeddc0SDimitry Andric   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
557704eeddc0SDimitry Andric       (MRI.getVRegDef(LHS.MI->getOperand(3).getReg())->getOpcode() ==
55784824e7fdSDimitry Andric        TargetOpcode::G_FMUL) &&
557904eeddc0SDimitry Andric       MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
558004eeddc0SDimitry Andric       MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
558104eeddc0SDimitry Andric     FMA = LHS.MI;
558204eeddc0SDimitry Andric     Z = RHS.Reg;
55834824e7fdSDimitry Andric   }
55844824e7fdSDimitry Andric   // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
558504eeddc0SDimitry Andric   else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
558604eeddc0SDimitry Andric            (MRI.getVRegDef(RHS.MI->getOperand(3).getReg())->getOpcode() ==
55874824e7fdSDimitry Andric             TargetOpcode::G_FMUL) &&
558804eeddc0SDimitry Andric            MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
558904eeddc0SDimitry Andric            MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
559004eeddc0SDimitry Andric     Z = LHS.Reg;
559104eeddc0SDimitry Andric     FMA = RHS.MI;
55924824e7fdSDimitry Andric   }
55934824e7fdSDimitry Andric 
55944824e7fdSDimitry Andric   if (FMA) {
55954824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMA->getOperand(3).getReg());
55964824e7fdSDimitry Andric     Register X = FMA->getOperand(1).getReg();
55974824e7fdSDimitry Andric     Register Y = FMA->getOperand(2).getReg();
55984824e7fdSDimitry Andric     Register U = FMulMI->getOperand(1).getReg();
55994824e7fdSDimitry Andric     Register V = FMulMI->getOperand(2).getReg();
56004824e7fdSDimitry Andric 
56014824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
56024824e7fdSDimitry Andric       Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
56034824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z});
56044824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
56054824e7fdSDimitry Andric                    {X, Y, InnerFMA});
56064824e7fdSDimitry Andric     };
56074824e7fdSDimitry Andric     return true;
56084824e7fdSDimitry Andric   }
56094824e7fdSDimitry Andric 
56104824e7fdSDimitry Andric   return false;
56114824e7fdSDimitry Andric }
56124824e7fdSDimitry Andric 
56134824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
56144824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
56154824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
56164824e7fdSDimitry Andric 
56174824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
56184824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
56194824e7fdSDimitry Andric     return false;
56204824e7fdSDimitry Andric 
56214824e7fdSDimitry Andric   if (!Aggressive)
56224824e7fdSDimitry Andric     return false;
56234824e7fdSDimitry Andric 
56244824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
56254824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
562604eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
562704eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
562804eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
562904eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
56304824e7fdSDimitry Andric 
56314824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
56324824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
56334824e7fdSDimitry Andric 
56344824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
56354824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
563604eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
563704eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
563804eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
56394824e7fdSDimitry Andric       std::swap(LHS, RHS);
56404824e7fdSDimitry Andric   }
56414824e7fdSDimitry Andric 
56424824e7fdSDimitry Andric   // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
56434824e7fdSDimitry Andric   auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
56444824e7fdSDimitry Andric                                  Register Y, MachineIRBuilder &B) {
56454824e7fdSDimitry Andric     Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
56464824e7fdSDimitry Andric     Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
56474824e7fdSDimitry Andric     Register InnerFMA =
56484824e7fdSDimitry Andric         B.buildInstr(PreferredFusedOpcode, {DstType}, {FpExtU, FpExtV, Z})
56494824e7fdSDimitry Andric             .getReg(0);
56504824e7fdSDimitry Andric     B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
56514824e7fdSDimitry Andric                  {X, Y, InnerFMA});
56524824e7fdSDimitry Andric   };
56534824e7fdSDimitry Andric 
56544824e7fdSDimitry Andric   MachineInstr *FMulMI, *FMAMI;
56554824e7fdSDimitry Andric   // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
56564824e7fdSDimitry Andric   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
565704eeddc0SDimitry Andric   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
565804eeddc0SDimitry Andric       mi_match(LHS.MI->getOperand(3).getReg(), MRI,
565904eeddc0SDimitry Andric                m_GFPExt(m_MInstr(FMulMI))) &&
56604824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
56614824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
56624824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
56634824e7fdSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
56644824e7fdSDimitry Andric       buildMatchInfo(FMulMI->getOperand(1).getReg(),
566504eeddc0SDimitry Andric                      FMulMI->getOperand(2).getReg(), RHS.Reg,
566604eeddc0SDimitry Andric                      LHS.MI->getOperand(1).getReg(),
566704eeddc0SDimitry Andric                      LHS.MI->getOperand(2).getReg(), B);
56684824e7fdSDimitry Andric     };
56694824e7fdSDimitry Andric     return true;
56704824e7fdSDimitry Andric   }
56714824e7fdSDimitry Andric 
56724824e7fdSDimitry Andric   // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
56734824e7fdSDimitry Andric   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
56744824e7fdSDimitry Andric   // FIXME: This turns two single-precision and one double-precision
56754824e7fdSDimitry Andric   // operation into two double-precision operations, which might not be
56764824e7fdSDimitry Andric   // interesting for all targets, especially GPUs.
567704eeddc0SDimitry Andric   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
56784824e7fdSDimitry Andric       FMAMI->getOpcode() == PreferredFusedOpcode) {
56794824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
56804824e7fdSDimitry Andric     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
56814824e7fdSDimitry Andric         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
56824824e7fdSDimitry Andric                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
56834824e7fdSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
56844824e7fdSDimitry Andric         Register X = FMAMI->getOperand(1).getReg();
56854824e7fdSDimitry Andric         Register Y = FMAMI->getOperand(2).getReg();
56864824e7fdSDimitry Andric         X = B.buildFPExt(DstType, X).getReg(0);
56874824e7fdSDimitry Andric         Y = B.buildFPExt(DstType, Y).getReg(0);
56884824e7fdSDimitry Andric         buildMatchInfo(FMulMI->getOperand(1).getReg(),
568904eeddc0SDimitry Andric                        FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y, B);
56904824e7fdSDimitry Andric       };
56914824e7fdSDimitry Andric 
56924824e7fdSDimitry Andric       return true;
56934824e7fdSDimitry Andric     }
56944824e7fdSDimitry Andric   }
56954824e7fdSDimitry Andric 
56964824e7fdSDimitry Andric   // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
56974824e7fdSDimitry Andric   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
569804eeddc0SDimitry Andric   if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
569904eeddc0SDimitry Andric       mi_match(RHS.MI->getOperand(3).getReg(), MRI,
570004eeddc0SDimitry Andric                m_GFPExt(m_MInstr(FMulMI))) &&
57014824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
57024824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
57034824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
57044824e7fdSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
57054824e7fdSDimitry Andric       buildMatchInfo(FMulMI->getOperand(1).getReg(),
570604eeddc0SDimitry Andric                      FMulMI->getOperand(2).getReg(), LHS.Reg,
570704eeddc0SDimitry Andric                      RHS.MI->getOperand(1).getReg(),
570804eeddc0SDimitry Andric                      RHS.MI->getOperand(2).getReg(), B);
57094824e7fdSDimitry Andric     };
57104824e7fdSDimitry Andric     return true;
57114824e7fdSDimitry Andric   }
57124824e7fdSDimitry Andric 
57134824e7fdSDimitry Andric   // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
57144824e7fdSDimitry Andric   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
57154824e7fdSDimitry Andric   // FIXME: This turns two single-precision and one double-precision
57164824e7fdSDimitry Andric   // operation into two double-precision operations, which might not be
57174824e7fdSDimitry Andric   // interesting for all targets, especially GPUs.
571804eeddc0SDimitry Andric   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
57194824e7fdSDimitry Andric       FMAMI->getOpcode() == PreferredFusedOpcode) {
57204824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
57214824e7fdSDimitry Andric     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
57224824e7fdSDimitry Andric         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
57234824e7fdSDimitry Andric                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
57244824e7fdSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
57254824e7fdSDimitry Andric         Register X = FMAMI->getOperand(1).getReg();
57264824e7fdSDimitry Andric         Register Y = FMAMI->getOperand(2).getReg();
57274824e7fdSDimitry Andric         X = B.buildFPExt(DstType, X).getReg(0);
57284824e7fdSDimitry Andric         Y = B.buildFPExt(DstType, Y).getReg(0);
57294824e7fdSDimitry Andric         buildMatchInfo(FMulMI->getOperand(1).getReg(),
573004eeddc0SDimitry Andric                        FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y, B);
57314824e7fdSDimitry Andric       };
57324824e7fdSDimitry Andric       return true;
57334824e7fdSDimitry Andric     }
57344824e7fdSDimitry Andric   }
57354824e7fdSDimitry Andric 
57364824e7fdSDimitry Andric   return false;
57374824e7fdSDimitry Andric }
57384824e7fdSDimitry Andric 
57394824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFMulToFMadOrFMA(
57404824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
57414824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
57424824e7fdSDimitry Andric 
57434824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
57444824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
57454824e7fdSDimitry Andric     return false;
57464824e7fdSDimitry Andric 
574704eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
574804eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
574904eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
575004eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
57514824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
57524824e7fdSDimitry Andric 
57534824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
57544824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
57554824e7fdSDimitry Andric   int FirstMulHasFewerUses = true;
575604eeddc0SDimitry Andric   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
575704eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
575804eeddc0SDimitry Andric       hasMoreUses(*LHS.MI, *RHS.MI, MRI))
57594824e7fdSDimitry Andric     FirstMulHasFewerUses = false;
57604824e7fdSDimitry Andric 
57614824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
57624824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
57634824e7fdSDimitry Andric 
57644824e7fdSDimitry Andric   // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
57654824e7fdSDimitry Andric   if (FirstMulHasFewerUses &&
576604eeddc0SDimitry Andric       (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
576704eeddc0SDimitry Andric        (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
57684824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
576904eeddc0SDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
577004eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
577104eeddc0SDimitry Andric                    {LHS.MI->getOperand(1).getReg(),
577204eeddc0SDimitry Andric                     LHS.MI->getOperand(2).getReg(), NegZ});
57734824e7fdSDimitry Andric     };
57744824e7fdSDimitry Andric     return true;
57754824e7fdSDimitry Andric   }
57764824e7fdSDimitry Andric   // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
577704eeddc0SDimitry Andric   else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
577804eeddc0SDimitry Andric             (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
57794824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
578004eeddc0SDimitry Andric       Register NegY =
578104eeddc0SDimitry Andric           B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
578204eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
578304eeddc0SDimitry Andric                    {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg});
57844824e7fdSDimitry Andric     };
57854824e7fdSDimitry Andric     return true;
57864824e7fdSDimitry Andric   }
57874824e7fdSDimitry Andric 
57884824e7fdSDimitry Andric   return false;
57894824e7fdSDimitry Andric }
57904824e7fdSDimitry Andric 
57914824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFNegFMulToFMadOrFMA(
57924824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
57934824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
57944824e7fdSDimitry Andric 
57954824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
57964824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
57974824e7fdSDimitry Andric     return false;
57984824e7fdSDimitry Andric 
57994824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
58004824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
58014824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
58024824e7fdSDimitry Andric 
58034824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
58044824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
58054824e7fdSDimitry Andric 
58064824e7fdSDimitry Andric   MachineInstr *FMulMI;
58074824e7fdSDimitry Andric   // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
58084824e7fdSDimitry Andric   if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
58094824e7fdSDimitry Andric       (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
58104824e7fdSDimitry Andric                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
58114824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
58124824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
58134824e7fdSDimitry Andric       Register NegX =
58144824e7fdSDimitry Andric           B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
58154824e7fdSDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
58164824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
58174824e7fdSDimitry Andric                    {NegX, FMulMI->getOperand(2).getReg(), NegZ});
58184824e7fdSDimitry Andric     };
58194824e7fdSDimitry Andric     return true;
58204824e7fdSDimitry Andric   }
58214824e7fdSDimitry Andric 
58224824e7fdSDimitry Andric   // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
58234824e7fdSDimitry Andric   if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
58244824e7fdSDimitry Andric       (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
58254824e7fdSDimitry Andric                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
58264824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
58274824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
58284824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
58294824e7fdSDimitry Andric                    {FMulMI->getOperand(1).getReg(),
58304824e7fdSDimitry Andric                     FMulMI->getOperand(2).getReg(), LHSReg});
58314824e7fdSDimitry Andric     };
58324824e7fdSDimitry Andric     return true;
58334824e7fdSDimitry Andric   }
58344824e7fdSDimitry Andric 
58354824e7fdSDimitry Andric   return false;
58364824e7fdSDimitry Andric }
58374824e7fdSDimitry Andric 
58384824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFpExtFMulToFMadOrFMA(
58394824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
58404824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
58414824e7fdSDimitry Andric 
58424824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
58434824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
58444824e7fdSDimitry Andric     return false;
58454824e7fdSDimitry Andric 
58464824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
58474824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
58484824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
58494824e7fdSDimitry Andric 
58504824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
58514824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
58524824e7fdSDimitry Andric 
58534824e7fdSDimitry Andric   MachineInstr *FMulMI;
58544824e7fdSDimitry Andric   // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
58554824e7fdSDimitry Andric   if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
58564824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
58574824e7fdSDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
58584824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
58594824e7fdSDimitry Andric       Register FpExtX =
58604824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
58614824e7fdSDimitry Andric       Register FpExtY =
58624824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
58634824e7fdSDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
58644824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
58654824e7fdSDimitry Andric                    {FpExtX, FpExtY, NegZ});
58664824e7fdSDimitry Andric     };
58674824e7fdSDimitry Andric     return true;
58684824e7fdSDimitry Andric   }
58694824e7fdSDimitry Andric 
58704824e7fdSDimitry Andric   // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
58714824e7fdSDimitry Andric   if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
58724824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
58734824e7fdSDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
58744824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
58754824e7fdSDimitry Andric       Register FpExtY =
58764824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
58774824e7fdSDimitry Andric       Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
58784824e7fdSDimitry Andric       Register FpExtZ =
58794824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
58804824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
58814824e7fdSDimitry Andric                    {NegY, FpExtZ, LHSReg});
58824824e7fdSDimitry Andric     };
58834824e7fdSDimitry Andric     return true;
58844824e7fdSDimitry Andric   }
58854824e7fdSDimitry Andric 
58864824e7fdSDimitry Andric   return false;
58874824e7fdSDimitry Andric }
58884824e7fdSDimitry Andric 
58894824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFpExtFNegFMulToFMadOrFMA(
58904824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
58914824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
58924824e7fdSDimitry Andric 
58934824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
58944824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
58954824e7fdSDimitry Andric     return false;
58964824e7fdSDimitry Andric 
58974824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
58984824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
58994824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
59004824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
59014824e7fdSDimitry Andric 
59024824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
59034824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
59044824e7fdSDimitry Andric 
59054824e7fdSDimitry Andric   auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
59064824e7fdSDimitry Andric                             MachineIRBuilder &B) {
59074824e7fdSDimitry Andric     Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
59084824e7fdSDimitry Andric     Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
59094824e7fdSDimitry Andric     B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z});
59104824e7fdSDimitry Andric   };
59114824e7fdSDimitry Andric 
59124824e7fdSDimitry Andric   MachineInstr *FMulMI;
59134824e7fdSDimitry Andric   // fold (fsub (fpext (fneg (fmul x, y))), z) ->
59144824e7fdSDimitry Andric   //      (fneg (fma (fpext x), (fpext y), z))
59154824e7fdSDimitry Andric   // fold (fsub (fneg (fpext (fmul x, y))), z) ->
59164824e7fdSDimitry Andric   //      (fneg (fma (fpext x), (fpext y), z))
59174824e7fdSDimitry Andric   if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
59184824e7fdSDimitry Andric        mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
59194824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
59204824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
59214824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
59224824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
59234824e7fdSDimitry Andric       Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
59244824e7fdSDimitry Andric       buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
59254824e7fdSDimitry Andric                      FMulMI->getOperand(2).getReg(), RHSReg, B);
59264824e7fdSDimitry Andric       B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
59274824e7fdSDimitry Andric     };
59284824e7fdSDimitry Andric     return true;
59294824e7fdSDimitry Andric   }
59304824e7fdSDimitry Andric 
59314824e7fdSDimitry Andric   // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
59324824e7fdSDimitry Andric   // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
59334824e7fdSDimitry Andric   if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
59344824e7fdSDimitry Andric        mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
59354824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
59364824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
59374824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
59384824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
59394824e7fdSDimitry Andric       buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
59404824e7fdSDimitry Andric                      FMulMI->getOperand(2).getReg(), LHSReg, B);
59414824e7fdSDimitry Andric     };
59424824e7fdSDimitry Andric     return true;
59434824e7fdSDimitry Andric   }
59444824e7fdSDimitry Andric 
59454824e7fdSDimitry Andric   return false;
59464824e7fdSDimitry Andric }
59474824e7fdSDimitry Andric 
594881ad6265SDimitry Andric bool CombinerHelper::matchCombineFMinMaxNaN(MachineInstr &MI,
594981ad6265SDimitry Andric                                             unsigned &IdxToPropagate) {
595081ad6265SDimitry Andric   bool PropagateNaN;
595181ad6265SDimitry Andric   switch (MI.getOpcode()) {
595281ad6265SDimitry Andric   default:
595381ad6265SDimitry Andric     return false;
595481ad6265SDimitry Andric   case TargetOpcode::G_FMINNUM:
595581ad6265SDimitry Andric   case TargetOpcode::G_FMAXNUM:
595681ad6265SDimitry Andric     PropagateNaN = false;
595781ad6265SDimitry Andric     break;
595881ad6265SDimitry Andric   case TargetOpcode::G_FMINIMUM:
595981ad6265SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
596081ad6265SDimitry Andric     PropagateNaN = true;
596181ad6265SDimitry Andric     break;
596281ad6265SDimitry Andric   }
596381ad6265SDimitry Andric 
596481ad6265SDimitry Andric   auto MatchNaN = [&](unsigned Idx) {
596581ad6265SDimitry Andric     Register MaybeNaNReg = MI.getOperand(Idx).getReg();
596681ad6265SDimitry Andric     const ConstantFP *MaybeCst = getConstantFPVRegVal(MaybeNaNReg, MRI);
596781ad6265SDimitry Andric     if (!MaybeCst || !MaybeCst->getValueAPF().isNaN())
596881ad6265SDimitry Andric       return false;
596981ad6265SDimitry Andric     IdxToPropagate = PropagateNaN ? Idx : (Idx == 1 ? 2 : 1);
597081ad6265SDimitry Andric     return true;
597181ad6265SDimitry Andric   };
597281ad6265SDimitry Andric 
597381ad6265SDimitry Andric   return MatchNaN(1) || MatchNaN(2);
597481ad6265SDimitry Andric }
597581ad6265SDimitry Andric 
597681ad6265SDimitry Andric bool CombinerHelper::matchAddSubSameReg(MachineInstr &MI, Register &Src) {
597781ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ADD && "Expected a G_ADD");
597881ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
597981ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
598081ad6265SDimitry Andric 
598181ad6265SDimitry Andric   // Helper lambda to check for opportunities for
598281ad6265SDimitry Andric   // A + (B - A) -> B
598381ad6265SDimitry Andric   // (B - A) + A -> B
598481ad6265SDimitry Andric   auto CheckFold = [&](Register MaybeSub, Register MaybeSameReg) {
598581ad6265SDimitry Andric     Register Reg;
598681ad6265SDimitry Andric     return mi_match(MaybeSub, MRI, m_GSub(m_Reg(Src), m_Reg(Reg))) &&
598781ad6265SDimitry Andric            Reg == MaybeSameReg;
598881ad6265SDimitry Andric   };
598981ad6265SDimitry Andric   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
599081ad6265SDimitry Andric }
599181ad6265SDimitry Andric 
5992bdd1243dSDimitry Andric bool CombinerHelper::matchBuildVectorIdentityFold(MachineInstr &MI,
5993bdd1243dSDimitry Andric                                                   Register &MatchInfo) {
5994bdd1243dSDimitry Andric   // This combine folds the following patterns:
5995bdd1243dSDimitry Andric   //
5996bdd1243dSDimitry Andric   //  G_BUILD_VECTOR_TRUNC (G_BITCAST(x), G_LSHR(G_BITCAST(x), k))
5997bdd1243dSDimitry Andric   //  G_BUILD_VECTOR(G_TRUNC(G_BITCAST(x)), G_TRUNC(G_LSHR(G_BITCAST(x), k)))
5998bdd1243dSDimitry Andric   //    into
5999bdd1243dSDimitry Andric   //      x
6000bdd1243dSDimitry Andric   //    if
6001bdd1243dSDimitry Andric   //      k == sizeof(VecEltTy)/2
6002bdd1243dSDimitry Andric   //      type(x) == type(dst)
6003bdd1243dSDimitry Andric   //
6004bdd1243dSDimitry Andric   //  G_BUILD_VECTOR(G_TRUNC(G_BITCAST(x)), undef)
6005bdd1243dSDimitry Andric   //    into
6006bdd1243dSDimitry Andric   //      x
6007bdd1243dSDimitry Andric   //    if
6008bdd1243dSDimitry Andric   //      type(x) == type(dst)
6009bdd1243dSDimitry Andric 
6010bdd1243dSDimitry Andric   LLT DstVecTy = MRI.getType(MI.getOperand(0).getReg());
6011bdd1243dSDimitry Andric   LLT DstEltTy = DstVecTy.getElementType();
6012bdd1243dSDimitry Andric 
6013bdd1243dSDimitry Andric   Register Lo, Hi;
6014bdd1243dSDimitry Andric 
6015bdd1243dSDimitry Andric   if (mi_match(
6016bdd1243dSDimitry Andric           MI, MRI,
6017bdd1243dSDimitry Andric           m_GBuildVector(m_GTrunc(m_GBitcast(m_Reg(Lo))), m_GImplicitDef()))) {
6018bdd1243dSDimitry Andric     MatchInfo = Lo;
6019bdd1243dSDimitry Andric     return MRI.getType(MatchInfo) == DstVecTy;
6020bdd1243dSDimitry Andric   }
6021bdd1243dSDimitry Andric 
6022bdd1243dSDimitry Andric   std::optional<ValueAndVReg> ShiftAmount;
6023bdd1243dSDimitry Andric   const auto LoPattern = m_GBitcast(m_Reg(Lo));
6024bdd1243dSDimitry Andric   const auto HiPattern = m_GLShr(m_GBitcast(m_Reg(Hi)), m_GCst(ShiftAmount));
6025bdd1243dSDimitry Andric   if (mi_match(
6026bdd1243dSDimitry Andric           MI, MRI,
6027bdd1243dSDimitry Andric           m_any_of(m_GBuildVectorTrunc(LoPattern, HiPattern),
6028bdd1243dSDimitry Andric                    m_GBuildVector(m_GTrunc(LoPattern), m_GTrunc(HiPattern))))) {
6029bdd1243dSDimitry Andric     if (Lo == Hi && ShiftAmount->Value == DstEltTy.getSizeInBits()) {
6030bdd1243dSDimitry Andric       MatchInfo = Lo;
6031bdd1243dSDimitry Andric       return MRI.getType(MatchInfo) == DstVecTy;
6032bdd1243dSDimitry Andric     }
6033bdd1243dSDimitry Andric   }
6034bdd1243dSDimitry Andric 
6035bdd1243dSDimitry Andric   return false;
6036bdd1243dSDimitry Andric }
6037bdd1243dSDimitry Andric 
6038bdd1243dSDimitry Andric bool CombinerHelper::matchTruncBuildVectorFold(MachineInstr &MI,
6039bdd1243dSDimitry Andric                                                Register &MatchInfo) {
6040bdd1243dSDimitry Andric   // Replace (G_TRUNC (G_BITCAST (G_BUILD_VECTOR x, y)) with just x
6041bdd1243dSDimitry Andric   // if type(x) == type(G_TRUNC)
6042bdd1243dSDimitry Andric   if (!mi_match(MI.getOperand(1).getReg(), MRI,
6043bdd1243dSDimitry Andric                 m_GBitcast(m_GBuildVector(m_Reg(MatchInfo), m_Reg()))))
6044bdd1243dSDimitry Andric     return false;
6045bdd1243dSDimitry Andric 
6046bdd1243dSDimitry Andric   return MRI.getType(MatchInfo) == MRI.getType(MI.getOperand(0).getReg());
6047bdd1243dSDimitry Andric }
6048bdd1243dSDimitry Andric 
6049bdd1243dSDimitry Andric bool CombinerHelper::matchTruncLshrBuildVectorFold(MachineInstr &MI,
6050bdd1243dSDimitry Andric                                                    Register &MatchInfo) {
6051bdd1243dSDimitry Andric   // Replace (G_TRUNC (G_LSHR (G_BITCAST (G_BUILD_VECTOR x, y)), K)) with
6052bdd1243dSDimitry Andric   //    y if K == size of vector element type
6053bdd1243dSDimitry Andric   std::optional<ValueAndVReg> ShiftAmt;
6054bdd1243dSDimitry Andric   if (!mi_match(MI.getOperand(1).getReg(), MRI,
6055bdd1243dSDimitry Andric                 m_GLShr(m_GBitcast(m_GBuildVector(m_Reg(), m_Reg(MatchInfo))),
6056bdd1243dSDimitry Andric                         m_GCst(ShiftAmt))))
6057bdd1243dSDimitry Andric     return false;
6058bdd1243dSDimitry Andric 
6059bdd1243dSDimitry Andric   LLT MatchTy = MRI.getType(MatchInfo);
6060bdd1243dSDimitry Andric   return ShiftAmt->Value.getZExtValue() == MatchTy.getSizeInBits() &&
6061bdd1243dSDimitry Andric          MatchTy == MRI.getType(MI.getOperand(0).getReg());
6062bdd1243dSDimitry Andric }
6063bdd1243dSDimitry Andric 
6064bdd1243dSDimitry Andric unsigned CombinerHelper::getFPMinMaxOpcForSelect(
6065bdd1243dSDimitry Andric     CmpInst::Predicate Pred, LLT DstTy,
6066bdd1243dSDimitry Andric     SelectPatternNaNBehaviour VsNaNRetVal) const {
6067bdd1243dSDimitry Andric   assert(VsNaNRetVal != SelectPatternNaNBehaviour::NOT_APPLICABLE &&
6068bdd1243dSDimitry Andric          "Expected a NaN behaviour?");
6069bdd1243dSDimitry Andric   // Choose an opcode based off of legality or the behaviour when one of the
6070bdd1243dSDimitry Andric   // LHS/RHS may be NaN.
6071bdd1243dSDimitry Andric   switch (Pred) {
6072bdd1243dSDimitry Andric   default:
6073bdd1243dSDimitry Andric     return 0;
6074bdd1243dSDimitry Andric   case CmpInst::FCMP_UGT:
6075bdd1243dSDimitry Andric   case CmpInst::FCMP_UGE:
6076bdd1243dSDimitry Andric   case CmpInst::FCMP_OGT:
6077bdd1243dSDimitry Andric   case CmpInst::FCMP_OGE:
6078bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_OTHER)
6079bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXNUM;
6080bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_NAN)
6081bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXIMUM;
6082bdd1243dSDimitry Andric     if (isLegal({TargetOpcode::G_FMAXNUM, {DstTy}}))
6083bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXNUM;
6084bdd1243dSDimitry Andric     if (isLegal({TargetOpcode::G_FMAXIMUM, {DstTy}}))
6085bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXIMUM;
6086bdd1243dSDimitry Andric     return 0;
6087bdd1243dSDimitry Andric   case CmpInst::FCMP_ULT:
6088bdd1243dSDimitry Andric   case CmpInst::FCMP_ULE:
6089bdd1243dSDimitry Andric   case CmpInst::FCMP_OLT:
6090bdd1243dSDimitry Andric   case CmpInst::FCMP_OLE:
6091bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_OTHER)
6092bdd1243dSDimitry Andric       return TargetOpcode::G_FMINNUM;
6093bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_NAN)
6094bdd1243dSDimitry Andric       return TargetOpcode::G_FMINIMUM;
6095bdd1243dSDimitry Andric     if (isLegal({TargetOpcode::G_FMINNUM, {DstTy}}))
6096bdd1243dSDimitry Andric       return TargetOpcode::G_FMINNUM;
6097bdd1243dSDimitry Andric     if (!isLegal({TargetOpcode::G_FMINIMUM, {DstTy}}))
6098bdd1243dSDimitry Andric       return 0;
6099bdd1243dSDimitry Andric     return TargetOpcode::G_FMINIMUM;
6100bdd1243dSDimitry Andric   }
6101bdd1243dSDimitry Andric }
6102bdd1243dSDimitry Andric 
6103bdd1243dSDimitry Andric CombinerHelper::SelectPatternNaNBehaviour
6104bdd1243dSDimitry Andric CombinerHelper::computeRetValAgainstNaN(Register LHS, Register RHS,
6105bdd1243dSDimitry Andric                                         bool IsOrderedComparison) const {
6106bdd1243dSDimitry Andric   bool LHSSafe = isKnownNeverNaN(LHS, MRI);
6107bdd1243dSDimitry Andric   bool RHSSafe = isKnownNeverNaN(RHS, MRI);
6108bdd1243dSDimitry Andric   // Completely unsafe.
6109bdd1243dSDimitry Andric   if (!LHSSafe && !RHSSafe)
6110bdd1243dSDimitry Andric     return SelectPatternNaNBehaviour::NOT_APPLICABLE;
6111bdd1243dSDimitry Andric   if (LHSSafe && RHSSafe)
6112bdd1243dSDimitry Andric     return SelectPatternNaNBehaviour::RETURNS_ANY;
6113bdd1243dSDimitry Andric   // An ordered comparison will return false when given a NaN, so it
6114bdd1243dSDimitry Andric   // returns the RHS.
6115bdd1243dSDimitry Andric   if (IsOrderedComparison)
6116bdd1243dSDimitry Andric     return LHSSafe ? SelectPatternNaNBehaviour::RETURNS_NAN
6117bdd1243dSDimitry Andric                    : SelectPatternNaNBehaviour::RETURNS_OTHER;
6118bdd1243dSDimitry Andric   // An unordered comparison will return true when given a NaN, so it
6119bdd1243dSDimitry Andric   // returns the LHS.
6120bdd1243dSDimitry Andric   return LHSSafe ? SelectPatternNaNBehaviour::RETURNS_OTHER
6121bdd1243dSDimitry Andric                  : SelectPatternNaNBehaviour::RETURNS_NAN;
6122bdd1243dSDimitry Andric }
6123bdd1243dSDimitry Andric 
6124bdd1243dSDimitry Andric bool CombinerHelper::matchFPSelectToMinMax(Register Dst, Register Cond,
6125bdd1243dSDimitry Andric                                            Register TrueVal, Register FalseVal,
6126bdd1243dSDimitry Andric                                            BuildFnTy &MatchInfo) {
6127bdd1243dSDimitry Andric   // Match: select (fcmp cond x, y) x, y
6128bdd1243dSDimitry Andric   //        select (fcmp cond x, y) y, x
6129bdd1243dSDimitry Andric   // And turn it into fminnum/fmaxnum or fmin/fmax based off of the condition.
6130bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(Dst);
6131bdd1243dSDimitry Andric   // Bail out early on pointers, since we'll never want to fold to a min/max.
6132bdd1243dSDimitry Andric   if (DstTy.isPointer())
6133bdd1243dSDimitry Andric     return false;
6134bdd1243dSDimitry Andric   // Match a floating point compare with a less-than/greater-than predicate.
6135bdd1243dSDimitry Andric   // TODO: Allow multiple users of the compare if they are all selects.
6136bdd1243dSDimitry Andric   CmpInst::Predicate Pred;
6137bdd1243dSDimitry Andric   Register CmpLHS, CmpRHS;
6138bdd1243dSDimitry Andric   if (!mi_match(Cond, MRI,
6139bdd1243dSDimitry Andric                 m_OneNonDBGUse(
6140bdd1243dSDimitry Andric                     m_GFCmp(m_Pred(Pred), m_Reg(CmpLHS), m_Reg(CmpRHS)))) ||
6141bdd1243dSDimitry Andric       CmpInst::isEquality(Pred))
6142bdd1243dSDimitry Andric     return false;
6143bdd1243dSDimitry Andric   SelectPatternNaNBehaviour ResWithKnownNaNInfo =
6144bdd1243dSDimitry Andric       computeRetValAgainstNaN(CmpLHS, CmpRHS, CmpInst::isOrdered(Pred));
6145bdd1243dSDimitry Andric   if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::NOT_APPLICABLE)
6146bdd1243dSDimitry Andric     return false;
6147bdd1243dSDimitry Andric   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
6148bdd1243dSDimitry Andric     std::swap(CmpLHS, CmpRHS);
6149bdd1243dSDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
6150bdd1243dSDimitry Andric     if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::RETURNS_NAN)
6151bdd1243dSDimitry Andric       ResWithKnownNaNInfo = SelectPatternNaNBehaviour::RETURNS_OTHER;
6152bdd1243dSDimitry Andric     else if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::RETURNS_OTHER)
6153bdd1243dSDimitry Andric       ResWithKnownNaNInfo = SelectPatternNaNBehaviour::RETURNS_NAN;
6154bdd1243dSDimitry Andric   }
6155bdd1243dSDimitry Andric   if (TrueVal != CmpLHS || FalseVal != CmpRHS)
6156bdd1243dSDimitry Andric     return false;
6157bdd1243dSDimitry Andric   // Decide what type of max/min this should be based off of the predicate.
6158bdd1243dSDimitry Andric   unsigned Opc = getFPMinMaxOpcForSelect(Pred, DstTy, ResWithKnownNaNInfo);
6159bdd1243dSDimitry Andric   if (!Opc || !isLegal({Opc, {DstTy}}))
6160bdd1243dSDimitry Andric     return false;
6161bdd1243dSDimitry Andric   // Comparisons between signed zero and zero may have different results...
6162bdd1243dSDimitry Andric   // unless we have fmaximum/fminimum. In that case, we know -0 < 0.
6163bdd1243dSDimitry Andric   if (Opc != TargetOpcode::G_FMAXIMUM && Opc != TargetOpcode::G_FMINIMUM) {
6164bdd1243dSDimitry Andric     // We don't know if a comparison between two 0s will give us a consistent
6165bdd1243dSDimitry Andric     // result. Be conservative and only proceed if at least one side is
6166bdd1243dSDimitry Andric     // non-zero.
6167bdd1243dSDimitry Andric     auto KnownNonZeroSide = getFConstantVRegValWithLookThrough(CmpLHS, MRI);
6168bdd1243dSDimitry Andric     if (!KnownNonZeroSide || !KnownNonZeroSide->Value.isNonZero()) {
6169bdd1243dSDimitry Andric       KnownNonZeroSide = getFConstantVRegValWithLookThrough(CmpRHS, MRI);
6170bdd1243dSDimitry Andric       if (!KnownNonZeroSide || !KnownNonZeroSide->Value.isNonZero())
6171bdd1243dSDimitry Andric         return false;
6172bdd1243dSDimitry Andric     }
6173bdd1243dSDimitry Andric   }
6174bdd1243dSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
6175bdd1243dSDimitry Andric     B.buildInstr(Opc, {Dst}, {CmpLHS, CmpRHS});
6176bdd1243dSDimitry Andric   };
6177bdd1243dSDimitry Andric   return true;
6178bdd1243dSDimitry Andric }
6179bdd1243dSDimitry Andric 
6180bdd1243dSDimitry Andric bool CombinerHelper::matchSimplifySelectToMinMax(MachineInstr &MI,
6181bdd1243dSDimitry Andric                                                  BuildFnTy &MatchInfo) {
6182bdd1243dSDimitry Andric   // TODO: Handle integer cases.
6183bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
6184bdd1243dSDimitry Andric   // Condition may be fed by a truncated compare.
6185bdd1243dSDimitry Andric   Register Cond = MI.getOperand(1).getReg();
6186bdd1243dSDimitry Andric   Register MaybeTrunc;
6187bdd1243dSDimitry Andric   if (mi_match(Cond, MRI, m_OneNonDBGUse(m_GTrunc(m_Reg(MaybeTrunc)))))
6188bdd1243dSDimitry Andric     Cond = MaybeTrunc;
6189bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6190bdd1243dSDimitry Andric   Register TrueVal = MI.getOperand(2).getReg();
6191bdd1243dSDimitry Andric   Register FalseVal = MI.getOperand(3).getReg();
6192bdd1243dSDimitry Andric   return matchFPSelectToMinMax(Dst, Cond, TrueVal, FalseVal, MatchInfo);
6193bdd1243dSDimitry Andric }
6194bdd1243dSDimitry Andric 
6195bdd1243dSDimitry Andric bool CombinerHelper::matchRedundantBinOpInEquality(MachineInstr &MI,
6196bdd1243dSDimitry Andric                                                    BuildFnTy &MatchInfo) {
6197bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
6198bdd1243dSDimitry Andric   // (X + Y) == X --> Y == 0
6199bdd1243dSDimitry Andric   // (X + Y) != X --> Y != 0
6200bdd1243dSDimitry Andric   // (X - Y) == X --> Y == 0
6201bdd1243dSDimitry Andric   // (X - Y) != X --> Y != 0
6202bdd1243dSDimitry Andric   // (X ^ Y) == X --> Y == 0
6203bdd1243dSDimitry Andric   // (X ^ Y) != X --> Y != 0
6204bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
6205bdd1243dSDimitry Andric   CmpInst::Predicate Pred;
6206bdd1243dSDimitry Andric   Register X, Y, OpLHS, OpRHS;
6207bdd1243dSDimitry Andric   bool MatchedSub = mi_match(
6208bdd1243dSDimitry Andric       Dst, MRI,
6209bdd1243dSDimitry Andric       m_c_GICmp(m_Pred(Pred), m_Reg(X), m_GSub(m_Reg(OpLHS), m_Reg(Y))));
6210bdd1243dSDimitry Andric   if (MatchedSub && X != OpLHS)
6211bdd1243dSDimitry Andric     return false;
6212bdd1243dSDimitry Andric   if (!MatchedSub) {
6213bdd1243dSDimitry Andric     if (!mi_match(Dst, MRI,
6214bdd1243dSDimitry Andric                   m_c_GICmp(m_Pred(Pred), m_Reg(X),
6215bdd1243dSDimitry Andric                             m_any_of(m_GAdd(m_Reg(OpLHS), m_Reg(OpRHS)),
6216bdd1243dSDimitry Andric                                      m_GXor(m_Reg(OpLHS), m_Reg(OpRHS))))))
6217bdd1243dSDimitry Andric       return false;
6218bdd1243dSDimitry Andric     Y = X == OpLHS ? OpRHS : X == OpRHS ? OpLHS : Register();
6219bdd1243dSDimitry Andric   }
6220bdd1243dSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
6221bdd1243dSDimitry Andric     auto Zero = B.buildConstant(MRI.getType(Y), 0);
6222bdd1243dSDimitry Andric     B.buildICmp(Pred, Dst, Y, Zero);
6223bdd1243dSDimitry Andric   };
6224bdd1243dSDimitry Andric   return CmpInst::isEquality(Pred) && Y.isValid();
6225bdd1243dSDimitry Andric }
6226bdd1243dSDimitry Andric 
622706c3fb27SDimitry Andric bool CombinerHelper::matchShiftsTooBig(MachineInstr &MI) {
622806c3fb27SDimitry Andric   Register ShiftReg = MI.getOperand(2).getReg();
622906c3fb27SDimitry Andric   LLT ResTy = MRI.getType(MI.getOperand(0).getReg());
623006c3fb27SDimitry Andric   auto IsShiftTooBig = [&](const Constant *C) {
623106c3fb27SDimitry Andric     auto *CI = dyn_cast<ConstantInt>(C);
623206c3fb27SDimitry Andric     return CI && CI->uge(ResTy.getScalarSizeInBits());
623306c3fb27SDimitry Andric   };
623406c3fb27SDimitry Andric   return matchUnaryPredicate(MRI, ShiftReg, IsShiftTooBig);
623506c3fb27SDimitry Andric }
623606c3fb27SDimitry Andric 
62375f757f3fSDimitry Andric bool CombinerHelper::matchCommuteConstantToRHS(MachineInstr &MI) {
62385f757f3fSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
62395f757f3fSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
62405f757f3fSDimitry Andric   auto *LHSDef = MRI.getVRegDef(LHS);
62415f757f3fSDimitry Andric   if (getIConstantVRegVal(LHS, MRI).has_value())
62420b57cec5SDimitry Andric     return true;
62435f757f3fSDimitry Andric 
62445f757f3fSDimitry Andric   // LHS may be a G_CONSTANT_FOLD_BARRIER. If so we commute
62455f757f3fSDimitry Andric   // as long as we don't already have a constant on the RHS.
62465f757f3fSDimitry Andric   if (LHSDef->getOpcode() != TargetOpcode::G_CONSTANT_FOLD_BARRIER)
62478bcb0991SDimitry Andric     return false;
62485f757f3fSDimitry Andric   return MRI.getVRegDef(RHS)->getOpcode() !=
62495f757f3fSDimitry Andric              TargetOpcode::G_CONSTANT_FOLD_BARRIER &&
62505f757f3fSDimitry Andric          !getIConstantVRegVal(RHS, MRI);
62515f757f3fSDimitry Andric }
62525f757f3fSDimitry Andric 
62535f757f3fSDimitry Andric bool CombinerHelper::matchCommuteFPConstantToRHS(MachineInstr &MI) {
62545f757f3fSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
62555f757f3fSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
62565f757f3fSDimitry Andric   std::optional<FPValueAndVReg> ValAndVReg;
62575f757f3fSDimitry Andric   if (!mi_match(LHS, MRI, m_GFCstOrSplat(ValAndVReg)))
62585f757f3fSDimitry Andric     return false;
62595f757f3fSDimitry Andric   return !mi_match(RHS, MRI, m_GFCstOrSplat(ValAndVReg));
62605f757f3fSDimitry Andric }
62615f757f3fSDimitry Andric 
62625f757f3fSDimitry Andric void CombinerHelper::applyCommuteBinOpOperands(MachineInstr &MI) {
62635f757f3fSDimitry Andric   Observer.changingInstr(MI);
62645f757f3fSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
62655f757f3fSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
62665f757f3fSDimitry Andric   MI.getOperand(1).setReg(RHSReg);
62675f757f3fSDimitry Andric   MI.getOperand(2).setReg(LHSReg);
62685f757f3fSDimitry Andric   Observer.changedInstr(MI);
62690b57cec5SDimitry Andric }
6270647cbc5dSDimitry Andric 
6271647cbc5dSDimitry Andric bool CombinerHelper::isOneOrOneSplat(Register Src, bool AllowUndefs) {
6272647cbc5dSDimitry Andric   LLT SrcTy = MRI.getType(Src);
6273647cbc5dSDimitry Andric   if (SrcTy.isFixedVector())
6274647cbc5dSDimitry Andric     return isConstantSplatVector(Src, 1, AllowUndefs);
6275647cbc5dSDimitry Andric   if (SrcTy.isScalar()) {
6276647cbc5dSDimitry Andric     if (AllowUndefs && getOpcodeDef<GImplicitDef>(Src, MRI) != nullptr)
6277647cbc5dSDimitry Andric       return true;
6278647cbc5dSDimitry Andric     auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
6279647cbc5dSDimitry Andric     return IConstant && IConstant->Value == 1;
6280647cbc5dSDimitry Andric   }
6281647cbc5dSDimitry Andric   return false; // scalable vector
6282647cbc5dSDimitry Andric }
6283647cbc5dSDimitry Andric 
6284647cbc5dSDimitry Andric bool CombinerHelper::isZeroOrZeroSplat(Register Src, bool AllowUndefs) {
6285647cbc5dSDimitry Andric   LLT SrcTy = MRI.getType(Src);
6286647cbc5dSDimitry Andric   if (SrcTy.isFixedVector())
6287647cbc5dSDimitry Andric     return isConstantSplatVector(Src, 0, AllowUndefs);
6288647cbc5dSDimitry Andric   if (SrcTy.isScalar()) {
6289647cbc5dSDimitry Andric     if (AllowUndefs && getOpcodeDef<GImplicitDef>(Src, MRI) != nullptr)
6290647cbc5dSDimitry Andric       return true;
6291647cbc5dSDimitry Andric     auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
6292647cbc5dSDimitry Andric     return IConstant && IConstant->Value == 0;
6293647cbc5dSDimitry Andric   }
6294647cbc5dSDimitry Andric   return false; // scalable vector
6295647cbc5dSDimitry Andric }
6296647cbc5dSDimitry Andric 
6297647cbc5dSDimitry Andric // Ignores COPYs during conformance checks.
6298647cbc5dSDimitry Andric // FIXME scalable vectors.
6299647cbc5dSDimitry Andric bool CombinerHelper::isConstantSplatVector(Register Src, int64_t SplatValue,
6300647cbc5dSDimitry Andric                                            bool AllowUndefs) {
6301647cbc5dSDimitry Andric   GBuildVector *BuildVector = getOpcodeDef<GBuildVector>(Src, MRI);
6302647cbc5dSDimitry Andric   if (!BuildVector)
6303647cbc5dSDimitry Andric     return false;
6304647cbc5dSDimitry Andric   unsigned NumSources = BuildVector->getNumSources();
6305647cbc5dSDimitry Andric 
6306647cbc5dSDimitry Andric   for (unsigned I = 0; I < NumSources; ++I) {
6307647cbc5dSDimitry Andric     GImplicitDef *ImplicitDef =
6308647cbc5dSDimitry Andric         getOpcodeDef<GImplicitDef>(BuildVector->getSourceReg(I), MRI);
6309647cbc5dSDimitry Andric     if (ImplicitDef && AllowUndefs)
6310647cbc5dSDimitry Andric       continue;
6311647cbc5dSDimitry Andric     if (ImplicitDef && !AllowUndefs)
6312647cbc5dSDimitry Andric       return false;
6313647cbc5dSDimitry Andric     std::optional<ValueAndVReg> IConstant =
6314647cbc5dSDimitry Andric         getIConstantVRegValWithLookThrough(BuildVector->getSourceReg(I), MRI);
6315647cbc5dSDimitry Andric     if (IConstant && IConstant->Value == SplatValue)
6316647cbc5dSDimitry Andric       continue;
6317647cbc5dSDimitry Andric     return false;
6318647cbc5dSDimitry Andric   }
6319647cbc5dSDimitry Andric   return true;
6320647cbc5dSDimitry Andric }
6321647cbc5dSDimitry Andric 
6322647cbc5dSDimitry Andric // Ignores COPYs during lookups.
6323647cbc5dSDimitry Andric // FIXME scalable vectors
6324647cbc5dSDimitry Andric std::optional<APInt>
6325647cbc5dSDimitry Andric CombinerHelper::getConstantOrConstantSplatVector(Register Src) {
6326647cbc5dSDimitry Andric   auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
6327647cbc5dSDimitry Andric   if (IConstant)
6328647cbc5dSDimitry Andric     return IConstant->Value;
6329647cbc5dSDimitry Andric 
6330647cbc5dSDimitry Andric   GBuildVector *BuildVector = getOpcodeDef<GBuildVector>(Src, MRI);
6331647cbc5dSDimitry Andric   if (!BuildVector)
6332647cbc5dSDimitry Andric     return std::nullopt;
6333647cbc5dSDimitry Andric   unsigned NumSources = BuildVector->getNumSources();
6334647cbc5dSDimitry Andric 
6335647cbc5dSDimitry Andric   std::optional<APInt> Value = std::nullopt;
6336647cbc5dSDimitry Andric   for (unsigned I = 0; I < NumSources; ++I) {
6337647cbc5dSDimitry Andric     std::optional<ValueAndVReg> IConstant =
6338647cbc5dSDimitry Andric         getIConstantVRegValWithLookThrough(BuildVector->getSourceReg(I), MRI);
6339647cbc5dSDimitry Andric     if (!IConstant)
6340647cbc5dSDimitry Andric       return std::nullopt;
6341647cbc5dSDimitry Andric     if (!Value)
6342647cbc5dSDimitry Andric       Value = IConstant->Value;
6343647cbc5dSDimitry Andric     else if (*Value != IConstant->Value)
6344647cbc5dSDimitry Andric       return std::nullopt;
6345647cbc5dSDimitry Andric   }
6346647cbc5dSDimitry Andric   return Value;
6347647cbc5dSDimitry Andric }
6348647cbc5dSDimitry Andric 
6349647cbc5dSDimitry Andric // TODO: use knownbits to determine zeros
6350647cbc5dSDimitry Andric bool CombinerHelper::tryFoldSelectOfConstants(GSelect *Select,
6351647cbc5dSDimitry Andric                                               BuildFnTy &MatchInfo) {
6352647cbc5dSDimitry Andric   uint32_t Flags = Select->getFlags();
6353647cbc5dSDimitry Andric   Register Dest = Select->getReg(0);
6354647cbc5dSDimitry Andric   Register Cond = Select->getCondReg();
6355647cbc5dSDimitry Andric   Register True = Select->getTrueReg();
6356647cbc5dSDimitry Andric   Register False = Select->getFalseReg();
6357647cbc5dSDimitry Andric   LLT CondTy = MRI.getType(Select->getCondReg());
6358647cbc5dSDimitry Andric   LLT TrueTy = MRI.getType(Select->getTrueReg());
6359647cbc5dSDimitry Andric 
6360647cbc5dSDimitry Andric   // We only do this combine for scalar boolean conditions.
6361647cbc5dSDimitry Andric   if (CondTy != LLT::scalar(1))
6362647cbc5dSDimitry Andric     return false;
6363647cbc5dSDimitry Andric 
6364647cbc5dSDimitry Andric   // Both are scalars.
6365647cbc5dSDimitry Andric   std::optional<ValueAndVReg> TrueOpt =
6366647cbc5dSDimitry Andric       getIConstantVRegValWithLookThrough(True, MRI);
6367647cbc5dSDimitry Andric   std::optional<ValueAndVReg> FalseOpt =
6368647cbc5dSDimitry Andric       getIConstantVRegValWithLookThrough(False, MRI);
6369647cbc5dSDimitry Andric 
6370647cbc5dSDimitry Andric   if (!TrueOpt || !FalseOpt)
6371647cbc5dSDimitry Andric     return false;
6372647cbc5dSDimitry Andric 
6373647cbc5dSDimitry Andric   APInt TrueValue = TrueOpt->Value;
6374647cbc5dSDimitry Andric   APInt FalseValue = FalseOpt->Value;
6375647cbc5dSDimitry Andric 
6376647cbc5dSDimitry Andric   // select Cond, 1, 0 --> zext (Cond)
6377647cbc5dSDimitry Andric   if (TrueValue.isOne() && FalseValue.isZero()) {
6378647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6379647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6380647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Dest, Cond);
6381647cbc5dSDimitry Andric     };
6382647cbc5dSDimitry Andric     return true;
6383647cbc5dSDimitry Andric   }
6384647cbc5dSDimitry Andric 
6385647cbc5dSDimitry Andric   // select Cond, -1, 0 --> sext (Cond)
6386647cbc5dSDimitry Andric   if (TrueValue.isAllOnes() && FalseValue.isZero()) {
6387647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6388647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6389647cbc5dSDimitry Andric       B.buildSExtOrTrunc(Dest, Cond);
6390647cbc5dSDimitry Andric     };
6391647cbc5dSDimitry Andric     return true;
6392647cbc5dSDimitry Andric   }
6393647cbc5dSDimitry Andric 
6394647cbc5dSDimitry Andric   // select Cond, 0, 1 --> zext (!Cond)
6395647cbc5dSDimitry Andric   if (TrueValue.isZero() && FalseValue.isOne()) {
6396647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6397647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6398647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(CondTy);
6399647cbc5dSDimitry Andric       B.buildNot(Inner, Cond);
6400647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Dest, Inner);
6401647cbc5dSDimitry Andric     };
6402647cbc5dSDimitry Andric     return true;
6403647cbc5dSDimitry Andric   }
6404647cbc5dSDimitry Andric 
6405647cbc5dSDimitry Andric   // select Cond, 0, -1 --> sext (!Cond)
6406647cbc5dSDimitry Andric   if (TrueValue.isZero() && FalseValue.isAllOnes()) {
6407647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6408647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6409647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(CondTy);
6410647cbc5dSDimitry Andric       B.buildNot(Inner, Cond);
6411647cbc5dSDimitry Andric       B.buildSExtOrTrunc(Dest, Inner);
6412647cbc5dSDimitry Andric     };
6413647cbc5dSDimitry Andric     return true;
6414647cbc5dSDimitry Andric   }
6415647cbc5dSDimitry Andric 
6416647cbc5dSDimitry Andric   // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6417647cbc5dSDimitry Andric   if (TrueValue - 1 == FalseValue) {
6418647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6419647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6420647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(TrueTy);
6421647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Inner, Cond);
6422647cbc5dSDimitry Andric       B.buildAdd(Dest, Inner, False);
6423647cbc5dSDimitry Andric     };
6424647cbc5dSDimitry Andric     return true;
6425647cbc5dSDimitry Andric   }
6426647cbc5dSDimitry Andric 
6427647cbc5dSDimitry Andric   // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6428647cbc5dSDimitry Andric   if (TrueValue + 1 == FalseValue) {
6429647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6430647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6431647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(TrueTy);
6432647cbc5dSDimitry Andric       B.buildSExtOrTrunc(Inner, Cond);
6433647cbc5dSDimitry Andric       B.buildAdd(Dest, Inner, False);
6434647cbc5dSDimitry Andric     };
6435647cbc5dSDimitry Andric     return true;
6436647cbc5dSDimitry Andric   }
6437647cbc5dSDimitry Andric 
6438647cbc5dSDimitry Andric   // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
6439647cbc5dSDimitry Andric   if (TrueValue.isPowerOf2() && FalseValue.isZero()) {
6440647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6441647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6442647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(TrueTy);
6443647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Inner, Cond);
6444647cbc5dSDimitry Andric       // The shift amount must be scalar.
6445647cbc5dSDimitry Andric       LLT ShiftTy = TrueTy.isVector() ? TrueTy.getElementType() : TrueTy;
6446647cbc5dSDimitry Andric       auto ShAmtC = B.buildConstant(ShiftTy, TrueValue.exactLogBase2());
6447647cbc5dSDimitry Andric       B.buildShl(Dest, Inner, ShAmtC, Flags);
6448647cbc5dSDimitry Andric     };
6449647cbc5dSDimitry Andric     return true;
6450647cbc5dSDimitry Andric   }
6451647cbc5dSDimitry Andric   // select Cond, -1, C --> or (sext Cond), C
6452647cbc5dSDimitry Andric   if (TrueValue.isAllOnes()) {
6453647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6454647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6455647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(TrueTy);
6456647cbc5dSDimitry Andric       B.buildSExtOrTrunc(Inner, Cond);
6457647cbc5dSDimitry Andric       B.buildOr(Dest, Inner, False, Flags);
6458647cbc5dSDimitry Andric     };
6459647cbc5dSDimitry Andric     return true;
6460647cbc5dSDimitry Andric   }
6461647cbc5dSDimitry Andric 
6462647cbc5dSDimitry Andric   // select Cond, C, -1 --> or (sext (not Cond)), C
6463647cbc5dSDimitry Andric   if (FalseValue.isAllOnes()) {
6464647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6465647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6466647cbc5dSDimitry Andric       Register Not = MRI.createGenericVirtualRegister(CondTy);
6467647cbc5dSDimitry Andric       B.buildNot(Not, Cond);
6468647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(TrueTy);
6469647cbc5dSDimitry Andric       B.buildSExtOrTrunc(Inner, Not);
6470647cbc5dSDimitry Andric       B.buildOr(Dest, Inner, True, Flags);
6471647cbc5dSDimitry Andric     };
6472647cbc5dSDimitry Andric     return true;
6473647cbc5dSDimitry Andric   }
6474647cbc5dSDimitry Andric 
6475647cbc5dSDimitry Andric   return false;
6476647cbc5dSDimitry Andric }
6477647cbc5dSDimitry Andric 
6478647cbc5dSDimitry Andric // TODO: use knownbits to determine zeros
6479647cbc5dSDimitry Andric bool CombinerHelper::tryFoldBoolSelectToLogic(GSelect *Select,
6480647cbc5dSDimitry Andric                                               BuildFnTy &MatchInfo) {
6481647cbc5dSDimitry Andric   uint32_t Flags = Select->getFlags();
6482647cbc5dSDimitry Andric   Register DstReg = Select->getReg(0);
6483647cbc5dSDimitry Andric   Register Cond = Select->getCondReg();
6484647cbc5dSDimitry Andric   Register True = Select->getTrueReg();
6485647cbc5dSDimitry Andric   Register False = Select->getFalseReg();
6486647cbc5dSDimitry Andric   LLT CondTy = MRI.getType(Select->getCondReg());
6487647cbc5dSDimitry Andric   LLT TrueTy = MRI.getType(Select->getTrueReg());
6488647cbc5dSDimitry Andric 
6489647cbc5dSDimitry Andric   // Boolean or fixed vector of booleans.
6490647cbc5dSDimitry Andric   if (CondTy.isScalableVector() ||
6491647cbc5dSDimitry Andric       (CondTy.isFixedVector() &&
6492647cbc5dSDimitry Andric        CondTy.getElementType().getScalarSizeInBits() != 1) ||
6493647cbc5dSDimitry Andric       CondTy.getScalarSizeInBits() != 1)
6494647cbc5dSDimitry Andric     return false;
6495647cbc5dSDimitry Andric 
6496647cbc5dSDimitry Andric   if (CondTy != TrueTy)
6497647cbc5dSDimitry Andric     return false;
6498647cbc5dSDimitry Andric 
6499647cbc5dSDimitry Andric   // select Cond, Cond, F --> or Cond, F
6500647cbc5dSDimitry Andric   // select Cond, 1, F    --> or Cond, F
6501647cbc5dSDimitry Andric   if ((Cond == True) || isOneOrOneSplat(True, /* AllowUndefs */ true)) {
6502647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6503647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6504647cbc5dSDimitry Andric       Register Ext = MRI.createGenericVirtualRegister(TrueTy);
6505647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Ext, Cond);
6506647cbc5dSDimitry Andric       B.buildOr(DstReg, Ext, False, Flags);
6507647cbc5dSDimitry Andric     };
6508647cbc5dSDimitry Andric     return true;
6509647cbc5dSDimitry Andric   }
6510647cbc5dSDimitry Andric 
6511647cbc5dSDimitry Andric   // select Cond, T, Cond --> and Cond, T
6512647cbc5dSDimitry Andric   // select Cond, T, 0    --> and Cond, T
6513647cbc5dSDimitry Andric   if ((Cond == False) || isZeroOrZeroSplat(False, /* AllowUndefs */ true)) {
6514647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6515647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6516647cbc5dSDimitry Andric       Register Ext = MRI.createGenericVirtualRegister(TrueTy);
6517647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Ext, Cond);
6518647cbc5dSDimitry Andric       B.buildAnd(DstReg, Ext, True);
6519647cbc5dSDimitry Andric     };
6520647cbc5dSDimitry Andric     return true;
6521647cbc5dSDimitry Andric   }
6522647cbc5dSDimitry Andric 
6523647cbc5dSDimitry Andric   // select Cond, T, 1 --> or (not Cond), T
6524647cbc5dSDimitry Andric   if (isOneOrOneSplat(False, /* AllowUndefs */ true)) {
6525647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6526647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6527647cbc5dSDimitry Andric       // First the not.
6528647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(CondTy);
6529647cbc5dSDimitry Andric       B.buildNot(Inner, Cond);
6530647cbc5dSDimitry Andric       // Then an ext to match the destination register.
6531647cbc5dSDimitry Andric       Register Ext = MRI.createGenericVirtualRegister(TrueTy);
6532647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Ext, Inner);
6533647cbc5dSDimitry Andric       B.buildOr(DstReg, Ext, True, Flags);
6534647cbc5dSDimitry Andric     };
6535647cbc5dSDimitry Andric     return true;
6536647cbc5dSDimitry Andric   }
6537647cbc5dSDimitry Andric 
6538647cbc5dSDimitry Andric   // select Cond, 0, F --> and (not Cond), F
6539647cbc5dSDimitry Andric   if (isZeroOrZeroSplat(True, /* AllowUndefs */ true)) {
6540647cbc5dSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
6541647cbc5dSDimitry Andric       B.setInstrAndDebugLoc(*Select);
6542647cbc5dSDimitry Andric       // First the not.
6543647cbc5dSDimitry Andric       Register Inner = MRI.createGenericVirtualRegister(CondTy);
6544647cbc5dSDimitry Andric       B.buildNot(Inner, Cond);
6545647cbc5dSDimitry Andric       // Then an ext to match the destination register.
6546647cbc5dSDimitry Andric       Register Ext = MRI.createGenericVirtualRegister(TrueTy);
6547647cbc5dSDimitry Andric       B.buildZExtOrTrunc(Ext, Inner);
6548647cbc5dSDimitry Andric       B.buildAnd(DstReg, Ext, False);
6549647cbc5dSDimitry Andric     };
6550647cbc5dSDimitry Andric     return true;
6551647cbc5dSDimitry Andric   }
6552647cbc5dSDimitry Andric 
6553647cbc5dSDimitry Andric   return false;
6554647cbc5dSDimitry Andric }
6555647cbc5dSDimitry Andric 
6556297eecfbSDimitry Andric bool CombinerHelper::tryFoldSelectToIntMinMax(GSelect *Select,
6557297eecfbSDimitry Andric                                               BuildFnTy &MatchInfo) {
6558297eecfbSDimitry Andric   Register DstReg = Select->getReg(0);
6559297eecfbSDimitry Andric   Register Cond = Select->getCondReg();
6560297eecfbSDimitry Andric   Register True = Select->getTrueReg();
6561297eecfbSDimitry Andric   Register False = Select->getFalseReg();
6562297eecfbSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
6563297eecfbSDimitry Andric 
65647a6dacacSDimitry Andric   if (DstTy.isPointer())
65657a6dacacSDimitry Andric     return false;
65667a6dacacSDimitry Andric 
6567297eecfbSDimitry Andric   // We need an G_ICMP on the condition register.
6568297eecfbSDimitry Andric   GICmp *Cmp = getOpcodeDef<GICmp>(Cond, MRI);
6569297eecfbSDimitry Andric   if (!Cmp)
6570297eecfbSDimitry Andric     return false;
6571297eecfbSDimitry Andric 
6572297eecfbSDimitry Andric   // We want to fold the icmp and replace the select.
6573297eecfbSDimitry Andric   if (!MRI.hasOneNonDBGUse(Cmp->getReg(0)))
6574297eecfbSDimitry Andric     return false;
6575297eecfbSDimitry Andric 
6576297eecfbSDimitry Andric   CmpInst::Predicate Pred = Cmp->getCond();
6577297eecfbSDimitry Andric   // We need a larger or smaller predicate for
6578297eecfbSDimitry Andric   // canonicalization.
6579297eecfbSDimitry Andric   if (CmpInst::isEquality(Pred))
6580297eecfbSDimitry Andric     return false;
6581297eecfbSDimitry Andric 
6582297eecfbSDimitry Andric   Register CmpLHS = Cmp->getLHSReg();
6583297eecfbSDimitry Andric   Register CmpRHS = Cmp->getRHSReg();
6584297eecfbSDimitry Andric 
6585297eecfbSDimitry Andric   // We can swap CmpLHS and CmpRHS for higher hitrate.
6586297eecfbSDimitry Andric   if (True == CmpRHS && False == CmpLHS) {
6587297eecfbSDimitry Andric     std::swap(CmpLHS, CmpRHS);
6588297eecfbSDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
6589297eecfbSDimitry Andric   }
6590297eecfbSDimitry Andric 
6591297eecfbSDimitry Andric   // (icmp X, Y) ? X : Y -> integer minmax.
6592297eecfbSDimitry Andric   // see matchSelectPattern in ValueTracking.
6593297eecfbSDimitry Andric   // Legality between G_SELECT and integer minmax can differ.
6594297eecfbSDimitry Andric   if (True == CmpLHS && False == CmpRHS) {
6595297eecfbSDimitry Andric     switch (Pred) {
6596297eecfbSDimitry Andric     case ICmpInst::ICMP_UGT:
6597297eecfbSDimitry Andric     case ICmpInst::ICMP_UGE: {
6598297eecfbSDimitry Andric       if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMAX, DstTy}))
6599297eecfbSDimitry Andric         return false;
6600297eecfbSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
6601297eecfbSDimitry Andric         B.buildUMax(DstReg, True, False);
6602297eecfbSDimitry Andric       };
6603297eecfbSDimitry Andric       return true;
6604297eecfbSDimitry Andric     }
6605297eecfbSDimitry Andric     case ICmpInst::ICMP_SGT:
6606297eecfbSDimitry Andric     case ICmpInst::ICMP_SGE: {
6607297eecfbSDimitry Andric       if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SMAX, DstTy}))
6608297eecfbSDimitry Andric         return false;
6609297eecfbSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
6610297eecfbSDimitry Andric         B.buildSMax(DstReg, True, False);
6611297eecfbSDimitry Andric       };
6612297eecfbSDimitry Andric       return true;
6613297eecfbSDimitry Andric     }
6614297eecfbSDimitry Andric     case ICmpInst::ICMP_ULT:
6615297eecfbSDimitry Andric     case ICmpInst::ICMP_ULE: {
6616297eecfbSDimitry Andric       if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMIN, DstTy}))
6617297eecfbSDimitry Andric         return false;
6618297eecfbSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
6619297eecfbSDimitry Andric         B.buildUMin(DstReg, True, False);
6620297eecfbSDimitry Andric       };
6621297eecfbSDimitry Andric       return true;
6622297eecfbSDimitry Andric     }
6623297eecfbSDimitry Andric     case ICmpInst::ICMP_SLT:
6624297eecfbSDimitry Andric     case ICmpInst::ICMP_SLE: {
6625297eecfbSDimitry Andric       if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SMIN, DstTy}))
6626297eecfbSDimitry Andric         return false;
6627297eecfbSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
6628297eecfbSDimitry Andric         B.buildSMin(DstReg, True, False);
6629297eecfbSDimitry Andric       };
6630297eecfbSDimitry Andric       return true;
6631297eecfbSDimitry Andric     }
6632297eecfbSDimitry Andric     default:
6633297eecfbSDimitry Andric       return false;
6634297eecfbSDimitry Andric     }
6635297eecfbSDimitry Andric   }
6636297eecfbSDimitry Andric 
6637297eecfbSDimitry Andric   return false;
6638297eecfbSDimitry Andric }
6639297eecfbSDimitry Andric 
6640647cbc5dSDimitry Andric bool CombinerHelper::matchSelect(MachineInstr &MI, BuildFnTy &MatchInfo) {
6641647cbc5dSDimitry Andric   GSelect *Select = cast<GSelect>(&MI);
6642647cbc5dSDimitry Andric 
6643647cbc5dSDimitry Andric   if (tryFoldSelectOfConstants(Select, MatchInfo))
6644647cbc5dSDimitry Andric     return true;
6645647cbc5dSDimitry Andric 
6646647cbc5dSDimitry Andric   if (tryFoldBoolSelectToLogic(Select, MatchInfo))
6647647cbc5dSDimitry Andric     return true;
6648647cbc5dSDimitry Andric 
6649297eecfbSDimitry Andric   if (tryFoldSelectToIntMinMax(Select, MatchInfo))
6650297eecfbSDimitry Andric     return true;
6651297eecfbSDimitry Andric 
6652647cbc5dSDimitry Andric   return false;
6653647cbc5dSDimitry Andric }
6654