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