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