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