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