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