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