1 //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h"
9 #include "llvm/ADT/SetVector.h"
10 #include "llvm/ADT/SmallBitVector.h"
11 #include "llvm/CodeGen/GlobalISel/Combiner.h"
12 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
13 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
14 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
15 #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
16 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
17 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
18 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
19 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
20 #include "llvm/CodeGen/GlobalISel/Utils.h"
21 #include "llvm/CodeGen/LowLevelType.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetInstrInfo.h"
29 #include "llvm/CodeGen/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/CodeGen/TargetOpcodes.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/DivisionByConstantInfo.h"
35 #include "llvm/Support/MathExtras.h"
36 #include <tuple>
37 
38 #define DEBUG_TYPE "gi-combiner"
39 
40 using namespace llvm;
41 using namespace MIPatternMatch;
42 
43 // Option to allow testing of the combiner while no targets know about indexed
44 // addressing.
45 static cl::opt<bool>
46     ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
47                        cl::desc("Force all indexed operations to be "
48                                 "legal for the GlobalISel combiner"));
49 
50 CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
51                                MachineIRBuilder &B, GISelKnownBits *KB,
52                                MachineDominatorTree *MDT,
53                                const LegalizerInfo *LI)
54     : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB),
55       MDT(MDT), LI(LI), RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
56       TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
57   (void)this->KB;
58 }
59 
60 const TargetLowering &CombinerHelper::getTargetLowering() const {
61   return *Builder.getMF().getSubtarget().getTargetLowering();
62 }
63 
64 /// \returns The little endian in-memory byte position of byte \p I in a
65 /// \p ByteWidth bytes wide type.
66 ///
67 /// E.g. Given a 4-byte type x, x[0] -> byte 0
68 static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
69   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
70   return I;
71 }
72 
73 /// Determines the LogBase2 value for a non-null input value using the
74 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
75 static Register buildLogBase2(Register V, MachineIRBuilder &MIB) {
76   auto &MRI = *MIB.getMRI();
77   LLT Ty = MRI.getType(V);
78   auto Ctlz = MIB.buildCTLZ(Ty, V);
79   auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
80   return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
81 }
82 
83 /// \returns The big endian in-memory byte position of byte \p I in a
84 /// \p ByteWidth bytes wide type.
85 ///
86 /// E.g. Given a 4-byte type x, x[0] -> byte 3
87 static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
88   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
89   return ByteWidth - I - 1;
90 }
91 
92 /// Given a map from byte offsets in memory to indices in a load/store,
93 /// determine if that map corresponds to a little or big endian byte pattern.
94 ///
95 /// \param MemOffset2Idx maps memory offsets to address offsets.
96 /// \param LowestIdx is the lowest index in \p MemOffset2Idx.
97 ///
98 /// \returns true if the map corresponds to a big endian byte pattern, false
99 /// if it corresponds to a little endian byte pattern, and None otherwise.
100 ///
101 /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
102 /// are as follows:
103 ///
104 /// AddrOffset   Little endian    Big endian
105 /// 0            0                3
106 /// 1            1                2
107 /// 2            2                1
108 /// 3            3                0
109 static Optional<bool>
110 isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
111             int64_t LowestIdx) {
112   // Need at least two byte positions to decide on endianness.
113   unsigned Width = MemOffset2Idx.size();
114   if (Width < 2)
115     return None;
116   bool BigEndian = true, LittleEndian = true;
117   for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
118     auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
119     if (MemOffsetAndIdx == MemOffset2Idx.end())
120       return None;
121     const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
122     assert(Idx >= 0 && "Expected non-negative byte offset?");
123     LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
124     BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
125     if (!BigEndian && !LittleEndian)
126       return None;
127   }
128 
129   assert((BigEndian != LittleEndian) &&
130          "Pattern cannot be both big and little endian!");
131   return BigEndian;
132 }
133 
134 bool CombinerHelper::isPreLegalize() const { return !LI; }
135 
136 bool CombinerHelper::isLegal(const LegalityQuery &Query) const {
137   assert(LI && "Must have LegalizerInfo to query isLegal!");
138   return LI->getAction(Query).Action == LegalizeActions::Legal;
139 }
140 
141 bool CombinerHelper::isLegalOrBeforeLegalizer(
142     const LegalityQuery &Query) const {
143   return isPreLegalize() || isLegal(Query);
144 }
145 
146 bool CombinerHelper::isConstantLegalOrBeforeLegalizer(const LLT Ty) const {
147   if (!Ty.isVector())
148     return isLegalOrBeforeLegalizer({TargetOpcode::G_CONSTANT, {Ty}});
149   // Vector constants are represented as a G_BUILD_VECTOR of scalar G_CONSTANTs.
150   if (isPreLegalize())
151     return true;
152   LLT EltTy = Ty.getElementType();
153   return isLegal({TargetOpcode::G_BUILD_VECTOR, {Ty, EltTy}}) &&
154          isLegal({TargetOpcode::G_CONSTANT, {EltTy}});
155 }
156 
157 void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
158                                     Register ToReg) const {
159   Observer.changingAllUsesOfReg(MRI, FromReg);
160 
161   if (MRI.constrainRegAttrs(ToReg, FromReg))
162     MRI.replaceRegWith(FromReg, ToReg);
163   else
164     Builder.buildCopy(ToReg, FromReg);
165 
166   Observer.finishedChangingAllUsesOfReg();
167 }
168 
169 void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
170                                       MachineOperand &FromRegOp,
171                                       Register ToReg) const {
172   assert(FromRegOp.getParent() && "Expected an operand in an MI");
173   Observer.changingInstr(*FromRegOp.getParent());
174 
175   FromRegOp.setReg(ToReg);
176 
177   Observer.changedInstr(*FromRegOp.getParent());
178 }
179 
180 void CombinerHelper::replaceOpcodeWith(MachineInstr &FromMI,
181                                        unsigned ToOpcode) const {
182   Observer.changingInstr(FromMI);
183 
184   FromMI.setDesc(Builder.getTII().get(ToOpcode));
185 
186   Observer.changedInstr(FromMI);
187 }
188 
189 const RegisterBank *CombinerHelper::getRegBank(Register Reg) const {
190   return RBI->getRegBank(Reg, MRI, *TRI);
191 }
192 
193 void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) {
194   if (RegBank)
195     MRI.setRegBank(Reg, *RegBank);
196 }
197 
198 bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
199   if (matchCombineCopy(MI)) {
200     applyCombineCopy(MI);
201     return true;
202   }
203   return false;
204 }
205 bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
206   if (MI.getOpcode() != TargetOpcode::COPY)
207     return false;
208   Register DstReg = MI.getOperand(0).getReg();
209   Register SrcReg = MI.getOperand(1).getReg();
210   return canReplaceReg(DstReg, SrcReg, MRI);
211 }
212 void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
213   Register DstReg = MI.getOperand(0).getReg();
214   Register SrcReg = MI.getOperand(1).getReg();
215   MI.eraseFromParent();
216   replaceRegWith(MRI, DstReg, SrcReg);
217 }
218 
219 bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
220   bool IsUndef = false;
221   SmallVector<Register, 4> Ops;
222   if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
223     applyCombineConcatVectors(MI, IsUndef, Ops);
224     return true;
225   }
226   return false;
227 }
228 
229 bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
230                                                SmallVectorImpl<Register> &Ops) {
231   assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
232          "Invalid instruction");
233   IsUndef = true;
234   MachineInstr *Undef = nullptr;
235 
236   // Walk over all the operands of concat vectors and check if they are
237   // build_vector themselves or undef.
238   // Then collect their operands in Ops.
239   for (const MachineOperand &MO : MI.uses()) {
240     Register Reg = MO.getReg();
241     MachineInstr *Def = MRI.getVRegDef(Reg);
242     assert(Def && "Operand not defined");
243     switch (Def->getOpcode()) {
244     case TargetOpcode::G_BUILD_VECTOR:
245       IsUndef = false;
246       // Remember the operands of the build_vector to fold
247       // them into the yet-to-build flattened concat vectors.
248       for (const MachineOperand &BuildVecMO : Def->uses())
249         Ops.push_back(BuildVecMO.getReg());
250       break;
251     case TargetOpcode::G_IMPLICIT_DEF: {
252       LLT OpType = MRI.getType(Reg);
253       // Keep one undef value for all the undef operands.
254       if (!Undef) {
255         Builder.setInsertPt(*MI.getParent(), MI);
256         Undef = Builder.buildUndef(OpType.getScalarType());
257       }
258       assert(MRI.getType(Undef->getOperand(0).getReg()) ==
259                  OpType.getScalarType() &&
260              "All undefs should have the same type");
261       // Break the undef vector in as many scalar elements as needed
262       // for the flattening.
263       for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
264            EltIdx != EltEnd; ++EltIdx)
265         Ops.push_back(Undef->getOperand(0).getReg());
266       break;
267     }
268     default:
269       return false;
270     }
271   }
272   return true;
273 }
274 void CombinerHelper::applyCombineConcatVectors(
275     MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
276   // We determined that the concat_vectors can be flatten.
277   // Generate the flattened build_vector.
278   Register DstReg = MI.getOperand(0).getReg();
279   Builder.setInsertPt(*MI.getParent(), MI);
280   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
281 
282   // Note: IsUndef is sort of redundant. We could have determine it by
283   // checking that at all Ops are undef.  Alternatively, we could have
284   // generate a build_vector of undefs and rely on another combine to
285   // clean that up.  For now, given we already gather this information
286   // in tryCombineConcatVectors, just save compile time and issue the
287   // right thing.
288   if (IsUndef)
289     Builder.buildUndef(NewDstReg);
290   else
291     Builder.buildBuildVector(NewDstReg, Ops);
292   MI.eraseFromParent();
293   replaceRegWith(MRI, DstReg, NewDstReg);
294 }
295 
296 bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
297   SmallVector<Register, 4> Ops;
298   if (matchCombineShuffleVector(MI, Ops)) {
299     applyCombineShuffleVector(MI, Ops);
300     return true;
301   }
302   return false;
303 }
304 
305 bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
306                                                SmallVectorImpl<Register> &Ops) {
307   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
308          "Invalid instruction kind");
309   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
310   Register Src1 = MI.getOperand(1).getReg();
311   LLT SrcType = MRI.getType(Src1);
312   // As bizarre as it may look, shuffle vector can actually produce
313   // scalar! This is because at the IR level a <1 x ty> shuffle
314   // vector is perfectly valid.
315   unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
316   unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
317 
318   // If the resulting vector is smaller than the size of the source
319   // vectors being concatenated, we won't be able to replace the
320   // shuffle vector into a concat_vectors.
321   //
322   // Note: We may still be able to produce a concat_vectors fed by
323   //       extract_vector_elt and so on. It is less clear that would
324   //       be better though, so don't bother for now.
325   //
326   // If the destination is a scalar, the size of the sources doesn't
327   // matter. we will lower the shuffle to a plain copy. This will
328   // work only if the source and destination have the same size. But
329   // that's covered by the next condition.
330   //
331   // TODO: If the size between the source and destination don't match
332   //       we could still emit an extract vector element in that case.
333   if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
334     return false;
335 
336   // Check that the shuffle mask can be broken evenly between the
337   // different sources.
338   if (DstNumElts % SrcNumElts != 0)
339     return false;
340 
341   // Mask length is a multiple of the source vector length.
342   // Check if the shuffle is some kind of concatenation of the input
343   // vectors.
344   unsigned NumConcat = DstNumElts / SrcNumElts;
345   SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
346   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
347   for (unsigned i = 0; i != DstNumElts; ++i) {
348     int Idx = Mask[i];
349     // Undef value.
350     if (Idx < 0)
351       continue;
352     // Ensure the indices in each SrcType sized piece are sequential and that
353     // the same source is used for the whole piece.
354     if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
355         (ConcatSrcs[i / SrcNumElts] >= 0 &&
356          ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
357       return false;
358     // Remember which source this index came from.
359     ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
360   }
361 
362   // The shuffle is concatenating multiple vectors together.
363   // Collect the different operands for that.
364   Register UndefReg;
365   Register Src2 = MI.getOperand(2).getReg();
366   for (auto Src : ConcatSrcs) {
367     if (Src < 0) {
368       if (!UndefReg) {
369         Builder.setInsertPt(*MI.getParent(), MI);
370         UndefReg = Builder.buildUndef(SrcType).getReg(0);
371       }
372       Ops.push_back(UndefReg);
373     } else if (Src == 0)
374       Ops.push_back(Src1);
375     else
376       Ops.push_back(Src2);
377   }
378   return true;
379 }
380 
381 void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
382                                                const ArrayRef<Register> Ops) {
383   Register DstReg = MI.getOperand(0).getReg();
384   Builder.setInsertPt(*MI.getParent(), MI);
385   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
386 
387   if (Ops.size() == 1)
388     Builder.buildCopy(NewDstReg, Ops[0]);
389   else
390     Builder.buildMerge(NewDstReg, Ops);
391 
392   MI.eraseFromParent();
393   replaceRegWith(MRI, DstReg, NewDstReg);
394 }
395 
396 namespace {
397 
398 /// Select a preference between two uses. CurrentUse is the current preference
399 /// while *ForCandidate is attributes of the candidate under consideration.
400 PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse,
401                                   const LLT TyForCandidate,
402                                   unsigned OpcodeForCandidate,
403                                   MachineInstr *MIForCandidate) {
404   if (!CurrentUse.Ty.isValid()) {
405     if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
406         CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
407       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
408     return CurrentUse;
409   }
410 
411   // We permit the extend to hoist through basic blocks but this is only
412   // sensible if the target has extending loads. If you end up lowering back
413   // into a load and extend during the legalizer then the end result is
414   // hoisting the extend up to the load.
415 
416   // Prefer defined extensions to undefined extensions as these are more
417   // likely to reduce the number of instructions.
418   if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
419       CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
420     return CurrentUse;
421   else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
422            OpcodeForCandidate != TargetOpcode::G_ANYEXT)
423     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
424 
425   // Prefer sign extensions to zero extensions as sign-extensions tend to be
426   // more expensive.
427   if (CurrentUse.Ty == TyForCandidate) {
428     if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
429         OpcodeForCandidate == TargetOpcode::G_ZEXT)
430       return CurrentUse;
431     else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
432              OpcodeForCandidate == TargetOpcode::G_SEXT)
433       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
434   }
435 
436   // This is potentially target specific. We've chosen the largest type
437   // because G_TRUNC is usually free. One potential catch with this is that
438   // some targets have a reduced number of larger registers than smaller
439   // registers and this choice potentially increases the live-range for the
440   // larger value.
441   if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
442     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
443   }
444   return CurrentUse;
445 }
446 
447 /// Find a suitable place to insert some instructions and insert them. This
448 /// function accounts for special cases like inserting before a PHI node.
449 /// The current strategy for inserting before PHI's is to duplicate the
450 /// instructions for each predecessor. However, while that's ok for G_TRUNC
451 /// on most targets since it generally requires no code, other targets/cases may
452 /// want to try harder to find a dominating block.
453 static void InsertInsnsWithoutSideEffectsBeforeUse(
454     MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
455     std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
456                        MachineOperand &UseMO)>
457         Inserter) {
458   MachineInstr &UseMI = *UseMO.getParent();
459 
460   MachineBasicBlock *InsertBB = UseMI.getParent();
461 
462   // If the use is a PHI then we want the predecessor block instead.
463   if (UseMI.isPHI()) {
464     MachineOperand *PredBB = std::next(&UseMO);
465     InsertBB = PredBB->getMBB();
466   }
467 
468   // If the block is the same block as the def then we want to insert just after
469   // the def instead of at the start of the block.
470   if (InsertBB == DefMI.getParent()) {
471     MachineBasicBlock::iterator InsertPt = &DefMI;
472     Inserter(InsertBB, std::next(InsertPt), UseMO);
473     return;
474   }
475 
476   // Otherwise we want the start of the BB
477   Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
478 }
479 } // end anonymous namespace
480 
481 bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
482   PreferredTuple Preferred;
483   if (matchCombineExtendingLoads(MI, Preferred)) {
484     applyCombineExtendingLoads(MI, Preferred);
485     return true;
486   }
487   return false;
488 }
489 
490 bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
491                                                 PreferredTuple &Preferred) {
492   // We match the loads and follow the uses to the extend instead of matching
493   // the extends and following the def to the load. This is because the load
494   // must remain in the same position for correctness (unless we also add code
495   // to find a safe place to sink it) whereas the extend is freely movable.
496   // It also prevents us from duplicating the load for the volatile case or just
497   // for performance.
498   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
499   if (!LoadMI)
500     return false;
501 
502   Register LoadReg = LoadMI->getDstReg();
503 
504   LLT LoadValueTy = MRI.getType(LoadReg);
505   if (!LoadValueTy.isScalar())
506     return false;
507 
508   // Most architectures are going to legalize <s8 loads into at least a 1 byte
509   // load, and the MMOs can only describe memory accesses in multiples of bytes.
510   // If we try to perform extload combining on those, we can end up with
511   // %a(s8) = extload %ptr (load 1 byte from %ptr)
512   // ... which is an illegal extload instruction.
513   if (LoadValueTy.getSizeInBits() < 8)
514     return false;
515 
516   // For non power-of-2 types, they will very likely be legalized into multiple
517   // loads. Don't bother trying to match them into extending loads.
518   if (!isPowerOf2_32(LoadValueTy.getSizeInBits()))
519     return false;
520 
521   // Find the preferred type aside from the any-extends (unless it's the only
522   // one) and non-extending ops. We'll emit an extending load to that type and
523   // and emit a variant of (extend (trunc X)) for the others according to the
524   // relative type sizes. At the same time, pick an extend to use based on the
525   // extend involved in the chosen type.
526   unsigned PreferredOpcode =
527       isa<GLoad>(&MI)
528           ? TargetOpcode::G_ANYEXT
529           : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
530   Preferred = {LLT(), PreferredOpcode, nullptr};
531   for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
532     if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
533         UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
534         (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
535       const auto &MMO = LoadMI->getMMO();
536       // For atomics, only form anyextending loads.
537       if (MMO.isAtomic() && UseMI.getOpcode() != TargetOpcode::G_ANYEXT)
538         continue;
539       // Check for legality.
540       if (LI) {
541         LegalityQuery::MemDesc MMDesc(MMO);
542         LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
543         LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
544         if (LI->getAction({LoadMI->getOpcode(), {UseTy, SrcTy}, {MMDesc}})
545                 .Action != LegalizeActions::Legal)
546           continue;
547       }
548       Preferred = ChoosePreferredUse(Preferred,
549                                      MRI.getType(UseMI.getOperand(0).getReg()),
550                                      UseMI.getOpcode(), &UseMI);
551     }
552   }
553 
554   // There were no extends
555   if (!Preferred.MI)
556     return false;
557   // It should be impossible to chose an extend without selecting a different
558   // type since by definition the result of an extend is larger.
559   assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
560 
561   LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
562   return true;
563 }
564 
565 void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
566                                                 PreferredTuple &Preferred) {
567   // Rewrite the load to the chosen extending load.
568   Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
569 
570   // Inserter to insert a truncate back to the original type at a given point
571   // with some basic CSE to limit truncate duplication to one per BB.
572   DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
573   auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
574                            MachineBasicBlock::iterator InsertBefore,
575                            MachineOperand &UseMO) {
576     MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
577     if (PreviouslyEmitted) {
578       Observer.changingInstr(*UseMO.getParent());
579       UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
580       Observer.changedInstr(*UseMO.getParent());
581       return;
582     }
583 
584     Builder.setInsertPt(*InsertIntoBB, InsertBefore);
585     Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
586     MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
587     EmittedInsns[InsertIntoBB] = NewMI;
588     replaceRegOpWith(MRI, UseMO, NewDstReg);
589   };
590 
591   Observer.changingInstr(MI);
592   MI.setDesc(
593       Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT
594                                ? TargetOpcode::G_SEXTLOAD
595                                : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT
596                                      ? TargetOpcode::G_ZEXTLOAD
597                                      : TargetOpcode::G_LOAD));
598 
599   // Rewrite all the uses to fix up the types.
600   auto &LoadValue = MI.getOperand(0);
601   SmallVector<MachineOperand *, 4> Uses;
602   for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
603     Uses.push_back(&UseMO);
604 
605   for (auto *UseMO : Uses) {
606     MachineInstr *UseMI = UseMO->getParent();
607 
608     // If the extend is compatible with the preferred extend then we should fix
609     // up the type and extend so that it uses the preferred use.
610     if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
611         UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
612       Register UseDstReg = UseMI->getOperand(0).getReg();
613       MachineOperand &UseSrcMO = UseMI->getOperand(1);
614       const LLT UseDstTy = MRI.getType(UseDstReg);
615       if (UseDstReg != ChosenDstReg) {
616         if (Preferred.Ty == UseDstTy) {
617           // If the use has the same type as the preferred use, then merge
618           // the vregs and erase the extend. For example:
619           //    %1:_(s8) = G_LOAD ...
620           //    %2:_(s32) = G_SEXT %1(s8)
621           //    %3:_(s32) = G_ANYEXT %1(s8)
622           //    ... = ... %3(s32)
623           // rewrites to:
624           //    %2:_(s32) = G_SEXTLOAD ...
625           //    ... = ... %2(s32)
626           replaceRegWith(MRI, UseDstReg, ChosenDstReg);
627           Observer.erasingInstr(*UseMO->getParent());
628           UseMO->getParent()->eraseFromParent();
629         } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
630           // If the preferred size is smaller, then keep the extend but extend
631           // from the result of the extending load. For example:
632           //    %1:_(s8) = G_LOAD ...
633           //    %2:_(s32) = G_SEXT %1(s8)
634           //    %3:_(s64) = G_ANYEXT %1(s8)
635           //    ... = ... %3(s64)
636           /// rewrites to:
637           //    %2:_(s32) = G_SEXTLOAD ...
638           //    %3:_(s64) = G_ANYEXT %2:_(s32)
639           //    ... = ... %3(s64)
640           replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
641         } else {
642           // If the preferred size is large, then insert a truncate. For
643           // example:
644           //    %1:_(s8) = G_LOAD ...
645           //    %2:_(s64) = G_SEXT %1(s8)
646           //    %3:_(s32) = G_ZEXT %1(s8)
647           //    ... = ... %3(s32)
648           /// rewrites to:
649           //    %2:_(s64) = G_SEXTLOAD ...
650           //    %4:_(s8) = G_TRUNC %2:_(s32)
651           //    %3:_(s64) = G_ZEXT %2:_(s8)
652           //    ... = ... %3(s64)
653           InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
654                                                  InsertTruncAt);
655         }
656         continue;
657       }
658       // The use is (one of) the uses of the preferred use we chose earlier.
659       // We're going to update the load to def this value later so just erase
660       // the old extend.
661       Observer.erasingInstr(*UseMO->getParent());
662       UseMO->getParent()->eraseFromParent();
663       continue;
664     }
665 
666     // The use isn't an extend. Truncate back to the type we originally loaded.
667     // This is free on many targets.
668     InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
669   }
670 
671   MI.getOperand(0).setReg(ChosenDstReg);
672   Observer.changedInstr(MI);
673 }
674 
675 bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI,
676                                                  BuildFnTy &MatchInfo) {
677   assert(MI.getOpcode() == TargetOpcode::G_AND);
678 
679   // If we have the following code:
680   //  %mask = G_CONSTANT 255
681   //  %ld   = G_LOAD %ptr, (load s16)
682   //  %and  = G_AND %ld, %mask
683   //
684   // Try to fold it into
685   //   %ld = G_ZEXTLOAD %ptr, (load s8)
686 
687   Register Dst = MI.getOperand(0).getReg();
688   if (MRI.getType(Dst).isVector())
689     return false;
690 
691   auto MaybeMask =
692       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
693   if (!MaybeMask)
694     return false;
695 
696   APInt MaskVal = MaybeMask->Value;
697 
698   if (!MaskVal.isMask())
699     return false;
700 
701   Register SrcReg = MI.getOperand(1).getReg();
702   GAnyLoad *LoadMI = getOpcodeDef<GAnyLoad>(SrcReg, MRI);
703   if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()) ||
704       !LoadMI->isSimple())
705     return false;
706 
707   Register LoadReg = LoadMI->getDstReg();
708   LLT LoadTy = MRI.getType(LoadReg);
709   Register PtrReg = LoadMI->getPointerReg();
710   uint64_t LoadSizeBits = LoadMI->getMemSizeInBits();
711   unsigned MaskSizeBits = MaskVal.countTrailingOnes();
712 
713   // The mask may not be larger than the in-memory type, as it might cover sign
714   // extended bits
715   if (MaskSizeBits > LoadSizeBits)
716     return false;
717 
718   // If the mask covers the whole destination register, there's nothing to
719   // extend
720   if (MaskSizeBits >= LoadTy.getSizeInBits())
721     return false;
722 
723   // Most targets cannot deal with loads of size < 8 and need to re-legalize to
724   // at least byte loads. Avoid creating such loads here
725   if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
726     return false;
727 
728   const MachineMemOperand &MMO = LoadMI->getMMO();
729   LegalityQuery::MemDesc MemDesc(MMO);
730   MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
731   if (!isLegalOrBeforeLegalizer(
732           {TargetOpcode::G_ZEXTLOAD, {LoadTy, MRI.getType(PtrReg)}, {MemDesc}}))
733     return false;
734 
735   MatchInfo = [=](MachineIRBuilder &B) {
736     B.setInstrAndDebugLoc(*LoadMI);
737     auto &MF = B.getMF();
738     auto PtrInfo = MMO.getPointerInfo();
739     auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MaskSizeBits / 8);
740     B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
741   };
742   return true;
743 }
744 
745 bool CombinerHelper::isPredecessor(const MachineInstr &DefMI,
746                                    const MachineInstr &UseMI) {
747   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
748          "shouldn't consider debug uses");
749   assert(DefMI.getParent() == UseMI.getParent());
750   if (&DefMI == &UseMI)
751     return true;
752   const MachineBasicBlock &MBB = *DefMI.getParent();
753   auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
754     return &MI == &DefMI || &MI == &UseMI;
755   });
756   if (DefOrUse == MBB.end())
757     llvm_unreachable("Block must contain both DefMI and UseMI!");
758   return &*DefOrUse == &DefMI;
759 }
760 
761 bool CombinerHelper::dominates(const MachineInstr &DefMI,
762                                const MachineInstr &UseMI) {
763   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
764          "shouldn't consider debug uses");
765   if (MDT)
766     return MDT->dominates(&DefMI, &UseMI);
767   else if (DefMI.getParent() != UseMI.getParent())
768     return false;
769 
770   return isPredecessor(DefMI, UseMI);
771 }
772 
773 bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) {
774   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
775   Register SrcReg = MI.getOperand(1).getReg();
776   Register LoadUser = SrcReg;
777 
778   if (MRI.getType(SrcReg).isVector())
779     return false;
780 
781   Register TruncSrc;
782   if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
783     LoadUser = TruncSrc;
784 
785   uint64_t SizeInBits = MI.getOperand(2).getImm();
786   // If the source is a G_SEXTLOAD from the same bit width, then we don't
787   // need any extend at all, just a truncate.
788   if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
789     // If truncating more than the original extended value, abort.
790     auto LoadSizeBits = LoadMI->getMemSizeInBits();
791     if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits)
792       return false;
793     if (LoadSizeBits == SizeInBits)
794       return true;
795   }
796   return false;
797 }
798 
799 void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) {
800   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
801   Builder.setInstrAndDebugLoc(MI);
802   Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
803   MI.eraseFromParent();
804 }
805 
806 bool CombinerHelper::matchSextInRegOfLoad(
807     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
808   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
809 
810   // Only supports scalars for now.
811   if (MRI.getType(MI.getOperand(0).getReg()).isVector())
812     return false;
813 
814   Register SrcReg = MI.getOperand(1).getReg();
815   auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI);
816   if (!LoadDef || !MRI.hasOneNonDBGUse(LoadDef->getOperand(0).getReg()) ||
817       !LoadDef->isSimple())
818     return false;
819 
820   // If the sign extend extends from a narrower width than the load's width,
821   // then we can narrow the load width when we combine to a G_SEXTLOAD.
822   // Avoid widening the load at all.
823   unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(),
824                                   LoadDef->getMemSizeInBits());
825 
826   // Don't generate G_SEXTLOADs with a < 1 byte width.
827   if (NewSizeBits < 8)
828     return false;
829   // Don't bother creating a non-power-2 sextload, it will likely be broken up
830   // anyway for most targets.
831   if (!isPowerOf2_32(NewSizeBits))
832     return false;
833 
834   const MachineMemOperand &MMO = LoadDef->getMMO();
835   LegalityQuery::MemDesc MMDesc(MMO);
836   MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
837   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD,
838                                  {MRI.getType(LoadDef->getDstReg()),
839                                   MRI.getType(LoadDef->getPointerReg())},
840                                  {MMDesc}}))
841     return false;
842 
843   MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits);
844   return true;
845 }
846 
847 void CombinerHelper::applySextInRegOfLoad(
848     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
849   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
850   Register LoadReg;
851   unsigned ScalarSizeBits;
852   std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
853   GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
854 
855   // If we have the following:
856   // %ld = G_LOAD %ptr, (load 2)
857   // %ext = G_SEXT_INREG %ld, 8
858   //    ==>
859   // %ld = G_SEXTLOAD %ptr (load 1)
860 
861   auto &MMO = LoadDef->getMMO();
862   Builder.setInstrAndDebugLoc(*LoadDef);
863   auto &MF = Builder.getMF();
864   auto PtrInfo = MMO.getPointerInfo();
865   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
866   Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
867                          LoadDef->getPointerReg(), *NewMMO);
868   MI.eraseFromParent();
869 }
870 
871 bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr,
872                                             Register &Base, Register &Offset) {
873   auto &MF = *MI.getParent()->getParent();
874   const auto &TLI = *MF.getSubtarget().getTargetLowering();
875 
876 #ifndef NDEBUG
877   unsigned Opcode = MI.getOpcode();
878   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
879          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
880 #endif
881 
882   Base = MI.getOperand(1).getReg();
883   MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base);
884   if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
885     return false;
886 
887   LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI);
888   // FIXME: The following use traversal needs a bail out for patholigical cases.
889   for (auto &Use : MRI.use_nodbg_instructions(Base)) {
890     if (Use.getOpcode() != TargetOpcode::G_PTR_ADD)
891       continue;
892 
893     Offset = Use.getOperand(2).getReg();
894     if (!ForceLegalIndexing &&
895         !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) {
896       LLVM_DEBUG(dbgs() << "    Ignoring candidate with illegal addrmode: "
897                         << Use);
898       continue;
899     }
900 
901     // Make sure the offset calculation is before the potentially indexed op.
902     // FIXME: we really care about dependency here. The offset calculation might
903     // be movable.
904     MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset);
905     if (!OffsetDef || !dominates(*OffsetDef, MI)) {
906       LLVM_DEBUG(dbgs() << "    Ignoring candidate with offset after mem-op: "
907                         << Use);
908       continue;
909     }
910 
911     // FIXME: check whether all uses of Base are load/store with foldable
912     // addressing modes. If so, using the normal addr-modes is better than
913     // forming an indexed one.
914 
915     bool MemOpDominatesAddrUses = true;
916     for (auto &PtrAddUse :
917          MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) {
918       if (!dominates(MI, PtrAddUse)) {
919         MemOpDominatesAddrUses = false;
920         break;
921       }
922     }
923 
924     if (!MemOpDominatesAddrUses) {
925       LLVM_DEBUG(
926           dbgs() << "    Ignoring candidate as memop does not dominate uses: "
927                  << Use);
928       continue;
929     }
930 
931     LLVM_DEBUG(dbgs() << "    Found match: " << Use);
932     Addr = Use.getOperand(0).getReg();
933     return true;
934   }
935 
936   return false;
937 }
938 
939 bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr,
940                                            Register &Base, Register &Offset) {
941   auto &MF = *MI.getParent()->getParent();
942   const auto &TLI = *MF.getSubtarget().getTargetLowering();
943 
944 #ifndef NDEBUG
945   unsigned Opcode = MI.getOpcode();
946   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
947          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
948 #endif
949 
950   Addr = MI.getOperand(1).getReg();
951   MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI);
952   if (!AddrDef || MRI.hasOneNonDBGUse(Addr))
953     return false;
954 
955   Base = AddrDef->getOperand(1).getReg();
956   Offset = AddrDef->getOperand(2).getReg();
957 
958   LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI);
959 
960   if (!ForceLegalIndexing &&
961       !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) {
962     LLVM_DEBUG(dbgs() << "    Skipping, not legal for target");
963     return false;
964   }
965 
966   MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
967   if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
968     LLVM_DEBUG(dbgs() << "    Skipping, frame index would need copy anyway.");
969     return false;
970   }
971 
972   if (MI.getOpcode() == TargetOpcode::G_STORE) {
973     // Would require a copy.
974     if (Base == MI.getOperand(0).getReg()) {
975       LLVM_DEBUG(dbgs() << "    Skipping, storing base so need copy anyway.");
976       return false;
977     }
978 
979     // We're expecting one use of Addr in MI, but it could also be the
980     // value stored, which isn't actually dominated by the instruction.
981     if (MI.getOperand(0).getReg() == Addr) {
982       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses");
983       return false;
984     }
985   }
986 
987   // FIXME: check whether all uses of the base pointer are constant PtrAdds.
988   // That might allow us to end base's liveness here by adjusting the constant.
989 
990   for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) {
991     if (!dominates(MI, UseMI)) {
992       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses.");
993       return false;
994     }
995   }
996 
997   return true;
998 }
999 
1000 bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) {
1001   IndexedLoadStoreMatchInfo MatchInfo;
1002   if (matchCombineIndexedLoadStore(MI, MatchInfo)) {
1003     applyCombineIndexedLoadStore(MI, MatchInfo);
1004     return true;
1005   }
1006   return false;
1007 }
1008 
1009 bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1010   unsigned Opcode = MI.getOpcode();
1011   if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD &&
1012       Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE)
1013     return false;
1014 
1015   // For now, no targets actually support these opcodes so don't waste time
1016   // running these unless we're forced to for testing.
1017   if (!ForceLegalIndexing)
1018     return false;
1019 
1020   MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1021                                           MatchInfo.Offset);
1022   if (!MatchInfo.IsPre &&
1023       !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1024                               MatchInfo.Offset))
1025     return false;
1026 
1027   return true;
1028 }
1029 
1030 void CombinerHelper::applyCombineIndexedLoadStore(
1031     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1032   MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
1033   MachineIRBuilder MIRBuilder(MI);
1034   unsigned Opcode = MI.getOpcode();
1035   bool IsStore = Opcode == TargetOpcode::G_STORE;
1036   unsigned NewOpcode;
1037   switch (Opcode) {
1038   case TargetOpcode::G_LOAD:
1039     NewOpcode = TargetOpcode::G_INDEXED_LOAD;
1040     break;
1041   case TargetOpcode::G_SEXTLOAD:
1042     NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD;
1043     break;
1044   case TargetOpcode::G_ZEXTLOAD:
1045     NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD;
1046     break;
1047   case TargetOpcode::G_STORE:
1048     NewOpcode = TargetOpcode::G_INDEXED_STORE;
1049     break;
1050   default:
1051     llvm_unreachable("Unknown load/store opcode");
1052   }
1053 
1054   auto MIB = MIRBuilder.buildInstr(NewOpcode);
1055   if (IsStore) {
1056     MIB.addDef(MatchInfo.Addr);
1057     MIB.addUse(MI.getOperand(0).getReg());
1058   } else {
1059     MIB.addDef(MI.getOperand(0).getReg());
1060     MIB.addDef(MatchInfo.Addr);
1061   }
1062 
1063   MIB.addUse(MatchInfo.Base);
1064   MIB.addUse(MatchInfo.Offset);
1065   MIB.addImm(MatchInfo.IsPre);
1066   MI.eraseFromParent();
1067   AddrDef.eraseFromParent();
1068 
1069   LLVM_DEBUG(dbgs() << "    Combinined to indexed operation");
1070 }
1071 
1072 bool CombinerHelper::matchCombineDivRem(MachineInstr &MI,
1073                                         MachineInstr *&OtherMI) {
1074   unsigned Opcode = MI.getOpcode();
1075   bool IsDiv, IsSigned;
1076 
1077   switch (Opcode) {
1078   default:
1079     llvm_unreachable("Unexpected opcode!");
1080   case TargetOpcode::G_SDIV:
1081   case TargetOpcode::G_UDIV: {
1082     IsDiv = true;
1083     IsSigned = Opcode == TargetOpcode::G_SDIV;
1084     break;
1085   }
1086   case TargetOpcode::G_SREM:
1087   case TargetOpcode::G_UREM: {
1088     IsDiv = false;
1089     IsSigned = Opcode == TargetOpcode::G_SREM;
1090     break;
1091   }
1092   }
1093 
1094   Register Src1 = MI.getOperand(1).getReg();
1095   unsigned DivOpcode, RemOpcode, DivremOpcode;
1096   if (IsSigned) {
1097     DivOpcode = TargetOpcode::G_SDIV;
1098     RemOpcode = TargetOpcode::G_SREM;
1099     DivremOpcode = TargetOpcode::G_SDIVREM;
1100   } else {
1101     DivOpcode = TargetOpcode::G_UDIV;
1102     RemOpcode = TargetOpcode::G_UREM;
1103     DivremOpcode = TargetOpcode::G_UDIVREM;
1104   }
1105 
1106   if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
1107     return false;
1108 
1109   // Combine:
1110   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1111   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1112   // into:
1113   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1114 
1115   // Combine:
1116   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1117   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1118   // into:
1119   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1120 
1121   for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
1122     if (MI.getParent() == UseMI.getParent() &&
1123         ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
1124          (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
1125         matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2))) {
1126       OtherMI = &UseMI;
1127       return true;
1128     }
1129   }
1130 
1131   return false;
1132 }
1133 
1134 void CombinerHelper::applyCombineDivRem(MachineInstr &MI,
1135                                         MachineInstr *&OtherMI) {
1136   unsigned Opcode = MI.getOpcode();
1137   assert(OtherMI && "OtherMI shouldn't be empty.");
1138 
1139   Register DestDivReg, DestRemReg;
1140   if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
1141     DestDivReg = MI.getOperand(0).getReg();
1142     DestRemReg = OtherMI->getOperand(0).getReg();
1143   } else {
1144     DestDivReg = OtherMI->getOperand(0).getReg();
1145     DestRemReg = MI.getOperand(0).getReg();
1146   }
1147 
1148   bool IsSigned =
1149       Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
1150 
1151   // Check which instruction is first in the block so we don't break def-use
1152   // deps by "moving" the instruction incorrectly.
1153   if (dominates(MI, *OtherMI))
1154     Builder.setInstrAndDebugLoc(MI);
1155   else
1156     Builder.setInstrAndDebugLoc(*OtherMI);
1157 
1158   Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
1159                               : TargetOpcode::G_UDIVREM,
1160                      {DestDivReg, DestRemReg},
1161                      {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()});
1162   MI.eraseFromParent();
1163   OtherMI->eraseFromParent();
1164 }
1165 
1166 bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI,
1167                                                    MachineInstr *&BrCond) {
1168   assert(MI.getOpcode() == TargetOpcode::G_BR);
1169 
1170   // Try to match the following:
1171   // bb1:
1172   //   G_BRCOND %c1, %bb2
1173   //   G_BR %bb3
1174   // bb2:
1175   // ...
1176   // bb3:
1177 
1178   // The above pattern does not have a fall through to the successor bb2, always
1179   // resulting in a branch no matter which path is taken. Here we try to find
1180   // and replace that pattern with conditional branch to bb3 and otherwise
1181   // fallthrough to bb2. This is generally better for branch predictors.
1182 
1183   MachineBasicBlock *MBB = MI.getParent();
1184   MachineBasicBlock::iterator BrIt(MI);
1185   if (BrIt == MBB->begin())
1186     return false;
1187   assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
1188 
1189   BrCond = &*std::prev(BrIt);
1190   if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
1191     return false;
1192 
1193   // Check that the next block is the conditional branch target. Also make sure
1194   // that it isn't the same as the G_BR's target (otherwise, this will loop.)
1195   MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
1196   return BrCondTarget != MI.getOperand(0).getMBB() &&
1197          MBB->isLayoutSuccessor(BrCondTarget);
1198 }
1199 
1200 void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI,
1201                                                    MachineInstr *&BrCond) {
1202   MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
1203   Builder.setInstrAndDebugLoc(*BrCond);
1204   LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
1205   // FIXME: Does int/fp matter for this? If so, we might need to restrict
1206   // this to i1 only since we might not know for sure what kind of
1207   // compare generated the condition value.
1208   auto True = Builder.buildConstant(
1209       Ty, getICmpTrueVal(getTargetLowering(), false, false));
1210   auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
1211 
1212   auto *FallthroughBB = BrCond->getOperand(1).getMBB();
1213   Observer.changingInstr(MI);
1214   MI.getOperand(0).setMBB(FallthroughBB);
1215   Observer.changedInstr(MI);
1216 
1217   // Change the conditional branch to use the inverted condition and
1218   // new target block.
1219   Observer.changingInstr(*BrCond);
1220   BrCond->getOperand(0).setReg(Xor.getReg(0));
1221   BrCond->getOperand(1).setMBB(BrTarget);
1222   Observer.changedInstr(*BrCond);
1223 }
1224 
1225 static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
1226   if (Ty.isVector())
1227     return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
1228                                 Ty.getNumElements());
1229   return IntegerType::get(C, Ty.getSizeInBits());
1230 }
1231 
1232 bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) {
1233   MachineIRBuilder HelperBuilder(MI);
1234   GISelObserverWrapper DummyObserver;
1235   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1236   return Helper.lowerMemcpyInline(MI) ==
1237          LegalizerHelper::LegalizeResult::Legalized;
1238 }
1239 
1240 bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
1241   MachineIRBuilder HelperBuilder(MI);
1242   GISelObserverWrapper DummyObserver;
1243   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1244   return Helper.lowerMemCpyFamily(MI, MaxLen) ==
1245          LegalizerHelper::LegalizeResult::Legalized;
1246 }
1247 
1248 static Optional<APFloat> constantFoldFpUnary(unsigned Opcode, LLT DstTy,
1249                                              const Register Op,
1250                                              const MachineRegisterInfo &MRI) {
1251   const ConstantFP *MaybeCst = getConstantFPVRegVal(Op, MRI);
1252   if (!MaybeCst)
1253     return None;
1254 
1255   APFloat V = MaybeCst->getValueAPF();
1256   switch (Opcode) {
1257   default:
1258     llvm_unreachable("Unexpected opcode!");
1259   case TargetOpcode::G_FNEG: {
1260     V.changeSign();
1261     return V;
1262   }
1263   case TargetOpcode::G_FABS: {
1264     V.clearSign();
1265     return V;
1266   }
1267   case TargetOpcode::G_FPTRUNC:
1268     break;
1269   case TargetOpcode::G_FSQRT: {
1270     bool Unused;
1271     V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
1272     V = APFloat(sqrt(V.convertToDouble()));
1273     break;
1274   }
1275   case TargetOpcode::G_FLOG2: {
1276     bool Unused;
1277     V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
1278     V = APFloat(log2(V.convertToDouble()));
1279     break;
1280   }
1281   }
1282   // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise,
1283   // `buildFConstant` will assert on size mismatch. Only `G_FPTRUNC`, `G_FSQRT`,
1284   // and `G_FLOG2` reach here.
1285   bool Unused;
1286   V.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven, &Unused);
1287   return V;
1288 }
1289 
1290 bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI,
1291                                                      Optional<APFloat> &Cst) {
1292   Register DstReg = MI.getOperand(0).getReg();
1293   Register SrcReg = MI.getOperand(1).getReg();
1294   LLT DstTy = MRI.getType(DstReg);
1295   Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI);
1296   return Cst.hasValue();
1297 }
1298 
1299 void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
1300                                                      Optional<APFloat> &Cst) {
1301   assert(Cst.hasValue() && "Optional is unexpectedly empty!");
1302   Builder.setInstrAndDebugLoc(MI);
1303   MachineFunction &MF = Builder.getMF();
1304   auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst);
1305   Register DstReg = MI.getOperand(0).getReg();
1306   Builder.buildFConstant(DstReg, *FPVal);
1307   MI.eraseFromParent();
1308 }
1309 
1310 bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
1311                                            PtrAddChain &MatchInfo) {
1312   // We're trying to match the following pattern:
1313   //   %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1314   //   %root = G_PTR_ADD %t1, G_CONSTANT imm2
1315   // -->
1316   //   %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1317 
1318   if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1319     return false;
1320 
1321   Register Add2 = MI.getOperand(1).getReg();
1322   Register Imm1 = MI.getOperand(2).getReg();
1323   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1324   if (!MaybeImmVal)
1325     return false;
1326 
1327   MachineInstr *Add2Def = MRI.getVRegDef(Add2);
1328   if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
1329     return false;
1330 
1331   Register Base = Add2Def->getOperand(1).getReg();
1332   Register Imm2 = Add2Def->getOperand(2).getReg();
1333   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1334   if (!MaybeImm2Val)
1335     return false;
1336 
1337   // Check if the new combined immediate forms an illegal addressing mode.
1338   // Do not combine if it was legal before but would get illegal.
1339   // To do so, we need to find a load/store user of the pointer to get
1340   // the access type.
1341   Type *AccessTy = nullptr;
1342   auto &MF = *MI.getMF();
1343   for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
1344     if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
1345       AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
1346                                MF.getFunction().getContext());
1347       break;
1348     }
1349   }
1350   TargetLoweringBase::AddrMode AMNew;
1351   APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
1352   AMNew.BaseOffs = CombinedImm.getSExtValue();
1353   if (AccessTy) {
1354     AMNew.HasBaseReg = true;
1355     TargetLoweringBase::AddrMode AMOld;
1356     AMOld.BaseOffs = MaybeImm2Val->Value.getSExtValue();
1357     AMOld.HasBaseReg = true;
1358     unsigned AS = MRI.getType(Add2).getAddressSpace();
1359     const auto &TLI = *MF.getSubtarget().getTargetLowering();
1360     if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
1361         !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
1362       return false;
1363   }
1364 
1365   // Pass the combined immediate to the apply function.
1366   MatchInfo.Imm = AMNew.BaseOffs;
1367   MatchInfo.Base = Base;
1368   MatchInfo.Bank = getRegBank(Imm2);
1369   return true;
1370 }
1371 
1372 void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
1373                                            PtrAddChain &MatchInfo) {
1374   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1375   MachineIRBuilder MIB(MI);
1376   LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1377   auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1378   setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
1379   Observer.changingInstr(MI);
1380   MI.getOperand(1).setReg(MatchInfo.Base);
1381   MI.getOperand(2).setReg(NewOffset.getReg(0));
1382   Observer.changedInstr(MI);
1383 }
1384 
1385 bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI,
1386                                           RegisterImmPair &MatchInfo) {
1387   // We're trying to match the following pattern with any of
1388   // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
1389   //   %t1 = SHIFT %base, G_CONSTANT imm1
1390   //   %root = SHIFT %t1, G_CONSTANT imm2
1391   // -->
1392   //   %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
1393 
1394   unsigned Opcode = MI.getOpcode();
1395   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1396           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1397           Opcode == TargetOpcode::G_USHLSAT) &&
1398          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1399 
1400   Register Shl2 = MI.getOperand(1).getReg();
1401   Register Imm1 = MI.getOperand(2).getReg();
1402   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1403   if (!MaybeImmVal)
1404     return false;
1405 
1406   MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2);
1407   if (Shl2Def->getOpcode() != Opcode)
1408     return false;
1409 
1410   Register Base = Shl2Def->getOperand(1).getReg();
1411   Register Imm2 = Shl2Def->getOperand(2).getReg();
1412   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1413   if (!MaybeImm2Val)
1414     return false;
1415 
1416   // Pass the combined immediate to the apply function.
1417   MatchInfo.Imm =
1418       (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue();
1419   MatchInfo.Reg = Base;
1420 
1421   // There is no simple replacement for a saturating unsigned left shift that
1422   // exceeds the scalar size.
1423   if (Opcode == TargetOpcode::G_USHLSAT &&
1424       MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
1425     return false;
1426 
1427   return true;
1428 }
1429 
1430 void CombinerHelper::applyShiftImmedChain(MachineInstr &MI,
1431                                           RegisterImmPair &MatchInfo) {
1432   unsigned Opcode = MI.getOpcode();
1433   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1434           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1435           Opcode == TargetOpcode::G_USHLSAT) &&
1436          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1437 
1438   Builder.setInstrAndDebugLoc(MI);
1439   LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1440   unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
1441   auto Imm = MatchInfo.Imm;
1442 
1443   if (Imm >= ScalarSizeInBits) {
1444     // Any logical shift that exceeds scalar size will produce zero.
1445     if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
1446       Builder.buildConstant(MI.getOperand(0), 0);
1447       MI.eraseFromParent();
1448       return;
1449     }
1450     // Arithmetic shift and saturating signed left shift have no effect beyond
1451     // scalar size.
1452     Imm = ScalarSizeInBits - 1;
1453   }
1454 
1455   LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
1456   Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
1457   Observer.changingInstr(MI);
1458   MI.getOperand(1).setReg(MatchInfo.Reg);
1459   MI.getOperand(2).setReg(NewImm);
1460   Observer.changedInstr(MI);
1461 }
1462 
1463 bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI,
1464                                               ShiftOfShiftedLogic &MatchInfo) {
1465   // We're trying to match the following pattern with any of
1466   // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination
1467   // with any of G_AND/G_OR/G_XOR logic instructions.
1468   //   %t1 = SHIFT %X, G_CONSTANT C0
1469   //   %t2 = LOGIC %t1, %Y
1470   //   %root = SHIFT %t2, G_CONSTANT C1
1471   // -->
1472   //   %t3 = SHIFT %X, G_CONSTANT (C0+C1)
1473   //   %t4 = SHIFT %Y, G_CONSTANT C1
1474   //   %root = LOGIC %t3, %t4
1475   unsigned ShiftOpcode = MI.getOpcode();
1476   assert((ShiftOpcode == TargetOpcode::G_SHL ||
1477           ShiftOpcode == TargetOpcode::G_ASHR ||
1478           ShiftOpcode == TargetOpcode::G_LSHR ||
1479           ShiftOpcode == TargetOpcode::G_USHLSAT ||
1480           ShiftOpcode == TargetOpcode::G_SSHLSAT) &&
1481          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1482 
1483   // Match a one-use bitwise logic op.
1484   Register LogicDest = MI.getOperand(1).getReg();
1485   if (!MRI.hasOneNonDBGUse(LogicDest))
1486     return false;
1487 
1488   MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest);
1489   unsigned LogicOpcode = LogicMI->getOpcode();
1490   if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
1491       LogicOpcode != TargetOpcode::G_XOR)
1492     return false;
1493 
1494   // Find a matching one-use shift by constant.
1495   const Register C1 = MI.getOperand(2).getReg();
1496   auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
1497   if (!MaybeImmVal)
1498     return false;
1499 
1500   const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
1501 
1502   auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
1503     // Shift should match previous one and should be a one-use.
1504     if (MI->getOpcode() != ShiftOpcode ||
1505         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1506       return false;
1507 
1508     // Must be a constant.
1509     auto MaybeImmVal =
1510         getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1511     if (!MaybeImmVal)
1512       return false;
1513 
1514     ShiftVal = MaybeImmVal->Value.getSExtValue();
1515     return true;
1516   };
1517 
1518   // Logic ops are commutative, so check each operand for a match.
1519   Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
1520   MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1);
1521   Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
1522   MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2);
1523   uint64_t C0Val;
1524 
1525   if (matchFirstShift(LogicMIOp1, C0Val)) {
1526     MatchInfo.LogicNonShiftReg = LogicMIReg2;
1527     MatchInfo.Shift2 = LogicMIOp1;
1528   } else if (matchFirstShift(LogicMIOp2, C0Val)) {
1529     MatchInfo.LogicNonShiftReg = LogicMIReg1;
1530     MatchInfo.Shift2 = LogicMIOp2;
1531   } else
1532     return false;
1533 
1534   MatchInfo.ValSum = C0Val + C1Val;
1535 
1536   // The fold is not valid if the sum of the shift values exceeds bitwidth.
1537   if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
1538     return false;
1539 
1540   MatchInfo.Logic = LogicMI;
1541   return true;
1542 }
1543 
1544 void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI,
1545                                               ShiftOfShiftedLogic &MatchInfo) {
1546   unsigned Opcode = MI.getOpcode();
1547   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1548           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT ||
1549           Opcode == TargetOpcode::G_SSHLSAT) &&
1550          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1551 
1552   LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
1553   LLT DestType = MRI.getType(MI.getOperand(0).getReg());
1554   Builder.setInstrAndDebugLoc(MI);
1555 
1556   Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
1557 
1558   Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
1559   Register Shift1 =
1560       Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
1561 
1562   Register Shift2Const = MI.getOperand(2).getReg();
1563   Register Shift2 = Builder
1564                         .buildInstr(Opcode, {DestType},
1565                                     {MatchInfo.LogicNonShiftReg, Shift2Const})
1566                         .getReg(0);
1567 
1568   Register Dest = MI.getOperand(0).getReg();
1569   Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
1570 
1571   // These were one use so it's safe to remove them.
1572   MatchInfo.Shift2->eraseFromParent();
1573   MatchInfo.Logic->eraseFromParent();
1574 
1575   MI.eraseFromParent();
1576 }
1577 
1578 bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
1579                                           unsigned &ShiftVal) {
1580   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
1581   auto MaybeImmVal =
1582       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1583   if (!MaybeImmVal)
1584     return false;
1585 
1586   ShiftVal = MaybeImmVal->Value.exactLogBase2();
1587   return (static_cast<int32_t>(ShiftVal) != -1);
1588 }
1589 
1590 void CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
1591                                           unsigned &ShiftVal) {
1592   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
1593   MachineIRBuilder MIB(MI);
1594   LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
1595   auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
1596   Observer.changingInstr(MI);
1597   MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
1598   MI.getOperand(2).setReg(ShiftCst.getReg(0));
1599   Observer.changedInstr(MI);
1600 }
1601 
1602 // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
1603 bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI,
1604                                              RegisterImmPair &MatchData) {
1605   assert(MI.getOpcode() == TargetOpcode::G_SHL && KB);
1606 
1607   Register LHS = MI.getOperand(1).getReg();
1608 
1609   Register ExtSrc;
1610   if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
1611       !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
1612       !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
1613     return false;
1614 
1615   // TODO: Should handle vector splat.
1616   Register RHS = MI.getOperand(2).getReg();
1617   auto MaybeShiftAmtVal = getIConstantVRegValWithLookThrough(RHS, MRI);
1618   if (!MaybeShiftAmtVal)
1619     return false;
1620 
1621   if (LI) {
1622     LLT SrcTy = MRI.getType(ExtSrc);
1623 
1624     // We only really care about the legality with the shifted value. We can
1625     // pick any type the constant shift amount, so ask the target what to
1626     // use. Otherwise we would have to guess and hope it is reported as legal.
1627     LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
1628     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
1629       return false;
1630   }
1631 
1632   int64_t ShiftAmt = MaybeShiftAmtVal->Value.getSExtValue();
1633   MatchData.Reg = ExtSrc;
1634   MatchData.Imm = ShiftAmt;
1635 
1636   unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countLeadingOnes();
1637   return MinLeadingZeros >= ShiftAmt;
1638 }
1639 
1640 void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI,
1641                                              const RegisterImmPair &MatchData) {
1642   Register ExtSrcReg = MatchData.Reg;
1643   int64_t ShiftAmtVal = MatchData.Imm;
1644 
1645   LLT ExtSrcTy = MRI.getType(ExtSrcReg);
1646   Builder.setInstrAndDebugLoc(MI);
1647   auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
1648   auto NarrowShift =
1649       Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
1650   Builder.buildZExt(MI.getOperand(0), NarrowShift);
1651   MI.eraseFromParent();
1652 }
1653 
1654 bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI,
1655                                               Register &MatchInfo) {
1656   GMerge &Merge = cast<GMerge>(MI);
1657   SmallVector<Register, 16> MergedValues;
1658   for (unsigned I = 0; I < Merge.getNumSources(); ++I)
1659     MergedValues.emplace_back(Merge.getSourceReg(I));
1660 
1661   auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI);
1662   if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources())
1663     return false;
1664 
1665   for (unsigned I = 0; I < MergedValues.size(); ++I)
1666     if (MergedValues[I] != Unmerge->getReg(I))
1667       return false;
1668 
1669   MatchInfo = Unmerge->getSourceReg();
1670   return true;
1671 }
1672 
1673 static Register peekThroughBitcast(Register Reg,
1674                                    const MachineRegisterInfo &MRI) {
1675   while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
1676     ;
1677 
1678   return Reg;
1679 }
1680 
1681 bool CombinerHelper::matchCombineUnmergeMergeToPlainValues(
1682     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1683   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1684          "Expected an unmerge");
1685   auto &Unmerge = cast<GUnmerge>(MI);
1686   Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
1687 
1688   auto *SrcInstr = getOpcodeDef<GMergeLikeOp>(SrcReg, MRI);
1689   if (!SrcInstr)
1690     return false;
1691 
1692   // Check the source type of the merge.
1693   LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
1694   LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
1695   bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
1696   if (SrcMergeTy != Dst0Ty && !SameSize)
1697     return false;
1698   // They are the same now (modulo a bitcast).
1699   // We can collect all the src registers.
1700   for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
1701     Operands.push_back(SrcInstr->getSourceReg(Idx));
1702   return true;
1703 }
1704 
1705 void CombinerHelper::applyCombineUnmergeMergeToPlainValues(
1706     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1707   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1708          "Expected an unmerge");
1709   assert((MI.getNumOperands() - 1 == Operands.size()) &&
1710          "Not enough operands to replace all defs");
1711   unsigned NumElems = MI.getNumOperands() - 1;
1712 
1713   LLT SrcTy = MRI.getType(Operands[0]);
1714   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
1715   bool CanReuseInputDirectly = DstTy == SrcTy;
1716   Builder.setInstrAndDebugLoc(MI);
1717   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1718     Register DstReg = MI.getOperand(Idx).getReg();
1719     Register SrcReg = Operands[Idx];
1720     if (CanReuseInputDirectly)
1721       replaceRegWith(MRI, DstReg, SrcReg);
1722     else
1723       Builder.buildCast(DstReg, SrcReg);
1724   }
1725   MI.eraseFromParent();
1726 }
1727 
1728 bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI,
1729                                                  SmallVectorImpl<APInt> &Csts) {
1730   unsigned SrcIdx = MI.getNumOperands() - 1;
1731   Register SrcReg = MI.getOperand(SrcIdx).getReg();
1732   MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg);
1733   if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT &&
1734       SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT)
1735     return false;
1736   // Break down the big constant in smaller ones.
1737   const MachineOperand &CstVal = SrcInstr->getOperand(1);
1738   APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT
1739                   ? CstVal.getCImm()->getValue()
1740                   : CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
1741 
1742   LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
1743   unsigned ShiftAmt = Dst0Ty.getSizeInBits();
1744   // Unmerge a constant.
1745   for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
1746     Csts.emplace_back(Val.trunc(ShiftAmt));
1747     Val = Val.lshr(ShiftAmt);
1748   }
1749 
1750   return true;
1751 }
1752 
1753 void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI,
1754                                                  SmallVectorImpl<APInt> &Csts) {
1755   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1756          "Expected an unmerge");
1757   assert((MI.getNumOperands() - 1 == Csts.size()) &&
1758          "Not enough operands to replace all defs");
1759   unsigned NumElems = MI.getNumOperands() - 1;
1760   Builder.setInstrAndDebugLoc(MI);
1761   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1762     Register DstReg = MI.getOperand(Idx).getReg();
1763     Builder.buildConstant(DstReg, Csts[Idx]);
1764   }
1765 
1766   MI.eraseFromParent();
1767 }
1768 
1769 bool CombinerHelper::matchCombineUnmergeUndef(
1770     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
1771   unsigned SrcIdx = MI.getNumOperands() - 1;
1772   Register SrcReg = MI.getOperand(SrcIdx).getReg();
1773   MatchInfo = [&MI](MachineIRBuilder &B) {
1774     unsigned NumElems = MI.getNumOperands() - 1;
1775     for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1776       Register DstReg = MI.getOperand(Idx).getReg();
1777       B.buildUndef(DstReg);
1778     }
1779   };
1780   return isa<GImplicitDef>(MRI.getVRegDef(SrcReg));
1781 }
1782 
1783 bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1784   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1785          "Expected an unmerge");
1786   // Check that all the lanes are dead except the first one.
1787   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1788     if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
1789       return false;
1790   }
1791   return true;
1792 }
1793 
1794 void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1795   Builder.setInstrAndDebugLoc(MI);
1796   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1797   // Truncating a vector is going to truncate every single lane,
1798   // whereas we want the full lowbits.
1799   // Do the operation on a scalar instead.
1800   LLT SrcTy = MRI.getType(SrcReg);
1801   if (SrcTy.isVector())
1802     SrcReg =
1803         Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0);
1804 
1805   Register Dst0Reg = MI.getOperand(0).getReg();
1806   LLT Dst0Ty = MRI.getType(Dst0Reg);
1807   if (Dst0Ty.isVector()) {
1808     auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg);
1809     Builder.buildCast(Dst0Reg, MIB);
1810   } else
1811     Builder.buildTrunc(Dst0Reg, SrcReg);
1812   MI.eraseFromParent();
1813 }
1814 
1815 bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) {
1816   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1817          "Expected an unmerge");
1818   Register Dst0Reg = MI.getOperand(0).getReg();
1819   LLT Dst0Ty = MRI.getType(Dst0Reg);
1820   // G_ZEXT on vector applies to each lane, so it will
1821   // affect all destinations. Therefore we won't be able
1822   // to simplify the unmerge to just the first definition.
1823   if (Dst0Ty.isVector())
1824     return false;
1825   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1826   LLT SrcTy = MRI.getType(SrcReg);
1827   if (SrcTy.isVector())
1828     return false;
1829 
1830   Register ZExtSrcReg;
1831   if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
1832     return false;
1833 
1834   // Finally we can replace the first definition with
1835   // a zext of the source if the definition is big enough to hold
1836   // all of ZExtSrc bits.
1837   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1838   return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
1839 }
1840 
1841 void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) {
1842   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1843          "Expected an unmerge");
1844 
1845   Register Dst0Reg = MI.getOperand(0).getReg();
1846 
1847   MachineInstr *ZExtInstr =
1848       MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg());
1849   assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT &&
1850          "Expecting a G_ZEXT");
1851 
1852   Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg();
1853   LLT Dst0Ty = MRI.getType(Dst0Reg);
1854   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1855 
1856   Builder.setInstrAndDebugLoc(MI);
1857 
1858   if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
1859     Builder.buildZExt(Dst0Reg, ZExtSrcReg);
1860   } else {
1861     assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
1862            "ZExt src doesn't fit in destination");
1863     replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
1864   }
1865 
1866   Register ZeroReg;
1867   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1868     if (!ZeroReg)
1869       ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
1870     replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
1871   }
1872   MI.eraseFromParent();
1873 }
1874 
1875 bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
1876                                                 unsigned TargetShiftSize,
1877                                                 unsigned &ShiftVal) {
1878   assert((MI.getOpcode() == TargetOpcode::G_SHL ||
1879           MI.getOpcode() == TargetOpcode::G_LSHR ||
1880           MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
1881 
1882   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
1883   if (Ty.isVector()) // TODO:
1884     return false;
1885 
1886   // Don't narrow further than the requested size.
1887   unsigned Size = Ty.getSizeInBits();
1888   if (Size <= TargetShiftSize)
1889     return false;
1890 
1891   auto MaybeImmVal =
1892       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1893   if (!MaybeImmVal)
1894     return false;
1895 
1896   ShiftVal = MaybeImmVal->Value.getSExtValue();
1897   return ShiftVal >= Size / 2 && ShiftVal < Size;
1898 }
1899 
1900 void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
1901                                                 const unsigned &ShiftVal) {
1902   Register DstReg = MI.getOperand(0).getReg();
1903   Register SrcReg = MI.getOperand(1).getReg();
1904   LLT Ty = MRI.getType(SrcReg);
1905   unsigned Size = Ty.getSizeInBits();
1906   unsigned HalfSize = Size / 2;
1907   assert(ShiftVal >= HalfSize);
1908 
1909   LLT HalfTy = LLT::scalar(HalfSize);
1910 
1911   Builder.setInstr(MI);
1912   auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
1913   unsigned NarrowShiftAmt = ShiftVal - HalfSize;
1914 
1915   if (MI.getOpcode() == TargetOpcode::G_LSHR) {
1916     Register Narrowed = Unmerge.getReg(1);
1917 
1918     //  dst = G_LSHR s64:x, C for C >= 32
1919     // =>
1920     //   lo, hi = G_UNMERGE_VALUES x
1921     //   dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
1922 
1923     if (NarrowShiftAmt != 0) {
1924       Narrowed = Builder.buildLShr(HalfTy, Narrowed,
1925         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
1926     }
1927 
1928     auto Zero = Builder.buildConstant(HalfTy, 0);
1929     Builder.buildMerge(DstReg, { Narrowed, Zero });
1930   } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
1931     Register Narrowed = Unmerge.getReg(0);
1932     //  dst = G_SHL s64:x, C for C >= 32
1933     // =>
1934     //   lo, hi = G_UNMERGE_VALUES x
1935     //   dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
1936     if (NarrowShiftAmt != 0) {
1937       Narrowed = Builder.buildShl(HalfTy, Narrowed,
1938         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
1939     }
1940 
1941     auto Zero = Builder.buildConstant(HalfTy, 0);
1942     Builder.buildMerge(DstReg, { Zero, Narrowed });
1943   } else {
1944     assert(MI.getOpcode() == TargetOpcode::G_ASHR);
1945     auto Hi = Builder.buildAShr(
1946       HalfTy, Unmerge.getReg(1),
1947       Builder.buildConstant(HalfTy, HalfSize - 1));
1948 
1949     if (ShiftVal == HalfSize) {
1950       // (G_ASHR i64:x, 32) ->
1951       //   G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
1952       Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi });
1953     } else if (ShiftVal == Size - 1) {
1954       // Don't need a second shift.
1955       // (G_ASHR i64:x, 63) ->
1956       //   %narrowed = (G_ASHR hi_32(x), 31)
1957       //   G_MERGE_VALUES %narrowed, %narrowed
1958       Builder.buildMerge(DstReg, { Hi, Hi });
1959     } else {
1960       auto Lo = Builder.buildAShr(
1961         HalfTy, Unmerge.getReg(1),
1962         Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
1963 
1964       // (G_ASHR i64:x, C) ->, for C >= 32
1965       //   G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
1966       Builder.buildMerge(DstReg, { Lo, Hi });
1967     }
1968   }
1969 
1970   MI.eraseFromParent();
1971 }
1972 
1973 bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
1974                                               unsigned TargetShiftAmount) {
1975   unsigned ShiftAmt;
1976   if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
1977     applyCombineShiftToUnmerge(MI, ShiftAmt);
1978     return true;
1979   }
1980 
1981   return false;
1982 }
1983 
1984 bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
1985   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
1986   Register DstReg = MI.getOperand(0).getReg();
1987   LLT DstTy = MRI.getType(DstReg);
1988   Register SrcReg = MI.getOperand(1).getReg();
1989   return mi_match(SrcReg, MRI,
1990                   m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg))));
1991 }
1992 
1993 void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
1994   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
1995   Register DstReg = MI.getOperand(0).getReg();
1996   Builder.setInstr(MI);
1997   Builder.buildCopy(DstReg, Reg);
1998   MI.eraseFromParent();
1999 }
2000 
2001 bool CombinerHelper::matchCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2002   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2003   Register SrcReg = MI.getOperand(1).getReg();
2004   return mi_match(SrcReg, MRI, m_GIntToPtr(m_Reg(Reg)));
2005 }
2006 
2007 void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2008   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2009   Register DstReg = MI.getOperand(0).getReg();
2010   Builder.setInstr(MI);
2011   Builder.buildZExtOrTrunc(DstReg, Reg);
2012   MI.eraseFromParent();
2013 }
2014 
2015 bool CombinerHelper::matchCombineAddP2IToPtrAdd(
2016     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2017   assert(MI.getOpcode() == TargetOpcode::G_ADD);
2018   Register LHS = MI.getOperand(1).getReg();
2019   Register RHS = MI.getOperand(2).getReg();
2020   LLT IntTy = MRI.getType(LHS);
2021 
2022   // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the
2023   // instruction.
2024   PtrReg.second = false;
2025   for (Register SrcReg : {LHS, RHS}) {
2026     if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) {
2027       // Don't handle cases where the integer is implicitly converted to the
2028       // pointer width.
2029       LLT PtrTy = MRI.getType(PtrReg.first);
2030       if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits())
2031         return true;
2032     }
2033 
2034     PtrReg.second = true;
2035   }
2036 
2037   return false;
2038 }
2039 
2040 void CombinerHelper::applyCombineAddP2IToPtrAdd(
2041     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2042   Register Dst = MI.getOperand(0).getReg();
2043   Register LHS = MI.getOperand(1).getReg();
2044   Register RHS = MI.getOperand(2).getReg();
2045 
2046   const bool DoCommute = PtrReg.second;
2047   if (DoCommute)
2048     std::swap(LHS, RHS);
2049   LHS = PtrReg.first;
2050 
2051   LLT PtrTy = MRI.getType(LHS);
2052 
2053   Builder.setInstrAndDebugLoc(MI);
2054   auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS);
2055   Builder.buildPtrToInt(Dst, PtrAdd);
2056   MI.eraseFromParent();
2057 }
2058 
2059 bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI,
2060                                                   APInt &NewCst) {
2061   auto &PtrAdd = cast<GPtrAdd>(MI);
2062   Register LHS = PtrAdd.getBaseReg();
2063   Register RHS = PtrAdd.getOffsetReg();
2064   MachineRegisterInfo &MRI = Builder.getMF().getRegInfo();
2065 
2066   if (auto RHSCst = getIConstantVRegVal(RHS, MRI)) {
2067     APInt Cst;
2068     if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) {
2069       auto DstTy = MRI.getType(PtrAdd.getReg(0));
2070       // G_INTTOPTR uses zero-extension
2071       NewCst = Cst.zextOrTrunc(DstTy.getSizeInBits());
2072       NewCst += RHSCst->sextOrTrunc(DstTy.getSizeInBits());
2073       return true;
2074     }
2075   }
2076 
2077   return false;
2078 }
2079 
2080 void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI,
2081                                                   APInt &NewCst) {
2082   auto &PtrAdd = cast<GPtrAdd>(MI);
2083   Register Dst = PtrAdd.getReg(0);
2084 
2085   Builder.setInstrAndDebugLoc(MI);
2086   Builder.buildConstant(Dst, NewCst);
2087   PtrAdd.eraseFromParent();
2088 }
2089 
2090 bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) {
2091   assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
2092   Register DstReg = MI.getOperand(0).getReg();
2093   Register SrcReg = MI.getOperand(1).getReg();
2094   LLT DstTy = MRI.getType(DstReg);
2095   return mi_match(SrcReg, MRI,
2096                   m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))));
2097 }
2098 
2099 bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
2100   assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2101   Register DstReg = MI.getOperand(0).getReg();
2102   Register SrcReg = MI.getOperand(1).getReg();
2103   LLT DstTy = MRI.getType(DstReg);
2104   if (mi_match(SrcReg, MRI,
2105                m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
2106     unsigned DstSize = DstTy.getScalarSizeInBits();
2107     unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2108     return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2109   }
2110   return false;
2111 }
2112 
2113 bool CombinerHelper::matchCombineExtOfExt(
2114     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2115   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2116           MI.getOpcode() == TargetOpcode::G_SEXT ||
2117           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2118          "Expected a G_[ASZ]EXT");
2119   Register SrcReg = MI.getOperand(1).getReg();
2120   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2121   // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
2122   unsigned Opc = MI.getOpcode();
2123   unsigned SrcOpc = SrcMI->getOpcode();
2124   if (Opc == SrcOpc ||
2125       (Opc == TargetOpcode::G_ANYEXT &&
2126        (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
2127       (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
2128     MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
2129     return true;
2130   }
2131   return false;
2132 }
2133 
2134 void CombinerHelper::applyCombineExtOfExt(
2135     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2136   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2137           MI.getOpcode() == TargetOpcode::G_SEXT ||
2138           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2139          "Expected a G_[ASZ]EXT");
2140 
2141   Register Reg = std::get<0>(MatchInfo);
2142   unsigned SrcExtOp = std::get<1>(MatchInfo);
2143 
2144   // Combine exts with the same opcode.
2145   if (MI.getOpcode() == SrcExtOp) {
2146     Observer.changingInstr(MI);
2147     MI.getOperand(1).setReg(Reg);
2148     Observer.changedInstr(MI);
2149     return;
2150   }
2151 
2152   // Combine:
2153   // - anyext([sz]ext x) to [sz]ext x
2154   // - sext(zext x) to zext x
2155   if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2156       (MI.getOpcode() == TargetOpcode::G_SEXT &&
2157        SrcExtOp == TargetOpcode::G_ZEXT)) {
2158     Register DstReg = MI.getOperand(0).getReg();
2159     Builder.setInstrAndDebugLoc(MI);
2160     Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
2161     MI.eraseFromParent();
2162   }
2163 }
2164 
2165 void CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) {
2166   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2167   Register DstReg = MI.getOperand(0).getReg();
2168   Register SrcReg = MI.getOperand(1).getReg();
2169   LLT DstTy = MRI.getType(DstReg);
2170 
2171   Builder.setInstrAndDebugLoc(MI);
2172   Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg,
2173                    MI.getFlags());
2174   MI.eraseFromParent();
2175 }
2176 
2177 bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) {
2178   assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG");
2179   Register SrcReg = MI.getOperand(1).getReg();
2180   return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg)));
2181 }
2182 
2183 bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) {
2184   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2185   Src = MI.getOperand(1).getReg();
2186   Register AbsSrc;
2187   return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc)));
2188 }
2189 
2190 bool CombinerHelper::matchCombineFAbsOfFNeg(MachineInstr &MI,
2191                                             BuildFnTy &MatchInfo) {
2192   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2193   Register Src = MI.getOperand(1).getReg();
2194   Register NegSrc;
2195 
2196   if (!mi_match(Src, MRI, m_GFNeg(m_Reg(NegSrc))))
2197     return false;
2198 
2199   MatchInfo = [=, &MI](MachineIRBuilder &B) {
2200     Observer.changingInstr(MI);
2201     MI.getOperand(1).setReg(NegSrc);
2202     Observer.changedInstr(MI);
2203   };
2204   return true;
2205 }
2206 
2207 bool CombinerHelper::matchCombineTruncOfExt(
2208     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2209   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2210   Register SrcReg = MI.getOperand(1).getReg();
2211   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2212   unsigned SrcOpc = SrcMI->getOpcode();
2213   if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
2214       SrcOpc == TargetOpcode::G_ZEXT) {
2215     MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
2216     return true;
2217   }
2218   return false;
2219 }
2220 
2221 void CombinerHelper::applyCombineTruncOfExt(
2222     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2223   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2224   Register SrcReg = MatchInfo.first;
2225   unsigned SrcExtOp = MatchInfo.second;
2226   Register DstReg = MI.getOperand(0).getReg();
2227   LLT SrcTy = MRI.getType(SrcReg);
2228   LLT DstTy = MRI.getType(DstReg);
2229   if (SrcTy == DstTy) {
2230     MI.eraseFromParent();
2231     replaceRegWith(MRI, DstReg, SrcReg);
2232     return;
2233   }
2234   Builder.setInstrAndDebugLoc(MI);
2235   if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
2236     Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
2237   else
2238     Builder.buildTrunc(DstReg, SrcReg);
2239   MI.eraseFromParent();
2240 }
2241 
2242 bool CombinerHelper::matchCombineTruncOfShl(
2243     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2244   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2245   Register DstReg = MI.getOperand(0).getReg();
2246   Register SrcReg = MI.getOperand(1).getReg();
2247   LLT DstTy = MRI.getType(DstReg);
2248   Register ShiftSrc;
2249   Register ShiftAmt;
2250 
2251   if (MRI.hasOneNonDBGUse(SrcReg) &&
2252       mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) &&
2253       isLegalOrBeforeLegalizer(
2254           {TargetOpcode::G_SHL,
2255            {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) {
2256     KnownBits Known = KB->getKnownBits(ShiftAmt);
2257     unsigned Size = DstTy.getSizeInBits();
2258     if (Known.countMaxActiveBits() <= Log2_32(Size)) {
2259       MatchInfo = std::make_pair(ShiftSrc, ShiftAmt);
2260       return true;
2261     }
2262   }
2263   return false;
2264 }
2265 
2266 void CombinerHelper::applyCombineTruncOfShl(
2267     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2268   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2269   Register DstReg = MI.getOperand(0).getReg();
2270   Register SrcReg = MI.getOperand(1).getReg();
2271   LLT DstTy = MRI.getType(DstReg);
2272   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2273 
2274   Register ShiftSrc = MatchInfo.first;
2275   Register ShiftAmt = MatchInfo.second;
2276   Builder.setInstrAndDebugLoc(MI);
2277   auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc);
2278   Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags());
2279   MI.eraseFromParent();
2280 }
2281 
2282 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
2283   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2284     return MO.isReg() &&
2285            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2286   });
2287 }
2288 
2289 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
2290   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2291     return !MO.isReg() ||
2292            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2293   });
2294 }
2295 
2296 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
2297   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
2298   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
2299   return all_of(Mask, [](int Elt) { return Elt < 0; });
2300 }
2301 
2302 bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
2303   assert(MI.getOpcode() == TargetOpcode::G_STORE);
2304   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
2305                       MRI);
2306 }
2307 
2308 bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
2309   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2310   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
2311                       MRI);
2312 }
2313 
2314 bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
2315   GSelect &SelMI = cast<GSelect>(MI);
2316   auto Cst =
2317       isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI);
2318   if (!Cst)
2319     return false;
2320   OpIdx = Cst->isZero() ? 3 : 2;
2321   return true;
2322 }
2323 
2324 bool CombinerHelper::eraseInst(MachineInstr &MI) {
2325   MI.eraseFromParent();
2326   return true;
2327 }
2328 
2329 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
2330                                     const MachineOperand &MOP2) {
2331   if (!MOP1.isReg() || !MOP2.isReg())
2332     return false;
2333   auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
2334   if (!InstAndDef1)
2335     return false;
2336   auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
2337   if (!InstAndDef2)
2338     return false;
2339   MachineInstr *I1 = InstAndDef1->MI;
2340   MachineInstr *I2 = InstAndDef2->MI;
2341 
2342   // Handle a case like this:
2343   //
2344   // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
2345   //
2346   // Even though %0 and %1 are produced by the same instruction they are not
2347   // the same values.
2348   if (I1 == I2)
2349     return MOP1.getReg() == MOP2.getReg();
2350 
2351   // If we have an instruction which loads or stores, we can't guarantee that
2352   // it is identical.
2353   //
2354   // For example, we may have
2355   //
2356   // %x1 = G_LOAD %addr (load N from @somewhere)
2357   // ...
2358   // call @foo
2359   // ...
2360   // %x2 = G_LOAD %addr (load N from @somewhere)
2361   // ...
2362   // %or = G_OR %x1, %x2
2363   //
2364   // It's possible that @foo will modify whatever lives at the address we're
2365   // loading from. To be safe, let's just assume that all loads and stores
2366   // are different (unless we have something which is guaranteed to not
2367   // change.)
2368   if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr))
2369     return false;
2370 
2371   // If both instructions are loads or stores, they are equal only if both
2372   // are dereferenceable invariant loads with the same number of bits.
2373   if (I1->mayLoadOrStore() && I2->mayLoadOrStore()) {
2374     GLoadStore *LS1 = dyn_cast<GLoadStore>(I1);
2375     GLoadStore *LS2 = dyn_cast<GLoadStore>(I2);
2376     if (!LS1 || !LS2)
2377       return false;
2378 
2379     if (!I2->isDereferenceableInvariantLoad(nullptr) ||
2380         (LS1->getMemSizeInBits() != LS2->getMemSizeInBits()))
2381       return false;
2382   }
2383 
2384   // Check for physical registers on the instructions first to avoid cases
2385   // like this:
2386   //
2387   // %a = COPY $physreg
2388   // ...
2389   // SOMETHING implicit-def $physreg
2390   // ...
2391   // %b = COPY $physreg
2392   //
2393   // These copies are not equivalent.
2394   if (any_of(I1->uses(), [](const MachineOperand &MO) {
2395         return MO.isReg() && MO.getReg().isPhysical();
2396       })) {
2397     // Check if we have a case like this:
2398     //
2399     // %a = COPY $physreg
2400     // %b = COPY %a
2401     //
2402     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
2403     // From that, we know that they must have the same value, since they must
2404     // have come from the same COPY.
2405     return I1->isIdenticalTo(*I2);
2406   }
2407 
2408   // We don't have any physical registers, so we don't necessarily need the
2409   // same vreg defs.
2410   //
2411   // On the off-chance that there's some target instruction feeding into the
2412   // instruction, let's use produceSameValue instead of isIdenticalTo.
2413   if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
2414     // Handle instructions with multiple defs that produce same values. Values
2415     // are same for operands with same index.
2416     // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2417     // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2418     // I1 and I2 are different instructions but produce same values,
2419     // %1 and %6 are same, %1 and %7 are not the same value.
2420     return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) ==
2421            I2->findRegisterDefOperandIdx(InstAndDef2->Reg);
2422   }
2423   return false;
2424 }
2425 
2426 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
2427   if (!MOP.isReg())
2428     return false;
2429   auto *MI = MRI.getVRegDef(MOP.getReg());
2430   auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI);
2431   return MaybeCst.hasValue() && MaybeCst->getBitWidth() <= 64 &&
2432          MaybeCst->getSExtValue() == C;
2433 }
2434 
2435 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
2436                                                      unsigned OpIdx) {
2437   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2438   Register OldReg = MI.getOperand(0).getReg();
2439   Register Replacement = MI.getOperand(OpIdx).getReg();
2440   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2441   MI.eraseFromParent();
2442   replaceRegWith(MRI, OldReg, Replacement);
2443   return true;
2444 }
2445 
2446 bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
2447                                                  Register Replacement) {
2448   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2449   Register OldReg = MI.getOperand(0).getReg();
2450   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2451   MI.eraseFromParent();
2452   replaceRegWith(MRI, OldReg, Replacement);
2453   return true;
2454 }
2455 
2456 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
2457   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2458   // Match (cond ? x : x)
2459   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
2460          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
2461                        MRI);
2462 }
2463 
2464 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
2465   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
2466          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
2467                        MRI);
2468 }
2469 
2470 bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
2471   return matchConstantOp(MI.getOperand(OpIdx), 0) &&
2472          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
2473                        MRI);
2474 }
2475 
2476 bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
2477   MachineOperand &MO = MI.getOperand(OpIdx);
2478   return MO.isReg() &&
2479          getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2480 }
2481 
2482 bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
2483                                                         unsigned OpIdx) {
2484   MachineOperand &MO = MI.getOperand(OpIdx);
2485   return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
2486 }
2487 
2488 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
2489   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2490   Builder.setInstr(MI);
2491   Builder.buildFConstant(MI.getOperand(0), C);
2492   MI.eraseFromParent();
2493   return true;
2494 }
2495 
2496 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
2497   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2498   Builder.setInstr(MI);
2499   Builder.buildConstant(MI.getOperand(0), C);
2500   MI.eraseFromParent();
2501   return true;
2502 }
2503 
2504 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) {
2505   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2506   Builder.setInstr(MI);
2507   Builder.buildConstant(MI.getOperand(0), C);
2508   MI.eraseFromParent();
2509   return true;
2510 }
2511 
2512 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
2513   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2514   Builder.setInstr(MI);
2515   Builder.buildUndef(MI.getOperand(0));
2516   MI.eraseFromParent();
2517   return true;
2518 }
2519 
2520 bool CombinerHelper::matchSimplifyAddToSub(
2521     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
2522   Register LHS = MI.getOperand(1).getReg();
2523   Register RHS = MI.getOperand(2).getReg();
2524   Register &NewLHS = std::get<0>(MatchInfo);
2525   Register &NewRHS = std::get<1>(MatchInfo);
2526 
2527   // Helper lambda to check for opportunities for
2528   // ((0-A) + B) -> B - A
2529   // (A + (0-B)) -> A - B
2530   auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
2531     if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
2532       return false;
2533     NewLHS = MaybeNewLHS;
2534     return true;
2535   };
2536 
2537   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
2538 }
2539 
2540 bool CombinerHelper::matchCombineInsertVecElts(
2541     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2542   assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2543          "Invalid opcode");
2544   Register DstReg = MI.getOperand(0).getReg();
2545   LLT DstTy = MRI.getType(DstReg);
2546   assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2547   unsigned NumElts = DstTy.getNumElements();
2548   // If this MI is part of a sequence of insert_vec_elts, then
2549   // don't do the combine in the middle of the sequence.
2550   if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
2551                                    TargetOpcode::G_INSERT_VECTOR_ELT)
2552     return false;
2553   MachineInstr *CurrInst = &MI;
2554   MachineInstr *TmpInst;
2555   int64_t IntImm;
2556   Register TmpReg;
2557   MatchInfo.resize(NumElts);
2558   while (mi_match(
2559       CurrInst->getOperand(0).getReg(), MRI,
2560       m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2561     if (IntImm >= NumElts)
2562       return false;
2563     if (!MatchInfo[IntImm])
2564       MatchInfo[IntImm] = TmpReg;
2565     CurrInst = TmpInst;
2566   }
2567   // Variable index.
2568   if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2569     return false;
2570   if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2571     for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2572       if (!MatchInfo[I - 1].isValid())
2573         MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2574     }
2575     return true;
2576   }
2577   // If we didn't end in a G_IMPLICIT_DEF, bail out.
2578   return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
2579 }
2580 
2581 void CombinerHelper::applyCombineInsertVecElts(
2582     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2583   Builder.setInstr(MI);
2584   Register UndefReg;
2585   auto GetUndef = [&]() {
2586     if (UndefReg)
2587       return UndefReg;
2588     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2589     UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
2590     return UndefReg;
2591   };
2592   for (unsigned I = 0; I < MatchInfo.size(); ++I) {
2593     if (!MatchInfo[I])
2594       MatchInfo[I] = GetUndef();
2595   }
2596   Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
2597   MI.eraseFromParent();
2598 }
2599 
2600 void CombinerHelper::applySimplifyAddToSub(
2601     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
2602   Builder.setInstr(MI);
2603   Register SubLHS, SubRHS;
2604   std::tie(SubLHS, SubRHS) = MatchInfo;
2605   Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
2606   MI.eraseFromParent();
2607 }
2608 
2609 bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
2610     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2611   // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
2612   //
2613   // Creates the new hand + logic instruction (but does not insert them.)
2614   //
2615   // On success, MatchInfo is populated with the new instructions. These are
2616   // inserted in applyHoistLogicOpWithSameOpcodeHands.
2617   unsigned LogicOpcode = MI.getOpcode();
2618   assert(LogicOpcode == TargetOpcode::G_AND ||
2619          LogicOpcode == TargetOpcode::G_OR ||
2620          LogicOpcode == TargetOpcode::G_XOR);
2621   MachineIRBuilder MIB(MI);
2622   Register Dst = MI.getOperand(0).getReg();
2623   Register LHSReg = MI.getOperand(1).getReg();
2624   Register RHSReg = MI.getOperand(2).getReg();
2625 
2626   // Don't recompute anything.
2627   if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
2628     return false;
2629 
2630   // Make sure we have (hand x, ...), (hand y, ...)
2631   MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
2632   MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
2633   if (!LeftHandInst || !RightHandInst)
2634     return false;
2635   unsigned HandOpcode = LeftHandInst->getOpcode();
2636   if (HandOpcode != RightHandInst->getOpcode())
2637     return false;
2638   if (!LeftHandInst->getOperand(1).isReg() ||
2639       !RightHandInst->getOperand(1).isReg())
2640     return false;
2641 
2642   // Make sure the types match up, and if we're doing this post-legalization,
2643   // we end up with legal types.
2644   Register X = LeftHandInst->getOperand(1).getReg();
2645   Register Y = RightHandInst->getOperand(1).getReg();
2646   LLT XTy = MRI.getType(X);
2647   LLT YTy = MRI.getType(Y);
2648   if (XTy != YTy)
2649     return false;
2650   if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
2651     return false;
2652 
2653   // Optional extra source register.
2654   Register ExtraHandOpSrcReg;
2655   switch (HandOpcode) {
2656   default:
2657     return false;
2658   case TargetOpcode::G_ANYEXT:
2659   case TargetOpcode::G_SEXT:
2660   case TargetOpcode::G_ZEXT: {
2661     // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
2662     break;
2663   }
2664   case TargetOpcode::G_AND:
2665   case TargetOpcode::G_ASHR:
2666   case TargetOpcode::G_LSHR:
2667   case TargetOpcode::G_SHL: {
2668     // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
2669     MachineOperand &ZOp = LeftHandInst->getOperand(2);
2670     if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
2671       return false;
2672     ExtraHandOpSrcReg = ZOp.getReg();
2673     break;
2674   }
2675   }
2676 
2677   // Record the steps to build the new instructions.
2678   //
2679   // Steps to build (logic x, y)
2680   auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
2681   OperandBuildSteps LogicBuildSteps = {
2682       [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
2683       [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
2684       [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
2685   InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
2686 
2687   // Steps to build hand (logic x, y), ...z
2688   OperandBuildSteps HandBuildSteps = {
2689       [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
2690       [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
2691   if (ExtraHandOpSrcReg.isValid())
2692     HandBuildSteps.push_back(
2693         [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
2694   InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
2695 
2696   MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
2697   return true;
2698 }
2699 
2700 void CombinerHelper::applyBuildInstructionSteps(
2701     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2702   assert(MatchInfo.InstrsToBuild.size() &&
2703          "Expected at least one instr to build?");
2704   Builder.setInstr(MI);
2705   for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
2706     assert(InstrToBuild.Opcode && "Expected a valid opcode?");
2707     assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
2708     MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
2709     for (auto &OperandFn : InstrToBuild.OperandFns)
2710       OperandFn(Instr);
2711   }
2712   MI.eraseFromParent();
2713 }
2714 
2715 bool CombinerHelper::matchAshrShlToSextInreg(
2716     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2717   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2718   int64_t ShlCst, AshrCst;
2719   Register Src;
2720   // FIXME: detect splat constant vectors.
2721   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2722                 m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst))))
2723     return false;
2724   if (ShlCst != AshrCst)
2725     return false;
2726   if (!isLegalOrBeforeLegalizer(
2727           {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
2728     return false;
2729   MatchInfo = std::make_tuple(Src, ShlCst);
2730   return true;
2731 }
2732 
2733 void CombinerHelper::applyAshShlToSextInreg(
2734     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2735   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2736   Register Src;
2737   int64_t ShiftAmt;
2738   std::tie(Src, ShiftAmt) = MatchInfo;
2739   unsigned Size = MRI.getType(Src).getScalarSizeInBits();
2740   Builder.setInstrAndDebugLoc(MI);
2741   Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
2742   MI.eraseFromParent();
2743 }
2744 
2745 /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
2746 bool CombinerHelper::matchOverlappingAnd(
2747     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
2748   assert(MI.getOpcode() == TargetOpcode::G_AND);
2749 
2750   Register Dst = MI.getOperand(0).getReg();
2751   LLT Ty = MRI.getType(Dst);
2752 
2753   Register R;
2754   int64_t C1;
2755   int64_t C2;
2756   if (!mi_match(
2757           Dst, MRI,
2758           m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
2759     return false;
2760 
2761   MatchInfo = [=](MachineIRBuilder &B) {
2762     if (C1 & C2) {
2763       B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
2764       return;
2765     }
2766     auto Zero = B.buildConstant(Ty, 0);
2767     replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
2768   };
2769   return true;
2770 }
2771 
2772 bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
2773                                        Register &Replacement) {
2774   // Given
2775   //
2776   // %y:_(sN) = G_SOMETHING
2777   // %x:_(sN) = G_SOMETHING
2778   // %res:_(sN) = G_AND %x, %y
2779   //
2780   // Eliminate the G_AND when it is known that x & y == x or x & y == y.
2781   //
2782   // Patterns like this can appear as a result of legalization. E.g.
2783   //
2784   // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
2785   // %one:_(s32) = G_CONSTANT i32 1
2786   // %and:_(s32) = G_AND %cmp, %one
2787   //
2788   // In this case, G_ICMP only produces a single bit, so x & 1 == x.
2789   assert(MI.getOpcode() == TargetOpcode::G_AND);
2790   if (!KB)
2791     return false;
2792 
2793   Register AndDst = MI.getOperand(0).getReg();
2794   LLT DstTy = MRI.getType(AndDst);
2795 
2796   // FIXME: This should be removed once GISelKnownBits supports vectors.
2797   if (DstTy.isVector())
2798     return false;
2799 
2800   Register LHS = MI.getOperand(1).getReg();
2801   Register RHS = MI.getOperand(2).getReg();
2802   KnownBits LHSBits = KB->getKnownBits(LHS);
2803   KnownBits RHSBits = KB->getKnownBits(RHS);
2804 
2805   // Check that x & Mask == x.
2806   // x & 1 == x, always
2807   // x & 0 == x, only if x is also 0
2808   // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
2809   //
2810   // Check if we can replace AndDst with the LHS of the G_AND
2811   if (canReplaceReg(AndDst, LHS, MRI) &&
2812       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2813     Replacement = LHS;
2814     return true;
2815   }
2816 
2817   // Check if we can replace AndDst with the RHS of the G_AND
2818   if (canReplaceReg(AndDst, RHS, MRI) &&
2819       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2820     Replacement = RHS;
2821     return true;
2822   }
2823 
2824   return false;
2825 }
2826 
2827 bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
2828   // Given
2829   //
2830   // %y:_(sN) = G_SOMETHING
2831   // %x:_(sN) = G_SOMETHING
2832   // %res:_(sN) = G_OR %x, %y
2833   //
2834   // Eliminate the G_OR when it is known that x | y == x or x | y == y.
2835   assert(MI.getOpcode() == TargetOpcode::G_OR);
2836   if (!KB)
2837     return false;
2838 
2839   Register OrDst = MI.getOperand(0).getReg();
2840   LLT DstTy = MRI.getType(OrDst);
2841 
2842   // FIXME: This should be removed once GISelKnownBits supports vectors.
2843   if (DstTy.isVector())
2844     return false;
2845 
2846   Register LHS = MI.getOperand(1).getReg();
2847   Register RHS = MI.getOperand(2).getReg();
2848   KnownBits LHSBits = KB->getKnownBits(LHS);
2849   KnownBits RHSBits = KB->getKnownBits(RHS);
2850 
2851   // Check that x | Mask == x.
2852   // x | 0 == x, always
2853   // x | 1 == x, only if x is also 1
2854   // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
2855   //
2856   // Check if we can replace OrDst with the LHS of the G_OR
2857   if (canReplaceReg(OrDst, LHS, MRI) &&
2858       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2859     Replacement = LHS;
2860     return true;
2861   }
2862 
2863   // Check if we can replace OrDst with the RHS of the G_OR
2864   if (canReplaceReg(OrDst, RHS, MRI) &&
2865       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2866     Replacement = RHS;
2867     return true;
2868   }
2869 
2870   return false;
2871 }
2872 
2873 bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
2874   // If the input is already sign extended, just drop the extension.
2875   Register Src = MI.getOperand(1).getReg();
2876   unsigned ExtBits = MI.getOperand(2).getImm();
2877   unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
2878   return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
2879 }
2880 
2881 static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
2882                              int64_t Cst, bool IsVector, bool IsFP) {
2883   // For i1, Cst will always be -1 regardless of boolean contents.
2884   return (ScalarSizeBits == 1 && Cst == -1) ||
2885          isConstTrueVal(TLI, Cst, IsVector, IsFP);
2886 }
2887 
2888 bool CombinerHelper::matchNotCmp(MachineInstr &MI,
2889                                  SmallVectorImpl<Register> &RegsToNegate) {
2890   assert(MI.getOpcode() == TargetOpcode::G_XOR);
2891   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2892   const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
2893   Register XorSrc;
2894   Register CstReg;
2895   // We match xor(src, true) here.
2896   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2897                 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
2898     return false;
2899 
2900   if (!MRI.hasOneNonDBGUse(XorSrc))
2901     return false;
2902 
2903   // Check that XorSrc is the root of a tree of comparisons combined with ANDs
2904   // and ORs. The suffix of RegsToNegate starting from index I is used a work
2905   // list of tree nodes to visit.
2906   RegsToNegate.push_back(XorSrc);
2907   // Remember whether the comparisons are all integer or all floating point.
2908   bool IsInt = false;
2909   bool IsFP = false;
2910   for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
2911     Register Reg = RegsToNegate[I];
2912     if (!MRI.hasOneNonDBGUse(Reg))
2913       return false;
2914     MachineInstr *Def = MRI.getVRegDef(Reg);
2915     switch (Def->getOpcode()) {
2916     default:
2917       // Don't match if the tree contains anything other than ANDs, ORs and
2918       // comparisons.
2919       return false;
2920     case TargetOpcode::G_ICMP:
2921       if (IsFP)
2922         return false;
2923       IsInt = true;
2924       // When we apply the combine we will invert the predicate.
2925       break;
2926     case TargetOpcode::G_FCMP:
2927       if (IsInt)
2928         return false;
2929       IsFP = true;
2930       // When we apply the combine we will invert the predicate.
2931       break;
2932     case TargetOpcode::G_AND:
2933     case TargetOpcode::G_OR:
2934       // Implement De Morgan's laws:
2935       // ~(x & y) -> ~x | ~y
2936       // ~(x | y) -> ~x & ~y
2937       // When we apply the combine we will change the opcode and recursively
2938       // negate the operands.
2939       RegsToNegate.push_back(Def->getOperand(1).getReg());
2940       RegsToNegate.push_back(Def->getOperand(2).getReg());
2941       break;
2942     }
2943   }
2944 
2945   // Now we know whether the comparisons are integer or floating point, check
2946   // the constant in the xor.
2947   int64_t Cst;
2948   if (Ty.isVector()) {
2949     MachineInstr *CstDef = MRI.getVRegDef(CstReg);
2950     auto MaybeCst = getBuildVectorConstantSplat(*CstDef, MRI);
2951     if (!MaybeCst)
2952       return false;
2953     if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
2954       return false;
2955   } else {
2956     if (!mi_match(CstReg, MRI, m_ICst(Cst)))
2957       return false;
2958     if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
2959       return false;
2960   }
2961 
2962   return true;
2963 }
2964 
2965 void CombinerHelper::applyNotCmp(MachineInstr &MI,
2966                                  SmallVectorImpl<Register> &RegsToNegate) {
2967   for (Register Reg : RegsToNegate) {
2968     MachineInstr *Def = MRI.getVRegDef(Reg);
2969     Observer.changingInstr(*Def);
2970     // For each comparison, invert the opcode. For each AND and OR, change the
2971     // opcode.
2972     switch (Def->getOpcode()) {
2973     default:
2974       llvm_unreachable("Unexpected opcode");
2975     case TargetOpcode::G_ICMP:
2976     case TargetOpcode::G_FCMP: {
2977       MachineOperand &PredOp = Def->getOperand(1);
2978       CmpInst::Predicate NewP = CmpInst::getInversePredicate(
2979           (CmpInst::Predicate)PredOp.getPredicate());
2980       PredOp.setPredicate(NewP);
2981       break;
2982     }
2983     case TargetOpcode::G_AND:
2984       Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
2985       break;
2986     case TargetOpcode::G_OR:
2987       Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
2988       break;
2989     }
2990     Observer.changedInstr(*Def);
2991   }
2992 
2993   replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
2994   MI.eraseFromParent();
2995 }
2996 
2997 bool CombinerHelper::matchXorOfAndWithSameReg(
2998     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2999   // Match (xor (and x, y), y) (or any of its commuted cases)
3000   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3001   Register &X = MatchInfo.first;
3002   Register &Y = MatchInfo.second;
3003   Register AndReg = MI.getOperand(1).getReg();
3004   Register SharedReg = MI.getOperand(2).getReg();
3005 
3006   // Find a G_AND on either side of the G_XOR.
3007   // Look for one of
3008   //
3009   // (xor (and x, y), SharedReg)
3010   // (xor SharedReg, (and x, y))
3011   if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3012     std::swap(AndReg, SharedReg);
3013     if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3014       return false;
3015   }
3016 
3017   // Only do this if we'll eliminate the G_AND.
3018   if (!MRI.hasOneNonDBGUse(AndReg))
3019     return false;
3020 
3021   // We can combine if SharedReg is the same as either the LHS or RHS of the
3022   // G_AND.
3023   if (Y != SharedReg)
3024     std::swap(X, Y);
3025   return Y == SharedReg;
3026 }
3027 
3028 void CombinerHelper::applyXorOfAndWithSameReg(
3029     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3030   // Fold (xor (and x, y), y) -> (and (not x), y)
3031   Builder.setInstrAndDebugLoc(MI);
3032   Register X, Y;
3033   std::tie(X, Y) = MatchInfo;
3034   auto Not = Builder.buildNot(MRI.getType(X), X);
3035   Observer.changingInstr(MI);
3036   MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3037   MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3038   MI.getOperand(2).setReg(Y);
3039   Observer.changedInstr(MI);
3040 }
3041 
3042 bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
3043   auto &PtrAdd = cast<GPtrAdd>(MI);
3044   Register DstReg = PtrAdd.getReg(0);
3045   LLT Ty = MRI.getType(DstReg);
3046   const DataLayout &DL = Builder.getMF().getDataLayout();
3047 
3048   if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3049     return false;
3050 
3051   if (Ty.isPointer()) {
3052     auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI);
3053     return ConstVal && *ConstVal == 0;
3054   }
3055 
3056   assert(Ty.isVector() && "Expecting a vector type");
3057   const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg());
3058   return isBuildVectorAllZeros(*VecMI, MRI);
3059 }
3060 
3061 void CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
3062   auto &PtrAdd = cast<GPtrAdd>(MI);
3063   Builder.setInstrAndDebugLoc(PtrAdd);
3064   Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg());
3065   PtrAdd.eraseFromParent();
3066 }
3067 
3068 /// The second source operand is known to be a power of 2.
3069 void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
3070   Register DstReg = MI.getOperand(0).getReg();
3071   Register Src0 = MI.getOperand(1).getReg();
3072   Register Pow2Src1 = MI.getOperand(2).getReg();
3073   LLT Ty = MRI.getType(DstReg);
3074   Builder.setInstrAndDebugLoc(MI);
3075 
3076   // Fold (urem x, pow2) -> (and x, pow2-1)
3077   auto NegOne = Builder.buildConstant(Ty, -1);
3078   auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3079   Builder.buildAnd(DstReg, Src0, Add);
3080   MI.eraseFromParent();
3081 }
3082 
3083 Optional<SmallVector<Register, 8>>
3084 CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3085   assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3086   // We want to detect if Root is part of a tree which represents a bunch
3087   // of loads being merged into a larger load. We'll try to recognize patterns
3088   // like, for example:
3089   //
3090   //  Reg   Reg
3091   //   \    /
3092   //    OR_1   Reg
3093   //     \    /
3094   //      OR_2
3095   //        \     Reg
3096   //         .. /
3097   //        Root
3098   //
3099   //  Reg   Reg   Reg   Reg
3100   //     \ /       \   /
3101   //     OR_1      OR_2
3102   //       \       /
3103   //        \    /
3104   //         ...
3105   //         Root
3106   //
3107   // Each "Reg" may have been produced by a load + some arithmetic. This
3108   // function will save each of them.
3109   SmallVector<Register, 8> RegsToVisit;
3110   SmallVector<const MachineInstr *, 7> Ors = {Root};
3111 
3112   // In the "worst" case, we're dealing with a load for each byte. So, there
3113   // are at most #bytes - 1 ORs.
3114   const unsigned MaxIter =
3115       MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3116   for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3117     if (Ors.empty())
3118       break;
3119     const MachineInstr *Curr = Ors.pop_back_val();
3120     Register OrLHS = Curr->getOperand(1).getReg();
3121     Register OrRHS = Curr->getOperand(2).getReg();
3122 
3123     // In the combine, we want to elimate the entire tree.
3124     if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3125       return None;
3126 
3127     // If it's a G_OR, save it and continue to walk. If it's not, then it's
3128     // something that may be a load + arithmetic.
3129     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3130       Ors.push_back(Or);
3131     else
3132       RegsToVisit.push_back(OrLHS);
3133     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3134       Ors.push_back(Or);
3135     else
3136       RegsToVisit.push_back(OrRHS);
3137   }
3138 
3139   // We're going to try and merge each register into a wider power-of-2 type,
3140   // so we ought to have an even number of registers.
3141   if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3142     return None;
3143   return RegsToVisit;
3144 }
3145 
3146 /// Helper function for findLoadOffsetsForLoadOrCombine.
3147 ///
3148 /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3149 /// and then moving that value into a specific byte offset.
3150 ///
3151 /// e.g. x[i] << 24
3152 ///
3153 /// \returns The load instruction and the byte offset it is moved into.
3154 static Optional<std::pair<GZExtLoad *, int64_t>>
3155 matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3156                          const MachineRegisterInfo &MRI) {
3157   assert(MRI.hasOneNonDBGUse(Reg) &&
3158          "Expected Reg to only have one non-debug use?");
3159   Register MaybeLoad;
3160   int64_t Shift;
3161   if (!mi_match(Reg, MRI,
3162                 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3163     Shift = 0;
3164     MaybeLoad = Reg;
3165   }
3166 
3167   if (Shift % MemSizeInBits != 0)
3168     return None;
3169 
3170   // TODO: Handle other types of loads.
3171   auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
3172   if (!Load)
3173     return None;
3174 
3175   if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
3176     return None;
3177 
3178   return std::make_pair(Load, Shift / MemSizeInBits);
3179 }
3180 
3181 Optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
3182 CombinerHelper::findLoadOffsetsForLoadOrCombine(
3183     SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
3184     const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
3185 
3186   // Each load found for the pattern. There should be one for each RegsToVisit.
3187   SmallSetVector<const MachineInstr *, 8> Loads;
3188 
3189   // The lowest index used in any load. (The lowest "i" for each x[i].)
3190   int64_t LowestIdx = INT64_MAX;
3191 
3192   // The load which uses the lowest index.
3193   GZExtLoad *LowestIdxLoad = nullptr;
3194 
3195   // Keeps track of the load indices we see. We shouldn't see any indices twice.
3196   SmallSet<int64_t, 8> SeenIdx;
3197 
3198   // Ensure each load is in the same MBB.
3199   // TODO: Support multiple MachineBasicBlocks.
3200   MachineBasicBlock *MBB = nullptr;
3201   const MachineMemOperand *MMO = nullptr;
3202 
3203   // Earliest instruction-order load in the pattern.
3204   GZExtLoad *EarliestLoad = nullptr;
3205 
3206   // Latest instruction-order load in the pattern.
3207   GZExtLoad *LatestLoad = nullptr;
3208 
3209   // Base pointer which every load should share.
3210   Register BasePtr;
3211 
3212   // We want to find a load for each register. Each load should have some
3213   // appropriate bit twiddling arithmetic. During this loop, we will also keep
3214   // track of the load which uses the lowest index. Later, we will check if we
3215   // can use its pointer in the final, combined load.
3216   for (auto Reg : RegsToVisit) {
3217     // Find the load, and find the position that it will end up in (e.g. a
3218     // shifted) value.
3219     auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3220     if (!LoadAndPos)
3221       return None;
3222     GZExtLoad *Load;
3223     int64_t DstPos;
3224     std::tie(Load, DstPos) = *LoadAndPos;
3225 
3226     // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
3227     // it is difficult to check for stores/calls/etc between loads.
3228     MachineBasicBlock *LoadMBB = Load->getParent();
3229     if (!MBB)
3230       MBB = LoadMBB;
3231     if (LoadMBB != MBB)
3232       return None;
3233 
3234     // Make sure that the MachineMemOperands of every seen load are compatible.
3235     auto &LoadMMO = Load->getMMO();
3236     if (!MMO)
3237       MMO = &LoadMMO;
3238     if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
3239       return None;
3240 
3241     // Find out what the base pointer and index for the load is.
3242     Register LoadPtr;
3243     int64_t Idx;
3244     if (!mi_match(Load->getOperand(1).getReg(), MRI,
3245                   m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
3246       LoadPtr = Load->getOperand(1).getReg();
3247       Idx = 0;
3248     }
3249 
3250     // Don't combine things like a[i], a[i] -> a bigger load.
3251     if (!SeenIdx.insert(Idx).second)
3252       return None;
3253 
3254     // Every load must share the same base pointer; don't combine things like:
3255     //
3256     // a[i], b[i + 1] -> a bigger load.
3257     if (!BasePtr.isValid())
3258       BasePtr = LoadPtr;
3259     if (BasePtr != LoadPtr)
3260       return None;
3261 
3262     if (Idx < LowestIdx) {
3263       LowestIdx = Idx;
3264       LowestIdxLoad = Load;
3265     }
3266 
3267     // Keep track of the byte offset that this load ends up at. If we have seen
3268     // the byte offset, then stop here. We do not want to combine:
3269     //
3270     // a[i] << 16, a[i + k] << 16 -> a bigger load.
3271     if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
3272       return None;
3273     Loads.insert(Load);
3274 
3275     // Keep track of the position of the earliest/latest loads in the pattern.
3276     // We will check that there are no load fold barriers between them later
3277     // on.
3278     //
3279     // FIXME: Is there a better way to check for load fold barriers?
3280     if (!EarliestLoad || dominates(*Load, *EarliestLoad))
3281       EarliestLoad = Load;
3282     if (!LatestLoad || dominates(*LatestLoad, *Load))
3283       LatestLoad = Load;
3284   }
3285 
3286   // We found a load for each register. Let's check if each load satisfies the
3287   // pattern.
3288   assert(Loads.size() == RegsToVisit.size() &&
3289          "Expected to find a load for each register?");
3290   assert(EarliestLoad != LatestLoad && EarliestLoad &&
3291          LatestLoad && "Expected at least two loads?");
3292 
3293   // Check if there are any stores, calls, etc. between any of the loads. If
3294   // there are, then we can't safely perform the combine.
3295   //
3296   // MaxIter is chosen based off the (worst case) number of iterations it
3297   // typically takes to succeed in the LLVM test suite plus some padding.
3298   //
3299   // FIXME: Is there a better way to check for load fold barriers?
3300   const unsigned MaxIter = 20;
3301   unsigned Iter = 0;
3302   for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
3303                                                  LatestLoad->getIterator())) {
3304     if (Loads.count(&MI))
3305       continue;
3306     if (MI.isLoadFoldBarrier())
3307       return None;
3308     if (Iter++ == MaxIter)
3309       return None;
3310   }
3311 
3312   return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
3313 }
3314 
3315 bool CombinerHelper::matchLoadOrCombine(
3316     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3317   assert(MI.getOpcode() == TargetOpcode::G_OR);
3318   MachineFunction &MF = *MI.getMF();
3319   // Assuming a little-endian target, transform:
3320   //  s8 *a = ...
3321   //  s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
3322   // =>
3323   //  s32 val = *((i32)a)
3324   //
3325   //  s8 *a = ...
3326   //  s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
3327   // =>
3328   //  s32 val = BSWAP(*((s32)a))
3329   Register Dst = MI.getOperand(0).getReg();
3330   LLT Ty = MRI.getType(Dst);
3331   if (Ty.isVector())
3332     return false;
3333 
3334   // We need to combine at least two loads into this type. Since the smallest
3335   // possible load is into a byte, we need at least a 16-bit wide type.
3336   const unsigned WideMemSizeInBits = Ty.getSizeInBits();
3337   if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
3338     return false;
3339 
3340   // Match a collection of non-OR instructions in the pattern.
3341   auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
3342   if (!RegsToVisit)
3343     return false;
3344 
3345   // We have a collection of non-OR instructions. Figure out how wide each of
3346   // the small loads should be based off of the number of potential loads we
3347   // found.
3348   const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
3349   if (NarrowMemSizeInBits % 8 != 0)
3350     return false;
3351 
3352   // Check if each register feeding into each OR is a load from the same
3353   // base pointer + some arithmetic.
3354   //
3355   // e.g. a[0], a[1] << 8, a[2] << 16, etc.
3356   //
3357   // Also verify that each of these ends up putting a[i] into the same memory
3358   // offset as a load into a wide type would.
3359   SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
3360   GZExtLoad *LowestIdxLoad, *LatestLoad;
3361   int64_t LowestIdx;
3362   auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
3363       MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
3364   if (!MaybeLoadInfo)
3365     return false;
3366   std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
3367 
3368   // We have a bunch of loads being OR'd together. Using the addresses + offsets
3369   // we found before, check if this corresponds to a big or little endian byte
3370   // pattern. If it does, then we can represent it using a load + possibly a
3371   // BSWAP.
3372   bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
3373   Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
3374   if (!IsBigEndian.hasValue())
3375     return false;
3376   bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
3377   if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
3378     return false;
3379 
3380   // Make sure that the load from the lowest index produces offset 0 in the
3381   // final value.
3382   //
3383   // This ensures that we won't combine something like this:
3384   //
3385   // load x[i] -> byte 2
3386   // load x[i+1] -> byte 0 ---> wide_load x[i]
3387   // load x[i+2] -> byte 1
3388   const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
3389   const unsigned ZeroByteOffset =
3390       *IsBigEndian
3391           ? bigEndianByteAt(NumLoadsInTy, 0)
3392           : littleEndianByteAt(NumLoadsInTy, 0);
3393   auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
3394   if (ZeroOffsetIdx == MemOffset2Idx.end() ||
3395       ZeroOffsetIdx->second != LowestIdx)
3396     return false;
3397 
3398   // We wil reuse the pointer from the load which ends up at byte offset 0. It
3399   // may not use index 0.
3400   Register Ptr = LowestIdxLoad->getPointerReg();
3401   const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
3402   LegalityQuery::MemDesc MMDesc(MMO);
3403   MMDesc.MemoryTy = Ty;
3404   if (!isLegalOrBeforeLegalizer(
3405           {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
3406     return false;
3407   auto PtrInfo = MMO.getPointerInfo();
3408   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
3409 
3410   // Load must be allowed and fast on the target.
3411   LLVMContext &C = MF.getFunction().getContext();
3412   auto &DL = MF.getDataLayout();
3413   bool Fast = false;
3414   if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
3415       !Fast)
3416     return false;
3417 
3418   MatchInfo = [=](MachineIRBuilder &MIB) {
3419     MIB.setInstrAndDebugLoc(*LatestLoad);
3420     Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
3421     MIB.buildLoad(LoadDst, Ptr, *NewMMO);
3422     if (NeedsBSwap)
3423       MIB.buildBSwap(Dst, LoadDst);
3424   };
3425   return true;
3426 }
3427 
3428 /// Check if the store \p Store is a truncstore that can be merged. That is,
3429 /// it's a store of a shifted value of \p SrcVal. If \p SrcVal is an empty
3430 /// Register then it does not need to match and SrcVal is set to the source
3431 /// value found.
3432 /// On match, returns the start byte offset of the \p SrcVal that is being
3433 /// stored.
3434 static Optional<int64_t> getTruncStoreByteOffset(GStore &Store, Register &SrcVal,
3435                                                  MachineRegisterInfo &MRI) {
3436   Register TruncVal;
3437   if (!mi_match(Store.getValueReg(), MRI, m_GTrunc(m_Reg(TruncVal))))
3438     return None;
3439 
3440   // The shift amount must be a constant multiple of the narrow type.
3441   // It is translated to the offset address in the wide source value "y".
3442   //
3443   // x = G_LSHR y, ShiftAmtC
3444   // s8 z = G_TRUNC x
3445   // store z, ...
3446   Register FoundSrcVal;
3447   int64_t ShiftAmt;
3448   if (!mi_match(TruncVal, MRI,
3449                 m_any_of(m_GLShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt)),
3450                          m_GAShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt))))) {
3451     if (!SrcVal.isValid() || TruncVal == SrcVal) {
3452       if (!SrcVal.isValid())
3453         SrcVal = TruncVal;
3454       return 0; // If it's the lowest index store.
3455     }
3456     return None;
3457   }
3458 
3459   unsigned NarrowBits = Store.getMMO().getMemoryType().getScalarSizeInBits();
3460   if (ShiftAmt % NarrowBits!= 0)
3461     return None;
3462   const unsigned Offset = ShiftAmt / NarrowBits;
3463 
3464   if (SrcVal.isValid() && FoundSrcVal != SrcVal)
3465     return None;
3466 
3467   if (!SrcVal.isValid())
3468     SrcVal = FoundSrcVal;
3469   else if (MRI.getType(SrcVal) != MRI.getType(FoundSrcVal))
3470     return None;
3471   return Offset;
3472 }
3473 
3474 /// Match a pattern where a wide type scalar value is stored by several narrow
3475 /// stores. Fold it into a single store or a BSWAP and a store if the targets
3476 /// supports it.
3477 ///
3478 /// Assuming little endian target:
3479 ///  i8 *p = ...
3480 ///  i32 val = ...
3481 ///  p[0] = (val >> 0) & 0xFF;
3482 ///  p[1] = (val >> 8) & 0xFF;
3483 ///  p[2] = (val >> 16) & 0xFF;
3484 ///  p[3] = (val >> 24) & 0xFF;
3485 /// =>
3486 ///  *((i32)p) = val;
3487 ///
3488 ///  i8 *p = ...
3489 ///  i32 val = ...
3490 ///  p[0] = (val >> 24) & 0xFF;
3491 ///  p[1] = (val >> 16) & 0xFF;
3492 ///  p[2] = (val >> 8) & 0xFF;
3493 ///  p[3] = (val >> 0) & 0xFF;
3494 /// =>
3495 ///  *((i32)p) = BSWAP(val);
3496 bool CombinerHelper::matchTruncStoreMerge(MachineInstr &MI,
3497                                           MergeTruncStoresInfo &MatchInfo) {
3498   auto &StoreMI = cast<GStore>(MI);
3499   LLT MemTy = StoreMI.getMMO().getMemoryType();
3500 
3501   // We only handle merging simple stores of 1-4 bytes.
3502   if (!MemTy.isScalar())
3503     return false;
3504   switch (MemTy.getSizeInBits()) {
3505   case 8:
3506   case 16:
3507   case 32:
3508     break;
3509   default:
3510     return false;
3511   }
3512   if (!StoreMI.isSimple())
3513     return false;
3514 
3515   // We do a simple search for mergeable stores prior to this one.
3516   // Any potential alias hazard along the way terminates the search.
3517   SmallVector<GStore *> FoundStores;
3518 
3519   // We're looking for:
3520   // 1) a (store(trunc(...)))
3521   // 2) of an LSHR/ASHR of a single wide value, by the appropriate shift to get
3522   //    the partial value stored.
3523   // 3) where the offsets form either a little or big-endian sequence.
3524 
3525   auto &LastStore = StoreMI;
3526 
3527   // The single base pointer that all stores must use.
3528   Register BaseReg;
3529   int64_t LastOffset;
3530   if (!mi_match(LastStore.getPointerReg(), MRI,
3531                 m_GPtrAdd(m_Reg(BaseReg), m_ICst(LastOffset)))) {
3532     BaseReg = LastStore.getPointerReg();
3533     LastOffset = 0;
3534   }
3535 
3536   GStore *LowestIdxStore = &LastStore;
3537   int64_t LowestIdxOffset = LastOffset;
3538 
3539   Register WideSrcVal;
3540   auto LowestShiftAmt = getTruncStoreByteOffset(LastStore, WideSrcVal, MRI);
3541   if (!LowestShiftAmt)
3542     return false; // Didn't match a trunc.
3543   assert(WideSrcVal.isValid());
3544 
3545   LLT WideStoreTy = MRI.getType(WideSrcVal);
3546   // The wide type might not be a multiple of the memory type, e.g. s48 and s32.
3547   if (WideStoreTy.getSizeInBits() % MemTy.getSizeInBits() != 0)
3548     return false;
3549   const unsigned NumStoresRequired =
3550       WideStoreTy.getSizeInBits() / MemTy.getSizeInBits();
3551 
3552   SmallVector<int64_t, 8> OffsetMap(NumStoresRequired, INT64_MAX);
3553   OffsetMap[*LowestShiftAmt] = LastOffset;
3554   FoundStores.emplace_back(&LastStore);
3555 
3556   // Search the block up for more stores.
3557   // We use a search threshold of 10 instructions here because the combiner
3558   // works top-down within a block, and we don't want to search an unbounded
3559   // number of predecessor instructions trying to find matching stores.
3560   // If we moved this optimization into a separate pass then we could probably
3561   // use a more efficient search without having a hard-coded threshold.
3562   const int MaxInstsToCheck = 10;
3563   int NumInstsChecked = 0;
3564   for (auto II = ++LastStore.getReverseIterator();
3565        II != LastStore.getParent()->rend() && NumInstsChecked < MaxInstsToCheck;
3566        ++II) {
3567     NumInstsChecked++;
3568     GStore *NewStore;
3569     if ((NewStore = dyn_cast<GStore>(&*II))) {
3570       if (NewStore->getMMO().getMemoryType() != MemTy || !NewStore->isSimple())
3571         break;
3572     } else if (II->isLoadFoldBarrier() || II->mayLoad()) {
3573       break;
3574     } else {
3575       continue; // This is a safe instruction we can look past.
3576     }
3577 
3578     Register NewBaseReg;
3579     int64_t MemOffset;
3580     // Check we're storing to the same base + some offset.
3581     if (!mi_match(NewStore->getPointerReg(), MRI,
3582                   m_GPtrAdd(m_Reg(NewBaseReg), m_ICst(MemOffset)))) {
3583       NewBaseReg = NewStore->getPointerReg();
3584       MemOffset = 0;
3585     }
3586     if (BaseReg != NewBaseReg)
3587       break;
3588 
3589     auto ShiftByteOffset = getTruncStoreByteOffset(*NewStore, WideSrcVal, MRI);
3590     if (!ShiftByteOffset)
3591       break;
3592     if (MemOffset < LowestIdxOffset) {
3593       LowestIdxOffset = MemOffset;
3594       LowestIdxStore = NewStore;
3595     }
3596 
3597     // Map the offset in the store and the offset in the combined value, and
3598     // early return if it has been set before.
3599     if (*ShiftByteOffset < 0 || *ShiftByteOffset >= NumStoresRequired ||
3600         OffsetMap[*ShiftByteOffset] != INT64_MAX)
3601       break;
3602     OffsetMap[*ShiftByteOffset] = MemOffset;
3603 
3604     FoundStores.emplace_back(NewStore);
3605     // Reset counter since we've found a matching inst.
3606     NumInstsChecked = 0;
3607     if (FoundStores.size() == NumStoresRequired)
3608       break;
3609   }
3610 
3611   if (FoundStores.size() != NumStoresRequired) {
3612     return false;
3613   }
3614 
3615   const auto &DL = LastStore.getMF()->getDataLayout();
3616   auto &C = LastStore.getMF()->getFunction().getContext();
3617   // Check that a store of the wide type is both allowed and fast on the target
3618   bool Fast = false;
3619   bool Allowed = getTargetLowering().allowsMemoryAccess(
3620       C, DL, WideStoreTy, LowestIdxStore->getMMO(), &Fast);
3621   if (!Allowed || !Fast)
3622     return false;
3623 
3624   // Check if the pieces of the value are going to the expected places in memory
3625   // to merge the stores.
3626   unsigned NarrowBits = MemTy.getScalarSizeInBits();
3627   auto checkOffsets = [&](bool MatchLittleEndian) {
3628     if (MatchLittleEndian) {
3629       for (unsigned i = 0; i != NumStoresRequired; ++i)
3630         if (OffsetMap[i] != i * (NarrowBits / 8) + LowestIdxOffset)
3631           return false;
3632     } else { // MatchBigEndian by reversing loop counter.
3633       for (unsigned i = 0, j = NumStoresRequired - 1; i != NumStoresRequired;
3634            ++i, --j)
3635         if (OffsetMap[j] != i * (NarrowBits / 8) + LowestIdxOffset)
3636           return false;
3637     }
3638     return true;
3639   };
3640 
3641   // Check if the offsets line up for the native data layout of this target.
3642   bool NeedBswap = false;
3643   bool NeedRotate = false;
3644   if (!checkOffsets(DL.isLittleEndian())) {
3645     // Special-case: check if byte offsets line up for the opposite endian.
3646     if (NarrowBits == 8 && checkOffsets(DL.isBigEndian()))
3647       NeedBswap = true;
3648     else if (NumStoresRequired == 2 && checkOffsets(DL.isBigEndian()))
3649       NeedRotate = true;
3650     else
3651       return false;
3652   }
3653 
3654   if (NeedBswap &&
3655       !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {WideStoreTy}}))
3656     return false;
3657   if (NeedRotate &&
3658       !isLegalOrBeforeLegalizer({TargetOpcode::G_ROTR, {WideStoreTy}}))
3659     return false;
3660 
3661   MatchInfo.NeedBSwap = NeedBswap;
3662   MatchInfo.NeedRotate = NeedRotate;
3663   MatchInfo.LowestIdxStore = LowestIdxStore;
3664   MatchInfo.WideSrcVal = WideSrcVal;
3665   MatchInfo.FoundStores = std::move(FoundStores);
3666   return true;
3667 }
3668 
3669 void CombinerHelper::applyTruncStoreMerge(MachineInstr &MI,
3670                                           MergeTruncStoresInfo &MatchInfo) {
3671 
3672   Builder.setInstrAndDebugLoc(MI);
3673   Register WideSrcVal = MatchInfo.WideSrcVal;
3674   LLT WideStoreTy = MRI.getType(WideSrcVal);
3675 
3676   if (MatchInfo.NeedBSwap) {
3677     WideSrcVal = Builder.buildBSwap(WideStoreTy, WideSrcVal).getReg(0);
3678   } else if (MatchInfo.NeedRotate) {
3679     assert(WideStoreTy.getSizeInBits() % 2 == 0 &&
3680            "Unexpected type for rotate");
3681     auto RotAmt =
3682         Builder.buildConstant(WideStoreTy, WideStoreTy.getSizeInBits() / 2);
3683     WideSrcVal =
3684         Builder.buildRotateRight(WideStoreTy, WideSrcVal, RotAmt).getReg(0);
3685   }
3686 
3687   Builder.buildStore(WideSrcVal, MatchInfo.LowestIdxStore->getPointerReg(),
3688                      MatchInfo.LowestIdxStore->getMMO().getPointerInfo(),
3689                      MatchInfo.LowestIdxStore->getMMO().getAlign());
3690 
3691   // Erase the old stores.
3692   for (auto *ST : MatchInfo.FoundStores)
3693     ST->eraseFromParent();
3694 }
3695 
3696 bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
3697                                             MachineInstr *&ExtMI) {
3698   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3699 
3700   Register DstReg = MI.getOperand(0).getReg();
3701 
3702   // TODO: Extending a vector may be expensive, don't do this until heuristics
3703   // are better.
3704   if (MRI.getType(DstReg).isVector())
3705     return false;
3706 
3707   // Try to match a phi, whose only use is an extend.
3708   if (!MRI.hasOneNonDBGUse(DstReg))
3709     return false;
3710   ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
3711   switch (ExtMI->getOpcode()) {
3712   case TargetOpcode::G_ANYEXT:
3713     return true; // G_ANYEXT is usually free.
3714   case TargetOpcode::G_ZEXT:
3715   case TargetOpcode::G_SEXT:
3716     break;
3717   default:
3718     return false;
3719   }
3720 
3721   // If the target is likely to fold this extend away, don't propagate.
3722   if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
3723     return false;
3724 
3725   // We don't want to propagate the extends unless there's a good chance that
3726   // they'll be optimized in some way.
3727   // Collect the unique incoming values.
3728   SmallPtrSet<MachineInstr *, 4> InSrcs;
3729   for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
3730     auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI);
3731     switch (DefMI->getOpcode()) {
3732     case TargetOpcode::G_LOAD:
3733     case TargetOpcode::G_TRUNC:
3734     case TargetOpcode::G_SEXT:
3735     case TargetOpcode::G_ZEXT:
3736     case TargetOpcode::G_ANYEXT:
3737     case TargetOpcode::G_CONSTANT:
3738       InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI));
3739       // Don't try to propagate if there are too many places to create new
3740       // extends, chances are it'll increase code size.
3741       if (InSrcs.size() > 2)
3742         return false;
3743       break;
3744     default:
3745       return false;
3746     }
3747   }
3748   return true;
3749 }
3750 
3751 void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
3752                                             MachineInstr *&ExtMI) {
3753   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3754   Register DstReg = ExtMI->getOperand(0).getReg();
3755   LLT ExtTy = MRI.getType(DstReg);
3756 
3757   // Propagate the extension into the block of each incoming reg's block.
3758   // Use a SetVector here because PHIs can have duplicate edges, and we want
3759   // deterministic iteration order.
3760   SmallSetVector<MachineInstr *, 8> SrcMIs;
3761   SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
3762   for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) {
3763     auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg());
3764     if (!SrcMIs.insert(SrcMI))
3765       continue;
3766 
3767     // Build an extend after each src inst.
3768     auto *MBB = SrcMI->getParent();
3769     MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
3770     if (InsertPt != MBB->end() && InsertPt->isPHI())
3771       InsertPt = MBB->getFirstNonPHI();
3772 
3773     Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
3774     Builder.setDebugLoc(MI.getDebugLoc());
3775     auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy,
3776                                           SrcMI->getOperand(0).getReg());
3777     OldToNewSrcMap[SrcMI] = NewExt;
3778   }
3779 
3780   // Create a new phi with the extended inputs.
3781   Builder.setInstrAndDebugLoc(MI);
3782   auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
3783   NewPhi.addDef(DstReg);
3784   for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
3785     if (!MO.isReg()) {
3786       NewPhi.addMBB(MO.getMBB());
3787       continue;
3788     }
3789     auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
3790     NewPhi.addUse(NewSrc->getOperand(0).getReg());
3791   }
3792   Builder.insertInstr(NewPhi);
3793   ExtMI->eraseFromParent();
3794 }
3795 
3796 bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI,
3797                                                 Register &Reg) {
3798   assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
3799   // If we have a constant index, look for a G_BUILD_VECTOR source
3800   // and find the source register that the index maps to.
3801   Register SrcVec = MI.getOperand(1).getReg();
3802   LLT SrcTy = MRI.getType(SrcVec);
3803   if (!isLegalOrBeforeLegalizer(
3804           {TargetOpcode::G_BUILD_VECTOR, {SrcTy, SrcTy.getElementType()}}))
3805     return false;
3806 
3807   auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
3808   if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
3809     return false;
3810 
3811   unsigned VecIdx = Cst->Value.getZExtValue();
3812   MachineInstr *BuildVecMI =
3813       getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, SrcVec, MRI);
3814   if (!BuildVecMI) {
3815     BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR_TRUNC, SrcVec, MRI);
3816     if (!BuildVecMI)
3817       return false;
3818     LLT ScalarTy = MRI.getType(BuildVecMI->getOperand(1).getReg());
3819     if (!isLegalOrBeforeLegalizer(
3820             {TargetOpcode::G_BUILD_VECTOR_TRUNC, {SrcTy, ScalarTy}}))
3821       return false;
3822   }
3823 
3824   EVT Ty(getMVTForLLT(SrcTy));
3825   if (!MRI.hasOneNonDBGUse(SrcVec) &&
3826       !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
3827     return false;
3828 
3829   Reg = BuildVecMI->getOperand(VecIdx + 1).getReg();
3830   return true;
3831 }
3832 
3833 void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI,
3834                                                 Register &Reg) {
3835   // Check the type of the register, since it may have come from a
3836   // G_BUILD_VECTOR_TRUNC.
3837   LLT ScalarTy = MRI.getType(Reg);
3838   Register DstReg = MI.getOperand(0).getReg();
3839   LLT DstTy = MRI.getType(DstReg);
3840 
3841   Builder.setInstrAndDebugLoc(MI);
3842   if (ScalarTy != DstTy) {
3843     assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
3844     Builder.buildTrunc(DstReg, Reg);
3845     MI.eraseFromParent();
3846     return;
3847   }
3848   replaceSingleDefInstWithReg(MI, Reg);
3849 }
3850 
3851 bool CombinerHelper::matchExtractAllEltsFromBuildVector(
3852     MachineInstr &MI,
3853     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3854   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3855   // This combine tries to find build_vector's which have every source element
3856   // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
3857   // the masked load scalarization is run late in the pipeline. There's already
3858   // a combine for a similar pattern starting from the extract, but that
3859   // doesn't attempt to do it if there are multiple uses of the build_vector,
3860   // which in this case is true. Starting the combine from the build_vector
3861   // feels more natural than trying to find sibling nodes of extracts.
3862   // E.g.
3863   //  %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
3864   //  %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
3865   //  %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
3866   //  %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
3867   //  %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
3868   // ==>
3869   // replace ext{1,2,3,4} with %s{1,2,3,4}
3870 
3871   Register DstReg = MI.getOperand(0).getReg();
3872   LLT DstTy = MRI.getType(DstReg);
3873   unsigned NumElts = DstTy.getNumElements();
3874 
3875   SmallBitVector ExtractedElts(NumElts);
3876   for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
3877     if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
3878       return false;
3879     auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
3880     if (!Cst)
3881       return false;
3882     unsigned Idx = Cst.getValue().getZExtValue();
3883     if (Idx >= NumElts)
3884       return false; // Out of range.
3885     ExtractedElts.set(Idx);
3886     SrcDstPairs.emplace_back(
3887         std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
3888   }
3889   // Match if every element was extracted.
3890   return ExtractedElts.all();
3891 }
3892 
3893 void CombinerHelper::applyExtractAllEltsFromBuildVector(
3894     MachineInstr &MI,
3895     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3896   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3897   for (auto &Pair : SrcDstPairs) {
3898     auto *ExtMI = Pair.second;
3899     replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
3900     ExtMI->eraseFromParent();
3901   }
3902   MI.eraseFromParent();
3903 }
3904 
3905 void CombinerHelper::applyBuildFn(
3906     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3907   Builder.setInstrAndDebugLoc(MI);
3908   MatchInfo(Builder);
3909   MI.eraseFromParent();
3910 }
3911 
3912 void CombinerHelper::applyBuildFnNoErase(
3913     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3914   Builder.setInstrAndDebugLoc(MI);
3915   MatchInfo(Builder);
3916 }
3917 
3918 bool CombinerHelper::matchOrShiftToFunnelShift(MachineInstr &MI,
3919                                                BuildFnTy &MatchInfo) {
3920   assert(MI.getOpcode() == TargetOpcode::G_OR);
3921 
3922   Register Dst = MI.getOperand(0).getReg();
3923   LLT Ty = MRI.getType(Dst);
3924   unsigned BitWidth = Ty.getScalarSizeInBits();
3925 
3926   Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
3927   unsigned FshOpc = 0;
3928 
3929   // Match (or (shl ...), (lshr ...)).
3930   if (!mi_match(Dst, MRI,
3931                 // m_GOr() handles the commuted version as well.
3932                 m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
3933                       m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
3934     return false;
3935 
3936   // Given constants C0 and C1 such that C0 + C1 is bit-width:
3937   // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
3938   // TODO: Match constant splat.
3939   int64_t CstShlAmt, CstLShrAmt;
3940   if (mi_match(ShlAmt, MRI, m_ICst(CstShlAmt)) &&
3941       mi_match(LShrAmt, MRI, m_ICst(CstLShrAmt)) &&
3942       CstShlAmt + CstLShrAmt == BitWidth) {
3943     FshOpc = TargetOpcode::G_FSHR;
3944     Amt = LShrAmt;
3945 
3946   } else if (mi_match(LShrAmt, MRI,
3947                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
3948              ShlAmt == Amt) {
3949     // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
3950     FshOpc = TargetOpcode::G_FSHL;
3951 
3952   } else if (mi_match(ShlAmt, MRI,
3953                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
3954              LShrAmt == Amt) {
3955     // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
3956     FshOpc = TargetOpcode::G_FSHR;
3957 
3958   } else {
3959     return false;
3960   }
3961 
3962   LLT AmtTy = MRI.getType(Amt);
3963   if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}))
3964     return false;
3965 
3966   MatchInfo = [=](MachineIRBuilder &B) {
3967     B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
3968   };
3969   return true;
3970 }
3971 
3972 /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate.
3973 bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) {
3974   unsigned Opc = MI.getOpcode();
3975   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
3976   Register X = MI.getOperand(1).getReg();
3977   Register Y = MI.getOperand(2).getReg();
3978   if (X != Y)
3979     return false;
3980   unsigned RotateOpc =
3981       Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR;
3982   return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}});
3983 }
3984 
3985 void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) {
3986   unsigned Opc = MI.getOpcode();
3987   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
3988   bool IsFSHL = Opc == TargetOpcode::G_FSHL;
3989   Observer.changingInstr(MI);
3990   MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL
3991                                          : TargetOpcode::G_ROTR));
3992   MI.RemoveOperand(2);
3993   Observer.changedInstr(MI);
3994 }
3995 
3996 // Fold (rot x, c) -> (rot x, c % BitSize)
3997 bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) {
3998   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
3999          MI.getOpcode() == TargetOpcode::G_ROTR);
4000   unsigned Bitsize =
4001       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4002   Register AmtReg = MI.getOperand(2).getReg();
4003   bool OutOfRange = false;
4004   auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
4005     if (auto *CI = dyn_cast<ConstantInt>(C))
4006       OutOfRange |= CI->getValue().uge(Bitsize);
4007     return true;
4008   };
4009   return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
4010 }
4011 
4012 void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) {
4013   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4014          MI.getOpcode() == TargetOpcode::G_ROTR);
4015   unsigned Bitsize =
4016       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4017   Builder.setInstrAndDebugLoc(MI);
4018   Register Amt = MI.getOperand(2).getReg();
4019   LLT AmtTy = MRI.getType(Amt);
4020   auto Bits = Builder.buildConstant(AmtTy, Bitsize);
4021   Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
4022   Observer.changingInstr(MI);
4023   MI.getOperand(2).setReg(Amt);
4024   Observer.changedInstr(MI);
4025 }
4026 
4027 bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI,
4028                                                    int64_t &MatchInfo) {
4029   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4030   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4031   auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg());
4032   auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg());
4033   Optional<bool> KnownVal;
4034   switch (Pred) {
4035   default:
4036     llvm_unreachable("Unexpected G_ICMP predicate?");
4037   case CmpInst::ICMP_EQ:
4038     KnownVal = KnownBits::eq(KnownLHS, KnownRHS);
4039     break;
4040   case CmpInst::ICMP_NE:
4041     KnownVal = KnownBits::ne(KnownLHS, KnownRHS);
4042     break;
4043   case CmpInst::ICMP_SGE:
4044     KnownVal = KnownBits::sge(KnownLHS, KnownRHS);
4045     break;
4046   case CmpInst::ICMP_SGT:
4047     KnownVal = KnownBits::sgt(KnownLHS, KnownRHS);
4048     break;
4049   case CmpInst::ICMP_SLE:
4050     KnownVal = KnownBits::sle(KnownLHS, KnownRHS);
4051     break;
4052   case CmpInst::ICMP_SLT:
4053     KnownVal = KnownBits::slt(KnownLHS, KnownRHS);
4054     break;
4055   case CmpInst::ICMP_UGE:
4056     KnownVal = KnownBits::uge(KnownLHS, KnownRHS);
4057     break;
4058   case CmpInst::ICMP_UGT:
4059     KnownVal = KnownBits::ugt(KnownLHS, KnownRHS);
4060     break;
4061   case CmpInst::ICMP_ULE:
4062     KnownVal = KnownBits::ule(KnownLHS, KnownRHS);
4063     break;
4064   case CmpInst::ICMP_ULT:
4065     KnownVal = KnownBits::ult(KnownLHS, KnownRHS);
4066     break;
4067   }
4068   if (!KnownVal)
4069     return false;
4070   MatchInfo =
4071       *KnownVal
4072           ? getICmpTrueVal(getTargetLowering(),
4073                            /*IsVector = */
4074                            MRI.getType(MI.getOperand(0).getReg()).isVector(),
4075                            /* IsFP = */ false)
4076           : 0;
4077   return true;
4078 }
4079 
4080 bool CombinerHelper::matchICmpToLHSKnownBits(
4081     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4082   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4083   // Given:
4084   //
4085   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4086   // %cmp = G_ICMP ne %x, 0
4087   //
4088   // Or:
4089   //
4090   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4091   // %cmp = G_ICMP eq %x, 1
4092   //
4093   // We can replace %cmp with %x assuming true is 1 on the target.
4094   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4095   if (!CmpInst::isEquality(Pred))
4096     return false;
4097   Register Dst = MI.getOperand(0).getReg();
4098   LLT DstTy = MRI.getType(Dst);
4099   if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(),
4100                      /* IsFP = */ false) != 1)
4101     return false;
4102   int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
4103   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
4104     return false;
4105   Register LHS = MI.getOperand(2).getReg();
4106   auto KnownLHS = KB->getKnownBits(LHS);
4107   if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
4108     return false;
4109   // Make sure replacing Dst with the LHS is a legal operation.
4110   LLT LHSTy = MRI.getType(LHS);
4111   unsigned LHSSize = LHSTy.getSizeInBits();
4112   unsigned DstSize = DstTy.getSizeInBits();
4113   unsigned Op = TargetOpcode::COPY;
4114   if (DstSize != LHSSize)
4115     Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
4116   if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
4117     return false;
4118   MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
4119   return true;
4120 }
4121 
4122 // Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
4123 bool CombinerHelper::matchAndOrDisjointMask(
4124     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4125   assert(MI.getOpcode() == TargetOpcode::G_AND);
4126 
4127   // Ignore vector types to simplify matching the two constants.
4128   // TODO: do this for vectors and scalars via a demanded bits analysis.
4129   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
4130   if (Ty.isVector())
4131     return false;
4132 
4133   Register Src;
4134   int64_t MaskAnd;
4135   int64_t MaskOr;
4136   if (!mi_match(MI, MRI,
4137                 m_GAnd(m_GOr(m_Reg(Src), m_ICst(MaskOr)), m_ICst(MaskAnd))))
4138     return false;
4139 
4140   // Check if MaskOr could turn on any bits in Src.
4141   if (MaskAnd & MaskOr)
4142     return false;
4143 
4144   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4145     Observer.changingInstr(MI);
4146     MI.getOperand(1).setReg(Src);
4147     Observer.changedInstr(MI);
4148   };
4149   return true;
4150 }
4151 
4152 /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
4153 bool CombinerHelper::matchBitfieldExtractFromSExtInReg(
4154     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4155   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
4156   Register Dst = MI.getOperand(0).getReg();
4157   Register Src = MI.getOperand(1).getReg();
4158   LLT Ty = MRI.getType(Src);
4159   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4160   if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
4161     return false;
4162   int64_t Width = MI.getOperand(2).getImm();
4163   Register ShiftSrc;
4164   int64_t ShiftImm;
4165   if (!mi_match(
4166           Src, MRI,
4167           m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
4168                                   m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
4169     return false;
4170   if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
4171     return false;
4172 
4173   MatchInfo = [=](MachineIRBuilder &B) {
4174     auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
4175     auto Cst2 = B.buildConstant(ExtractTy, Width);
4176     B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
4177   };
4178   return true;
4179 }
4180 
4181 /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
4182 bool CombinerHelper::matchBitfieldExtractFromAnd(
4183     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4184   assert(MI.getOpcode() == TargetOpcode::G_AND);
4185   Register Dst = MI.getOperand(0).getReg();
4186   LLT Ty = MRI.getType(Dst);
4187   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4188   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
4189           TargetOpcode::G_UBFX, Ty, ExtractTy))
4190     return false;
4191 
4192   int64_t AndImm, LSBImm;
4193   Register ShiftSrc;
4194   const unsigned Size = Ty.getScalarSizeInBits();
4195   if (!mi_match(MI.getOperand(0).getReg(), MRI,
4196                 m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
4197                        m_ICst(AndImm))))
4198     return false;
4199 
4200   // The mask is a mask of the low bits iff imm & (imm+1) == 0.
4201   auto MaybeMask = static_cast<uint64_t>(AndImm);
4202   if (MaybeMask & (MaybeMask + 1))
4203     return false;
4204 
4205   // LSB must fit within the register.
4206   if (static_cast<uint64_t>(LSBImm) >= Size)
4207     return false;
4208 
4209   uint64_t Width = APInt(Size, AndImm).countTrailingOnes();
4210   MatchInfo = [=](MachineIRBuilder &B) {
4211     auto WidthCst = B.buildConstant(ExtractTy, Width);
4212     auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
4213     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
4214   };
4215   return true;
4216 }
4217 
4218 bool CombinerHelper::matchBitfieldExtractFromShr(
4219     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4220   const unsigned Opcode = MI.getOpcode();
4221   assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
4222 
4223   const Register Dst = MI.getOperand(0).getReg();
4224 
4225   const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
4226                                   ? TargetOpcode::G_SBFX
4227                                   : TargetOpcode::G_UBFX;
4228 
4229   // Check if the type we would use for the extract is legal
4230   LLT Ty = MRI.getType(Dst);
4231   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4232   if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
4233     return false;
4234 
4235   Register ShlSrc;
4236   int64_t ShrAmt;
4237   int64_t ShlAmt;
4238   const unsigned Size = Ty.getScalarSizeInBits();
4239 
4240   // Try to match shr (shl x, c1), c2
4241   if (!mi_match(Dst, MRI,
4242                 m_BinOp(Opcode,
4243                         m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
4244                         m_ICst(ShrAmt))))
4245     return false;
4246 
4247   // Make sure that the shift sizes can fit a bitfield extract
4248   if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
4249     return false;
4250 
4251   // Skip this combine if the G_SEXT_INREG combine could handle it
4252   if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
4253     return false;
4254 
4255   // Calculate start position and width of the extract
4256   const int64_t Pos = ShrAmt - ShlAmt;
4257   const int64_t Width = Size - ShrAmt;
4258 
4259   MatchInfo = [=](MachineIRBuilder &B) {
4260     auto WidthCst = B.buildConstant(ExtractTy, Width);
4261     auto PosCst = B.buildConstant(ExtractTy, Pos);
4262     B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
4263   };
4264   return true;
4265 }
4266 
4267 bool CombinerHelper::matchBitfieldExtractFromShrAnd(
4268     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4269   const unsigned Opcode = MI.getOpcode();
4270   assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
4271 
4272   const Register Dst = MI.getOperand(0).getReg();
4273   LLT Ty = MRI.getType(Dst);
4274   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4275   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
4276           TargetOpcode::G_UBFX, Ty, ExtractTy))
4277     return false;
4278 
4279   // Try to match shr (and x, c1), c2
4280   Register AndSrc;
4281   int64_t ShrAmt;
4282   int64_t SMask;
4283   if (!mi_match(Dst, MRI,
4284                 m_BinOp(Opcode,
4285                         m_OneNonDBGUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
4286                         m_ICst(ShrAmt))))
4287     return false;
4288 
4289   const unsigned Size = Ty.getScalarSizeInBits();
4290   if (ShrAmt < 0 || ShrAmt >= Size)
4291     return false;
4292 
4293   // Check that ubfx can do the extraction, with no holes in the mask.
4294   uint64_t UMask = SMask;
4295   UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
4296   UMask &= maskTrailingOnes<uint64_t>(Size);
4297   if (!isMask_64(UMask))
4298     return false;
4299 
4300   // Calculate start position and width of the extract.
4301   const int64_t Pos = ShrAmt;
4302   const int64_t Width = countTrailingOnes(UMask) - ShrAmt;
4303 
4304   // It's preferable to keep the shift, rather than form G_SBFX.
4305   // TODO: remove the G_AND via demanded bits analysis.
4306   if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
4307     return false;
4308 
4309   MatchInfo = [=](MachineIRBuilder &B) {
4310     auto WidthCst = B.buildConstant(ExtractTy, Width);
4311     auto PosCst = B.buildConstant(ExtractTy, Pos);
4312     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
4313   };
4314   return true;
4315 }
4316 
4317 bool CombinerHelper::reassociationCanBreakAddressingModePattern(
4318     MachineInstr &PtrAdd) {
4319   assert(PtrAdd.getOpcode() == TargetOpcode::G_PTR_ADD);
4320 
4321   Register Src1Reg = PtrAdd.getOperand(1).getReg();
4322   MachineInstr *Src1Def = getOpcodeDef(TargetOpcode::G_PTR_ADD, Src1Reg, MRI);
4323   if (!Src1Def)
4324     return false;
4325 
4326   Register Src2Reg = PtrAdd.getOperand(2).getReg();
4327 
4328   if (MRI.hasOneNonDBGUse(Src1Reg))
4329     return false;
4330 
4331   auto C1 = getIConstantVRegVal(Src1Def->getOperand(2).getReg(), MRI);
4332   if (!C1)
4333     return false;
4334   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4335   if (!C2)
4336     return false;
4337 
4338   const APInt &C1APIntVal = *C1;
4339   const APInt &C2APIntVal = *C2;
4340   const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
4341 
4342   for (auto &UseMI : MRI.use_nodbg_instructions(Src1Reg)) {
4343     // This combine may end up running before ptrtoint/inttoptr combines
4344     // manage to eliminate redundant conversions, so try to look through them.
4345     MachineInstr *ConvUseMI = &UseMI;
4346     unsigned ConvUseOpc = ConvUseMI->getOpcode();
4347     while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
4348            ConvUseOpc == TargetOpcode::G_PTRTOINT) {
4349       Register DefReg = ConvUseMI->getOperand(0).getReg();
4350       if (!MRI.hasOneNonDBGUse(DefReg))
4351         break;
4352       ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
4353       ConvUseOpc = ConvUseMI->getOpcode();
4354     }
4355     auto LoadStore = ConvUseOpc == TargetOpcode::G_LOAD ||
4356                      ConvUseOpc == TargetOpcode::G_STORE;
4357     if (!LoadStore)
4358       continue;
4359     // Is x[offset2] already not a legal addressing mode? If so then
4360     // reassociating the constants breaks nothing (we test offset2 because
4361     // that's the one we hope to fold into the load or store).
4362     TargetLoweringBase::AddrMode AM;
4363     AM.HasBaseReg = true;
4364     AM.BaseOffs = C2APIntVal.getSExtValue();
4365     unsigned AS =
4366         MRI.getType(ConvUseMI->getOperand(1).getReg()).getAddressSpace();
4367     Type *AccessTy =
4368         getTypeForLLT(MRI.getType(ConvUseMI->getOperand(0).getReg()),
4369                       PtrAdd.getMF()->getFunction().getContext());
4370     const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
4371     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4372                                    AccessTy, AS))
4373       continue;
4374 
4375     // Would x[offset1+offset2] still be a legal addressing mode?
4376     AM.BaseOffs = CombinedValue;
4377     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4378                                    AccessTy, AS))
4379       return true;
4380   }
4381 
4382   return false;
4383 }
4384 
4385 bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI,
4386                                                   MachineInstr *RHS,
4387                                                   BuildFnTy &MatchInfo) {
4388   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4389   Register Src1Reg = MI.getOperand(1).getReg();
4390   if (RHS->getOpcode() != TargetOpcode::G_ADD)
4391     return false;
4392   auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
4393   if (!C2)
4394     return false;
4395 
4396   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4397     LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
4398 
4399     auto NewBase =
4400         Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg());
4401     Observer.changingInstr(MI);
4402     MI.getOperand(1).setReg(NewBase.getReg(0));
4403     MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
4404     Observer.changedInstr(MI);
4405   };
4406   return !reassociationCanBreakAddressingModePattern(MI);
4407 }
4408 
4409 bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI,
4410                                                   MachineInstr *LHS,
4411                                                   MachineInstr *RHS,
4412                                                   BuildFnTy &MatchInfo) {
4413   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
4414   // if and only if (G_PTR_ADD X, C) has one use.
4415   Register LHSBase;
4416   Optional<ValueAndVReg> LHSCstOff;
4417   if (!mi_match(MI.getBaseReg(), MRI,
4418                 m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
4419     return false;
4420 
4421   auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
4422   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4423     // When we change LHSPtrAdd's offset register we might cause it to use a reg
4424     // before its def. Sink the instruction so the outer PTR_ADD to ensure this
4425     // doesn't happen.
4426     LHSPtrAdd->moveBefore(&MI);
4427     Register RHSReg = MI.getOffsetReg();
4428     Observer.changingInstr(MI);
4429     MI.getOperand(2).setReg(LHSCstOff->VReg);
4430     Observer.changedInstr(MI);
4431     Observer.changingInstr(*LHSPtrAdd);
4432     LHSPtrAdd->getOperand(2).setReg(RHSReg);
4433     Observer.changedInstr(*LHSPtrAdd);
4434   };
4435   return !reassociationCanBreakAddressingModePattern(MI);
4436 }
4437 
4438 bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI,
4439                                                         MachineInstr *LHS,
4440                                                         MachineInstr *RHS,
4441                                                         BuildFnTy &MatchInfo) {
4442   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4443   auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
4444   if (!LHSPtrAdd)
4445     return false;
4446 
4447   Register Src2Reg = MI.getOperand(2).getReg();
4448   Register LHSSrc1 = LHSPtrAdd->getBaseReg();
4449   Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
4450   auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
4451   if (!C1)
4452     return false;
4453   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4454   if (!C2)
4455     return false;
4456 
4457   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4458     auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
4459     Observer.changingInstr(MI);
4460     MI.getOperand(1).setReg(LHSSrc1);
4461     MI.getOperand(2).setReg(NewCst.getReg(0));
4462     Observer.changedInstr(MI);
4463   };
4464   return !reassociationCanBreakAddressingModePattern(MI);
4465 }
4466 
4467 bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI,
4468                                         BuildFnTy &MatchInfo) {
4469   auto &PtrAdd = cast<GPtrAdd>(MI);
4470   // We're trying to match a few pointer computation patterns here for
4471   // re-association opportunities.
4472   // 1) Isolating a constant operand to be on the RHS, e.g.:
4473   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4474   //
4475   // 2) Folding two constants in each sub-tree as long as such folding
4476   // doesn't break a legal addressing mode.
4477   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4478   //
4479   // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
4480   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
4481   // iif (G_PTR_ADD X, C) has one use.
4482   MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg());
4483   MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg());
4484 
4485   // Try to match example 2.
4486   if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
4487     return true;
4488 
4489   // Try to match example 3.
4490   if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
4491     return true;
4492 
4493   // Try to match example 1.
4494   if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
4495     return true;
4496 
4497   return false;
4498 }
4499 
4500 bool CombinerHelper::matchConstantFold(MachineInstr &MI, APInt &MatchInfo) {
4501   Register Op1 = MI.getOperand(1).getReg();
4502   Register Op2 = MI.getOperand(2).getReg();
4503   auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
4504   if (!MaybeCst)
4505     return false;
4506   MatchInfo = *MaybeCst;
4507   return true;
4508 }
4509 
4510 bool CombinerHelper::matchNarrowBinopFeedingAnd(
4511     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4512   // Look for a binop feeding into an AND with a mask:
4513   //
4514   // %add = G_ADD %lhs, %rhs
4515   // %and = G_AND %add, 000...11111111
4516   //
4517   // Check if it's possible to perform the binop at a narrower width and zext
4518   // back to the original width like so:
4519   //
4520   // %narrow_lhs = G_TRUNC %lhs
4521   // %narrow_rhs = G_TRUNC %rhs
4522   // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
4523   // %new_add = G_ZEXT %narrow_add
4524   // %and = G_AND %new_add, 000...11111111
4525   //
4526   // This can allow later combines to eliminate the G_AND if it turns out
4527   // that the mask is irrelevant.
4528   assert(MI.getOpcode() == TargetOpcode::G_AND);
4529   Register Dst = MI.getOperand(0).getReg();
4530   Register AndLHS = MI.getOperand(1).getReg();
4531   Register AndRHS = MI.getOperand(2).getReg();
4532   LLT WideTy = MRI.getType(Dst);
4533 
4534   // If the potential binop has more than one use, then it's possible that one
4535   // of those uses will need its full width.
4536   if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
4537     return false;
4538 
4539   // Check if the LHS feeding the AND is impacted by the high bits that we're
4540   // masking out.
4541   //
4542   // e.g. for 64-bit x, y:
4543   //
4544   // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
4545   MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
4546   if (!LHSInst)
4547     return false;
4548   unsigned LHSOpc = LHSInst->getOpcode();
4549   switch (LHSOpc) {
4550   default:
4551     return false;
4552   case TargetOpcode::G_ADD:
4553   case TargetOpcode::G_SUB:
4554   case TargetOpcode::G_MUL:
4555   case TargetOpcode::G_AND:
4556   case TargetOpcode::G_OR:
4557   case TargetOpcode::G_XOR:
4558     break;
4559   }
4560 
4561   // Find the mask on the RHS.
4562   auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
4563   if (!Cst)
4564     return false;
4565   auto Mask = Cst->Value;
4566   if (!Mask.isMask())
4567     return false;
4568 
4569   // No point in combining if there's nothing to truncate.
4570   unsigned NarrowWidth = Mask.countTrailingOnes();
4571   if (NarrowWidth == WideTy.getSizeInBits())
4572     return false;
4573   LLT NarrowTy = LLT::scalar(NarrowWidth);
4574 
4575   // Check if adding the zext + truncates could be harmful.
4576   auto &MF = *MI.getMF();
4577   const auto &TLI = getTargetLowering();
4578   LLVMContext &Ctx = MF.getFunction().getContext();
4579   auto &DL = MF.getDataLayout();
4580   if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) ||
4581       !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx))
4582     return false;
4583   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
4584       !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
4585     return false;
4586   Register BinOpLHS = LHSInst->getOperand(1).getReg();
4587   Register BinOpRHS = LHSInst->getOperand(2).getReg();
4588   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4589     auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
4590     auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
4591     auto NarrowBinOp =
4592         Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
4593     auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
4594     Observer.changingInstr(MI);
4595     MI.getOperand(1).setReg(Ext.getReg(0));
4596     Observer.changedInstr(MI);
4597   };
4598   return true;
4599 }
4600 
4601 bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) {
4602   unsigned Opc = MI.getOpcode();
4603   assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO);
4604 
4605   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(2)))
4606     return false;
4607 
4608   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4609     Observer.changingInstr(MI);
4610     unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO
4611                                                    : TargetOpcode::G_SADDO;
4612     MI.setDesc(Builder.getTII().get(NewOpc));
4613     MI.getOperand(3).setReg(MI.getOperand(2).getReg());
4614     Observer.changedInstr(MI);
4615   };
4616   return true;
4617 }
4618 
4619 bool CombinerHelper::matchMulOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
4620   // (G_*MULO x, 0) -> 0 + no carry out
4621   assert(MI.getOpcode() == TargetOpcode::G_UMULO ||
4622          MI.getOpcode() == TargetOpcode::G_SMULO);
4623   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
4624     return false;
4625   Register Dst = MI.getOperand(0).getReg();
4626   Register Carry = MI.getOperand(1).getReg();
4627   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Dst)) ||
4628       !isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
4629     return false;
4630   MatchInfo = [=](MachineIRBuilder &B) {
4631     B.buildConstant(Dst, 0);
4632     B.buildConstant(Carry, 0);
4633   };
4634   return true;
4635 }
4636 
4637 bool CombinerHelper::matchAddOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
4638   // (G_*ADDO x, 0) -> x + no carry out
4639   assert(MI.getOpcode() == TargetOpcode::G_UADDO ||
4640          MI.getOpcode() == TargetOpcode::G_SADDO);
4641   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
4642     return false;
4643   Register Carry = MI.getOperand(1).getReg();
4644   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
4645     return false;
4646   Register Dst = MI.getOperand(0).getReg();
4647   Register LHS = MI.getOperand(2).getReg();
4648   MatchInfo = [=](MachineIRBuilder &B) {
4649     B.buildCopy(Dst, LHS);
4650     B.buildConstant(Carry, 0);
4651   };
4652   return true;
4653 }
4654 
4655 MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) {
4656   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4657   auto &UDiv = cast<GenericMachineInstr>(MI);
4658   Register Dst = UDiv.getReg(0);
4659   Register LHS = UDiv.getReg(1);
4660   Register RHS = UDiv.getReg(2);
4661   LLT Ty = MRI.getType(Dst);
4662   LLT ScalarTy = Ty.getScalarType();
4663   const unsigned EltBits = ScalarTy.getScalarSizeInBits();
4664   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4665   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
4666   auto &MIB = Builder;
4667   MIB.setInstrAndDebugLoc(MI);
4668 
4669   bool UseNPQ = false;
4670   SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4671 
4672   auto BuildUDIVPattern = [&](const Constant *C) {
4673     auto *CI = cast<ConstantInt>(C);
4674     const APInt &Divisor = CI->getValue();
4675     UnsignedDivisonByConstantInfo magics =
4676         UnsignedDivisonByConstantInfo::get(Divisor);
4677     unsigned PreShift = 0, PostShift = 0;
4678 
4679     // If the divisor is even, we can avoid using the expensive fixup by
4680     // shifting the divided value upfront.
4681     if (magics.IsAdd != 0 && !Divisor[0]) {
4682       PreShift = Divisor.countTrailingZeros();
4683       // Get magic number for the shifted divisor.
4684       magics =
4685           UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
4686       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
4687     }
4688 
4689     APInt Magic = magics.Magic;
4690 
4691     unsigned SelNPQ;
4692     if (magics.IsAdd == 0 || Divisor.isOneValue()) {
4693       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
4694              "We shouldn't generate an undefined shift!");
4695       PostShift = magics.ShiftAmount;
4696       SelNPQ = false;
4697     } else {
4698       PostShift = magics.ShiftAmount - 1;
4699       SelNPQ = true;
4700     }
4701 
4702     PreShifts.push_back(
4703         MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
4704     MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
4705     NPQFactors.push_back(
4706         MIB.buildConstant(ScalarTy,
4707                           SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4708                                  : APInt::getZero(EltBits))
4709             .getReg(0));
4710     PostShifts.push_back(
4711         MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
4712     UseNPQ |= SelNPQ;
4713     return true;
4714   };
4715 
4716   // Collect the shifts/magic values from each element.
4717   bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
4718   (void)Matched;
4719   assert(Matched && "Expected unary predicate match to succeed");
4720 
4721   Register PreShift, PostShift, MagicFactor, NPQFactor;
4722   auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
4723   if (RHSDef) {
4724     PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
4725     MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
4726     NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
4727     PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
4728   } else {
4729     assert(MRI.getType(RHS).isScalar() &&
4730            "Non-build_vector operation should have been a scalar");
4731     PreShift = PreShifts[0];
4732     MagicFactor = MagicFactors[0];
4733     PostShift = PostShifts[0];
4734   }
4735 
4736   Register Q = LHS;
4737   Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
4738 
4739   // Multiply the numerator (operand 0) by the magic value.
4740   Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
4741 
4742   if (UseNPQ) {
4743     Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
4744 
4745     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4746     // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
4747     if (Ty.isVector())
4748       NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
4749     else
4750       NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
4751 
4752     Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
4753   }
4754 
4755   Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
4756   auto One = MIB.buildConstant(Ty, 1);
4757   auto IsOne = MIB.buildICmp(
4758       CmpInst::Predicate::ICMP_EQ,
4759       Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One);
4760   return MIB.buildSelect(Ty, IsOne, LHS, Q);
4761 }
4762 
4763 bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
4764   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4765   Register Dst = MI.getOperand(0).getReg();
4766   Register RHS = MI.getOperand(2).getReg();
4767   LLT DstTy = MRI.getType(Dst);
4768   auto *RHSDef = MRI.getVRegDef(RHS);
4769   if (!isConstantOrConstantVector(*RHSDef, MRI))
4770     return false;
4771 
4772   auto &MF = *MI.getMF();
4773   AttributeList Attr = MF.getFunction().getAttributes();
4774   const auto &TLI = getTargetLowering();
4775   LLVMContext &Ctx = MF.getFunction().getContext();
4776   auto &DL = MF.getDataLayout();
4777   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
4778     return false;
4779 
4780   // Don't do this for minsize because the instruction sequence is usually
4781   // larger.
4782   if (MF.getFunction().hasMinSize())
4783     return false;
4784 
4785   // Don't do this if the types are not going to be legal.
4786   if (LI) {
4787     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
4788       return false;
4789     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
4790       return false;
4791     if (!isLegalOrBeforeLegalizer(
4792             {TargetOpcode::G_ICMP,
4793              {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
4794               DstTy}}))
4795       return false;
4796   }
4797 
4798   auto CheckEltValue = [&](const Constant *C) {
4799     if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
4800       return !CI->isZero();
4801     return false;
4802   };
4803   return matchUnaryPredicate(MRI, RHS, CheckEltValue);
4804 }
4805 
4806 void CombinerHelper::applyUDivByConst(MachineInstr &MI) {
4807   auto *NewMI = buildUDivUsingMul(MI);
4808   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
4809 }
4810 
4811 bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) {
4812   assert(MI.getOpcode() == TargetOpcode::G_UMULH);
4813   Register RHS = MI.getOperand(2).getReg();
4814   Register Dst = MI.getOperand(0).getReg();
4815   LLT Ty = MRI.getType(Dst);
4816   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4817   auto MatchPow2ExceptOne = [&](const Constant *C) {
4818     if (auto *CI = dyn_cast<ConstantInt>(C))
4819       return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
4820     return false;
4821   };
4822   if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
4823     return false;
4824   return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}});
4825 }
4826 
4827 void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) {
4828   Register LHS = MI.getOperand(1).getReg();
4829   Register RHS = MI.getOperand(2).getReg();
4830   Register Dst = MI.getOperand(0).getReg();
4831   LLT Ty = MRI.getType(Dst);
4832   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4833   unsigned NumEltBits = Ty.getScalarSizeInBits();
4834 
4835   Builder.setInstrAndDebugLoc(MI);
4836   auto LogBase2 = buildLogBase2(RHS, Builder);
4837   auto ShiftAmt =
4838       Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
4839   auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
4840   Builder.buildLShr(Dst, LHS, Trunc);
4841   MI.eraseFromParent();
4842 }
4843 
4844 bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI,
4845                                                BuildFnTy &MatchInfo) {
4846   unsigned Opc = MI.getOpcode();
4847   assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB ||
4848          Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
4849          Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA);
4850 
4851   Register Dst = MI.getOperand(0).getReg();
4852   Register X = MI.getOperand(1).getReg();
4853   Register Y = MI.getOperand(2).getReg();
4854   LLT Type = MRI.getType(Dst);
4855 
4856   // fold (fadd x, fneg(y)) -> (fsub x, y)
4857   // fold (fadd fneg(y), x) -> (fsub x, y)
4858   // G_ADD is commutative so both cases are checked by m_GFAdd
4859   if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
4860       isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) {
4861     Opc = TargetOpcode::G_FSUB;
4862   }
4863   /// fold (fsub x, fneg(y)) -> (fadd x, y)
4864   else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
4865            isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) {
4866     Opc = TargetOpcode::G_FADD;
4867   }
4868   // fold (fmul fneg(x), fneg(y)) -> (fmul x, y)
4869   // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y)
4870   // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z)
4871   // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z)
4872   else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
4873             Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) &&
4874            mi_match(X, MRI, m_GFNeg(m_Reg(X))) &&
4875            mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) {
4876     // no opcode change
4877   } else
4878     return false;
4879 
4880   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4881     Observer.changingInstr(MI);
4882     MI.setDesc(B.getTII().get(Opc));
4883     MI.getOperand(1).setReg(X);
4884     MI.getOperand(2).setReg(Y);
4885     Observer.changedInstr(MI);
4886   };
4887   return true;
4888 }
4889 
4890 /// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
4891 /// due to global flags or MachineInstr flags.
4892 static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
4893   if (MI.getOpcode() != TargetOpcode::G_FMUL)
4894     return false;
4895   return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
4896 }
4897 
4898 static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
4899                         const MachineRegisterInfo &MRI) {
4900   return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
4901                        MRI.use_instr_nodbg_end()) >
4902          std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
4903                        MRI.use_instr_nodbg_end());
4904 }
4905 
4906 bool CombinerHelper::canCombineFMadOrFMA(MachineInstr &MI,
4907                                          bool &AllowFusionGlobally,
4908                                          bool &HasFMAD, bool &Aggressive,
4909                                          bool CanReassociate) {
4910 
4911   auto *MF = MI.getMF();
4912   const auto &TLI = *MF->getSubtarget().getTargetLowering();
4913   const TargetOptions &Options = MF->getTarget().Options;
4914   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
4915 
4916   if (CanReassociate &&
4917       !(Options.UnsafeFPMath || MI.getFlag(MachineInstr::MIFlag::FmReassoc)))
4918     return false;
4919 
4920   // Floating-point multiply-add with intermediate rounding.
4921   HasFMAD = (LI && TLI.isFMADLegal(MI, DstType));
4922   // Floating-point multiply-add without intermediate rounding.
4923   bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
4924                 isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
4925   // No valid opcode, do not combine.
4926   if (!HasFMAD && !HasFMA)
4927     return false;
4928 
4929   AllowFusionGlobally = Options.AllowFPOpFusion == FPOpFusion::Fast ||
4930                         Options.UnsafeFPMath || HasFMAD;
4931   // If the addition is not contractable, do not combine.
4932   if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
4933     return false;
4934 
4935   Aggressive = TLI.enableAggressiveFMAFusion(DstType);
4936   return true;
4937 }
4938 
4939 bool CombinerHelper::matchCombineFAddFMulToFMadOrFMA(
4940     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4941   assert(MI.getOpcode() == TargetOpcode::G_FADD);
4942 
4943   bool AllowFusionGlobally, HasFMAD, Aggressive;
4944   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
4945     return false;
4946 
4947   Register Op1 = MI.getOperand(1).getReg();
4948   Register Op2 = MI.getOperand(2).getReg();
4949   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
4950   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
4951   unsigned PreferredFusedOpcode =
4952       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
4953 
4954   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
4955   // prefer to fold the multiply with fewer uses.
4956   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
4957       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
4958     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
4959       std::swap(LHS, RHS);
4960   }
4961 
4962   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
4963   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
4964       (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
4965     MatchInfo = [=, &MI](MachineIRBuilder &B) {
4966       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
4967                    {LHS.MI->getOperand(1).getReg(),
4968                     LHS.MI->getOperand(2).getReg(), RHS.Reg});
4969     };
4970     return true;
4971   }
4972 
4973   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
4974   if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
4975       (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
4976     MatchInfo = [=, &MI](MachineIRBuilder &B) {
4977       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
4978                    {RHS.MI->getOperand(1).getReg(),
4979                     RHS.MI->getOperand(2).getReg(), LHS.Reg});
4980     };
4981     return true;
4982   }
4983 
4984   return false;
4985 }
4986 
4987 bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA(
4988     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4989   assert(MI.getOpcode() == TargetOpcode::G_FADD);
4990 
4991   bool AllowFusionGlobally, HasFMAD, Aggressive;
4992   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
4993     return false;
4994 
4995   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
4996   Register Op1 = MI.getOperand(1).getReg();
4997   Register Op2 = MI.getOperand(2).getReg();
4998   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
4999   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5000   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
5001 
5002   unsigned PreferredFusedOpcode =
5003       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5004 
5005   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5006   // prefer to fold the multiply with fewer uses.
5007   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5008       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5009     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5010       std::swap(LHS, RHS);
5011   }
5012 
5013   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
5014   MachineInstr *FpExtSrc;
5015   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
5016       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
5017       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5018                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
5019     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5020       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
5021       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
5022       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5023                    {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg});
5024     };
5025     return true;
5026   }
5027 
5028   // fold (fadd z, (fpext (fmul x, y))) -> (fma (fpext x), (fpext y), z)
5029   // Note: Commutes FADD operands.
5030   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
5031       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
5032       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5033                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
5034     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5035       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
5036       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
5037       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5038                    {FpExtX.getReg(0), FpExtY.getReg(0), LHS.Reg});
5039     };
5040     return true;
5041   }
5042 
5043   return false;
5044 }
5045 
5046 bool CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA(
5047     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5048   assert(MI.getOpcode() == TargetOpcode::G_FADD);
5049 
5050   bool AllowFusionGlobally, HasFMAD, Aggressive;
5051   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
5052     return false;
5053 
5054   Register Op1 = MI.getOperand(1).getReg();
5055   Register Op2 = MI.getOperand(2).getReg();
5056   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5057   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5058   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5059 
5060   unsigned PreferredFusedOpcode =
5061       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5062 
5063   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5064   // prefer to fold the multiply with fewer uses.
5065   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5066       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5067     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5068       std::swap(LHS, RHS);
5069   }
5070 
5071   MachineInstr *FMA = nullptr;
5072   Register Z;
5073   // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
5074   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
5075       (MRI.getVRegDef(LHS.MI->getOperand(3).getReg())->getOpcode() ==
5076        TargetOpcode::G_FMUL) &&
5077       MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
5078       MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
5079     FMA = LHS.MI;
5080     Z = RHS.Reg;
5081   }
5082   // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
5083   else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
5084            (MRI.getVRegDef(RHS.MI->getOperand(3).getReg())->getOpcode() ==
5085             TargetOpcode::G_FMUL) &&
5086            MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
5087            MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
5088     Z = LHS.Reg;
5089     FMA = RHS.MI;
5090   }
5091 
5092   if (FMA) {
5093     MachineInstr *FMulMI = MRI.getVRegDef(FMA->getOperand(3).getReg());
5094     Register X = FMA->getOperand(1).getReg();
5095     Register Y = FMA->getOperand(2).getReg();
5096     Register U = FMulMI->getOperand(1).getReg();
5097     Register V = FMulMI->getOperand(2).getReg();
5098 
5099     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5100       Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
5101       B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z});
5102       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5103                    {X, Y, InnerFMA});
5104     };
5105     return true;
5106   }
5107 
5108   return false;
5109 }
5110 
5111 bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
5112     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5113   assert(MI.getOpcode() == TargetOpcode::G_FADD);
5114 
5115   bool AllowFusionGlobally, HasFMAD, Aggressive;
5116   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5117     return false;
5118 
5119   if (!Aggressive)
5120     return false;
5121 
5122   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
5123   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
5124   Register Op1 = MI.getOperand(1).getReg();
5125   Register Op2 = MI.getOperand(2).getReg();
5126   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5127   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5128 
5129   unsigned PreferredFusedOpcode =
5130       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5131 
5132   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5133   // prefer to fold the multiply with fewer uses.
5134   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5135       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5136     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5137       std::swap(LHS, RHS);
5138   }
5139 
5140   // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
5141   auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
5142                                  Register Y, MachineIRBuilder &B) {
5143     Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
5144     Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
5145     Register InnerFMA =
5146         B.buildInstr(PreferredFusedOpcode, {DstType}, {FpExtU, FpExtV, Z})
5147             .getReg(0);
5148     B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5149                  {X, Y, InnerFMA});
5150   };
5151 
5152   MachineInstr *FMulMI, *FMAMI;
5153   // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
5154   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
5155   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
5156       mi_match(LHS.MI->getOperand(3).getReg(), MRI,
5157                m_GFPExt(m_MInstr(FMulMI))) &&
5158       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5159       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5160                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5161     MatchInfo = [=](MachineIRBuilder &B) {
5162       buildMatchInfo(FMulMI->getOperand(1).getReg(),
5163                      FMulMI->getOperand(2).getReg(), RHS.Reg,
5164                      LHS.MI->getOperand(1).getReg(),
5165                      LHS.MI->getOperand(2).getReg(), B);
5166     };
5167     return true;
5168   }
5169 
5170   // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
5171   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
5172   // FIXME: This turns two single-precision and one double-precision
5173   // operation into two double-precision operations, which might not be
5174   // interesting for all targets, especially GPUs.
5175   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
5176       FMAMI->getOpcode() == PreferredFusedOpcode) {
5177     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
5178     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5179         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5180                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
5181       MatchInfo = [=](MachineIRBuilder &B) {
5182         Register X = FMAMI->getOperand(1).getReg();
5183         Register Y = FMAMI->getOperand(2).getReg();
5184         X = B.buildFPExt(DstType, X).getReg(0);
5185         Y = B.buildFPExt(DstType, Y).getReg(0);
5186         buildMatchInfo(FMulMI->getOperand(1).getReg(),
5187                        FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y, B);
5188       };
5189 
5190       return true;
5191     }
5192   }
5193 
5194   // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
5195   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
5196   if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
5197       mi_match(RHS.MI->getOperand(3).getReg(), MRI,
5198                m_GFPExt(m_MInstr(FMulMI))) &&
5199       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5200       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5201                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5202     MatchInfo = [=](MachineIRBuilder &B) {
5203       buildMatchInfo(FMulMI->getOperand(1).getReg(),
5204                      FMulMI->getOperand(2).getReg(), LHS.Reg,
5205                      RHS.MI->getOperand(1).getReg(),
5206                      RHS.MI->getOperand(2).getReg(), B);
5207     };
5208     return true;
5209   }
5210 
5211   // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
5212   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
5213   // FIXME: This turns two single-precision and one double-precision
5214   // operation into two double-precision operations, which might not be
5215   // interesting for all targets, especially GPUs.
5216   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
5217       FMAMI->getOpcode() == PreferredFusedOpcode) {
5218     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
5219     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5220         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5221                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
5222       MatchInfo = [=](MachineIRBuilder &B) {
5223         Register X = FMAMI->getOperand(1).getReg();
5224         Register Y = FMAMI->getOperand(2).getReg();
5225         X = B.buildFPExt(DstType, X).getReg(0);
5226         Y = B.buildFPExt(DstType, Y).getReg(0);
5227         buildMatchInfo(FMulMI->getOperand(1).getReg(),
5228                        FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y, B);
5229       };
5230       return true;
5231     }
5232   }
5233 
5234   return false;
5235 }
5236 
5237 bool CombinerHelper::matchCombineFSubFMulToFMadOrFMA(
5238     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5239   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5240 
5241   bool AllowFusionGlobally, HasFMAD, Aggressive;
5242   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5243     return false;
5244 
5245   Register Op1 = MI.getOperand(1).getReg();
5246   Register Op2 = MI.getOperand(2).getReg();
5247   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5248   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5249   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5250 
5251   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5252   // prefer to fold the multiply with fewer uses.
5253   int FirstMulHasFewerUses = true;
5254   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5255       isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
5256       hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5257     FirstMulHasFewerUses = false;
5258 
5259   unsigned PreferredFusedOpcode =
5260       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5261 
5262   // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
5263   if (FirstMulHasFewerUses &&
5264       (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5265        (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
5266     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5267       Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
5268       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5269                    {LHS.MI->getOperand(1).getReg(),
5270                     LHS.MI->getOperand(2).getReg(), NegZ});
5271     };
5272     return true;
5273   }
5274   // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
5275   else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
5276             (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
5277     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5278       Register NegY =
5279           B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
5280       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5281                    {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg});
5282     };
5283     return true;
5284   }
5285 
5286   return false;
5287 }
5288 
5289 bool CombinerHelper::matchCombineFSubFNegFMulToFMadOrFMA(
5290     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5291   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5292 
5293   bool AllowFusionGlobally, HasFMAD, Aggressive;
5294   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5295     return false;
5296 
5297   Register LHSReg = MI.getOperand(1).getReg();
5298   Register RHSReg = MI.getOperand(2).getReg();
5299   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5300 
5301   unsigned PreferredFusedOpcode =
5302       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5303 
5304   MachineInstr *FMulMI;
5305   // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
5306   if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
5307       (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
5308                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
5309       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
5310     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5311       Register NegX =
5312           B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
5313       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
5314       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5315                    {NegX, FMulMI->getOperand(2).getReg(), NegZ});
5316     };
5317     return true;
5318   }
5319 
5320   // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
5321   if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
5322       (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
5323                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
5324       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
5325     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5326       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5327                    {FMulMI->getOperand(1).getReg(),
5328                     FMulMI->getOperand(2).getReg(), LHSReg});
5329     };
5330     return true;
5331   }
5332 
5333   return false;
5334 }
5335 
5336 bool CombinerHelper::matchCombineFSubFpExtFMulToFMadOrFMA(
5337     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5338   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5339 
5340   bool AllowFusionGlobally, HasFMAD, Aggressive;
5341   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5342     return false;
5343 
5344   Register LHSReg = MI.getOperand(1).getReg();
5345   Register RHSReg = MI.getOperand(2).getReg();
5346   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5347 
5348   unsigned PreferredFusedOpcode =
5349       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5350 
5351   MachineInstr *FMulMI;
5352   // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
5353   if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
5354       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5355       (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
5356     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5357       Register FpExtX =
5358           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
5359       Register FpExtY =
5360           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
5361       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
5362       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5363                    {FpExtX, FpExtY, NegZ});
5364     };
5365     return true;
5366   }
5367 
5368   // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
5369   if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
5370       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5371       (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
5372     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5373       Register FpExtY =
5374           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
5375       Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
5376       Register FpExtZ =
5377           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
5378       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5379                    {NegY, FpExtZ, LHSReg});
5380     };
5381     return true;
5382   }
5383 
5384   return false;
5385 }
5386 
5387 bool CombinerHelper::matchCombineFSubFpExtFNegFMulToFMadOrFMA(
5388     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5389   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5390 
5391   bool AllowFusionGlobally, HasFMAD, Aggressive;
5392   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5393     return false;
5394 
5395   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
5396   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5397   Register LHSReg = MI.getOperand(1).getReg();
5398   Register RHSReg = MI.getOperand(2).getReg();
5399 
5400   unsigned PreferredFusedOpcode =
5401       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5402 
5403   auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
5404                             MachineIRBuilder &B) {
5405     Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
5406     Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
5407     B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z});
5408   };
5409 
5410   MachineInstr *FMulMI;
5411   // fold (fsub (fpext (fneg (fmul x, y))), z) ->
5412   //      (fneg (fma (fpext x), (fpext y), z))
5413   // fold (fsub (fneg (fpext (fmul x, y))), z) ->
5414   //      (fneg (fma (fpext x), (fpext y), z))
5415   if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
5416        mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
5417       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5418       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
5419                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5420     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5421       Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
5422       buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
5423                      FMulMI->getOperand(2).getReg(), RHSReg, B);
5424       B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
5425     };
5426     return true;
5427   }
5428 
5429   // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
5430   // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
5431   if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
5432        mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
5433       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5434       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
5435                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5436     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5437       buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
5438                      FMulMI->getOperand(2).getReg(), LHSReg, B);
5439     };
5440     return true;
5441   }
5442 
5443   return false;
5444 }
5445 
5446 bool CombinerHelper::tryCombine(MachineInstr &MI) {
5447   if (tryCombineCopy(MI))
5448     return true;
5449   if (tryCombineExtendingLoads(MI))
5450     return true;
5451   if (tryCombineIndexedLoadStore(MI))
5452     return true;
5453   return false;
5454 }
5455