LLVM 24.0.0git
CombinerHelper.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
9#include "llvm/ADT/APFloat.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SetVector.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/InstrTypes.h"
45#include <optional>
46#include <tuple>
47
48#define DEBUG_TYPE "gi-combiner"
49
50using namespace llvm;
51using namespace MIPatternMatch;
52
53// Option to allow testing of the combiner while no targets know about indexed
54// addressing.
55static cl::opt<bool>
56 ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
57 cl::desc("Force all indexed operations to be "
58 "legal for the GlobalISel combiner"));
59
64 const LegalizerInfo *LI)
65 : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), VT(VT),
67 TII(Builder.getMF().getSubtarget().getInstrInfo()),
68 RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
69 TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
70 (void)this->VT;
71}
72
74 return *Builder.getMF().getSubtarget().getTargetLowering();
75}
76
78 return Builder.getMF();
79}
80
81LLVMContext &CombinerHelper::getContext() const { return Builder.getContext(); }
82
83/// \returns The little endian in-memory byte position of byte \p I in a
84/// \p ByteWidth bytes wide type.
85///
86/// E.g. Given a 4-byte type x, x[0] -> byte 0
87static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
88 assert(I < ByteWidth && "I must be in [0, ByteWidth)");
89 return I;
90}
91
92/// Determines the LogBase2 value for a non-null input value using the
93/// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
95 auto &MRI = *MIB.getMRI();
96 LLT Ty = MRI.getType(V);
97 auto Ctlz = MIB.buildCTLZ(Ty, V);
98 auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
99 return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
100}
101
102/// \returns The big endian in-memory byte position of byte \p I in a
103/// \p ByteWidth bytes wide type.
104///
105/// E.g. Given a 4-byte type x, x[0] -> byte 3
106static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
107 assert(I < ByteWidth && "I must be in [0, ByteWidth)");
108 return ByteWidth - I - 1;
109}
110
111/// Given a map from byte offsets in memory to indices in a load/store,
112/// determine if that map corresponds to a little or big endian byte pattern.
113///
114/// \param MemOffset2Idx maps memory offsets to address offsets.
115/// \param LowestIdx is the lowest index in \p MemOffset2Idx.
116///
117/// \returns true if the map corresponds to a big endian byte pattern, false if
118/// it corresponds to a little endian byte pattern, and std::nullopt otherwise.
119///
120/// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
121/// are as follows:
122///
123/// AddrOffset Little endian Big endian
124/// 0 0 3
125/// 1 1 2
126/// 2 2 1
127/// 3 3 0
128static std::optional<bool>
130 int64_t LowestIdx) {
131 // Need at least two byte positions to decide on endianness.
132 unsigned Width = MemOffset2Idx.size();
133 if (Width < 2)
134 return std::nullopt;
135 bool BigEndian = true, LittleEndian = true;
136 for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
137 auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
138 if (MemOffsetAndIdx == MemOffset2Idx.end())
139 return std::nullopt;
140 const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
141 assert(Idx >= 0 && "Expected non-negative byte offset?");
142 LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
143 BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
144 if (!BigEndian && !LittleEndian)
145 return std::nullopt;
146 }
147
148 assert((BigEndian != LittleEndian) &&
149 "Pattern cannot be both big and little endian!");
150 return BigEndian;
151}
152
154
155bool CombinerHelper::isLegal(const LegalityQuery &Query) const {
156 assert(LI && "Must have LegalizerInfo to query isLegal!");
157 return LI->getAction(Query).Action == LegalizeActions::Legal;
158}
159
161 const LegalityQuery &Query) const {
162 return isPreLegalize() || isLegal(Query);
163}
164
166 return isLegal(Query) ||
167 LI->getAction(Query).Action == LegalizeActions::WidenScalar;
168}
169
171 const LegalityQuery &Query) const {
172 LegalizeAction Action = LI->getAction(Query).Action;
173 return Action == LegalizeActions::Legal ||
175}
176
177bool CombinerHelper::isImmConstantLegalOrBeforeLegalizer(unsigned Opc,
178 const LLT Ty) const {
179 if (!Ty.isVector())
180 return isLegalOrBeforeLegalizer({Opc, {Ty}});
181 if (isPreLegalize())
182 return true;
183 // Scalable vectors cannot be constant folded here.
184 if (!Ty.isFixedVector())
185 return false;
186 LLT EltTy = Ty.getElementType();
187 return isLegal({TargetOpcode::G_BUILD_VECTOR, {Ty, EltTy}}) &&
188 isLegal({Opc, {EltTy}});
189}
190
192 return isImmConstantLegalOrBeforeLegalizer(TargetOpcode::G_CONSTANT, Ty);
193}
194
196 return isImmConstantLegalOrBeforeLegalizer(TargetOpcode::G_FCONSTANT, Ty);
197}
198
200 Register ToReg) const {
201 Observer.changingAllUsesOfReg(MRI, FromReg);
202
203 if (MRI.constrainRegAttrs(ToReg, FromReg))
204 MRI.replaceRegWith(FromReg, ToReg);
205 else
206 Builder.buildCopy(FromReg, ToReg);
207
208 Observer.finishedChangingAllUsesOfReg();
209}
210
212 MachineOperand &FromRegOp,
213 Register ToReg) const {
214 assert(FromRegOp.getParent() && "Expected an operand in an MI");
215 Observer.changingInstr(*FromRegOp.getParent());
216
217 FromRegOp.setReg(ToReg);
218
219 Observer.changedInstr(*FromRegOp.getParent());
220}
221
223 unsigned ToOpcode) const {
224 Observer.changingInstr(FromMI);
225
226 FromMI.setDesc(Builder.getTII().get(ToOpcode));
227
228 Observer.changedInstr(FromMI);
229}
230
232 return RBI->getRegBank(Reg, MRI, *TRI);
233}
234
236 const RegisterBank *RegBank) const {
237 if (RegBank)
238 MRI.setRegBank(Reg, *RegBank);
239}
240
242 if (MI.getOpcode() != TargetOpcode::COPY)
243 return false;
244 Register DstReg = MI.getOperand(0).getReg();
245 Register SrcReg = MI.getOperand(1).getReg();
246 return canReplaceReg(DstReg, SrcReg, MRI);
247}
249 Register DstReg = MI.getOperand(0).getReg();
250 Register SrcReg = MI.getOperand(1).getReg();
251 replaceRegWith(MRI, DstReg, SrcReg);
252 MI.eraseFromParent();
253}
254
256 MachineInstr &MI, BuildFnTy &MatchInfo) const {
257 assert(MI.getOpcode() == TargetOpcode::G_FREEZE && "Invalid instruction");
258
259 // Ported from InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating.
260 Register DstOp = MI.getOperand(0).getReg();
261 Register OrigOp = MI.getOperand(1).getReg();
262
263 if (!MRI.hasOneNonDBGUse(OrigOp))
264 return false;
265
266 MachineInstr *OrigDef;
267 if (!mi_match(OrigOp, MRI, m_MInstr(OrigDef)))
268 return false;
269 // Even if only a single operand of the PHI is not guaranteed non-poison,
270 // moving freeze() backwards across a PHI can cause optimization issues for
271 // other users of that operand.
272 //
273 // Moving freeze() from one of the output registers of a G_UNMERGE_VALUES to
274 // the source register is unprofitable because it makes the freeze() more
275 // strict than is necessary (it would affect the whole register instead of
276 // just the subreg being frozen).
277 if (OrigDef->isPHI() || isa<GUnmerge>(OrigDef))
278 return false;
279
280 if (canCreateUndefOrPoison(OrigOp, MRI,
281 /*ConsiderFlagsAndMetadata=*/false))
282 return false;
283
284 std::optional<MachineOperand> MaybePoisonOperand;
285 for (MachineOperand &Operand : OrigDef->uses()) {
286 if (!Operand.isReg())
287 return false;
288
289 if (isGuaranteedNotToBeUndefOrPoison(Operand.getReg(), MRI))
290 continue;
291
292 if (!MaybePoisonOperand)
293 MaybePoisonOperand = Operand;
294 else {
295 // We have more than one maybe-poison operand. Moving the freeze is
296 // unsafe.
297 return false;
298 }
299 }
300
301 // Eliminate freeze if all operands are guaranteed non-poison.
302 if (!MaybePoisonOperand) {
303 MatchInfo = [=](MachineIRBuilder &B) {
304 Observer.changingInstr(*OrigDef);
305 cast<GenericMachineInstr>(OrigDef)->dropPoisonGeneratingFlags();
306 Observer.changedInstr(*OrigDef);
307 B.buildCopy(DstOp, OrigOp);
308 };
309 return true;
310 }
311
312 Register MaybePoisonOperandReg = MaybePoisonOperand->getReg();
313 LLT MaybePoisonOperandRegTy = MRI.getType(MaybePoisonOperandReg);
314
316 {TargetOpcode::G_FREEZE, {MaybePoisonOperandRegTy}}))
317 return false;
318
319 MatchInfo = [=](MachineIRBuilder &B) mutable {
320 Observer.changingInstr(*OrigDef);
321 cast<GenericMachineInstr>(OrigDef)->dropPoisonGeneratingFlags();
322 Observer.changedInstr(*OrigDef);
323 B.setInsertPt(*OrigDef->getParent(), OrigDef->getIterator());
324 auto Freeze = B.buildFreeze(MaybePoisonOperandRegTy, MaybePoisonOperandReg);
326 MRI, *OrigDef->findRegisterUseOperand(MaybePoisonOperandReg, TRI),
327 Freeze.getReg(0));
328 replaceRegWith(MRI, DstOp, OrigOp);
329 };
330 return true;
331}
332
335 assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
336 "Invalid instruction");
337 bool IsUndef = true;
338 MachineInstr *Undef = nullptr;
339
340 // Walk over all the operands of concat vectors and check if they are
341 // build_vector themselves or undef.
342 // Then collect their operands in Ops.
343 for (const MachineOperand &MO : MI.uses()) {
344 Register Reg = MO.getReg();
345 MachineInstr *Def;
346 if (!mi_match(Reg, MRI, m_MInstr(Def)))
347 return false;
348 if (!MRI.hasOneNonDBGUse(Reg))
349 return false;
350 switch (Def->getOpcode()) {
351 case TargetOpcode::G_BUILD_VECTOR:
352 IsUndef = false;
353 // Remember the operands of the build_vector to fold
354 // them into the yet-to-build flattened concat vectors.
355 for (const MachineOperand &BuildVecMO : Def->uses())
356 Ops.push_back(BuildVecMO.getReg());
357 break;
358 case TargetOpcode::G_IMPLICIT_DEF: {
359 LLT OpType = MRI.getType(Reg);
360 // Keep one undef value for all the undef operands.
361 if (!Undef) {
362 Builder.setInsertPt(*MI.getParent(), MI);
363 Undef = Builder.buildUndef(OpType.getScalarType());
364 }
365 assert(MRI.getType(Undef->getOperand(0).getReg()) ==
366 OpType.getScalarType() &&
367 "All undefs should have the same type");
368 // Break the undef vector in as many scalar elements as needed
369 // for the flattening.
370 for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
371 EltIdx != EltEnd; ++EltIdx)
372 Ops.push_back(Undef->getOperand(0).getReg());
373 break;
374 }
375 default:
376 return false;
377 }
378 }
379
380 // Check if the combine is illegal
381 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
383 {TargetOpcode::G_BUILD_VECTOR, {DstTy, MRI.getType(Ops[0])}})) {
384 return false;
385 }
386
387 if (IsUndef)
388 Ops.clear();
389
390 return true;
391}
394 // We determined that the concat_vectors can be flatten.
395 // Generate the flattened build_vector.
396 Register DstReg = MI.getOperand(0).getReg();
397 Builder.setInsertPt(*MI.getParent(), MI);
398 Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
399
400 // Note: IsUndef is sort of redundant. We could have determine it by
401 // checking that at all Ops are undef. Alternatively, we could have
402 // generate a build_vector of undefs and rely on another combine to
403 // clean that up. For now, given we already gather this information
404 // in matchCombineConcatVectors, just save compile time and issue the
405 // right thing.
406 if (Ops.empty())
407 Builder.buildUndef(NewDstReg);
408 else
409 Builder.buildBuildVector(NewDstReg, Ops);
410 replaceRegWith(MRI, DstReg, NewDstReg);
411 MI.eraseFromParent();
412}
413
416 auto &BV = cast<GBuildVector>(MI);
417
418 // Look at the first operand for a unmerge(bitcast) from a scalar type.
419 GUnmerge *Unmerge = getOpcodeDef<GUnmerge>(BV.getSourceReg(0), MRI);
420 if (!Unmerge || Unmerge->getReg(0) != BV.getSourceReg(0))
421 return false;
422 Register BCSrc;
423 if (!mi_match(Unmerge->getSourceReg(), MRI, m_GBitcast(m_Reg(BCSrc))))
424 return false;
425 LLT InputTy = MRI.getType(BCSrc);
426 unsigned Factor = Unmerge->getNumDefs();
427 if (!InputTy.isScalar() || BV.getNumSources() % Factor != 0)
428 return false;
429
430 // Check if the build_vector is legal
431 LLT BVDstTy = LLT::fixed_vector(BV.getNumSources() / Factor, InputTy);
432 if (!isLegal({TargetOpcode::G_BUILD_VECTOR, {BVDstTy, InputTy}}))
433 return false;
434
435 // Check all other operands are bitcasts or undef.
436 for (unsigned Idx = 0; Idx < BV.getNumSources(); Idx += Factor) {
437 GUnmerge *Unmerge = getOpcodeDef<GUnmerge>(BV.getSourceReg(Idx), MRI);
438 if (!all_of(iota_range<unsigned>(0, Factor, false), [&](unsigned J) {
439 if (mi_match(BV.getSourceReg(Idx + J), MRI, m_GImplicitDef()))
440 return true;
441 return Unmerge && BV.getSourceReg(Idx + J) == Unmerge->getReg(J);
442 }))
443 return false;
444 if (!Unmerge)
445 Ops.push_back(0);
446 else {
447 Register BCSrc;
448 if (!mi_match(
449 Unmerge->getSourceReg(), MRI,
450 m_GBitcast(m_all_of(m_Reg(BCSrc), m_SpecificType(InputTy)))))
451 return false;
452 Ops.push_back(BCSrc);
453 }
454 }
455
456 return true;
457}
458
461 LLT SrcTy = MRI.getType(Ops[0]);
462 // Build undef if any operations require it.
463 Register Undef = 0;
464 for (Register &Op : Ops) {
465 if (!Op) {
466 if (!Undef)
467 Undef = Builder.buildUndef(SrcTy).getReg(0);
468 Op = Undef;
469 }
470 }
471
472 LLT BVDstTy = LLT::fixed_vector(Ops.size(), SrcTy);
473 auto BV = Builder.buildBuildVector(BVDstTy, Ops);
474 Builder.buildBitcast(MI.getOperand(0).getReg(), BV);
475 MI.eraseFromParent();
476}
477
479 auto &Shuffle = cast<GShuffleVector>(MI);
480
481 Register SrcVec1 = Shuffle.getSrc1Reg();
482 Register SrcVec2 = Shuffle.getSrc2Reg();
483 LLT EltTy = MRI.getType(SrcVec1).getElementType();
484 int Width = MRI.getType(SrcVec1).getNumElements();
485
486 auto Unmerge1 = Builder.buildUnmerge(EltTy, SrcVec1);
487 auto Unmerge2 = Builder.buildUnmerge(EltTy, SrcVec2);
488
489 SmallVector<Register> Extracts;
490 // Select only applicable elements from unmerged values.
491 for (int Val : Shuffle.getMask()) {
492 if (Val == -1)
493 Extracts.push_back(Builder.buildUndef(EltTy).getReg(0));
494 else if (Val < Width)
495 Extracts.push_back(Unmerge1.getReg(Val));
496 else
497 Extracts.push_back(Unmerge2.getReg(Val - Width));
498 }
499 assert(Extracts.size() > 0 && "Expected at least one element in the shuffle");
500 if (Extracts.size() == 1)
501 Builder.buildCopy(MI.getOperand(0).getReg(), Extracts[0]);
502 else
503 Builder.buildBuildVector(MI.getOperand(0).getReg(), Extracts);
504 MI.eraseFromParent();
505}
506
508 auto &Shuffle = cast<GShuffleVector>(MI);
509 Register SrcVec1 = Shuffle.getSrc1Reg();
510 Register SrcVec2 = Shuffle.getSrc2Reg();
511 auto *BuildMI1 = getOpcodeDef<GBuildVector>(SrcVec1, MRI);
512 auto *BuildMI2 = getOpcodeDef<GBuildVector>(SrcVec2, MRI);
513 assert((BuildMI1 && (BuildMI2 || MRI.getVRegDef(SrcVec2)->getOpcode() ==
514 TargetOpcode::G_IMPLICIT_DEF)) &&
515 "Unexpected input to applyCombineShuffleOfBuildVector");
516 LLT EltTy = MRI.getType(SrcVec1).getElementType();
517 int NumElts = MRI.getType(SrcVec1).getNumElements();
518
519 SmallVector<Register> Extracts;
520 for (int Val : Shuffle.getMask()) {
521 if (Val == -1)
522 Extracts.push_back(Builder.buildUndef(EltTy).getReg(0));
523 else if (Val < NumElts)
524 Extracts.push_back(BuildMI1->getSourceReg(Val));
525 else if (BuildMI2)
526 Extracts.push_back(BuildMI2->getSourceReg(Val - NumElts));
527 else
528 Extracts.push_back(Builder.buildUndef(EltTy).getReg(0));
529 }
530
531 if (Extracts.size() == 1)
532 Builder.buildCopy(MI.getOperand(0).getReg(), Extracts[0]);
533 else
534 Builder.buildBuildVector(MI.getOperand(0).getReg(), Extracts);
535 MI.eraseFromParent();
536}
537
540 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
541 GConcatVectors *ConcatMI1, *ConcatMI2;
542 if (!mi_match(MI.getOperand(1).getReg(), MRI, m_GConcatVectors(ConcatMI1)) ||
543 !mi_match(MI.getOperand(2).getReg(), MRI, m_GConcatVectors(ConcatMI2)))
544 return false;
545
546 // Check that the sources of the Concat instructions have the same type
547 if (MRI.getType(ConcatMI1->getSourceReg(0)) !=
548 MRI.getType(ConcatMI2->getSourceReg(0)))
549 return false;
550
551 LLT ConcatSrcTy = MRI.getType(ConcatMI1->getReg(1));
552 LLT ShuffleSrcTy1 = MRI.getType(MI.getOperand(1).getReg());
553 unsigned ConcatSrcNumElt = ConcatSrcTy.getNumElements();
554 for (unsigned i = 0; i < Mask.size(); i += ConcatSrcNumElt) {
555 // Check if the index takes a whole source register from G_CONCAT_VECTORS
556 // Assumes that all Sources of G_CONCAT_VECTORS are the same type
557 if (Mask[i] == -1) {
558 for (unsigned j = 1; j < ConcatSrcNumElt; j++) {
559 if (i + j >= Mask.size())
560 return false;
561 if (Mask[i + j] != -1)
562 return false;
563 }
565 {TargetOpcode::G_IMPLICIT_DEF, {ConcatSrcTy}}))
566 return false;
567 Ops.push_back(0);
568 } else if (Mask[i] % ConcatSrcNumElt == 0) {
569 for (unsigned j = 1; j < ConcatSrcNumElt; j++) {
570 if (i + j >= Mask.size())
571 return false;
572 if (Mask[i + j] != Mask[i] + static_cast<int>(j))
573 return false;
574 }
575 // Retrieve the source register from its respective G_CONCAT_VECTORS
576 // instruction
577 if (Mask[i] < ShuffleSrcTy1.getNumElements()) {
578 Ops.push_back(ConcatMI1->getSourceReg(Mask[i] / ConcatSrcNumElt));
579 } else {
580 Ops.push_back(ConcatMI2->getSourceReg(Mask[i] / ConcatSrcNumElt -
581 ConcatMI1->getNumSources()));
582 }
583 } else {
584 return false;
585 }
586 }
587
589 {TargetOpcode::G_CONCAT_VECTORS,
590 {MRI.getType(MI.getOperand(0).getReg()), ConcatSrcTy}}))
591 return false;
592
593 return !Ops.empty();
594}
595
598 LLT SrcTy;
599 for (Register &Reg : Ops) {
600 if (Reg != 0)
601 SrcTy = MRI.getType(Reg);
602 }
603 assert(SrcTy.isValid() && "Unexpected full undef vector in concat combine");
604
605 Register UndefReg = 0;
606
607 for (Register &Reg : Ops) {
608 if (Reg == 0) {
609 if (UndefReg == 0)
610 UndefReg = Builder.buildUndef(SrcTy).getReg(0);
611 Reg = UndefReg;
612 }
613 }
614
615 if (Ops.size() > 1)
616 Builder.buildConcatVectors(MI.getOperand(0).getReg(), Ops);
617 else
618 Builder.buildCopy(MI.getOperand(0).getReg(), Ops[0]);
619 MI.eraseFromParent();
620}
621
624 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
625 "Invalid instruction kind");
626 LLT DstType = MRI.getType(MI.getOperand(0).getReg());
627 Register Src1 = MI.getOperand(1).getReg();
628 LLT SrcType = MRI.getType(Src1);
629
630 unsigned DstNumElts = DstType.getNumElements();
631 unsigned SrcNumElts = SrcType.getNumElements();
632
633 // If the resulting vector is smaller than the size of the source
634 // vectors being concatenated, we won't be able to replace the
635 // shuffle vector into a concat_vectors.
636 //
637 // Note: We may still be able to produce a concat_vectors fed by
638 // extract_vector_elt and so on. It is less clear that would
639 // be better though, so don't bother for now.
640 //
641 // If the destination is a scalar, the size of the sources doesn't
642 // matter. we will lower the shuffle to a plain copy. This will
643 // work only if the source and destination have the same size. But
644 // that's covered by the next condition.
645 //
646 // TODO: If the size between the source and destination don't match
647 // we could still emit an extract vector element in that case.
648 if (DstNumElts < 2 * SrcNumElts)
649 return false;
650
651 // Check that the shuffle mask can be broken evenly between the
652 // different sources.
653 if (DstNumElts % SrcNumElts != 0)
654 return false;
655
656 // Mask length is a multiple of the source vector length.
657 // Check if the shuffle is some kind of concatenation of the input
658 // vectors.
659 unsigned NumConcat = DstNumElts / SrcNumElts;
660 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
661 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
662 for (unsigned i = 0; i != DstNumElts; ++i) {
663 int Idx = Mask[i];
664 // Undef value.
665 if (Idx < 0)
666 continue;
667 // Ensure the indices in each SrcType sized piece are sequential and that
668 // the same source is used for the whole piece.
669 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
670 (ConcatSrcs[i / SrcNumElts] >= 0 &&
671 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
672 return false;
673 // Remember which source this index came from.
674 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
675 }
676
677 // The shuffle is concatenating multiple vectors together.
678 // Collect the different operands for that.
679 Register UndefReg;
680 Register Src2 = MI.getOperand(2).getReg();
681 for (auto Src : ConcatSrcs) {
682 if (Src < 0) {
683 if (!UndefReg) {
684 Builder.setInsertPt(*MI.getParent(), MI);
685 UndefReg = Builder.buildUndef(SrcType).getReg(0);
686 }
687 Ops.push_back(UndefReg);
688 } else if (Src == 0)
689 Ops.push_back(Src1);
690 else
691 Ops.push_back(Src2);
692 }
693 return true;
694}
695
697 ArrayRef<Register> Ops) const {
698 Register DstReg = MI.getOperand(0).getReg();
699 Builder.setInsertPt(*MI.getParent(), MI);
700 Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
701
702 if (Ops.size() == 1)
703 Builder.buildCopy(NewDstReg, Ops[0]);
704 else
705 Builder.buildMergeLikeInstr(NewDstReg, Ops);
706
707 replaceRegWith(MRI, DstReg, NewDstReg);
708 MI.eraseFromParent();
709}
710
711namespace {
712
713/// Select a preference between two uses. CurrentUse is the current preference
714/// while *ForCandidate is attributes of the candidate under consideration.
715PreferredTuple ChoosePreferredUse(MachineInstr &LoadMI,
716 PreferredTuple &CurrentUse,
717 const LLT TyForCandidate,
718 unsigned OpcodeForCandidate,
719 MachineInstr *MIForCandidate) {
720 if (!CurrentUse.Ty.isValid()) {
721 if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
722 CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
723 return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
724 return CurrentUse;
725 }
726
727 // We permit the extend to hoist through basic blocks but this is only
728 // sensible if the target has extending loads. If you end up lowering back
729 // into a load and extend during the legalizer then the end result is
730 // hoisting the extend up to the load.
731
732 // Prefer defined extensions to undefined extensions as these are more
733 // likely to reduce the number of instructions.
734 if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
735 CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
736 return CurrentUse;
737 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
738 OpcodeForCandidate != TargetOpcode::G_ANYEXT)
739 return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
740
741 // Prefer sign extensions to zero extensions as sign-extensions tend to be
742 // more expensive. Don't do this if the load is already a zero-extend load
743 // though, otherwise we'll rewrite a zero-extend load into a sign-extend
744 // later.
745 if (!isa<GZExtLoad>(LoadMI) && CurrentUse.Ty == TyForCandidate) {
746 if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
747 OpcodeForCandidate == TargetOpcode::G_ZEXT)
748 return CurrentUse;
749 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
750 OpcodeForCandidate == TargetOpcode::G_SEXT)
751 return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
752 }
753
754 // This is potentially target specific. We've chosen the largest type
755 // because G_TRUNC is usually free. One potential catch with this is that
756 // some targets have a reduced number of larger registers than smaller
757 // registers and this choice potentially increases the live-range for the
758 // larger value.
759 if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
760 return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
761 }
762 return CurrentUse;
763}
764
765/// Find a suitable place to insert some instructions and insert them. This
766/// function accounts for special cases like inserting before a PHI node.
767/// The current strategy for inserting before PHI's is to duplicate the
768/// instructions for each predecessor. However, while that's ok for G_TRUNC
769/// on most targets since it generally requires no code, other targets/cases may
770/// want to try harder to find a dominating block.
771static void InsertInsnsWithoutSideEffectsBeforeUse(
774 MachineOperand &UseMO)>
775 Inserter) {
776 MachineInstr &UseMI = *UseMO.getParent();
777
778 MachineBasicBlock *InsertBB = UseMI.getParent();
779
780 // If the use is a PHI then we want the predecessor block instead.
781 if (UseMI.isPHI()) {
782 MachineOperand *PredBB = std::next(&UseMO);
783 InsertBB = PredBB->getMBB();
784 }
785
786 // If the block is the same block as the def then we want to insert just after
787 // the def instead of at the start of the block.
788 if (InsertBB == DefMI.getParent()) {
790 Inserter(InsertBB, std::next(InsertPt), UseMO);
791 return;
792 }
793
794 // Otherwise we want the start of the BB
795 Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
796}
797} // end anonymous namespace
798
800 PreferredTuple Preferred;
801 if (matchCombineExtendingLoads(MI, Preferred)) {
802 applyCombineExtendingLoads(MI, Preferred);
803 return true;
804 }
805 return false;
806}
807
808static unsigned getExtLoadOpcForExtend(unsigned ExtOpc) {
809 unsigned CandidateLoadOpc;
810 switch (ExtOpc) {
811 case TargetOpcode::G_ANYEXT:
812 CandidateLoadOpc = TargetOpcode::G_LOAD;
813 break;
814 case TargetOpcode::G_SEXT:
815 CandidateLoadOpc = TargetOpcode::G_SEXTLOAD;
816 break;
817 case TargetOpcode::G_ZEXT:
818 CandidateLoadOpc = TargetOpcode::G_ZEXTLOAD;
819 break;
820 default:
821 llvm_unreachable("Unexpected extend opc");
822 }
823 return CandidateLoadOpc;
824}
825
827 MachineInstr &MI, PreferredTuple &Preferred) const {
828 // We match the loads and follow the uses to the extend instead of matching
829 // the extends and following the def to the load. This is because the load
830 // must remain in the same position for correctness (unless we also add code
831 // to find a safe place to sink it) whereas the extend is freely movable.
832 // It also prevents us from duplicating the load for the volatile case or just
833 // for performance.
834 GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
835 if (!LoadMI)
836 return false;
837
838 Register LoadReg = LoadMI->getDstReg();
839
840 LLT LoadValueTy = MRI.getType(LoadReg);
841 if (!LoadValueTy.isScalar())
842 return false;
843
844 // Most architectures are going to legalize <s8 loads into at least a 1 byte
845 // load, and the MMOs can only describe memory accesses in multiples of bytes.
846 // If we try to perform extload combining on those, we can end up with
847 // %a(s8) = extload %ptr (load 1 byte from %ptr)
848 // ... which is an illegal extload instruction.
849 if (LoadValueTy.getSizeInBits() < 8)
850 return false;
851
852 // For non power-of-2 types, they will very likely be legalized into multiple
853 // loads. Don't bother trying to match them into extending loads.
855 return false;
856
857 // Find the preferred type aside from the any-extends (unless it's the only
858 // one) and non-extending ops. We'll emit an extending load to that type and
859 // and emit a variant of (extend (trunc X)) for the others according to the
860 // relative type sizes. At the same time, pick an extend to use based on the
861 // extend involved in the chosen type.
862 unsigned PreferredOpcode =
863 isa<GLoad>(&MI)
864 ? TargetOpcode::G_ANYEXT
865 : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
866 Preferred = {LLT(), PreferredOpcode, nullptr};
867 for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
868 if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
869 UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
870 (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
871 const auto &MMO = LoadMI->getMMO();
872 // Don't do anything for atomics.
873 if (MMO.isAtomic())
874 continue;
875 // Check for legality.
876 if (!isPreLegalize()) {
877 LegalityQuery::MemDesc MMDesc(MMO);
878 unsigned CandidateLoadOpc = getExtLoadOpcForExtend(UseMI.getOpcode());
879 LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
880 LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
881 if (LI->getAction({CandidateLoadOpc, {UseTy, SrcTy}, {MMDesc}})
882 .Action != LegalizeActions::Legal)
883 continue;
884 }
885 Preferred = ChoosePreferredUse(MI, Preferred,
886 MRI.getType(UseMI.getOperand(0).getReg()),
887 UseMI.getOpcode(), &UseMI);
888 }
889 }
890
891 // There were no extends
892 if (!Preferred.MI)
893 return false;
894 // It should be impossible to chose an extend without selecting a different
895 // type since by definition the result of an extend is larger.
896 assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
897
898 LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
899 return true;
900}
901
903 MachineInstr &MI, PreferredTuple &Preferred) const {
904 // Rewrite the load to the chosen extending load.
905 Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
906
907 // Inserter to insert a truncate back to the original type at a given point
908 // with some basic CSE to limit truncate duplication to one per BB.
910 auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
911 MachineBasicBlock::iterator InsertBefore,
912 MachineOperand &UseMO) {
913 MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
914 if (PreviouslyEmitted) {
915 Observer.changingInstr(*UseMO.getParent());
916 UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
917 Observer.changedInstr(*UseMO.getParent());
918 return;
919 }
920
921 Builder.setInsertPt(*InsertIntoBB, InsertBefore);
922 Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
923 MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
924 EmittedInsns[InsertIntoBB] = NewMI;
925 replaceRegOpWith(MRI, UseMO, NewDstReg);
926 };
927
928 Observer.changingInstr(MI);
929 unsigned LoadOpc = getExtLoadOpcForExtend(Preferred.ExtendOpcode);
930 MI.setDesc(Builder.getTII().get(LoadOpc));
931
932 // Rewrite all the uses to fix up the types.
933 auto &LoadValue = MI.getOperand(0);
935 llvm::make_pointer_range(MRI.use_operands(LoadValue.getReg())));
936
937 for (auto *UseMO : Uses) {
938 MachineInstr *UseMI = UseMO->getParent();
939
940 // If the extend is compatible with the preferred extend then we should fix
941 // up the type and extend so that it uses the preferred use.
942 if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
943 UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
944 Register UseDstReg = UseMI->getOperand(0).getReg();
945 MachineOperand &UseSrcMO = UseMI->getOperand(1);
946 const LLT UseDstTy = MRI.getType(UseDstReg);
947 if (UseDstReg != ChosenDstReg) {
948 if (Preferred.Ty == UseDstTy) {
949 // If the use has the same type as the preferred use, then merge
950 // the vregs and erase the extend. For example:
951 // %1:_(s8) = G_LOAD ...
952 // %2:_(s32) = G_SEXT %1(s8)
953 // %3:_(s32) = G_ANYEXT %1(s8)
954 // ... = ... %3(s32)
955 // rewrites to:
956 // %2:_(s32) = G_SEXTLOAD ...
957 // ... = ... %2(s32)
958 replaceRegWith(MRI, UseDstReg, ChosenDstReg);
959 Observer.erasingInstr(*UseMO->getParent());
960 UseMO->getParent()->eraseFromParent();
961 } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
962 // If the preferred size is smaller, then keep the extend but extend
963 // from the result of the extending load. For example:
964 // %1:_(s8) = G_LOAD ...
965 // %2:_(s32) = G_SEXT %1(s8)
966 // %3:_(s64) = G_ANYEXT %1(s8)
967 // ... = ... %3(s64)
968 /// rewrites to:
969 // %2:_(s32) = G_SEXTLOAD ...
970 // %3:_(s64) = G_ANYEXT %2:_(s32)
971 // ... = ... %3(s64)
972 replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
973 } else {
974 // If the preferred size is large, then insert a truncate. For
975 // example:
976 // %1:_(s8) = G_LOAD ...
977 // %2:_(s64) = G_SEXT %1(s8)
978 // %3:_(s32) = G_ZEXT %1(s8)
979 // ... = ... %3(s32)
980 /// rewrites to:
981 // %2:_(s64) = G_SEXTLOAD ...
982 // %4:_(s8) = G_TRUNC %2:_(s32)
983 // %3:_(s64) = G_ZEXT %2:_(s8)
984 // ... = ... %3(s64)
985 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
986 InsertTruncAt);
987 }
988 continue;
989 }
990 // The use is (one of) the uses of the preferred use we chose earlier.
991 // We're going to update the load to def this value later so just erase
992 // the old extend.
993 Observer.erasingInstr(*UseMO->getParent());
994 UseMO->getParent()->eraseFromParent();
995 continue;
996 }
997
998 // The use isn't an extend. Truncate back to the type we originally loaded.
999 // This is free on many targets.
1000 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
1001 }
1002
1003 MI.getOperand(0).setReg(ChosenDstReg);
1004 Observer.changedInstr(MI);
1005}
1006
1008 BuildFnTy &MatchInfo) const {
1009 assert(MI.getOpcode() == TargetOpcode::G_AND);
1010
1011 // If we have the following code:
1012 // %mask = G_CONSTANT 255
1013 // %ld = G_LOAD %ptr, (load s16)
1014 // %and = G_AND %ld, %mask
1015 //
1016 // Try to fold it into
1017 // %ld = G_ZEXTLOAD %ptr, (load s8)
1018
1019 Register Dst = MI.getOperand(0).getReg();
1020 if (MRI.getType(Dst).isVector())
1021 return false;
1022
1023 auto MaybeMask =
1024 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1025 if (!MaybeMask)
1026 return false;
1027
1028 APInt MaskVal = MaybeMask->Value;
1029
1030 if (!MaskVal.isMask())
1031 return false;
1032
1033 Register SrcReg = MI.getOperand(1).getReg();
1034 // Don't use getOpcodeDef() here since intermediate instructions may have
1035 // multiple users.
1036 GAnyLoad *LoadMI;
1037 Register PtrReg;
1038 const MachineMemOperand *MMO;
1039 if (!mi_match(SrcReg, MRI, m_GAnyLoad(LoadMI, m_Reg(PtrReg), m_MMO(MMO))))
1040 return false;
1041
1042 Register LoadReg = LoadMI->getDstReg();
1043 LLT RegTy = MRI.getType(LoadReg);
1044 unsigned RegSize = RegTy.getSizeInBits();
1045 unsigned LoadSizeBits = MMO->getSizeInBits().getValue();
1046 unsigned MaskSizeBits = MaskVal.countr_one();
1047
1048 if ((isa<GSExtLoad>(LoadMI) || MaskSizeBits < LoadSizeBits) &&
1049 !MRI.hasOneNonDBGUse(LoadReg))
1050 return false;
1051
1052 // The mask may not be larger than the in-memory type, as it might cover sign
1053 // extended bits
1054 if (MaskSizeBits > LoadSizeBits)
1055 return false;
1056
1057 // If the mask covers the whole destination register, there's nothing to
1058 // extend
1059 if (MaskSizeBits >= RegSize)
1060 return false;
1061
1062 // Most targets cannot deal with loads of size < 8 and need to re-legalize to
1063 // at least byte loads. Avoid creating such loads here
1064 if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
1065 return false;
1066
1067 LegalityQuery::MemDesc MemDesc(*MMO);
1068
1069 // Don't modify the memory access size if this is atomic/volatile, but we can
1070 // still adjust the opcode to indicate the high bit behavior.
1071 if (!MMO->isAtomic() && !MMO->isVolatile())
1072 MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
1073 else if (LoadSizeBits > MaskSizeBits || LoadSizeBits == RegSize)
1074 return false;
1075
1076 // TODO: Could check if it's legal with the reduced or original memory size.
1078 {TargetOpcode::G_ZEXTLOAD, {RegTy, MRI.getType(PtrReg)}, {MemDesc}}))
1079 return false;
1080
1081 MatchInfo = [=](MachineIRBuilder &B) {
1082 B.setInstrAndDebugLoc(*LoadMI);
1083 auto &MF = B.getMF();
1084 auto PtrInfo = MMO->getPointerInfo();
1085 auto *NewMMO = MF.getMachineMemOperand(MMO, PtrInfo, MemDesc.MemoryTy);
1086 B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
1087 replaceRegWith(MRI, LoadReg, Dst);
1088 LoadMI->eraseFromParent();
1089 };
1090 return true;
1091}
1092
1094 const MachineInstr &UseMI) const {
1095 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
1096 "shouldn't consider debug uses");
1097 assert(DefMI.getParent() == UseMI.getParent());
1098 if (&DefMI == &UseMI)
1099 return true;
1100 const MachineBasicBlock &MBB = *DefMI.getParent();
1101 auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
1102 return &MI == &DefMI || &MI == &UseMI;
1103 });
1104 if (DefOrUse == MBB.end())
1105 llvm_unreachable("Block must contain both DefMI and UseMI!");
1106 return &*DefOrUse == &DefMI;
1107}
1108
1110 const MachineInstr &UseMI) const {
1111 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
1112 "shouldn't consider debug uses");
1113 if (MDT)
1114 return MDT->dominates(&DefMI, &UseMI);
1115 else if (DefMI.getParent() != UseMI.getParent())
1116 return false;
1117
1118 return isPredecessor(DefMI, UseMI);
1119}
1120
1122 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
1123 Register SrcReg = MI.getOperand(1).getReg();
1124 Register LoadUser = SrcReg;
1125
1126 if (MRI.getType(SrcReg).isVector())
1127 return false;
1128
1129 Register TruncSrc;
1130 if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
1131 LoadUser = TruncSrc;
1132
1133 uint64_t SizeInBits = MI.getOperand(2).getImm();
1134 // If the source is a G_SEXTLOAD from the same bit width, then we don't
1135 // need any extend at all, just a truncate.
1136 if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
1137 // If truncating more than the original extended value, abort.
1138 auto LoadSizeBits = LoadMI->getMemSizeInBits();
1139 if (TruncSrc &&
1140 MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits.getValue())
1141 return false;
1142 if (LoadSizeBits == SizeInBits)
1143 return true;
1144 }
1145 return false;
1146}
1147
1149 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) const {
1150 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
1151
1152 Register DstReg = MI.getOperand(0).getReg();
1153 LLT RegTy = MRI.getType(DstReg);
1154
1155 // Only supports scalars for now.
1156 if (RegTy.isVector())
1157 return false;
1158
1159 Register SrcReg = MI.getOperand(1).getReg();
1160 Register PtrReg;
1161 const MachineMemOperand *MMO;
1162 if (!mi_match(SrcReg, MRI, m_GLoad(m_Reg(PtrReg), m_MMO(MMO))))
1163 return false;
1164
1165 uint64_t MemBits = MMO->getSizeInBits().getValue();
1166 uint64_t ExtFrom = MI.getOperand(2).getImm();
1167
1168 if (MemBits > ExtFrom && !MRI.hasOneNonDBGUse(SrcReg))
1169 return false;
1170
1171 // If the sign extend extends from a narrower width than the load's width,
1172 // then we can narrow the load width when we combine to a G_SEXTLOAD.
1173 // Avoid widening the load at all.
1174 unsigned NewSizeBits = std::min(ExtFrom, MemBits);
1175
1176 // Don't generate G_SEXTLOADs with a < 1 byte width.
1177 if (NewSizeBits < 8)
1178 return false;
1179 // Don't bother creating a non-power-2 sextload, it will likely be broken up
1180 // anyway for most targets.
1181 if (!isPowerOf2_32(NewSizeBits))
1182 return false;
1183
1184 LegalityQuery::MemDesc MMDesc(*MMO);
1185
1186 // Don't modify the memory access size if this is atomic/volatile, but we can
1187 // still adjust the opcode to indicate the high bit behavior.
1188 if (!MMO->isAtomic() && !MMO->isVolatile())
1189 MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
1190 else if (MemBits > NewSizeBits || MemBits == RegTy.getSizeInBits())
1191 return false;
1192
1193 // TODO: Could check if it's legal with the reduced or original memory size.
1195 {TargetOpcode::G_SEXTLOAD, {RegTy, MRI.getType(PtrReg)}, {MMDesc}}))
1196 return false;
1197
1198 MatchInfo = std::make_tuple(SrcReg, NewSizeBits);
1199 return true;
1200}
1201
1203 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) const {
1204 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
1205 Register LoadReg;
1206 unsigned ScalarSizeBits;
1207 std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
1208 GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
1209
1210 // If we have the following:
1211 // %ld = G_LOAD %ptr, (load 2)
1212 // %ext = G_SEXT_INREG %ld, 8
1213 // ==>
1214 // %ld = G_SEXTLOAD %ptr (load 1)
1215
1216 auto &MMO = LoadDef->getMMO();
1217 Builder.setInstrAndDebugLoc(*LoadDef);
1218 auto &MF = Builder.getMF();
1219 auto PtrInfo = MMO.getPointerInfo();
1220 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
1221 Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
1222 LoadDef->getPointerReg(), *NewMMO);
1223 replaceRegWith(MRI, LoadReg, MI.getOperand(0).getReg());
1224 MI.eraseFromParent();
1225
1226 // Not all loads can be deleted, so make sure the old one is removed.
1227 LoadDef->eraseFromParent();
1228}
1229
1230/// Return true if 'MI' is a load or a store that may be fold it's address
1231/// operand into the load / store addressing mode.
1235 auto *MF = MI->getMF();
1236 auto *Addr = getOpcodeDef<GPtrAdd>(MI->getPointerReg(), MRI);
1237 if (!Addr)
1238 return false;
1239
1240 AM.HasBaseReg = true;
1241 if (auto CstOff = getIConstantVRegVal(Addr->getOffsetReg(), MRI))
1242 AM.BaseOffs = CstOff->getSExtValue(); // [reg +/- imm]
1243 else
1244 AM.Scale = 1; // [reg +/- reg]
1245
1246 return TLI.isLegalAddressingMode(
1247 MF->getDataLayout(), AM,
1248 getTypeForLLT(MI->getMMO().getMemoryType(),
1249 MF->getFunction().getContext()),
1250 MI->getMMO().getAddrSpace());
1251}
1252
1253static unsigned getIndexedOpc(unsigned LdStOpc) {
1254 switch (LdStOpc) {
1255 case TargetOpcode::G_LOAD:
1256 return TargetOpcode::G_INDEXED_LOAD;
1257 case TargetOpcode::G_STORE:
1258 return TargetOpcode::G_INDEXED_STORE;
1259 case TargetOpcode::G_ZEXTLOAD:
1260 return TargetOpcode::G_INDEXED_ZEXTLOAD;
1261 case TargetOpcode::G_SEXTLOAD:
1262 return TargetOpcode::G_INDEXED_SEXTLOAD;
1263 default:
1264 llvm_unreachable("Unexpected opcode");
1265 }
1266}
1267
1268bool CombinerHelper::isIndexedLoadStoreLegal(GLoadStore &LdSt) const {
1269 // Check for legality.
1270 LLT PtrTy = MRI.getType(LdSt.getPointerReg());
1271 LLT Ty = MRI.getType(LdSt.getReg(0));
1272 LLT MemTy = LdSt.getMMO().getMemoryType();
1274 {{MemTy, MemTy.getSizeInBits().getKnownMinValue(),
1276 unsigned IndexedOpc = getIndexedOpc(LdSt.getOpcode());
1277 SmallVector<LLT> OpTys;
1278 if (IndexedOpc == TargetOpcode::G_INDEXED_STORE)
1279 OpTys = {PtrTy, Ty, Ty};
1280 else
1281 OpTys = {Ty, PtrTy}; // For G_INDEXED_LOAD, G_INDEXED_[SZ]EXTLOAD
1282
1283 LegalityQuery Q(IndexedOpc, OpTys, MemDescrs);
1284 return isLegal(Q);
1285}
1286
1288 "post-index-use-threshold", cl::Hidden, cl::init(32),
1289 cl::desc("Number of uses of a base pointer to check before it is no longer "
1290 "considered for post-indexing."));
1291
1292bool CombinerHelper::findPostIndexCandidate(GLoadStore &LdSt, Register &Addr,
1294 bool &RematOffset) const {
1295 // We're looking for the following pattern, for either load or store:
1296 // %baseptr:_(p0) = ...
1297 // G_STORE %val(s64), %baseptr(p0)
1298 // %offset:_(s64) = G_CONSTANT i64 -256
1299 // %new_addr:_(p0) = G_PTR_ADD %baseptr, %offset(s64)
1300 const auto &TLI = getTargetLowering();
1301
1302 Register Ptr = LdSt.getPointerReg();
1303 // If the store is the only use, don't bother.
1304 if (MRI.hasOneNonDBGUse(Ptr))
1305 return false;
1306
1307 if (!isIndexedLoadStoreLegal(LdSt))
1308 return false;
1309
1310 if (getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Ptr, MRI))
1311 return false;
1312
1313 MachineInstr *StoredValDef = getDefIgnoringCopies(LdSt.getReg(0), MRI);
1314 MachineInstr *PtrDef;
1315 if (!mi_match(Ptr, MRI, m_MInstr(PtrDef)))
1316 return false;
1317
1318 unsigned NumUsesChecked = 0;
1319 for (auto &Use : MRI.use_nodbg_instructions(Ptr)) {
1320 if (++NumUsesChecked > PostIndexUseThreshold)
1321 return false; // Try to avoid exploding compile time.
1322
1323 auto *PtrAdd = dyn_cast<GPtrAdd>(&Use);
1324 // The use itself might be dead. This can happen during combines if DCE
1325 // hasn't had a chance to run yet. Don't allow it to form an indexed op.
1326 if (!PtrAdd || MRI.use_nodbg_empty(PtrAdd->getReg(0)))
1327 continue;
1328
1329 // Check the user of this isn't the store, otherwise we'd be generate a
1330 // indexed store defining its own use.
1331 if (StoredValDef == &Use)
1332 continue;
1333
1334 Offset = PtrAdd->getOffsetReg();
1335 if (!ForceLegalIndexing &&
1336 !TLI.isIndexingLegal(LdSt, PtrAdd->getBaseReg(), Offset,
1337 /*IsPre*/ false, MRI))
1338 continue;
1339
1340 // Make sure the offset calculation is before the potentially indexed op.
1341 MachineInstr *OffsetDef;
1342 if (!mi_match(Offset, MRI, m_MInstr(OffsetDef)))
1343 continue;
1344 RematOffset = false;
1345 if (!dominates(*OffsetDef, LdSt)) {
1346 // If the offset however is just a G_CONSTANT, we can always just
1347 // rematerialize it where we need it.
1348 if (OffsetDef->getOpcode() != TargetOpcode::G_CONSTANT)
1349 continue;
1350 RematOffset = true;
1351 }
1352
1353 for (auto &BasePtrUse : MRI.use_nodbg_instructions(PtrAdd->getBaseReg())) {
1354 if (&BasePtrUse == PtrDef)
1355 continue;
1356
1357 // If the user is a later load/store that can be post-indexed, then don't
1358 // combine this one.
1359 auto *BasePtrLdSt = dyn_cast<GLoadStore>(&BasePtrUse);
1360 if (BasePtrLdSt && BasePtrLdSt != &LdSt &&
1361 dominates(LdSt, *BasePtrLdSt) &&
1362 isIndexedLoadStoreLegal(*BasePtrLdSt))
1363 return false;
1364
1365 // Now we're looking for the key G_PTR_ADD instruction, which contains
1366 // the offset add that we want to fold.
1367 if (auto *BasePtrUseDef = dyn_cast<GPtrAdd>(&BasePtrUse)) {
1368 Register PtrAddDefReg = BasePtrUseDef->getReg(0);
1369 for (auto &BaseUseUse : MRI.use_nodbg_instructions(PtrAddDefReg)) {
1370 // If the use is in a different block, then we may produce worse code
1371 // due to the extra register pressure.
1372 if (BaseUseUse.getParent() != LdSt.getParent())
1373 return false;
1374
1375 if (auto *UseUseLdSt = dyn_cast<GLoadStore>(&BaseUseUse))
1376 if (canFoldInAddressingMode(UseUseLdSt, TLI, MRI))
1377 return false;
1378 }
1379 if (!dominates(LdSt, BasePtrUse))
1380 return false; // All use must be dominated by the load/store.
1381 }
1382 }
1383
1384 Addr = PtrAdd->getReg(0);
1385 Base = PtrAdd->getBaseReg();
1386 return true;
1387 }
1388
1389 return false;
1390}
1391
1392bool CombinerHelper::findPreIndexCandidate(GLoadStore &LdSt, Register &Addr,
1393 Register &Base,
1394 Register &Offset) const {
1395 auto &MF = *LdSt.getParent()->getParent();
1396 const auto &TLI = *MF.getSubtarget().getTargetLowering();
1397
1398 Addr = LdSt.getPointerReg();
1399 if (!mi_match(Addr, MRI, m_GPtrAdd(m_Reg(Base), m_Reg(Offset))) ||
1400 MRI.hasOneNonDBGUse(Addr))
1401 return false;
1402
1403 if (!ForceLegalIndexing &&
1404 !TLI.isIndexingLegal(LdSt, Base, Offset, /*IsPre*/ true, MRI))
1405 return false;
1406
1407 if (!isIndexedLoadStoreLegal(LdSt))
1408 return false;
1409
1410 MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
1411 if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
1412 return false;
1413
1414 if (auto *St = dyn_cast<GStore>(&LdSt)) {
1415 // Would require a copy.
1416 if (Base == St->getValueReg())
1417 return false;
1418
1419 // We're expecting one use of Addr in MI, but it could also be the
1420 // value stored, which isn't actually dominated by the instruction.
1421 if (St->getValueReg() == Addr)
1422 return false;
1423 }
1424
1425 // Avoid increasing cross-block register pressure.
1426 for (auto &AddrUse : MRI.use_nodbg_instructions(Addr))
1427 if (AddrUse.getParent() != LdSt.getParent())
1428 return false;
1429
1430 // FIXME: check whether all uses of the base pointer are constant PtrAdds.
1431 // That might allow us to end base's liveness here by adjusting the constant.
1432 bool RealUse = false;
1433 for (auto &AddrUse : MRI.use_nodbg_instructions(Addr)) {
1434 if (!dominates(LdSt, AddrUse))
1435 return false; // All use must be dominated by the load/store.
1436
1437 // If Ptr may be folded in addressing mode of other use, then it's
1438 // not profitable to do this transformation.
1439 if (auto *UseLdSt = dyn_cast<GLoadStore>(&AddrUse)) {
1440 if (!canFoldInAddressingMode(UseLdSt, TLI, MRI))
1441 RealUse = true;
1442 } else {
1443 RealUse = true;
1444 }
1445 }
1446 return RealUse;
1447}
1448
1450 MachineInstr &MI, BuildFnTy &MatchInfo) const {
1451 assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
1452
1453 // Check if there is a load that defines the vector being extracted from.
1454 auto *LoadMI = getOpcodeDef<GLoad>(MI.getOperand(1).getReg(), MRI);
1455 if (!LoadMI)
1456 return false;
1457
1458 Register Vector = MI.getOperand(1).getReg();
1459 LLT VecEltTy = MRI.getType(Vector).getElementType();
1460
1461 assert(MRI.getType(MI.getOperand(0).getReg()) == VecEltTy);
1462
1463 // Checking whether we should reduce the load width.
1464 if (!MRI.hasOneNonDBGUse(Vector))
1465 return false;
1466
1467 // Check if the defining load is simple.
1468 if (!LoadMI->isSimple())
1469 return false;
1470
1471 // If the vector element type is not a multiple of a byte then we are unable
1472 // to correctly compute an address to load only the extracted element as a
1473 // scalar.
1474 if (!VecEltTy.isByteSized())
1475 return false;
1476
1477 // Check for load fold barriers between the extraction and the load.
1478 if (MI.getParent() != LoadMI->getParent())
1479 return false;
1480 const unsigned MaxIter = 20;
1481 unsigned Iter = 0;
1482 for (const auto &Instr :
1483 instructionsWithoutDebug(LoadMI->getIterator(), MI.getIterator())) {
1484 if (Instr.isLoadFoldBarrier())
1485 return false;
1486 if (Iter++ == MaxIter)
1487 return false;
1488 }
1489
1490 // Check if the new load that we are going to create is legal
1491 // if we are in the post-legalization phase.
1492 MachineMemOperand MMO = LoadMI->getMMO();
1493 Align Alignment = MMO.getAlign();
1494 MachinePointerInfo PtrInfo;
1495 uint64_t Offset;
1496
1497 // Finding the appropriate PtrInfo if offset is a known constant.
1498 // This is required to create the memory operand for the narrowed load.
1499 // This machine memory operand object helps us infer about legality
1500 // before we proceed to combine the instruction.
1501 Register Idx = MI.getOperand(2).getReg();
1502 if (auto CVal = getIConstantVRegVal(Idx, MRI)) {
1503 int Elt = CVal->getZExtValue();
1504 Offset = VecEltTy.getSizeInBits() * Elt / 8;
1505 PtrInfo = MMO.getPointerInfo().getWithOffset(Offset);
1506 } else {
1507 // Discard the pointer info except the address space because the memory
1508 // operand can't represent this new access since the offset is variable.
1509 Offset = VecEltTy.getSizeInBits() / 8;
1511 }
1512
1513 Alignment = commonAlignment(Alignment, Offset);
1514
1515 Register VecPtr = LoadMI->getPointerReg();
1516 LLT PtrTy = MRI.getType(VecPtr);
1517
1518 MachineFunction &MF = *MI.getMF();
1519 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, VecEltTy);
1520
1521 LegalityQuery::MemDesc MMDesc(*NewMMO);
1522
1524 {TargetOpcode::G_LOAD, {VecEltTy, PtrTy}, {MMDesc}}))
1525 return false;
1526
1527 // Load must be allowed and fast on the target.
1529 auto &DL = MF.getDataLayout();
1530 unsigned Fast = 0;
1531 if (!getTargetLowering().allowsMemoryAccess(C, DL, VecEltTy, *NewMMO,
1532 &Fast) ||
1533 !Fast)
1534 return false;
1535
1536 Register Result = MI.getOperand(0).getReg();
1537 Register Index = MI.getOperand(2).getReg();
1538
1539 MatchInfo = [=](MachineIRBuilder &B) {
1540 GISelObserverWrapper DummyObserver;
1541 LegalizerHelper Helper(B.getMF(), DummyObserver, B);
1542 //// Get pointer to the vector element.
1543 Register finalPtr = Helper.getVectorElementPointer(
1544 LoadMI->getPointerReg(), MRI.getType(LoadMI->getOperand(0).getReg()),
1545 Index);
1546 // New G_LOAD instruction.
1547 B.buildLoad(Result, finalPtr, PtrInfo, Alignment);
1548 // Remove original GLOAD instruction.
1549 LoadMI->eraseFromParent();
1550 };
1551
1552 return true;
1553}
1554
1556 MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) const {
1557 auto &LdSt = cast<GLoadStore>(MI);
1558
1559 if (LdSt.isAtomic())
1560 return false;
1561
1562 MatchInfo.IsPre = findPreIndexCandidate(LdSt, MatchInfo.Addr, MatchInfo.Base,
1563 MatchInfo.Offset);
1564 if (!MatchInfo.IsPre &&
1565 !findPostIndexCandidate(LdSt, MatchInfo.Addr, MatchInfo.Base,
1566 MatchInfo.Offset, MatchInfo.RematOffset))
1567 return false;
1568
1569 return true;
1570}
1571
1573 MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) const {
1574 MachineInstr &AddrDef = *MRI.getVRegDef(MatchInfo.Addr);
1575 unsigned Opcode = MI.getOpcode();
1576 bool IsStore = Opcode == TargetOpcode::G_STORE;
1577 unsigned NewOpcode = getIndexedOpc(Opcode);
1578
1579 // If the offset constant didn't happen to dominate the load/store, we can
1580 // just clone it as needed.
1581 if (MatchInfo.RematOffset) {
1582 auto *OldCst = MRI.getVRegDef(MatchInfo.Offset);
1583 auto NewCst = Builder.buildConstant(MRI.getType(MatchInfo.Offset),
1584 *OldCst->getOperand(1).getCImm());
1585 MatchInfo.Offset = NewCst.getReg(0);
1586 }
1587
1588 auto MIB = Builder.buildInstr(NewOpcode);
1589 if (IsStore) {
1590 MIB.addDef(MatchInfo.Addr);
1591 MIB.addUse(MI.getOperand(0).getReg());
1592 } else {
1593 MIB.addDef(MI.getOperand(0).getReg());
1594 MIB.addDef(MatchInfo.Addr);
1595 }
1596
1597 MIB.addUse(MatchInfo.Base);
1598 MIB.addUse(MatchInfo.Offset);
1599 MIB.addImm(MatchInfo.IsPre);
1600 MIB->cloneMemRefs(*MI.getMF(), MI);
1601 MI.eraseFromParent();
1602 AddrDef.eraseFromParent();
1603
1604 LLVM_DEBUG(dbgs() << " Combinined to indexed operation");
1605}
1606
1608 MachineInstr *&OtherMI) const {
1609 unsigned Opcode = MI.getOpcode();
1610 bool IsDiv, IsSigned;
1611
1612 switch (Opcode) {
1613 default:
1614 llvm_unreachable("Unexpected opcode!");
1615 case TargetOpcode::G_SDIV:
1616 case TargetOpcode::G_UDIV: {
1617 IsDiv = true;
1618 IsSigned = Opcode == TargetOpcode::G_SDIV;
1619 break;
1620 }
1621 case TargetOpcode::G_SREM:
1622 case TargetOpcode::G_UREM: {
1623 IsDiv = false;
1624 IsSigned = Opcode == TargetOpcode::G_SREM;
1625 break;
1626 }
1627 }
1628
1629 Register Src1 = MI.getOperand(1).getReg();
1630 unsigned DivOpcode, RemOpcode, DivremOpcode;
1631 if (IsSigned) {
1632 DivOpcode = TargetOpcode::G_SDIV;
1633 RemOpcode = TargetOpcode::G_SREM;
1634 DivremOpcode = TargetOpcode::G_SDIVREM;
1635 } else {
1636 DivOpcode = TargetOpcode::G_UDIV;
1637 RemOpcode = TargetOpcode::G_UREM;
1638 DivremOpcode = TargetOpcode::G_UDIVREM;
1639 }
1640
1641 if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
1642 return false;
1643
1644 // Combine:
1645 // %div:_ = G_[SU]DIV %src1:_, %src2:_
1646 // %rem:_ = G_[SU]REM %src1:_, %src2:_
1647 // into:
1648 // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1649
1650 // Combine:
1651 // %rem:_ = G_[SU]REM %src1:_, %src2:_
1652 // %div:_ = G_[SU]DIV %src1:_, %src2:_
1653 // into:
1654 // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1655
1656 for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
1657 if (MI.getParent() == UseMI.getParent() &&
1658 ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
1659 (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
1660 matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2)) &&
1661 matchEqualDefs(MI.getOperand(1), UseMI.getOperand(1))) {
1662 OtherMI = &UseMI;
1663 return true;
1664 }
1665 }
1666
1667 return false;
1668}
1669
1671 MachineInstr *&OtherMI) const {
1672 unsigned Opcode = MI.getOpcode();
1673 assert(OtherMI && "OtherMI shouldn't be empty.");
1674
1675 Register DestDivReg, DestRemReg;
1676 if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
1677 DestDivReg = MI.getOperand(0).getReg();
1678 DestRemReg = OtherMI->getOperand(0).getReg();
1679 } else {
1680 DestDivReg = OtherMI->getOperand(0).getReg();
1681 DestRemReg = MI.getOperand(0).getReg();
1682 }
1683
1684 bool IsSigned =
1685 Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
1686
1687 // Check which instruction is first in the block so we don't break def-use
1688 // deps by "moving" the instruction incorrectly. Also keep track of which
1689 // instruction is first so we pick it's operands, avoiding use-before-def
1690 // bugs.
1691 MachineInstr *FirstInst = dominates(MI, *OtherMI) ? &MI : OtherMI;
1692 Builder.setInstrAndDebugLoc(*FirstInst);
1693
1694 Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
1695 : TargetOpcode::G_UDIVREM,
1696 {DestDivReg, DestRemReg},
1697 { FirstInst->getOperand(1), FirstInst->getOperand(2) });
1698 MI.eraseFromParent();
1699 OtherMI->eraseFromParent();
1700}
1701
1703 MachineInstr &MI, MachineInstr *&BrCond) const {
1704 assert(MI.getOpcode() == TargetOpcode::G_BR);
1705
1706 // Try to match the following:
1707 // bb1:
1708 // G_BRCOND %c1, %bb2
1709 // G_BR %bb3
1710 // bb2:
1711 // ...
1712 // bb3:
1713
1714 // The above pattern does not have a fall through to the successor bb2, always
1715 // resulting in a branch no matter which path is taken. Here we try to find
1716 // and replace that pattern with conditional branch to bb3 and otherwise
1717 // fallthrough to bb2. This is generally better for branch predictors.
1718
1719 MachineBasicBlock *MBB = MI.getParent();
1721 if (BrIt == MBB->begin())
1722 return false;
1723 assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
1724
1725 BrCond = &*std::prev(BrIt);
1726 if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
1727 return false;
1728
1729 // Check that the next block is the conditional branch target. Also make sure
1730 // that it isn't the same as the G_BR's target (otherwise, this will loop.)
1731 MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
1732 return BrCondTarget != MI.getOperand(0).getMBB() &&
1733 MBB->isLayoutSuccessor(BrCondTarget);
1734}
1735
1737 MachineInstr &MI, MachineInstr *&BrCond) const {
1738 MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
1739 Builder.setInstrAndDebugLoc(*BrCond);
1740 LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
1741 auto True =
1742 Builder.buildConstant(Ty, getICmpTrueVal(getTargetLowering(), false));
1743 auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
1744
1745 auto *FallthroughBB = BrCond->getOperand(1).getMBB();
1746 Observer.changingInstr(MI);
1747 MI.getOperand(0).setMBB(FallthroughBB);
1748 Observer.changedInstr(MI);
1749
1750 // Change the conditional branch to use the inverted condition and
1751 // new target block.
1752 Observer.changingInstr(*BrCond);
1753 BrCond->getOperand(0).setReg(Xor.getReg(0));
1754 BrCond->getOperand(1).setMBB(BrTarget);
1755 Observer.changedInstr(*BrCond);
1756}
1757
1760 unsigned MaxLen) const {
1761 auto &[Dst, Src, KnownLen, Alignment, DstAlignCanChange, MemOps] = MatchInfo;
1762 return canLowerMemCpyFamily(MI, MRI, MaxLen, Dst, Src, KnownLen, Alignment,
1763 DstAlignCanChange, MemOps);
1764}
1765
1767 MachineInstr &MI, MemCpyFamilyLoweringInfo &MatchInfo) const {
1768 auto &[Dst, Src, KnownLen, Alignment, DstAlignCanChange, MemOps] = MatchInfo;
1769 MachineIRBuilder HelperBuilder(MI);
1770 GISelObserverWrapper DummyObserver;
1771 LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1772 bool Changed = Helper.lowerMemCpyFamily(MI, Dst, Src, KnownLen, Alignment,
1773 DstAlignCanChange, MemOps) ==
1775 assert(Changed && "expected memcpy-family instruction to lower");
1776 (void)Changed;
1777}
1778
1780 unsigned MaxLen) const {
1781 MachineIRBuilder HelperBuilder(MI);
1782 GISelObserverWrapper DummyObserver;
1783 LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1784 return Helper.lowerMemCpyFamily(MI, MaxLen) ==
1786}
1787
1789 PtrAddChain &MatchInfo) const {
1790 // We're trying to match the following pattern:
1791 // %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1792 // %root = G_PTR_ADD %t1, G_CONSTANT imm2
1793 // -->
1794 // %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1795
1796 if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1797 return false;
1798
1799 Register Add2 = MI.getOperand(1).getReg();
1800 Register Imm1 = MI.getOperand(2).getReg();
1801 auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1802 if (!MaybeImmVal)
1803 return false;
1804
1805 Register Base, Imm2;
1806 uint32_t LHSPtrAddFlags;
1807 if (!mi_match(Add2, MRI,
1808 m_GPtrAdd(m_Reg(Base), m_Reg(Imm2), m_MIFlags(LHSPtrAddFlags))))
1809 return false;
1810
1811 auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1812 if (!MaybeImm2Val)
1813 return false;
1814
1815 // Check if the new combined immediate forms an illegal addressing mode.
1816 // Do not combine if it was legal before but would get illegal.
1817 // To do so, we need to find a load/store user of the pointer to get
1818 // the access type.
1819 Type *AccessTy = nullptr;
1820 auto &MF = *MI.getMF();
1821 for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
1822 if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
1823 AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
1824 MF.getFunction().getContext());
1825 break;
1826 }
1827 }
1829 APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
1830 AMNew.BaseOffs = CombinedImm.getSExtValue();
1831 if (AccessTy) {
1832 AMNew.HasBaseReg = true;
1834 AMOld.BaseOffs = MaybeImmVal->Value.getSExtValue();
1835 AMOld.HasBaseReg = true;
1836 unsigned AS = MRI.getType(Add2).getAddressSpace();
1837 const auto &TLI = *MF.getSubtarget().getTargetLowering();
1838 if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
1839 !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
1840 return false;
1841 }
1842
1843 // Reassociating nuw additions preserves nuw. If both original G_PTR_ADDs are
1844 // inbounds, reaching the same result in one G_PTR_ADD is also inbounds.
1845 // The nusw constraints are satisfied because imm1+imm2 cannot exceed the
1846 // largest signed integer that fits into the index type, which is the maximum
1847 // size of allocated objects according to the IR Language Reference.
1848 unsigned PtrAddFlags = MI.getFlags();
1849 bool IsNoUWrap = PtrAddFlags & LHSPtrAddFlags & MachineInstr::MIFlag::NoUWrap;
1850 bool IsInBounds =
1851 PtrAddFlags & LHSPtrAddFlags & MachineInstr::MIFlag::InBounds;
1852 unsigned Flags = 0;
1853 if (IsNoUWrap)
1855 if (IsInBounds) {
1858 }
1859
1860 // Pass the combined immediate to the apply function.
1861 MatchInfo.Imm = AMNew.BaseOffs;
1862 MatchInfo.Base = Base;
1863 MatchInfo.Bank = getRegBank(Imm2);
1864 MatchInfo.Flags = Flags;
1865 return true;
1866}
1867
1869 PtrAddChain &MatchInfo) const {
1870 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1871 MachineIRBuilder MIB(MI);
1872 LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1873 auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1874 setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
1875 Observer.changingInstr(MI);
1876 MI.getOperand(1).setReg(MatchInfo.Base);
1877 MI.getOperand(2).setReg(NewOffset.getReg(0));
1878 MI.setFlags(MatchInfo.Flags);
1879 Observer.changedInstr(MI);
1880}
1881
1883 RegisterImmPair &MatchInfo) const {
1884 // We're trying to match the following pattern with any of
1885 // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
1886 // %t1 = SHIFT %base, G_CONSTANT imm1
1887 // %root = SHIFT %t1, G_CONSTANT imm2
1888 // -->
1889 // %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
1890
1891 unsigned Opcode = MI.getOpcode();
1892 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1893 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1894 Opcode == TargetOpcode::G_USHLSAT) &&
1895 "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1896
1897 Register Shl2 = MI.getOperand(1).getReg();
1898 Register Imm1 = MI.getOperand(2).getReg();
1899 auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1900 if (!MaybeImmVal)
1901 return false;
1902
1903 MachineInstr *Shl2Def;
1904 if (!mi_match(Shl2, MRI, m_MInstr(Shl2Def)) || Shl2Def->getOpcode() != Opcode)
1905 return false;
1906
1907 Register Base = Shl2Def->getOperand(1).getReg();
1908 Register Imm2 = Shl2Def->getOperand(2).getReg();
1909 auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1910 if (!MaybeImm2Val)
1911 return false;
1912
1913 // Pass the combined immediate to the apply function.
1914 MatchInfo.Imm =
1915 (MaybeImmVal->Value.getZExtValue() + MaybeImm2Val->Value).getZExtValue();
1916 MatchInfo.Reg = Base;
1917
1918 // There is no simple replacement for a saturating unsigned left shift that
1919 // exceeds the scalar size.
1920 if (Opcode == TargetOpcode::G_USHLSAT &&
1921 MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
1922 return false;
1923
1924 return true;
1925}
1926
1928 RegisterImmPair &MatchInfo) const {
1929 unsigned Opcode = MI.getOpcode();
1930 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1931 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1932 Opcode == TargetOpcode::G_USHLSAT) &&
1933 "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1934
1935 LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1936 unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
1937 auto Imm = MatchInfo.Imm;
1938
1939 if (Imm >= ScalarSizeInBits) {
1940 // Any logical shift that exceeds scalar size will produce zero.
1941 if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
1942 Builder.buildConstant(MI.getOperand(0), 0);
1943 MI.eraseFromParent();
1944 return;
1945 }
1946 // Arithmetic shift and saturating signed left shift have no effect beyond
1947 // scalar size.
1948 Imm = ScalarSizeInBits - 1;
1949 }
1950
1951 LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
1952 Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
1953 Observer.changingInstr(MI);
1954 MI.getOperand(1).setReg(MatchInfo.Reg);
1955 MI.getOperand(2).setReg(NewImm);
1956 Observer.changedInstr(MI);
1957}
1958
1960 MachineInstr &MI, ShiftOfShiftedLogic &MatchInfo) const {
1961 // We're trying to match the following pattern with any of
1962 // G_SHL/G_ASHR/G_LSHR shift instructions in combination
1963 // with any of G_AND/G_OR/G_XOR logic instructions.
1964 // %t1 = SHIFT %X, G_CONSTANT C0
1965 // %t2 = LOGIC %t1, %Y
1966 // %root = SHIFT %t2, G_CONSTANT C1
1967 // -->
1968 // %t3 = SHIFT %X, G_CONSTANT (C0+C1)
1969 // %t4 = SHIFT %Y, G_CONSTANT C1
1970 // %root = LOGIC %t3, %t4
1971 unsigned ShiftOpcode = MI.getOpcode();
1972 assert((ShiftOpcode == TargetOpcode::G_SHL ||
1973 ShiftOpcode == TargetOpcode::G_ASHR ||
1974 ShiftOpcode == TargetOpcode::G_LSHR) &&
1975 "Expected G_SHL, G_ASHR and G_LSHR");
1976
1977 // Match a one-use bitwise logic op.
1978 Register LogicDest = MI.getOperand(1).getReg();
1979 if (!MRI.hasOneNonDBGUse(LogicDest))
1980 return false;
1981
1982 MachineInstr *LogicMI;
1983 if (!mi_match(LogicDest, MRI, m_MInstr(LogicMI)))
1984 return false;
1985 unsigned LogicOpcode = LogicMI->getOpcode();
1986 if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
1987 LogicOpcode != TargetOpcode::G_XOR)
1988 return false;
1989
1990 // Find a matching one-use shift by constant.
1991 const Register C1 = MI.getOperand(2).getReg();
1992 auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
1993 if (!MaybeImmVal || MaybeImmVal->Value == 0)
1994 return false;
1995
1996 const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
1997
1998 auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
1999 // Shift should match previous one and should be a one-use.
2000 if (MI->getOpcode() != ShiftOpcode ||
2001 !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
2002 return false;
2003
2004 // Must be a constant.
2005 auto MaybeImmVal =
2006 getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
2007 if (!MaybeImmVal)
2008 return false;
2009
2010 ShiftVal = MaybeImmVal->Value.getSExtValue();
2011 return true;
2012 };
2013
2014 // Logic ops are commutative, so check each operand for a match.
2015 Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
2016 MachineInstr *LogicMIOp1;
2017 Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
2018 MachineInstr *LogicMIOp2;
2019 if (!mi_match(LogicMIReg1, MRI, m_MInstr(LogicMIOp1)) ||
2020 !mi_match(LogicMIReg2, MRI, m_MInstr(LogicMIOp2)))
2021 return false;
2022 uint64_t C0Val;
2023
2024 if (matchFirstShift(LogicMIOp1, C0Val)) {
2025 MatchInfo.LogicNonShiftReg = LogicMIReg2;
2026 MatchInfo.Shift2 = LogicMIOp1;
2027 } else if (matchFirstShift(LogicMIOp2, C0Val)) {
2028 MatchInfo.LogicNonShiftReg = LogicMIReg1;
2029 MatchInfo.Shift2 = LogicMIOp2;
2030 } else
2031 return false;
2032
2033 MatchInfo.ValSum = C0Val + C1Val;
2034
2035 // The fold is not valid if the sum of the shift values exceeds bitwidth.
2036 if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
2037 return false;
2038
2039 MatchInfo.Logic = LogicMI;
2040 return true;
2041}
2042
2044 MachineInstr &MI, ShiftOfShiftedLogic &MatchInfo) const {
2045 unsigned Opcode = MI.getOpcode();
2046 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
2047 Opcode == TargetOpcode::G_LSHR) &&
2048 "Expected G_SHL, G_ASHR and G_LSHR");
2049
2050 LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
2051 LLT DestType = MRI.getType(MI.getOperand(0).getReg());
2052
2053 Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
2054
2055 Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
2056 Register Shift1 =
2057 Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
2058
2059 // If LogicNonShiftReg is the same to Shift1Base, and shift1 const is the same
2060 // to MatchInfo.Shift2 const, CSEMIRBuilder will reuse the old shift1 when
2061 // build shift2. So, if we erase MatchInfo.Shift2 at the end, actually we
2062 // remove old shift1. And it will cause crash later. So erase it earlier to
2063 // avoid the crash.
2064 MatchInfo.Shift2->eraseFromParent();
2065
2066 Register Shift2Const = MI.getOperand(2).getReg();
2067 Register Shift2 = Builder
2068 .buildInstr(Opcode, {DestType},
2069 {MatchInfo.LogicNonShiftReg, Shift2Const})
2070 .getReg(0);
2071
2072 Register Dest = MI.getOperand(0).getReg();
2073 Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
2074
2075 // This was one use so it's safe to remove it.
2076 MatchInfo.Logic->eraseFromParent();
2077
2078 MI.eraseFromParent();
2079}
2080
2086
2088 LshrOfTruncOfLshr &MatchInfo,
2089 MachineInstr &ShiftMI) const {
2090 assert(MI.getOpcode() == TargetOpcode::G_LSHR && "Expected a G_LSHR");
2091
2092 Register N0 = MI.getOperand(1).getReg();
2093 Register N1 = MI.getOperand(2).getReg();
2094 unsigned OpSizeInBits = MRI.getType(N0).getScalarSizeInBits();
2095
2096 APInt N1C, N001C;
2097 if (!mi_match(N1, MRI, m_ICstOrSplat(N1C)))
2098 return false;
2099 auto N001 = ShiftMI.getOperand(2).getReg();
2100 if (!mi_match(N001, MRI, m_ICstOrSplat(N001C)))
2101 return false;
2102
2103 if (N001C.getBitWidth() > N1C.getBitWidth())
2104 N1C = N1C.zext(N001C.getBitWidth());
2105 else
2106 N001C = N001C.zext(N1C.getBitWidth());
2107
2108 Register InnerShift = ShiftMI.getOperand(0).getReg();
2109 LLT InnerShiftTy = MRI.getType(InnerShift);
2110 uint64_t InnerShiftSize = InnerShiftTy.getScalarSizeInBits();
2111 if ((N1C + N001C).ult(InnerShiftSize)) {
2112 MatchInfo.Src = ShiftMI.getOperand(1).getReg();
2113 MatchInfo.ShiftAmt = N1C + N001C;
2114 MatchInfo.ShiftAmtTy = MRI.getType(N001);
2115 MatchInfo.InnerShiftTy = InnerShiftTy;
2116
2117 if ((N001C + OpSizeInBits) == InnerShiftSize)
2118 return true;
2119 if (MRI.hasOneNonDBGUse(N0) && MRI.hasOneNonDBGUse(InnerShift)) {
2120 MatchInfo.Mask = true;
2121 MatchInfo.MaskVal = APInt(N1C.getBitWidth(), OpSizeInBits) - N1C;
2122 return true;
2123 }
2124 }
2125 return false;
2126}
2127
2129 MachineInstr &MI, LshrOfTruncOfLshr &MatchInfo) const {
2130 assert(MI.getOpcode() == TargetOpcode::G_LSHR && "Expected a G_LSHR");
2131
2132 Register Dst = MI.getOperand(0).getReg();
2133 auto ShiftAmt =
2134 Builder.buildConstant(MatchInfo.ShiftAmtTy, MatchInfo.ShiftAmt);
2135 auto Shift =
2136 Builder.buildLShr(MatchInfo.InnerShiftTy, MatchInfo.Src, ShiftAmt);
2137 if (MatchInfo.Mask == true) {
2138 APInt MaskVal =
2140 MatchInfo.MaskVal.getZExtValue());
2141 auto Mask = Builder.buildConstant(MatchInfo.InnerShiftTy, MaskVal);
2142 auto And = Builder.buildAnd(MatchInfo.InnerShiftTy, Shift, Mask);
2143 Builder.buildTrunc(Dst, And);
2144 } else
2145 Builder.buildTrunc(Dst, Shift);
2146 MI.eraseFromParent();
2147}
2148
2150 unsigned &ShiftVal) const {
2151 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2152 auto MaybeImmVal =
2153 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
2154 if (!MaybeImmVal)
2155 return false;
2156
2157 ShiftVal = MaybeImmVal->Value.exactLogBase2();
2158 return (static_cast<int32_t>(ShiftVal) != -1);
2159}
2160
2162 unsigned &ShiftVal) const {
2163 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2164 MachineIRBuilder MIB(MI);
2165 LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
2166 auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
2167 Observer.changingInstr(MI);
2168 MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
2169 MI.getOperand(2).setReg(ShiftCst.getReg(0));
2170 if (ShiftVal == ShiftTy.getScalarSizeInBits() - 1)
2172 Observer.changedInstr(MI);
2173}
2174
2176 BuildFnTy &MatchInfo) const {
2177 GSub &Sub = cast<GSub>(MI);
2178
2179 LLT Ty = MRI.getType(Sub.getReg(0));
2180
2181 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_ADD, {Ty}}))
2182 return false;
2183
2185 return false;
2186
2187 APInt Imm = getIConstantFromReg(Sub.getRHSReg(), MRI);
2188
2189 MatchInfo = [=, &MI](MachineIRBuilder &B) {
2190 auto NegCst = B.buildConstant(Ty, -Imm);
2191 Observer.changingInstr(MI);
2192 MI.setDesc(B.getTII().get(TargetOpcode::G_ADD));
2193 MI.getOperand(2).setReg(NegCst.getReg(0));
2195 if (Imm.isMinSignedValue())
2197 Observer.changedInstr(MI);
2198 };
2199 return true;
2200}
2201
2202// shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
2204 RegisterImmPair &MatchData) const {
2205 assert(MI.getOpcode() == TargetOpcode::G_SHL && VT);
2206 if (!getTargetLowering().isDesirableToPullExtFromShl(MI))
2207 return false;
2208
2209 Register LHS = MI.getOperand(1).getReg();
2210
2211 Register ExtSrc;
2212 if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
2213 !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
2214 !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
2215 return false;
2216
2217 Register RHS = MI.getOperand(2).getReg();
2218 auto MaybeShiftAmtVal = isConstantOrConstantSplatVector(RHS, MRI);
2219 if (!MaybeShiftAmtVal)
2220 return false;
2221
2222 if (LI) {
2223 LLT SrcTy = MRI.getType(ExtSrc);
2224
2225 // We only really care about the legality with the shifted value. We can
2226 // pick any type the constant shift amount, so ask the target what to
2227 // use. Otherwise we would have to guess and hope it is reported as legal.
2228 LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
2229 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
2230 return false;
2231 }
2232
2233 int64_t ShiftAmt = MaybeShiftAmtVal->getSExtValue();
2234 MatchData.Reg = ExtSrc;
2235 MatchData.Imm = ShiftAmt;
2236
2237 unsigned MinLeadingZeros = VT->getKnownZeroes(ExtSrc).countl_one();
2238 unsigned SrcTySize = MRI.getType(ExtSrc).getScalarSizeInBits();
2239 return MinLeadingZeros >= ShiftAmt && ShiftAmt < SrcTySize;
2240}
2241
2243 MachineInstr &MI, const RegisterImmPair &MatchData) const {
2244 Register ExtSrcReg = MatchData.Reg;
2245 int64_t ShiftAmtVal = MatchData.Imm;
2246
2247 LLT ExtSrcTy = MRI.getType(ExtSrcReg);
2248 auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
2249 auto NarrowShift =
2250 Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
2251 Builder.buildZExt(MI.getOperand(0), NarrowShift);
2252 MI.eraseFromParent();
2253}
2254
2256 const MachineRegisterInfo &MRI) {
2257 while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
2258 ;
2259
2260 return Reg;
2261}
2262
2265 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2266 "Expected an unmerge");
2267 auto &Unmerge = cast<GUnmerge>(MI);
2268 Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
2269
2270 auto *SrcInstr = getOpcodeDef<GMergeLikeInstr>(SrcReg, MRI);
2271 if (!SrcInstr)
2272 return false;
2273
2274 // Check the source type of the merge.
2275 LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
2276 LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
2277 bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
2278 if (SrcMergeTy != Dst0Ty && !SameSize)
2279 return false;
2280 // They are the same now (modulo a bitcast).
2281 // We can collect all the src registers.
2282 for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
2283 Operands.push_back(SrcInstr->getSourceReg(Idx));
2284 return true;
2285}
2286
2289 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2290 "Expected an unmerge");
2291 assert((MI.getNumOperands() - 1 == Operands.size()) &&
2292 "Not enough operands to replace all defs");
2293 unsigned NumElems = MI.getNumOperands() - 1;
2294
2295 LLT SrcTy = MRI.getType(Operands[0]);
2296 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2297 bool CanReuseInputDirectly = DstTy == SrcTy;
2298 for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
2299 Register DstReg = MI.getOperand(Idx).getReg();
2300 Register SrcReg = Operands[Idx];
2301
2302 // This combine may run after RegBankSelect, so we need to be aware of
2303 // register banks.
2304 const auto &DstCB = MRI.getRegClassOrRegBank(DstReg);
2305 if (!DstCB.isNull() && DstCB != MRI.getRegClassOrRegBank(SrcReg)) {
2306 SrcReg = Builder.buildCopy(MRI.getType(SrcReg), SrcReg).getReg(0);
2307 MRI.setRegClassOrRegBank(SrcReg, DstCB);
2308 }
2309
2310 if (CanReuseInputDirectly)
2311 replaceRegWith(MRI, DstReg, SrcReg);
2312 else
2313 Builder.buildCast(DstReg, SrcReg);
2314 }
2315 MI.eraseFromParent();
2316}
2317
2319 MachineInstr &MI, SmallVectorImpl<APInt> &Csts) const {
2320 unsigned SrcIdx = MI.getNumOperands() - 1;
2321 Register SrcReg = MI.getOperand(SrcIdx).getReg();
2322 // Break down the big constant in smaller ones.
2323 APInt Val;
2324 if (!mi_match(SrcReg, MRI, m_GConstantOrFConstantBits(Val)))
2325 return false;
2326
2327 LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
2328 unsigned ShiftAmt = Dst0Ty.getSizeInBits();
2329 // Unmerge a constant.
2330 for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
2331 Csts.emplace_back(Val.trunc(ShiftAmt));
2332 Val = Val.lshr(ShiftAmt);
2333 }
2334
2335 return true;
2336}
2337
2339 MachineInstr &MI, SmallVectorImpl<APInt> &Csts) const {
2340 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2341 "Expected an unmerge");
2342 assert((MI.getNumOperands() - 1 == Csts.size()) &&
2343 "Not enough operands to replace all defs");
2344 unsigned NumElems = MI.getNumOperands() - 1;
2345 for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
2346 Register DstReg = MI.getOperand(Idx).getReg();
2347 Builder.buildConstant(DstReg, Csts[Idx]);
2348 }
2349
2350 MI.eraseFromParent();
2351}
2352
2355 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
2356 unsigned SrcIdx = MI.getNumOperands() - 1;
2357 Register SrcReg = MI.getOperand(SrcIdx).getReg();
2358 MatchInfo = [&MI](MachineIRBuilder &B) {
2359 unsigned NumElems = MI.getNumOperands() - 1;
2360 for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
2361 Register DstReg = MI.getOperand(Idx).getReg();
2362 B.buildUndef(DstReg);
2363 }
2364 };
2365 return mi_match(SrcReg, MRI, m_GImplicitDef());
2366}
2367
2369 MachineInstr &MI) const {
2370 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2371 "Expected an unmerge");
2372 if (!MRI.getType(MI.getOperand(0).getReg()).isScalar() ||
2373 !MRI.getType(MI.getOperand(MI.getNumDefs()).getReg()).isScalar())
2374 return false;
2375 // Check that all the lanes are dead except the first one.
2376 for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
2377 if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
2378 return false;
2379 }
2380 return true;
2381}
2382
2384 MachineInstr &MI) const {
2385 Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
2386 Register Dst0Reg = MI.getOperand(0).getReg();
2387 Builder.buildTrunc(Dst0Reg, SrcReg);
2388 MI.eraseFromParent();
2389}
2390
2392 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2393 "Expected an unmerge");
2394 Register Dst0Reg = MI.getOperand(0).getReg();
2395 LLT Dst0Ty = MRI.getType(Dst0Reg);
2396 // G_ZEXT on vector applies to each lane, so it will
2397 // affect all destinations. Therefore we won't be able
2398 // to simplify the unmerge to just the first definition.
2399 if (Dst0Ty.isVector())
2400 return false;
2401 Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
2402 LLT SrcTy = MRI.getType(SrcReg);
2403 if (SrcTy.isVector())
2404 return false;
2405
2406 Register ZExtSrcReg;
2407 if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
2408 return false;
2409
2410 // Finally we can replace the first definition with
2411 // a zext of the source if the definition is big enough to hold
2412 // all of ZExtSrc bits.
2413 LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
2414 return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
2415}
2416
2418 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
2419 "Expected an unmerge");
2420
2421 Register Dst0Reg = MI.getOperand(0).getReg();
2422
2423 GZext *ZExtInstr =
2424 cast<GZext>(MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg()));
2425 Register ZExtSrcReg = ZExtInstr->getSrcReg();
2426 LLT Dst0Ty = MRI.getType(Dst0Reg);
2427 LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
2428
2429 if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
2430 Builder.buildZExt(Dst0Reg, ZExtSrcReg);
2431 } else {
2432 assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
2433 "ZExt src doesn't fit in destination");
2434 replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
2435 }
2436
2437 Register ZeroReg;
2438 for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
2439 if (!ZeroReg)
2440 ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
2441 replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
2442 }
2443 MI.eraseFromParent();
2444}
2445
2447 unsigned TargetShiftSize,
2448 unsigned &ShiftVal) const {
2449 assert((MI.getOpcode() == TargetOpcode::G_SHL ||
2450 MI.getOpcode() == TargetOpcode::G_LSHR ||
2451 MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
2452
2453 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2454 if (Ty.isVector()) // TODO:
2455 return false;
2456
2457 // Don't narrow further than the requested size.
2458 unsigned Size = Ty.getSizeInBits();
2459 if (Size <= TargetShiftSize)
2460 return false;
2461
2462 auto MaybeImmVal =
2463 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
2464 if (!MaybeImmVal)
2465 return false;
2466
2467 ShiftVal = MaybeImmVal->Value.getSExtValue();
2468 return ShiftVal >= Size / 2 && ShiftVal < Size;
2469}
2470
2472 MachineInstr &MI, const unsigned &ShiftVal) const {
2473 Register DstReg = MI.getOperand(0).getReg();
2474 Register SrcReg = MI.getOperand(1).getReg();
2475 LLT Ty = MRI.getType(SrcReg);
2476 unsigned Size = Ty.getSizeInBits();
2477 unsigned HalfSize = Size / 2;
2478 assert(ShiftVal >= HalfSize);
2479
2480 LLT HalfTy = Ty.changeElementSize(HalfSize);
2481
2482 auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
2483 unsigned NarrowShiftAmt = ShiftVal - HalfSize;
2484
2485 if (MI.getOpcode() == TargetOpcode::G_LSHR) {
2486 Register Narrowed = Unmerge.getReg(1);
2487
2488 // dst = G_LSHR s64:x, C for C >= 32
2489 // =>
2490 // lo, hi = G_UNMERGE_VALUES x
2491 // dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
2492
2493 if (NarrowShiftAmt != 0) {
2494 Narrowed = Builder.buildLShr(HalfTy, Narrowed,
2495 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
2496 }
2497
2498 auto Zero = Builder.buildConstant(HalfTy, 0);
2499 Builder.buildMergeLikeInstr(DstReg, {Narrowed, Zero});
2500 } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
2501 Register Narrowed = Unmerge.getReg(0);
2502 // dst = G_SHL s64:x, C for C >= 32
2503 // =>
2504 // lo, hi = G_UNMERGE_VALUES x
2505 // dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
2506 if (NarrowShiftAmt != 0) {
2507 Narrowed = Builder.buildShl(HalfTy, Narrowed,
2508 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
2509 }
2510
2511 auto Zero = Builder.buildConstant(HalfTy, 0);
2512 Builder.buildMergeLikeInstr(DstReg, {Zero, Narrowed});
2513 } else {
2514 assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2515 auto Hi = Builder.buildAShr(
2516 HalfTy, Unmerge.getReg(1),
2517 Builder.buildConstant(HalfTy, HalfSize - 1));
2518
2519 if (ShiftVal == HalfSize) {
2520 // (G_ASHR i64:x, 32) ->
2521 // G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
2522 Builder.buildMergeLikeInstr(DstReg, {Unmerge.getReg(1), Hi});
2523 } else if (ShiftVal == Size - 1) {
2524 // Don't need a second shift.
2525 // (G_ASHR i64:x, 63) ->
2526 // %narrowed = (G_ASHR hi_32(x), 31)
2527 // G_MERGE_VALUES %narrowed, %narrowed
2528 Builder.buildMergeLikeInstr(DstReg, {Hi, Hi});
2529 } else {
2530 auto Lo = Builder.buildAShr(
2531 HalfTy, Unmerge.getReg(1),
2532 Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
2533
2534 // (G_ASHR i64:x, C) ->, for C >= 32
2535 // G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
2536 Builder.buildMergeLikeInstr(DstReg, {Lo, Hi});
2537 }
2538 }
2539
2540 MI.eraseFromParent();
2541}
2542
2544 MachineInstr &MI, unsigned TargetShiftAmount) const {
2545 unsigned ShiftAmt;
2546 if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
2547 applyCombineShiftToUnmerge(MI, ShiftAmt);
2548 return true;
2549 }
2550
2551 return false;
2552}
2553
2555 Register &Reg) const {
2556 assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
2557 Register DstReg = MI.getOperand(0).getReg();
2558 Register SrcReg = MI.getOperand(1).getReg();
2559 Register OriginalSrcReg = getSrcRegIgnoringCopies(SrcReg, MRI);
2560 if (OriginalSrcReg.isValid())
2561 SrcReg = OriginalSrcReg;
2562 LLT DstTy = MRI.getType(DstReg);
2563 return mi_match(SrcReg, MRI,
2564 m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy)))) &&
2565 canReplaceReg(DstReg, Reg, MRI);
2566}
2567
2569 Register &Reg) const {
2570 assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2571 Register DstReg = MI.getOperand(0).getReg();
2572 Register SrcReg = MI.getOperand(1).getReg();
2573 LLT DstTy = MRI.getType(DstReg);
2574 if (mi_match(SrcReg, MRI,
2575 m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy)))) &&
2576 canReplaceReg(DstReg, Reg, MRI)) {
2577 unsigned DstSize = DstTy.getScalarSizeInBits();
2578 unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2579 return VT->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2580 }
2581 return false;
2582}
2583
2585 const unsigned ShiftSize = ShiftTy.getScalarSizeInBits();
2586 const unsigned TruncSize = TruncTy.getScalarSizeInBits();
2587
2588 // ShiftTy > 32 > TruncTy -> 32
2589 if (ShiftSize > 32 && TruncSize < 32)
2590 return ShiftTy.changeElementSize(32);
2591
2592 // TODO: We could also reduce to 16 bits, but that's more target-dependent.
2593 // Some targets like it, some don't, some only like it under certain
2594 // conditions/processor versions, etc.
2595 // A TL hook might be needed for this.
2596
2597 // Don't combine
2598 return ShiftTy;
2599}
2600
2602 MachineInstr &MI, std::pair<MachineInstr *, LLT> &MatchInfo) const {
2603 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2604 Register DstReg = MI.getOperand(0).getReg();
2605 Register SrcReg = MI.getOperand(1).getReg();
2606
2607 if (!MRI.hasOneNonDBGUse(SrcReg))
2608 return false;
2609
2610 LLT SrcTy = MRI.getType(SrcReg);
2611 LLT DstTy = MRI.getType(DstReg);
2612
2613 MachineInstr *SrcMI = getDefIgnoringCopies(SrcReg, MRI);
2614 const auto &TL = getTargetLowering();
2615
2616 LLT NewShiftTy;
2617 switch (SrcMI->getOpcode()) {
2618 default:
2619 return false;
2620 case TargetOpcode::G_SHL: {
2621 NewShiftTy = DstTy;
2622
2623 // Make sure new shift amount is legal.
2624 KnownBits Known = VT->getKnownBits(SrcMI->getOperand(2).getReg());
2625 if (Known.getMaxValue().uge(NewShiftTy.getScalarSizeInBits()))
2626 return false;
2627 break;
2628 }
2629 case TargetOpcode::G_LSHR:
2630 case TargetOpcode::G_ASHR: {
2631 // For right shifts, we conservatively do not do the transform if the TRUNC
2632 // has any STORE users. The reason is that if we change the type of the
2633 // shift, we may break the truncstore combine.
2634 //
2635 // TODO: Fix truncstore combine to handle (trunc(lshr (trunc x), k)).
2636 for (auto &User : MRI.use_instructions(DstReg))
2637 if (User.getOpcode() == TargetOpcode::G_STORE)
2638 return false;
2639
2640 NewShiftTy = getMidVTForTruncRightShiftCombine(SrcTy, DstTy);
2641 if (NewShiftTy == SrcTy)
2642 return false;
2643
2644 // Make sure we won't lose information by truncating the high bits.
2645 KnownBits Known = VT->getKnownBits(SrcMI->getOperand(2).getReg());
2646 if (Known.getMaxValue().ugt(NewShiftTy.getScalarSizeInBits() -
2647 DstTy.getScalarSizeInBits()))
2648 return false;
2649 break;
2650 }
2651 }
2652
2654 {SrcMI->getOpcode(),
2655 {NewShiftTy, TL.getPreferredShiftAmountTy(NewShiftTy)}}))
2656 return false;
2657
2658 MatchInfo = std::make_pair(SrcMI, NewShiftTy);
2659 return true;
2660}
2661
2663 MachineInstr &MI, std::pair<MachineInstr *, LLT> &MatchInfo) const {
2664 MachineInstr *ShiftMI = MatchInfo.first;
2665 LLT NewShiftTy = MatchInfo.second;
2666
2667 Register Dst = MI.getOperand(0).getReg();
2668 LLT DstTy = MRI.getType(Dst);
2669
2670 Register ShiftAmt = ShiftMI->getOperand(2).getReg();
2671 Register ShiftSrc = ShiftMI->getOperand(1).getReg();
2672 ShiftSrc = Builder.buildTrunc(NewShiftTy, ShiftSrc).getReg(0);
2673
2674 const auto &TL = getTargetLowering();
2675 LLT PrefShiftTy = TL.getPreferredShiftAmountTy(NewShiftTy);
2676 if (MRI.getType(ShiftAmt) != PrefShiftTy)
2677 ShiftAmt = Builder.buildZExtOrTrunc(PrefShiftTy, ShiftAmt).getReg(0);
2678
2679 Register NewShift =
2680 Builder
2681 .buildInstr(ShiftMI->getOpcode(), {NewShiftTy}, {ShiftSrc, ShiftAmt})
2682 .getReg(0);
2683
2684 if (NewShiftTy == DstTy)
2685 replaceRegWith(MRI, Dst, NewShift);
2686 else
2687 Builder.buildTrunc(Dst, NewShift);
2688
2689 eraseInst(MI);
2690}
2691
2693 return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2694 return !MO.isReg() ||
2695 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2696 });
2697}
2698
2700 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
2701 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
2702 return all_of(Mask, [](int Elt) { return Elt < 0; });
2703}
2704
2706 MachineInstr &MI) const {
2707 assert((MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT ||
2708 MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT) &&
2709 "Expected an insert/extract element op");
2710 LLT VecTy = MRI.getType(MI.getOperand(1).getReg());
2711 if (VecTy.isScalableVector())
2712 return false;
2713
2714 unsigned IdxIdx =
2715 MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
2716 auto Idx = getIConstantVRegVal(MI.getOperand(IdxIdx).getReg(), MRI);
2717 if (!Idx)
2718 return false;
2719 return Idx->getZExtValue() >= VecTy.getNumElements();
2720}
2721
2722void CombinerHelper::eraseInst(MachineInstr &MI) const { MI.eraseFromParent(); }
2723
2725 const MachineOperand &MOP2) const {
2726 if (!MOP1.isReg() || !MOP2.isReg())
2727 return false;
2728 auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
2729 if (!InstAndDef1)
2730 return false;
2731 auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
2732 if (!InstAndDef2)
2733 return false;
2734 MachineInstr *I1 = InstAndDef1->MI;
2735 MachineInstr *I2 = InstAndDef2->MI;
2736
2737 // Handle a case like this:
2738 //
2739 // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
2740 //
2741 // Even though %0 and %1 are produced by the same instruction they are not
2742 // the same values.
2743 if (I1 == I2)
2744 return MOP1.getReg() == MOP2.getReg();
2745
2746 // If we have an instruction which loads or stores, we can't guarantee that
2747 // it is identical.
2748 //
2749 // For example, we may have
2750 //
2751 // %x1 = G_LOAD %addr (load N from @somewhere)
2752 // ...
2753 // call @foo
2754 // ...
2755 // %x2 = G_LOAD %addr (load N from @somewhere)
2756 // ...
2757 // %or = G_OR %x1, %x2
2758 //
2759 // It's possible that @foo will modify whatever lives at the address we're
2760 // loading from. To be safe, let's just assume that all loads and stores
2761 // are different (unless we have something which is guaranteed to not
2762 // change.)
2763 if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad())
2764 return false;
2765
2766 // If both instructions are loads or stores, they are equal only if both
2767 // are dereferenceable invariant loads with the same number of bits.
2768 if (I1->mayLoadOrStore() && I2->mayLoadOrStore()) {
2771 if (!LS1 || !LS2)
2772 return false;
2773
2774 if (!I2->isDereferenceableInvariantLoad() ||
2775 (LS1->getMemSizeInBits() != LS2->getMemSizeInBits()))
2776 return false;
2777 }
2778
2779 // Check for physical registers on the instructions first to avoid cases
2780 // like this:
2781 //
2782 // %a = COPY $physreg
2783 // ...
2784 // SOMETHING implicit-def $physreg
2785 // ...
2786 // %b = COPY $physreg
2787 //
2788 // These copies are not equivalent.
2789 if (any_of(I1->uses(), [](const MachineOperand &MO) {
2790 return MO.isReg() && MO.getReg().isPhysical();
2791 })) {
2792 // Check if we have a case like this:
2793 //
2794 // %a = COPY $physreg
2795 // %b = COPY %a
2796 //
2797 // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
2798 // From that, we know that they must have the same value, since they must
2799 // have come from the same COPY.
2800 return I1->isIdenticalTo(*I2);
2801 }
2802
2803 // We don't have any physical registers, so we don't necessarily need the
2804 // same vreg defs.
2805 //
2806 // On the off-chance that there's some target instruction feeding into the
2807 // instruction, let's use produceSameValue instead of isIdenticalTo.
2808 if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
2809 // Handle instructions with multiple defs that produce same values. Values
2810 // are same for operands with same index.
2811 // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2812 // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2813 // I1 and I2 are different instructions but produce same values,
2814 // %1 and %6 are same, %1 and %7 are not the same value.
2815 return I1->findRegisterDefOperandIdx(InstAndDef1->Reg, /*TRI=*/nullptr) ==
2816 I2->findRegisterDefOperandIdx(InstAndDef2->Reg, /*TRI=*/nullptr);
2817 }
2818 return false;
2819}
2820
2822 int64_t C) const {
2823 if (!MOP.isReg())
2824 return false;
2825 auto MaybeCst = isConstantOrConstantSplatVector(MOP.getReg(), MRI);
2826 // Compare as APInt so constants wider than 64 bits (e.g. i128 2) still match.
2827 return MaybeCst &&
2828 APInt::isSameValue(*MaybeCst, APInt(64, C, /*isSigned=*/true),
2829 /*SignedCompare=*/true);
2830}
2831
2833 double C) const {
2834 if (!MOP.isReg())
2835 return false;
2836 std::optional<FPValueAndVReg> MaybeCst;
2837 if (!mi_match(MOP.getReg(), MRI, m_GFCstOrSplat(MaybeCst)))
2838 return false;
2839
2840 return MaybeCst->Value.isExactlyValue(C);
2841}
2842
2844 unsigned OpIdx) const {
2845 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2846 Register OldReg = MI.getOperand(0).getReg();
2847 Register Replacement = MI.getOperand(OpIdx).getReg();
2848 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2849 replaceRegWith(MRI, OldReg, Replacement);
2850 MI.eraseFromParent();
2851}
2852
2854 Register Replacement) const {
2855 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2856 Register OldReg = MI.getOperand(0).getReg();
2857 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2858 replaceRegWith(MRI, OldReg, Replacement);
2859 MI.eraseFromParent();
2860}
2861
2863 unsigned ConstIdx) const {
2864 Register ConstReg = MI.getOperand(ConstIdx).getReg();
2865 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2866
2867 // Get the shift amount
2868 auto VRegAndVal = getIConstantVRegValWithLookThrough(ConstReg, MRI);
2869 if (!VRegAndVal)
2870 return false;
2871
2872 // Return true of shift amount >= Bitwidth
2873 return (VRegAndVal->Value.uge(DstTy.getSizeInBits()));
2874}
2875
2877 assert((MI.getOpcode() == TargetOpcode::G_FSHL ||
2878 MI.getOpcode() == TargetOpcode::G_FSHR) &&
2879 "This is not a funnel shift operation");
2880
2881 Register ConstReg = MI.getOperand(3).getReg();
2882 LLT ConstTy = MRI.getType(ConstReg);
2883 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2884
2885 auto VRegAndVal = getIConstantVRegValWithLookThrough(ConstReg, MRI);
2886 assert((VRegAndVal) && "Value is not a constant");
2887
2888 // Calculate the new Shift Amount = Old Shift Amount % BitWidth
2889 APInt NewConst = VRegAndVal->Value.urem(
2890 APInt(ConstTy.getSizeInBits(), DstTy.getScalarSizeInBits()));
2891
2892 auto NewConstInstr = Builder.buildConstant(ConstTy, NewConst.getZExtValue());
2893 Builder.buildInstr(
2894 MI.getOpcode(), {MI.getOperand(0)},
2895 {MI.getOperand(1), MI.getOperand(2), NewConstInstr.getReg(0)});
2896
2897 MI.eraseFromParent();
2898}
2899
2901 assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2902 // Match (cond ? x : x)
2903 return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
2904 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
2905 MRI);
2906}
2907
2909 const MachineOperand &MO, bool OrNegative, bool OrZero) const {
2910 return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, VT, OrNegative, OrZero);
2911}
2912
2914 double C) const {
2915 assert(MI.getNumDefs() == 1 && "Expected only one def?");
2916 Builder.buildFConstant(MI.getOperand(0), C);
2917 MI.eraseFromParent();
2918}
2919
2921 int64_t C) const {
2922 assert(MI.getNumDefs() == 1 && "Expected only one def?");
2923 Builder.buildConstant(MI.getOperand(0), C);
2924 MI.eraseFromParent();
2925}
2926
2928 assert(MI.getNumDefs() == 1 && "Expected only one def?");
2929 Builder.buildConstant(MI.getOperand(0), C);
2930 MI.eraseFromParent();
2931}
2932
2934 ConstantFP *CFP) const {
2935 assert(MI.getNumDefs() == 1 && "Expected only one def?");
2936 Builder.buildFConstant(MI.getOperand(0), CFP->getValueAPF());
2937 MI.eraseFromParent();
2938}
2939
2941 assert(MI.getNumDefs() == 1 && "Expected only one def?");
2942 Builder.buildUndef(MI.getOperand(0));
2943 MI.eraseFromParent();
2944}
2945
2947 MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) const {
2948 assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2949 "Invalid opcode");
2950 Register DstReg = MI.getOperand(0).getReg();
2951 LLT DstTy = MRI.getType(DstReg);
2952 assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2953
2954 if (DstTy.isScalableVector())
2955 return false;
2956
2957 unsigned NumElts = DstTy.getNumElements();
2958 // If this MI is part of a sequence of insert_vec_elts, then
2959 // don't do the combine in the middle of the sequence.
2960 if (MRI.hasOneNonDBGUse(DstReg) &&
2961 MRI.use_nodbg_instructions(DstReg).begin()->getOpcode() ==
2962 TargetOpcode::G_INSERT_VECTOR_ELT)
2963 return false;
2964 MachineInstr *CurrInst = &MI;
2965 MachineInstr *TmpInst;
2966 int64_t IntImm;
2967 Register TmpReg;
2968 MatchInfo.resize(NumElts);
2969 while (mi_match(
2970 *CurrInst, MRI,
2971 m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2972 if (IntImm >= NumElts || IntImm < 0)
2973 return false;
2974 if (!MatchInfo[IntImm])
2975 MatchInfo[IntImm] = TmpReg;
2976 CurrInst = TmpInst;
2977 }
2978 // Variable index.
2979 if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2980 return false;
2981 if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2982 for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2983 if (!MatchInfo[I - 1].isValid())
2984 MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2985 }
2986 return true;
2987 }
2988 // If we didn't end in a G_IMPLICIT_DEF and the source is not fully
2989 // overwritten, bail out.
2990 return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF ||
2991 all_of(MatchInfo, [](Register Reg) { return !!Reg; });
2992}
2993
2995 MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) const {
2996 Register UndefReg;
2997 auto GetUndef = [&]() {
2998 if (UndefReg)
2999 return UndefReg;
3000 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3001 UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
3002 return UndefReg;
3003 };
3004 for (Register &Reg : MatchInfo) {
3005 if (!Reg)
3006 Reg = GetUndef();
3007 }
3008 Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
3009 MI.eraseFromParent();
3010}
3011
3012bool CombinerHelper::matchBinopWithNegInner(Register MInner, Register Other,
3013 unsigned RootOpc, Register Dst,
3014 LLT Ty,
3015 BuildFnTy &MatchInfo) const {
3016 /// Helper function for matchBinopWithNeg: tries to match one commuted form
3017 /// of `a bitwiseop (~b +/- c)` -> `a bitwiseop ~(b -/+ c)`.
3018 MachineInstr *InnerDef;
3019 if (!mi_match(MInner, MRI, m_MInstr(InnerDef)))
3020 return false;
3021
3022 unsigned InnerOpc = InnerDef->getOpcode();
3023 if (InnerOpc != TargetOpcode::G_ADD && InnerOpc != TargetOpcode::G_SUB)
3024 return false;
3025
3026 if (!MRI.hasOneNonDBGUse(MInner))
3027 return false;
3028
3029 Register InnerLHS = InnerDef->getOperand(1).getReg();
3030 Register InnerRHS = InnerDef->getOperand(2).getReg();
3031 Register NotSrc;
3032 Register B, C;
3033
3034 // Check if either operand is ~b
3035 auto TryMatch = [&](Register MaybeNot, Register Other) {
3036 if (mi_match(MaybeNot, MRI, m_Not(m_Reg(NotSrc)))) {
3037 if (!MRI.hasOneNonDBGUse(MaybeNot))
3038 return false;
3039 B = NotSrc;
3040 C = Other;
3041 return true;
3042 }
3043 return false;
3044 };
3045
3046 // For SUB, the not must be the LHS. For ADD, it can be either operand.
3047 if (!TryMatch(InnerLHS, InnerRHS) &&
3048 !(InnerOpc == TargetOpcode::G_ADD && TryMatch(InnerRHS, InnerLHS)))
3049 return false;
3050
3051 // Flip add/sub
3052 unsigned FlippedOpc = (InnerOpc == TargetOpcode::G_ADD) ? TargetOpcode::G_SUB
3053 : TargetOpcode::G_ADD;
3054
3055 Register A = Other;
3056 MatchInfo = [=](MachineIRBuilder &Builder) {
3057 auto NewInner = Builder.buildInstr(FlippedOpc, {Ty}, {B, C});
3058 auto NewNot = Builder.buildNot(Ty, NewInner);
3059 Builder.buildInstr(RootOpc, {Dst}, {A, NewNot});
3060 };
3061 return true;
3062}
3063
3065 BuildFnTy &MatchInfo) const {
3066 // Fold `a bitwiseop (~b +/- c)` -> `a bitwiseop ~(b -/+ c)`
3067 // Root MI is one of G_AND, G_OR, G_XOR.
3068 // We also look for commuted forms of operations. Pattern shouldn't apply
3069 // if there are multiple reasons of inner operations.
3070
3071 unsigned RootOpc = MI.getOpcode();
3072 Register Dst = MI.getOperand(0).getReg();
3073 LLT Ty = MRI.getType(Dst);
3074
3075 Register LHS = MI.getOperand(1).getReg();
3076 Register RHS = MI.getOperand(2).getReg();
3077 // Check the commuted and uncommuted forms of the operation.
3078 return matchBinopWithNegInner(LHS, RHS, RootOpc, Dst, Ty, MatchInfo) ||
3079 matchBinopWithNegInner(RHS, LHS, RootOpc, Dst, Ty, MatchInfo);
3080}
3081
3083 MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) const {
3084 // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
3085 //
3086 // Creates the new hand + logic instruction (but does not insert them.)
3087 //
3088 // On success, MatchInfo is populated with the new instructions. These are
3089 // inserted in applyHoistLogicOpWithSameOpcodeHands.
3090 unsigned LogicOpcode = MI.getOpcode();
3091 assert(LogicOpcode == TargetOpcode::G_AND ||
3092 LogicOpcode == TargetOpcode::G_OR ||
3093 LogicOpcode == TargetOpcode::G_XOR);
3094 Register Dst = MI.getOperand(0).getReg();
3095 Register LHSReg = MI.getOperand(1).getReg();
3096 Register RHSReg = MI.getOperand(2).getReg();
3097
3098 // Don't recompute anything.
3099 if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
3100 return false;
3101
3102 // Make sure we have (hand x, ...), (hand y, ...)
3103 MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
3104 MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
3105 if (!LeftHandInst || !RightHandInst)
3106 return false;
3107 unsigned HandOpcode = LeftHandInst->getOpcode();
3108 if (HandOpcode != RightHandInst->getOpcode())
3109 return false;
3110 if (LeftHandInst->getNumOperands() < 2 ||
3111 !LeftHandInst->getOperand(1).isReg() ||
3112 RightHandInst->getNumOperands() < 2 ||
3113 !RightHandInst->getOperand(1).isReg())
3114 return false;
3115
3116 // Make sure the types match up, and if we're doing this post-legalization,
3117 // we end up with legal types.
3118 Register X = LeftHandInst->getOperand(1).getReg();
3119 Register Y = RightHandInst->getOperand(1).getReg();
3120 LLT XTy = MRI.getType(X);
3121 LLT YTy = MRI.getType(Y);
3122 if (!XTy.isValid() || XTy != YTy)
3123 return false;
3124
3125 // Optional extra source register.
3126 Register ExtraHandOpSrcReg;
3127 switch (HandOpcode) {
3128 default:
3129 return false;
3130 case TargetOpcode::G_ANYEXT:
3131 case TargetOpcode::G_SEXT:
3132 case TargetOpcode::G_ZEXT: {
3133 // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
3134 break;
3135 }
3136 case TargetOpcode::G_TRUNC: {
3137 // Match: logic (trunc X), (trunc Y) -> trunc (logic X, Y)
3138 const MachineFunction *MF = MI.getMF();
3139 LLVMContext &Ctx = MF->getFunction().getContext();
3140
3141 LLT DstTy = MRI.getType(Dst);
3143
3144 // Be extra careful sinking truncate. If it's free, there's no benefit in
3145 // widening a binop.
3146 if (TLI.isZExtFree(DstTy, XTy, Ctx) && TLI.isTruncateFree(XTy, DstTy, Ctx))
3147 return false;
3148 break;
3149 }
3150 case TargetOpcode::G_AND:
3151 case TargetOpcode::G_ASHR:
3152 case TargetOpcode::G_LSHR:
3153 case TargetOpcode::G_SHL: {
3154 // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
3155 MachineOperand &ZOp = LeftHandInst->getOperand(2);
3156 if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
3157 return false;
3158 ExtraHandOpSrcReg = ZOp.getReg();
3159 break;
3160 }
3161 }
3162
3163 if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
3164 return false;
3165
3166 // Record the steps to build the new instructions.
3167 //
3168 // Steps to build (logic x, y)
3169 auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
3170 OperandBuildSteps LogicBuildSteps = {
3171 [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
3172 [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
3173 [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
3174 InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
3175
3176 // Steps to build hand (logic x, y), ...z
3177 OperandBuildSteps HandBuildSteps = {
3178 [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
3179 [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
3180 if (ExtraHandOpSrcReg.isValid())
3181 HandBuildSteps.push_back(
3182 [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
3183 InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
3184
3185 MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
3186 return true;
3187}
3188
3190 MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) const {
3191 assert(MatchInfo.InstrsToBuild.size() &&
3192 "Expected at least one instr to build?");
3193 for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
3194 assert(InstrToBuild.Opcode && "Expected a valid opcode?");
3195 assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
3196 MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
3197 for (auto &OperandFn : InstrToBuild.OperandFns)
3198 OperandFn(Instr);
3199 }
3200 MI.eraseFromParent();
3201}
3202
3204 MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) const {
3205 assert(MI.getOpcode() == TargetOpcode::G_ASHR);
3206 int64_t ShlCst, AshrCst;
3207 Register Src;
3208 if (!mi_match(MI.getOperand(0).getReg(), MRI,
3209 m_GAShr(m_GShl(m_Reg(Src), m_ICstOrSplat(ShlCst)),
3210 m_ICstOrSplat(AshrCst))))
3211 return false;
3212 if (ShlCst != AshrCst)
3213 return false;
3215 {TargetOpcode::G_SEXT_INREG,
3216 {MRI.getType(Src)},
3217 {},
3218 {MRI.getType(Src).getScalarSizeInBits() - ShlCst}}))
3219 return false;
3220 MatchInfo = std::make_tuple(Src, ShlCst);
3221 return true;
3222}
3223
3225 MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) const {
3226 assert(MI.getOpcode() == TargetOpcode::G_ASHR);
3227 Register Src;
3228 int64_t ShiftAmt;
3229 std::tie(Src, ShiftAmt) = MatchInfo;
3230 unsigned Size = MRI.getType(Src).getScalarSizeInBits();
3231 Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
3232 MI.eraseFromParent();
3233}
3234
3235/// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
3238 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
3239 assert(MI.getOpcode() == TargetOpcode::G_AND);
3240
3241 Register Dst = MI.getOperand(0).getReg();
3242 LLT Ty = MRI.getType(Dst);
3243
3244 Register R;
3245 int64_t C1;
3246 int64_t C2;
3247 if (!mi_match(
3248 Dst, MRI,
3249 m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
3250 return false;
3251
3252 MatchInfo = [=](MachineIRBuilder &B) {
3253 if (C1 & C2) {
3254 B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
3255 return;
3256 }
3257 auto Zero = B.buildConstant(Ty, 0);
3258 replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
3259 };
3260 return true;
3261}
3262
3264 Register &Replacement) const {
3265 // Given
3266 //
3267 // %y:_(sN) = G_SOMETHING
3268 // %x:_(sN) = G_SOMETHING
3269 // %res:_(sN) = G_AND %x, %y
3270 //
3271 // Eliminate the G_AND when it is known that x & y == x or x & y == y.
3272 //
3273 // Patterns like this can appear as a result of legalization. E.g.
3274 //
3275 // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
3276 // %one:_(s32) = G_CONSTANT i32 1
3277 // %and:_(s32) = G_AND %cmp, %one
3278 //
3279 // In this case, G_ICMP only produces a single bit, so x & 1 == x.
3280 assert(MI.getOpcode() == TargetOpcode::G_AND);
3281 if (!VT)
3282 return false;
3283
3284 Register AndDst = MI.getOperand(0).getReg();
3285 Register LHS = MI.getOperand(1).getReg();
3286 Register RHS = MI.getOperand(2).getReg();
3287
3288 // Check the RHS (maybe a constant) first, and if we have no KnownBits there,
3289 // we can't do anything. If we do, then it depends on whether we have
3290 // KnownBits on the LHS.
3291 KnownBits RHSBits = VT->getKnownBits(RHS);
3292 if (RHSBits.isUnknown())
3293 return false;
3294
3295 KnownBits LHSBits = VT->getKnownBits(LHS);
3296
3297 // Check that x & Mask == x.
3298 // x & 1 == x, always
3299 // x & 0 == x, only if x is also 0
3300 // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
3301 //
3302 // Check if we can replace AndDst with the LHS of the G_AND
3303 if (canReplaceReg(AndDst, LHS, MRI) &&
3304 (LHSBits.Zero | RHSBits.One).isAllOnes()) {
3305 Replacement = LHS;
3306 return true;
3307 }
3308
3309 // Check if we can replace AndDst with the RHS of the G_AND
3310 if (canReplaceReg(AndDst, RHS, MRI) &&
3311 (LHSBits.One | RHSBits.Zero).isAllOnes()) {
3312 Replacement = RHS;
3313 return true;
3314 }
3315
3316 return false;
3317}
3318
3320 Register &Replacement) const {
3321 // Given
3322 //
3323 // %y:_(sN) = G_SOMETHING
3324 // %x:_(sN) = G_SOMETHING
3325 // %res:_(sN) = G_OR %x, %y
3326 //
3327 // Eliminate the G_OR when it is known that x | y == x or x | y == y.
3328 assert(MI.getOpcode() == TargetOpcode::G_OR);
3329 if (!VT)
3330 return false;
3331
3332 Register OrDst = MI.getOperand(0).getReg();
3333 Register LHS = MI.getOperand(1).getReg();
3334 Register RHS = MI.getOperand(2).getReg();
3335
3336 KnownBits LHSBits = VT->getKnownBits(LHS);
3337 KnownBits RHSBits = VT->getKnownBits(RHS);
3338
3339 // Check that x | Mask == x.
3340 // x | 0 == x, always
3341 // x | 1 == x, only if x is also 1
3342 // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
3343 //
3344 // Check if we can replace OrDst with the LHS of the G_OR
3345 if (canReplaceReg(OrDst, LHS, MRI) &&
3346 (LHSBits.One | RHSBits.Zero).isAllOnes()) {
3347 Replacement = LHS;
3348 return true;
3349 }
3350
3351 // Check if we can replace OrDst with the RHS of the G_OR
3352 if (canReplaceReg(OrDst, RHS, MRI) &&
3353 (LHSBits.Zero | RHSBits.One).isAllOnes()) {
3354 Replacement = RHS;
3355 return true;
3356 }
3357
3358 return false;
3359}
3360
3362 // If the input is already sign extended, just drop the extension.
3363 Register Src = MI.getOperand(1).getReg();
3364 unsigned ExtBits = MI.getOperand(2).getImm();
3365 unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
3366 return VT->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
3367}
3368
3369static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
3370 int64_t Cst, bool IsVector) {
3371 // For i1, Cst will always be -1 regardless of boolean contents.
3372 return (ScalarSizeBits == 1 && Cst == -1) ||
3373 isConstTrueVal(TLI, Cst, IsVector);
3374}
3375
3376// This pattern aims to match the following shape to avoid extra mov
3377// instructions
3378// G_BUILD_VECTOR(
3379// G_UNMERGE_VALUES(src, 0)
3380// G_UNMERGE_VALUES(src, 1)
3381// G_IMPLICIT_DEF
3382// G_IMPLICIT_DEF
3383// )
3384// ->
3385// G_CONCAT_VECTORS(
3386// src,
3387// undef
3388// )
3391 Register &UnmergeSrc) const {
3392 auto &BV = cast<GBuildVector>(MI);
3393
3394 unsigned BuildUseCount = BV.getNumSources();
3395 if (BuildUseCount % 2 != 0)
3396 return false;
3397
3398 unsigned NumUnmerge = BuildUseCount / 2;
3399
3400 auto *Unmerge = getOpcodeDef<GUnmerge>(BV.getSourceReg(0), MRI);
3401
3402 // Check the first operand is an unmerge and has the correct number of
3403 // operands
3404 if (!Unmerge || Unmerge->getNumDefs() != NumUnmerge)
3405 return false;
3406
3407 UnmergeSrc = Unmerge->getSourceReg();
3408
3409 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3410 LLT UnmergeSrcTy = MRI.getType(UnmergeSrc);
3411
3412 if (!UnmergeSrcTy.isVector())
3413 return false;
3414
3415 // Ensure we only generate legal instructions post-legalizer
3416 if (!IsPreLegalize &&
3417 !isLegal({TargetOpcode::G_CONCAT_VECTORS, {DstTy, UnmergeSrcTy}}))
3418 return false;
3419
3420 // Check that all of the operands before the midpoint come from the same
3421 // unmerge and are in the same order as they are used in the build_vector
3422 for (unsigned I = 0; I < NumUnmerge; ++I) {
3423 auto MaybeUnmergeReg = BV.getSourceReg(I);
3424 auto *LoopUnmerge = getOpcodeDef<GUnmerge>(MaybeUnmergeReg, MRI);
3425
3426 if (!LoopUnmerge || LoopUnmerge != Unmerge)
3427 return false;
3428
3429 if (LoopUnmerge->getOperand(I).getReg() != MaybeUnmergeReg)
3430 return false;
3431 }
3432
3433 // Check that all of the unmerged values are used
3434 if (Unmerge->getNumDefs() != NumUnmerge)
3435 return false;
3436
3437 // Check that all of the operands after the mid point are undefs.
3438 for (unsigned I = NumUnmerge; I < BuildUseCount; ++I) {
3439 auto *Undef = getDefIgnoringCopies(BV.getSourceReg(I), MRI);
3440
3441 if (Undef->getOpcode() != TargetOpcode::G_IMPLICIT_DEF)
3442 return false;
3443 }
3444
3445 return true;
3446}
3447
3451 Register &UnmergeSrc) const {
3452 assert(UnmergeSrc && "Expected there to be one matching G_UNMERGE_VALUES");
3453 B.setInstrAndDebugLoc(MI);
3454
3455 Register UndefVec = B.buildUndef(MRI.getType(UnmergeSrc)).getReg(0);
3456 B.buildConcatVectors(MI.getOperand(0), {UnmergeSrc, UndefVec});
3457
3458 MI.eraseFromParent();
3459}
3460
3461// This combine tries to reduce the number of scalarised G_TRUNC instructions by
3462// using vector truncates instead
3463//
3464// EXAMPLE:
3465// %a(i32), %b(i32) = G_UNMERGE_VALUES %src(<2 x i32>)
3466// %T_a(i16) = G_TRUNC %a(i32)
3467// %T_b(i16) = G_TRUNC %b(i32)
3468// %Undef(i16) = G_IMPLICIT_DEF(i16)
3469// %dst(v4i16) = G_BUILD_VECTORS %T_a(i16), %T_b(i16), %Undef(i16), %Undef(i16)
3470//
3471// ===>
3472// %Undef(<2 x i32>) = G_IMPLICIT_DEF(<2 x i32>)
3473// %Mid(<4 x s32>) = G_CONCAT_VECTORS %src(<2 x i32>), %Undef(<2 x i32>)
3474// %dst(<4 x s16>) = G_TRUNC %Mid(<4 x s32>)
3475//
3476// Only matches sources made up of G_TRUNCs followed by G_IMPLICIT_DEFs
3478 Register &MatchInfo) const {
3479 auto BuildMI = cast<GBuildVector>(&MI);
3480 unsigned NumOperands = BuildMI->getNumSources();
3481 LLT DstTy = MRI.getType(BuildMI->getReg(0));
3482
3483 // Check the G_BUILD_VECTOR sources
3484 unsigned I;
3485 GUnmerge *UnmergeMI = nullptr;
3486
3487 // Check all source TRUNCs come from the same UNMERGE instruction
3488 // and that the element order matches (BUILD_VECTOR position I
3489 // corresponds to UNMERGE result I)
3490 for (I = 0; I < NumOperands; ++I) {
3491 // Check if the G_TRUNC instructions all come from the same MI
3492 Register TruncSrcReg;
3493 if (!mi_match(BuildMI->getSourceReg(I), MRI, m_GTrunc(m_Reg(TruncSrcReg))))
3494 break;
3495
3496 if (!UnmergeMI) {
3497 if (!mi_match(TruncSrcReg, MRI, m_GUnmerge(UnmergeMI)))
3498 return false;
3499 } else {
3500 MachineInstr *UnmergeSrcMI;
3501 if (!mi_match(TruncSrcReg, MRI, m_MInstr(UnmergeSrcMI)) ||
3502 UnmergeMI != UnmergeSrcMI)
3503 return false;
3504 }
3505 // Element order must match: position I must use UNMERGE result I.
3506 if (UnmergeMI->getOperand(I).getReg() != TruncSrcReg)
3507 return false;
3508 }
3509 if (I < 2)
3510 return false;
3511
3512 // Check the remaining source elements are only G_IMPLICIT_DEF
3513 for (; I < NumOperands; ++I) {
3514 if (!mi_match(BuildMI->getSourceReg(I), MRI, m_GImplicitDef()))
3515 return false;
3516 }
3517
3518 // Check the size of unmerge source
3519 MatchInfo = UnmergeMI->getSourceReg();
3520 LLT UnmergeSrcTy = MRI.getType(MatchInfo);
3521 if (!UnmergeSrcTy.isVector())
3522 return false;
3523
3524 if (!DstTy.getElementCount().isKnownMultipleOf(UnmergeSrcTy.getNumElements()))
3525 return false;
3526
3527 // Check the unmerge source and destination element types match
3528 LLT UnmergeSrcEltTy = UnmergeSrcTy.getElementType();
3529 Register UnmergeDstReg = UnmergeMI->getOperand(0).getReg();
3530 LLT UnmergeDstEltTy = MRI.getType(UnmergeDstReg);
3531 if (UnmergeSrcEltTy != UnmergeDstEltTy)
3532 return false;
3533
3534 // Only generate legal instructions post-legalizer
3535 if (!IsPreLegalize) {
3536 LLT MidTy = DstTy.changeElementType(UnmergeSrcTy.getScalarType());
3537
3538 if (DstTy.getElementCount() != UnmergeSrcTy.getElementCount() &&
3539 !isLegal({TargetOpcode::G_CONCAT_VECTORS, {MidTy, UnmergeSrcTy}}))
3540 return false;
3541
3542 if (!isLegal({TargetOpcode::G_TRUNC, {DstTy, MidTy}}))
3543 return false;
3544 }
3545
3546 return true;
3547}
3548
3550 Register &MatchInfo) const {
3551 Register MidReg;
3552 auto BuildMI = cast<GBuildVector>(&MI);
3553 Register DstReg = BuildMI->getReg(0);
3554 LLT DstTy = MRI.getType(DstReg);
3555 LLT UnmergeSrcTy = MRI.getType(MatchInfo);
3556 unsigned DstTyNumElt = DstTy.getNumElements();
3557 unsigned UnmergeSrcTyNumElt = UnmergeSrcTy.getNumElements();
3558
3559 // No need to pad vector if only G_TRUNC is needed
3560 if (DstTyNumElt / UnmergeSrcTyNumElt == 1) {
3561 MidReg = MatchInfo;
3562 } else {
3563 Register UndefReg = Builder.buildUndef(UnmergeSrcTy).getReg(0);
3564 SmallVector<Register> ConcatRegs = {MatchInfo};
3565 for (unsigned I = 1; I < DstTyNumElt / UnmergeSrcTyNumElt; ++I)
3566 ConcatRegs.push_back(UndefReg);
3567
3568 auto MidTy = DstTy.changeElementType(UnmergeSrcTy.getScalarType());
3569 MidReg = Builder.buildConcatVectors(MidTy, ConcatRegs).getReg(0);
3570 }
3571
3572 Builder.buildTrunc(DstReg, MidReg);
3573 MI.eraseFromParent();
3574}
3575
3577 MachineInstr &MI, SmallVectorImpl<Register> &RegsToNegate) const {
3578 assert(MI.getOpcode() == TargetOpcode::G_XOR);
3579 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3580 const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
3581 Register XorSrc;
3582 Register CstReg;
3583 // We match xor(src, true) here.
3584 if (!mi_match(MI.getOperand(0).getReg(), MRI,
3585 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
3586 return false;
3587
3588 if (!MRI.hasOneNonDBGUse(XorSrc))
3589 return false;
3590
3591 // Check that XorSrc is the root of a tree of comparisons combined with ANDs
3592 // and ORs. The suffix of RegsToNegate starting from index I is used a work
3593 // list of tree nodes to visit.
3594 RegsToNegate.push_back(XorSrc);
3595 // Remember whether the comparisons are all integer or all floating point.
3596 bool IsInt = false;
3597 bool IsFP = false;
3598 for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
3599 Register Reg = RegsToNegate[I];
3600 if (!MRI.hasOneNonDBGUse(Reg))
3601 return false;
3602 MachineInstr *Def;
3603 if (!mi_match(Reg, MRI, m_MInstr(Def)))
3604 return false;
3605 switch (Def->getOpcode()) {
3606 default:
3607 // Don't match if the tree contains anything other than ANDs, ORs and
3608 // comparisons.
3609 return false;
3610 case TargetOpcode::G_ICMP:
3611 if (IsFP)
3612 return false;
3613 IsInt = true;
3614 // When we apply the combine we will invert the predicate.
3615 break;
3616 case TargetOpcode::G_FCMP:
3617 if (IsInt)
3618 return false;
3619 IsFP = true;
3620 // When we apply the combine we will invert the predicate.
3621 break;
3622 case TargetOpcode::G_AND:
3623 case TargetOpcode::G_OR:
3624 // Implement De Morgan's laws:
3625 // ~(x & y) -> ~x | ~y
3626 // ~(x | y) -> ~x & ~y
3627 // When we apply the combine we will change the opcode and recursively
3628 // negate the operands.
3629 RegsToNegate.push_back(Def->getOperand(1).getReg());
3630 RegsToNegate.push_back(Def->getOperand(2).getReg());
3631 break;
3632 }
3633 }
3634
3635 // Now we know whether the comparisons are integer or floating point, check
3636 // the constant in the xor.
3637 int64_t Cst;
3638 if (Ty.isVector()) {
3639 int64_t SplatCst;
3640 if (!mi_match(CstReg, MRI, m_ICstOrSplat(SplatCst)))
3641 return false;
3642 if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), SplatCst, true))
3643 return false;
3644 } else {
3645 if (!mi_match(CstReg, MRI, m_ICst(Cst)))
3646 return false;
3647 if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false))
3648 return false;
3649 }
3650
3651 return true;
3652}
3653
3655 MachineInstr &MI, SmallVectorImpl<Register> &RegsToNegate) const {
3656 for (Register Reg : RegsToNegate) {
3657 MachineInstr *Def = MRI.getVRegDef(Reg);
3658 Observer.changingInstr(*Def);
3659 // For each comparison, invert the opcode. For each AND and OR, change the
3660 // opcode.
3661 switch (Def->getOpcode()) {
3662 default:
3663 llvm_unreachable("Unexpected opcode");
3664 case TargetOpcode::G_ICMP:
3665 case TargetOpcode::G_FCMP: {
3666 MachineOperand &PredOp = Def->getOperand(1);
3669 PredOp.setPredicate(NewP);
3670 break;
3671 }
3672 case TargetOpcode::G_AND:
3673 Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
3674 break;
3675 case TargetOpcode::G_OR:
3676 Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3677 break;
3678 }
3679 Observer.changedInstr(*Def);
3680 }
3681
3682 replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
3683 MI.eraseFromParent();
3684}
3685
3687 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) const {
3688 // Match (xor (and x, y), y) (or any of its commuted cases)
3689 assert(MI.getOpcode() == TargetOpcode::G_XOR);
3690 Register &X = MatchInfo.first;
3691 Register &Y = MatchInfo.second;
3692 Register AndReg = MI.getOperand(1).getReg();
3693 Register SharedReg = MI.getOperand(2).getReg();
3694
3695 // Find a G_AND on either side of the G_XOR.
3696 // Look for one of
3697 //
3698 // (xor (and x, y), SharedReg)
3699 // (xor SharedReg, (and x, y))
3700 if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3701 std::swap(AndReg, SharedReg);
3702 if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3703 return false;
3704 }
3705
3706 // Only do this if we'll eliminate the G_AND.
3707 if (!MRI.hasOneNonDBGUse(AndReg))
3708 return false;
3709
3710 // We can combine if SharedReg is the same as either the LHS or RHS of the
3711 // G_AND.
3712 if (Y != SharedReg)
3713 std::swap(X, Y);
3714 return Y == SharedReg;
3715}
3716
3718 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) const {
3719 // Fold (xor (and x, y), y) -> (and (not x), y)
3720 Register X, Y;
3721 std::tie(X, Y) = MatchInfo;
3722 auto Not = Builder.buildNot(MRI.getType(X), X);
3723 Observer.changingInstr(MI);
3724 MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3725 MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3726 MI.getOperand(2).setReg(Y);
3727 Observer.changedInstr(MI);
3728}
3729
3731 auto &PtrAdd = cast<GPtrAdd>(MI);
3732 Register DstReg = PtrAdd.getReg(0);
3733 LLT Ty = MRI.getType(DstReg);
3734 const DataLayout &DL = Builder.getMF().getDataLayout();
3735
3736 if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3737 return false;
3738
3739 if (!Ty.isVector())
3740 return false;
3741 const MachineInstr *VecMI;
3742 if (!mi_match(PtrAdd.getBaseReg(), MRI, m_MInstr(VecMI)))
3743 return false;
3744 return isBuildVectorAllZeros(*VecMI, MRI);
3745}
3746
3747/// The second source operand is known to be a power of 2.
3749 Register DstReg = MI.getOperand(0).getReg();
3750 Register Src0 = MI.getOperand(1).getReg();
3751 Register Pow2Src1 = MI.getOperand(2).getReg();
3752 LLT Ty = MRI.getType(DstReg);
3753
3754 // Fold (urem x, pow2) -> (and x, pow2-1)
3755 auto NegOne = Builder.buildConstant(Ty, -1);
3756 auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3757 Builder.buildAnd(DstReg, Src0, Add);
3758 MI.eraseFromParent();
3759}
3760
3762 unsigned &SelectOpNo) const {
3763 Register LHS = MI.getOperand(1).getReg();
3764 Register RHS = MI.getOperand(2).getReg();
3765
3766 Register OtherOperandReg = RHS;
3767 SelectOpNo = 1;
3768 Register SelectTrue, SelectFalse;
3769
3770 // Don't do this unless the old select is going away. We want to eliminate the
3771 // binary operator, not replace a binop with a select.
3772 if (!mi_match(LHS, MRI,
3773 m_GISelect(m_Reg(), m_Reg(SelectTrue), m_Reg(SelectFalse))) ||
3774 !MRI.hasOneNonDBGUse(LHS)) {
3775 OtherOperandReg = LHS;
3776 SelectOpNo = 2;
3777 if (!mi_match(RHS, MRI,
3778 m_GISelect(m_Reg(), m_Reg(SelectTrue), m_Reg(SelectFalse))) ||
3779 !MRI.hasOneNonDBGUse(RHS))
3780 return false;
3781 }
3782
3783 MachineInstr *SelectLHS, *SelectRHS;
3784 if (!mi_match(SelectTrue, MRI, m_MInstr(SelectLHS)) ||
3785 !mi_match(SelectFalse, MRI, m_MInstr(SelectRHS)))
3786 return false;
3787
3788 if (!isConstantOrConstantVector(*SelectLHS, MRI,
3789 /*AllowFP*/ true,
3790 /*AllowOpaqueConstants*/ false))
3791 return false;
3792 if (!isConstantOrConstantVector(*SelectRHS, MRI,
3793 /*AllowFP*/ true,
3794 /*AllowOpaqueConstants*/ false))
3795 return false;
3796
3797 unsigned BinOpcode = MI.getOpcode();
3798
3799 // We know that one of the operands is a select of constants. Now verify that
3800 // the other binary operator operand is either a constant, or we can handle a
3801 // variable.
3802 bool CanFoldNonConst =
3803 (BinOpcode == TargetOpcode::G_AND || BinOpcode == TargetOpcode::G_OR) &&
3804 (isNullOrNullSplat(*SelectLHS, MRI) ||
3805 isAllOnesOrAllOnesSplat(*SelectLHS, MRI)) &&
3806 (isNullOrNullSplat(*SelectRHS, MRI) ||
3807 isAllOnesOrAllOnesSplat(*SelectRHS, MRI));
3808 if (CanFoldNonConst)
3809 return true;
3810
3811 MachineInstr *OtherOperandDef;
3812 if (!mi_match(OtherOperandReg, MRI, m_MInstr(OtherOperandDef)))
3813 return false;
3814 return isConstantOrConstantVector(*OtherOperandDef, MRI,
3815 /*AllowFP*/ true,
3816 /*AllowOpaqueConstants*/ false);
3817}
3818
3819/// \p SelectOperand is the operand in binary operator \p MI that is the select
3820/// to fold.
3822 MachineInstr &MI, const unsigned &SelectOperand) const {
3823 Register Dst = MI.getOperand(0).getReg();
3824 Register LHS = MI.getOperand(1).getReg();
3825 Register RHS = MI.getOperand(2).getReg();
3826 GSelect *Select =
3827 cast<GSelect>(MRI.getVRegDef(MI.getOperand(SelectOperand).getReg()));
3828
3829 Register SelectCond = Select->getCondReg();
3830 Register SelectTrue = Select->getTrueReg();
3831 Register SelectFalse = Select->getFalseReg();
3832
3833 LLT Ty = MRI.getType(Dst);
3834 unsigned BinOpcode = MI.getOpcode();
3835
3836 Register FoldTrue, FoldFalse;
3837
3838 // We have a select-of-constants followed by a binary operator with a
3839 // constant. Eliminate the binop by pulling the constant math into the select.
3840 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
3841 if (SelectOperand == 1) {
3842 // TODO: SelectionDAG verifies this actually constant folds before
3843 // committing to the combine.
3844
3845 FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {SelectTrue, RHS}).getReg(0);
3846 FoldFalse =
3847 Builder.buildInstr(BinOpcode, {Ty}, {SelectFalse, RHS}).getReg(0);
3848 } else {
3849 FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectTrue}).getReg(0);
3850 FoldFalse =
3851 Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectFalse}).getReg(0);
3852 }
3853
3854 Builder.buildSelect(Dst, SelectCond, FoldTrue, FoldFalse, MI.getFlags());
3855 MI.eraseFromParent();
3856}
3857
3858std::optional<SmallVector<Register, 8>>
3859CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3860 assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3861 // We want to detect if Root is part of a tree which represents a bunch
3862 // of loads being merged into a larger load. We'll try to recognize patterns
3863 // like, for example:
3864 //
3865 // Reg Reg
3866 // \ /
3867 // OR_1 Reg
3868 // \ /
3869 // OR_2
3870 // \ Reg
3871 // .. /
3872 // Root
3873 //
3874 // Reg Reg Reg Reg
3875 // \ / \ /
3876 // OR_1 OR_2
3877 // \ /
3878 // \ /
3879 // ...
3880 // Root
3881 //
3882 // Each "Reg" may have been produced by a load + some arithmetic. This
3883 // function will save each of them.
3884 SmallVector<Register, 8> RegsToVisit;
3886
3887 // In the "worst" case, we're dealing with a load for each byte. So, there
3888 // are at most #bytes - 1 ORs.
3889 const unsigned MaxIter =
3890 MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3891 for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3892 if (Ors.empty())
3893 break;
3894 const MachineInstr *Curr = Ors.pop_back_val();
3895 Register OrLHS = Curr->getOperand(1).getReg();
3896 Register OrRHS = Curr->getOperand(2).getReg();
3897
3898 // In the combine, we want to elimate the entire tree.
3899 if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3900 return std::nullopt;
3901
3902 // If it's a G_OR, save it and continue to walk. If it's not, then it's
3903 // something that may be a load + arithmetic.
3904 if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3905 Ors.push_back(Or);
3906 else
3907 RegsToVisit.push_back(OrLHS);
3908 if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3909 Ors.push_back(Or);
3910 else
3911 RegsToVisit.push_back(OrRHS);
3912 }
3913
3914 // We're going to try and merge each register into a wider power-of-2 type,
3915 // so we ought to have an even number of registers.
3916 if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3917 return std::nullopt;
3918 return RegsToVisit;
3919}
3920
3921/// Helper function for findLoadOffsetsForLoadOrCombine.
3922///
3923/// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3924/// and then moving that value into a specific byte offset.
3925///
3926/// e.g. x[i] << 24
3927///
3928/// \returns The load instruction and the byte offset it is moved into.
3929static std::optional<std::pair<GZExtLoad *, int64_t>>
3930matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3931 const MachineRegisterInfo &MRI) {
3932 assert(MRI.hasOneNonDBGUse(Reg) &&
3933 "Expected Reg to only have one non-debug use?");
3934 Register MaybeLoad;
3935 int64_t Shift;
3936 if (!mi_match(Reg, MRI, m_OneUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3937 Shift = 0;
3938 MaybeLoad = Reg;
3939 }
3940
3941 if (Shift % MemSizeInBits != 0)
3942 return std::nullopt;
3943
3944 // TODO: Handle other types of loads.
3945 auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
3946 if (!Load)
3947 return std::nullopt;
3948
3949 if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
3950 return std::nullopt;
3951
3952 return std::make_pair(Load, Shift / MemSizeInBits);
3953}
3954
3955std::optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
3956CombinerHelper::findLoadOffsetsForLoadOrCombine(
3958 const SmallVector<Register, 8> &RegsToVisit,
3959 const unsigned MemSizeInBits) const {
3960
3961 // Each load found for the pattern. There should be one for each RegsToVisit.
3962 SmallSetVector<const MachineInstr *, 8> Loads;
3963
3964 // The lowest index used in any load. (The lowest "i" for each x[i].)
3965 int64_t LowestIdx = INT64_MAX;
3966
3967 // The load which uses the lowest index.
3968 GZExtLoad *LowestIdxLoad = nullptr;
3969
3970 // Keeps track of the load indices we see. We shouldn't see any indices twice.
3971 SmallSet<int64_t, 8> SeenIdx;
3972
3973 // Ensure each load is in the same MBB.
3974 // TODO: Support multiple MachineBasicBlocks.
3975 MachineBasicBlock *MBB = nullptr;
3976 const MachineMemOperand *MMO = nullptr;
3977
3978 // Earliest instruction-order load in the pattern.
3979 GZExtLoad *EarliestLoad = nullptr;
3980
3981 // Latest instruction-order load in the pattern.
3982 GZExtLoad *LatestLoad = nullptr;
3983
3984 // Base pointer which every load should share.
3986
3987 // We want to find a load for each register. Each load should have some
3988 // appropriate bit twiddling arithmetic. During this loop, we will also keep
3989 // track of the load which uses the lowest index. Later, we will check if we
3990 // can use its pointer in the final, combined load.
3991 for (auto Reg : RegsToVisit) {
3992 // Find the load, and find the position that it will end up in (e.g. a
3993 // shifted) value.
3994 auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3995 if (!LoadAndPos)
3996 return std::nullopt;
3997 GZExtLoad *Load;
3998 int64_t DstPos;
3999 std::tie(Load, DstPos) = *LoadAndPos;
4000
4001 // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
4002 // it is difficult to check for stores/calls/etc between loads.
4003 MachineBasicBlock *LoadMBB = Load->getParent();
4004 if (!MBB)
4005 MBB = LoadMBB;
4006 if (LoadMBB != MBB)
4007 return std::nullopt;
4008
4009 // Make sure that the MachineMemOperands of every seen load are compatible.
4010 auto &LoadMMO = Load->getMMO();
4011 if (!MMO)
4012 MMO = &LoadMMO;
4013 if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
4014 return std::nullopt;
4015
4016 // Find out what the base pointer and index for the load is.
4017 Register LoadPtr;
4018 int64_t Idx;
4019 if (!mi_match(Load->getOperand(1).getReg(), MRI,
4020 m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
4021 LoadPtr = Load->getOperand(1).getReg();
4022 Idx = 0;
4023 }
4024
4025 // Don't combine things like a[i], a[i] -> a bigger load.
4026 if (!SeenIdx.insert(Idx).second)
4027 return std::nullopt;
4028
4029 // Every load must share the same base pointer; don't combine things like:
4030 //
4031 // a[i], b[i + 1] -> a bigger load.
4032 if (!BasePtr.isValid())
4033 BasePtr = LoadPtr;
4034 if (BasePtr != LoadPtr)
4035 return std::nullopt;
4036
4037 if (Idx < LowestIdx) {
4038 LowestIdx = Idx;
4039 LowestIdxLoad = Load;
4040 }
4041
4042 // Keep track of the byte offset that this load ends up at. If we have seen
4043 // the byte offset, then stop here. We do not want to combine:
4044 //
4045 // a[i] << 16, a[i + k] << 16 -> a bigger load.
4046 if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
4047 return std::nullopt;
4048 Loads.insert(Load);
4049
4050 // Keep track of the position of the earliest/latest loads in the pattern.
4051 // We will check that there are no load fold barriers between them later
4052 // on.
4053 //
4054 // FIXME: Is there a better way to check for load fold barriers?
4055 if (!EarliestLoad || dominates(*Load, *EarliestLoad))
4056 EarliestLoad = Load;
4057 if (!LatestLoad || dominates(*LatestLoad, *Load))
4058 LatestLoad = Load;
4059 }
4060
4061 // We found a load for each register. Let's check if each load satisfies the
4062 // pattern.
4063 assert(Loads.size() == RegsToVisit.size() &&
4064 "Expected to find a load for each register?");
4065 assert(EarliestLoad != LatestLoad && EarliestLoad &&
4066 LatestLoad && "Expected at least two loads?");
4067
4068 // Check if there are any stores, calls, etc. between any of the loads. If
4069 // there are, then we can't safely perform the combine.
4070 //
4071 // MaxIter is chosen based off the (worst case) number of iterations it
4072 // typically takes to succeed in the LLVM test suite plus some padding.
4073 //
4074 // FIXME: Is there a better way to check for load fold barriers?
4075 const unsigned MaxIter = 20;
4076 unsigned Iter = 0;
4077 for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
4078 LatestLoad->getIterator())) {
4079 if (Loads.count(&MI))
4080 continue;
4081 if (MI.isLoadFoldBarrier())
4082 return std::nullopt;
4083 if (Iter++ == MaxIter)
4084 return std::nullopt;
4085 }
4086
4087 return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
4088}
4089
4092 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4093 assert(MI.getOpcode() == TargetOpcode::G_OR);
4094 MachineFunction &MF = *MI.getMF();
4095 // Assuming a little-endian target, transform:
4096 // s8 *a = ...
4097 // s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4098 // =>
4099 // s32 val = *((i32)a)
4100 //
4101 // s8 *a = ...
4102 // s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4103 // =>
4104 // s32 val = BSWAP(*((s32)a))
4105 Register Dst = MI.getOperand(0).getReg();
4106 LLT Ty = MRI.getType(Dst);
4107 if (Ty.isVector())
4108 return false;
4109
4110 // We need to combine at least two loads into this type. Since the smallest
4111 // possible load is into a byte, we need at least a 16-bit wide type.
4112 const unsigned WideMemSizeInBits = Ty.getSizeInBits();
4113 if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
4114 return false;
4115
4116 // Match a collection of non-OR instructions in the pattern.
4117 auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
4118 if (!RegsToVisit)
4119 return false;
4120
4121 // We have a collection of non-OR instructions. Figure out how wide each of
4122 // the small loads should be based off of the number of potential loads we
4123 // found.
4124 const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
4125 if (NarrowMemSizeInBits % 8 != 0)
4126 return false;
4127
4128 // Check if each register feeding into each OR is a load from the same
4129 // base pointer + some arithmetic.
4130 //
4131 // e.g. a[0], a[1] << 8, a[2] << 16, etc.
4132 //
4133 // Also verify that each of these ends up putting a[i] into the same memory
4134 // offset as a load into a wide type would.
4136 GZExtLoad *LowestIdxLoad, *LatestLoad;
4137 int64_t LowestIdx;
4138 auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
4139 MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
4140 if (!MaybeLoadInfo)
4141 return false;
4142 std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
4143
4144 // We have a bunch of loads being OR'd together. Using the addresses + offsets
4145 // we found before, check if this corresponds to a big or little endian byte
4146 // pattern. If it does, then we can represent it using a load + possibly a
4147 // BSWAP.
4148 bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
4149 std::optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
4150 if (!IsBigEndian)
4151 return false;
4152 bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
4153 if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
4154 return false;
4155
4156 // Make sure that the load from the lowest index produces offset 0 in the
4157 // final value.
4158 //
4159 // This ensures that we won't combine something like this:
4160 //
4161 // load x[i] -> byte 2
4162 // load x[i+1] -> byte 0 ---> wide_load x[i]
4163 // load x[i+2] -> byte 1
4164 const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
4165 const unsigned ZeroByteOffset =
4166 *IsBigEndian
4167 ? bigEndianByteAt(NumLoadsInTy, 0)
4168 : littleEndianByteAt(NumLoadsInTy, 0);
4169 auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
4170 if (ZeroOffsetIdx == MemOffset2Idx.end() ||
4171 ZeroOffsetIdx->second != LowestIdx)
4172 return false;
4173
4174 // We wil reuse the pointer from the load which ends up at byte offset 0. It
4175 // may not use index 0.
4176 Register Ptr = LowestIdxLoad->getPointerReg();
4177 const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
4178 LegalityQuery::MemDesc MMDesc(MMO);
4179 MMDesc.MemoryTy = Ty;
4181 {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
4182 return false;
4183 auto PtrInfo = MMO.getPointerInfo();
4184 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
4185
4186 // Load must be allowed and fast on the target.
4188 auto &DL = MF.getDataLayout();
4189 unsigned Fast = 0;
4190 if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
4191 !Fast)
4192 return false;
4193
4194 MatchInfo = [=](MachineIRBuilder &MIB) {
4195 MIB.setInstrAndDebugLoc(*LatestLoad);
4196 Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
4197 MIB.buildLoad(LoadDst, Ptr, *NewMMO);
4198 if (NeedsBSwap)
4199 MIB.buildBSwap(Dst, LoadDst);
4200 };
4201 return true;
4202}
4203
4205 MachineInstr *&ExtMI) const {
4206 auto &PHI = cast<GPhi>(MI);
4207 Register DstReg = PHI.getReg(0);
4208
4209 // TODO: Extending a vector may be expensive, don't do this until heuristics
4210 // are better.
4211 if (MRI.getType(DstReg).isVector())
4212 return false;
4213
4214 // Try to match a phi, whose only use is an extend.
4215 if (!MRI.hasOneNonDBGUse(DstReg))
4216 return false;
4217 ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
4218 switch (ExtMI->getOpcode()) {
4219 case TargetOpcode::G_ANYEXT:
4220 return true; // G_ANYEXT is usually free.
4221 case TargetOpcode::G_ZEXT:
4222 case TargetOpcode::G_SEXT:
4223 break;
4224 default:
4225 return false;
4226 }
4227
4228 // If the target is likely to fold this extend away, don't propagate.
4229 if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
4230 return false;
4231
4232 // We don't want to propagate the extends unless there's a good chance that
4233 // they'll be optimized in some way.
4234 // Collect the unique incoming values.
4236 for (unsigned I = 0; I < PHI.getNumIncomingValues(); ++I) {
4237 auto *DefMI = getDefIgnoringCopies(PHI.getIncomingValue(I), MRI);
4238 switch (DefMI->getOpcode()) {
4239 case TargetOpcode::G_LOAD:
4240 case TargetOpcode::G_TRUNC:
4241 case TargetOpcode::G_SEXT:
4242 case TargetOpcode::G_ZEXT:
4243 case TargetOpcode::G_ANYEXT:
4244 case TargetOpcode::G_CONSTANT:
4245 InSrcs.insert(DefMI);
4246 // Don't try to propagate if there are too many places to create new
4247 // extends, chances are it'll increase code size.
4248 if (InSrcs.size() > 2)
4249 return false;
4250 break;
4251 default:
4252 return false;
4253 }
4254 }
4255 return true;
4256}
4257
4259 MachineInstr *&ExtMI) const {
4260 auto &PHI = cast<GPhi>(MI);
4261 Register DstReg = ExtMI->getOperand(0).getReg();
4262 LLT ExtTy = MRI.getType(DstReg);
4263
4264 // Propagate the extension into the block of each incoming reg's block.
4265 // Use a SetVector here because PHIs can have duplicate edges, and we want
4266 // deterministic iteration order.
4269 for (unsigned I = 0; I < PHI.getNumIncomingValues(); ++I) {
4270 auto SrcReg = PHI.getIncomingValue(I);
4271 MachineInstr *SrcMI;
4272 if (!mi_match(SrcReg, MRI, m_MInstr(SrcMI)))
4273 continue;
4274 if (!SrcMIs.insert(SrcMI))
4275 continue;
4276
4277 // Build an extend after each src inst.
4278 auto *MBB = SrcMI->getParent();
4280 if (InsertPt != MBB->end() && InsertPt->isPHI())
4281 InsertPt = MBB->getFirstNonPHI();
4282
4283 Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
4284 Builder.setDebugLoc(MI.getDebugLoc());
4285 auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy, SrcReg);
4286 OldToNewSrcMap[SrcMI] = NewExt;
4287 }
4288
4289 // Create a new phi with the extended inputs.
4290 Builder.setInstrAndDebugLoc(MI);
4291 auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
4292 NewPhi.addDef(DstReg);
4293 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
4294 if (!MO.isReg()) {
4295 NewPhi.addMBB(MO.getMBB());
4296 continue;
4297 }
4298 auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
4299 NewPhi.addUse(NewSrc->getOperand(0).getReg());
4300 }
4301 Builder.insertInstr(NewPhi);
4302 ExtMI->eraseFromParent();
4303}
4304
4306 Register &Reg) const {
4307 assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
4308 // If we have a constant index, look for a G_BUILD_VECTOR source
4309 // and find the source register that the index maps to.
4310 Register SrcVec = MI.getOperand(1).getReg();
4311 LLT SrcTy = MRI.getType(SrcVec);
4312 if (SrcTy.isScalableVector())
4313 return false;
4314
4315 auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
4316 if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
4317 return false;
4318
4319 unsigned VecIdx = Cst->Value.getZExtValue();
4320
4321 // Check if we have a build_vector or build_vector_trunc with an optional
4322 // trunc in front.
4323 MachineInstr *SrcVecMI;
4324 Register TruncSrc;
4325 if (mi_match(SrcVec, MRI, m_GTrunc(m_Reg(TruncSrc)))) {
4326 if (!mi_match(TruncSrc, MRI, m_MInstr(SrcVecMI)))
4327 return false;
4328 } else if (!mi_match(SrcVec, MRI, m_MInstr(SrcVecMI)))
4329 return false;
4330
4331 if (SrcVecMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR &&
4332 SrcVecMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR_TRUNC)
4333 return false;
4334
4335 EVT Ty(getMVTForLLT(SrcTy));
4336 if (!MRI.hasOneNonDBGUse(SrcVec) &&
4337 !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
4338 return false;
4339
4340 Reg = SrcVecMI->getOperand(VecIdx + 1).getReg();
4341 return true;
4342}
4343
4345 Register &Reg) const {
4346 // Check the type of the register, since it may have come from a
4347 // G_BUILD_VECTOR_TRUNC.
4348 LLT ScalarTy = MRI.getType(Reg);
4349 Register DstReg = MI.getOperand(0).getReg();
4350 LLT DstTy = MRI.getType(DstReg);
4351
4352 if (ScalarTy != DstTy) {
4353 assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
4354 Builder.buildTrunc(DstReg, Reg);
4355 MI.eraseFromParent();
4356 return;
4357 }
4359}
4360
4363 SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) const {
4364 assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4365 // This combine tries to find build_vector's which have every source element
4366 // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
4367 // the masked load scalarization is run late in the pipeline. There's already
4368 // a combine for a similar pattern starting from the extract, but that
4369 // doesn't attempt to do it if there are multiple uses of the build_vector,
4370 // which in this case is true. Starting the combine from the build_vector
4371 // feels more natural than trying to find sibling nodes of extracts.
4372 // E.g.
4373 // %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
4374 // %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
4375 // %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
4376 // %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
4377 // %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
4378 // ==>
4379 // replace ext{1,2,3,4} with %s{1,2,3,4}
4380
4381 Register DstReg = MI.getOperand(0).getReg();
4382 LLT DstTy = MRI.getType(DstReg);
4383 unsigned NumElts = DstTy.getNumElements();
4384
4385 SmallBitVector ExtractedElts(NumElts);
4386 for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
4387 if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
4388 return false;
4389 auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
4390 if (!Cst)
4391 return false;
4392 unsigned Idx = Cst->getZExtValue();
4393 if (Idx >= NumElts)
4394 return false; // Out of range.
4395 ExtractedElts.set(Idx);
4396 SrcDstPairs.emplace_back(
4397 std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
4398 }
4399 // Match if every element was extracted.
4400 return ExtractedElts.all();
4401}
4402
4405 SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) const {
4406 assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4407 for (auto &Pair : SrcDstPairs) {
4408 auto *ExtMI = Pair.second;
4409 replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
4410 ExtMI->eraseFromParent();
4411 }
4412 MI.eraseFromParent();
4413}
4414
4417 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4418 applyBuildFnNoErase(MI, MatchInfo);
4419 MI.eraseFromParent();
4420}
4421
4424 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4425 MatchInfo(Builder);
4426}
4427
4429 bool AllowScalarConstants,
4430 BuildFnTy &MatchInfo) const {
4431 assert(MI.getOpcode() == TargetOpcode::G_OR);
4432
4433 Register Dst = MI.getOperand(0).getReg();
4434 LLT Ty = MRI.getType(Dst);
4435 unsigned BitWidth = Ty.getScalarSizeInBits();
4436
4437 Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
4438 unsigned FshOpc = 0;
4439
4440 // Match (or (shl ...), (lshr ...)).
4441 if (!mi_match(Dst, MRI,
4442 // m_GOr() handles the commuted version as well.
4443 m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
4444 m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
4445 return false;
4446
4447 // Given constants C0 and C1 such that C0 + C1 is bit-width:
4448 // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
4449 int64_t CstShlAmt = 0, CstLShrAmt;
4450 if (mi_match(ShlAmt, MRI, m_ICstOrSplat(CstShlAmt)) &&
4451 mi_match(LShrAmt, MRI, m_ICstOrSplat(CstLShrAmt)) &&
4452 CstShlAmt + CstLShrAmt == BitWidth) {
4453 FshOpc = TargetOpcode::G_FSHR;
4454 Amt = LShrAmt;
4455 } else if (mi_match(LShrAmt, MRI,
4457 ShlAmt == Amt) {
4458 // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
4459 FshOpc = TargetOpcode::G_FSHL;
4460 } else if (mi_match(ShlAmt, MRI,
4462 LShrAmt == Amt) {
4463 // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
4464 FshOpc = TargetOpcode::G_FSHR;
4465 } else {
4466 return false;
4467 }
4468
4469 LLT AmtTy = MRI.getType(Amt);
4470 if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}) &&
4471 (!AllowScalarConstants || CstShlAmt == 0 || !Ty.isScalar()))
4472 return false;
4473
4474 MatchInfo = [=](MachineIRBuilder &B) {
4475 B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
4476 };
4477 return true;
4478}
4479
4480// Fold (rot x, c) -> (rot x, c % BitSize)
4482 assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4483 MI.getOpcode() == TargetOpcode::G_ROTR);
4484 unsigned Bitsize =
4485 MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4486 Register AmtReg = MI.getOperand(2).getReg();
4487 bool OutOfRange = false;
4488 auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
4489 if (auto *CI = dyn_cast<ConstantInt>(C))
4490 OutOfRange |= CI->getValue().uge(Bitsize);
4491 return true;
4492 };
4493 return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
4494}
4495
4497 assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4498 MI.getOpcode() == TargetOpcode::G_ROTR);
4499 unsigned Bitsize =
4500 MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4501 Register Amt = MI.getOperand(2).getReg();
4502 LLT AmtTy = MRI.getType(Amt);
4503 auto Bits = Builder.buildConstant(AmtTy, Bitsize);
4504 Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
4505 Observer.changingInstr(MI);
4506 MI.getOperand(2).setReg(Amt);
4507 Observer.changedInstr(MI);
4508}
4509
4511 int64_t &MatchInfo) const {
4512 assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4513 auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4514
4515 // We want to avoid calling KnownBits on the LHS if possible, as this combine
4516 // has no filter and runs on every G_ICMP instruction. We can avoid calling
4517 // KnownBits on the LHS in two cases:
4518 //
4519 // - The RHS is unknown: Constants are always on RHS. If the RHS is unknown
4520 // we cannot do any transforms so we can safely bail out early.
4521 // - The RHS is zero: we don't need to know the LHS to do unsigned <0 and
4522 // >=0.
4523 auto KnownRHS = VT->getKnownBits(MI.getOperand(3).getReg());
4524 if (KnownRHS.isUnknown())
4525 return false;
4526
4527 std::optional<bool> KnownVal;
4528 if (KnownRHS.isZero()) {
4529 // ? uge 0 -> always true
4530 // ? ult 0 -> always false
4531 if (Pred == CmpInst::ICMP_UGE)
4532 KnownVal = true;
4533 else if (Pred == CmpInst::ICMP_ULT)
4534 KnownVal = false;
4535 }
4536
4537 if (!KnownVal) {
4538 auto KnownLHS = VT->getKnownBits(MI.getOperand(2).getReg());
4539 KnownVal = ICmpInst::compare(KnownLHS, KnownRHS, Pred);
4540 }
4541
4542 if (!KnownVal)
4543 return false;
4544 MatchInfo =
4545 *KnownVal
4547 /*IsVector = */
4548 MRI.getType(MI.getOperand(0).getReg()).isVector())
4549 : 0;
4550 return true;
4551}
4552
4555 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4556 assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4557 // Given:
4558 //
4559 // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4560 // %cmp = G_ICMP ne %x, 0
4561 //
4562 // Or:
4563 //
4564 // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4565 // %cmp = G_ICMP eq %x, 1
4566 //
4567 // We can replace %cmp with %x assuming true is 1 on the target.
4568 auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4569 if (!CmpInst::isEquality(Pred))
4570 return false;
4571 Register Dst = MI.getOperand(0).getReg();
4572 LLT DstTy = MRI.getType(Dst);
4573 if (getICmpTrueVal(getTargetLowering(), DstTy.isVector()) != 1)
4574 return false;
4575 int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
4576 if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
4577 return false;
4578 Register LHS = MI.getOperand(2).getReg();
4579 auto KnownLHS = VT->getKnownBits(LHS);
4580 if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
4581 return false;
4582 // Make sure replacing Dst with the LHS is a legal operation.
4583 LLT LHSTy = MRI.getType(LHS);
4584 unsigned LHSSize = LHSTy.getSizeInBits();
4585 unsigned DstSize = DstTy.getSizeInBits();
4586 unsigned Op = TargetOpcode::COPY;
4587 if (DstSize != LHSSize)
4588 Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
4589 if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
4590 return false;
4591 MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
4592 return true;
4593}
4594
4595// Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
4598 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4599 assert(MI.getOpcode() == TargetOpcode::G_AND);
4600
4601 // Ignore vector types to simplify matching the two constants.
4602 // TODO: do this for vectors and scalars via a demanded bits analysis.
4603 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
4604 if (Ty.isVector())
4605 return false;
4606
4607 Register Src;
4608 Register AndMaskReg;
4609 int64_t AndMaskBits;
4610 int64_t OrMaskBits;
4611 if (!mi_match(MI, MRI,
4612 m_GAnd(m_GOr(m_Reg(Src), m_ICst(OrMaskBits)),
4613 m_all_of(m_ICst(AndMaskBits), m_Reg(AndMaskReg)))))
4614 return false;
4615
4616 // Check if OrMask could turn on any bits in Src.
4617 if (AndMaskBits & OrMaskBits)
4618 return false;
4619
4620 MatchInfo = [=, &MI](MachineIRBuilder &B) {
4621 Observer.changingInstr(MI);
4622 // Canonicalize the result to have the constant on the RHS.
4623 if (MI.getOperand(1).getReg() == AndMaskReg)
4624 MI.getOperand(2).setReg(AndMaskReg);
4625 MI.getOperand(1).setReg(Src);
4626 Observer.changedInstr(MI);
4627 };
4628 return true;
4629}
4630
4631/// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
4634 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4635 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
4636 Register Dst = MI.getOperand(0).getReg();
4637 Register Src = MI.getOperand(1).getReg();
4638 LLT Ty = MRI.getType(Src);
4640 if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
4641 return false;
4642 int64_t Width = MI.getOperand(2).getImm();
4643 Register ShiftSrc;
4644 int64_t ShiftImm;
4645 if (!mi_match(Src, MRI,
4646 m_OneUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
4647 m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
4648 return false;
4649 if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
4650 return false;
4651
4652 MatchInfo = [=](MachineIRBuilder &B) {
4653 auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
4654 auto Cst2 = B.buildConstant(ExtractTy, Width);
4655 B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
4656 };
4657 return true;
4658}
4659
4660/// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
4662 BuildFnTy &MatchInfo) const {
4663 GAnd *And = cast<GAnd>(&MI);
4664 Register Dst = And->getReg(0);
4665 LLT Ty = MRI.getType(Dst);
4667 // Note that isLegalOrBeforeLegalizer is stricter and does not take custom
4668 // into account.
4669 if (LI && !LI->isLegalOrCustom({TargetOpcode::G_UBFX, {Ty, ExtractTy}}))
4670 return false;
4671
4672 int64_t AndImm, LSBImm;
4673 Register ShiftSrc;
4674 const unsigned Size = Ty.getScalarSizeInBits();
4675 if (!mi_match(And->getReg(0), MRI,
4676 m_GAnd(m_OneUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
4677 m_ICst(AndImm))))
4678 return false;
4679
4680 // AndImm is sign-extended to 64 bits by m_ICst; restrict it to the operand
4681 // width so an all-ones mask (a redundant AND) is not misread as a wider mask.
4682 uint64_t MaybeMask = static_cast<uint64_t>(AndImm);
4683 if (Size < 64)
4684 MaybeMask &= maskTrailingOnes<uint64_t>(Size);
4685
4686 // The mask is a mask of the low bits iff imm & (imm+1) == 0.
4687 if (MaybeMask & (MaybeMask + 1))
4688 return false;
4689
4690 // LSB must fit within the register.
4691 if (static_cast<uint64_t>(LSBImm) >= Size)
4692 return false;
4693
4694 uint64_t Width = APInt(Size, MaybeMask).countr_one();
4695 // The extracted field [LSB, LSB+Width) must fit within the register.
4696 // Otherwise this is a redundant AND (e.g. an all-ones mask combined with a
4697 // non-zero shift) that is better handled by other combines, and would form
4698 // an out-of-range bitfield extract.
4699 if (static_cast<uint64_t>(LSBImm) + Width > Size)
4700 return false;
4701
4702 MatchInfo = [=](MachineIRBuilder &B) {
4703 auto WidthCst = B.buildConstant(ExtractTy, Width);
4704 auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
4705 B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
4706 };
4707 return true;
4708}
4709
4712 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4713 const unsigned Opcode = MI.getOpcode();
4714 assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
4715
4716 const Register Dst = MI.getOperand(0).getReg();
4717
4718 const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
4719 ? TargetOpcode::G_SBFX
4720 : TargetOpcode::G_UBFX;
4721
4722 // Check if the type we would use for the extract is legal
4723 LLT Ty = MRI.getType(Dst);
4725 if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
4726 return false;
4727
4728 Register ShlSrc;
4729 int64_t ShrAmt;
4730 int64_t ShlAmt;
4731 const unsigned Size = Ty.getScalarSizeInBits();
4732
4733 // Try to match shr (shl x, c1), c2
4734 if (!mi_match(Dst, MRI,
4735 m_BinOp(Opcode, m_OneUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
4736 m_ICst(ShrAmt))))
4737 return false;
4738
4739 // Make sure that the shift sizes can fit a bitfield extract
4740 if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
4741 return false;
4742
4743 // Skip this combine if the G_SEXT_INREG combine could handle it
4744 if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
4745 return false;
4746
4747 // Calculate start position and width of the extract
4748 const int64_t Pos = ShrAmt - ShlAmt;
4749 const int64_t Width = Size - ShrAmt;
4750
4751 MatchInfo = [=](MachineIRBuilder &B) {
4752 auto WidthCst = B.buildConstant(ExtractTy, Width);
4753 auto PosCst = B.buildConstant(ExtractTy, Pos);
4754 B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
4755 };
4756 return true;
4757}
4758
4761 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
4762 const unsigned Opcode = MI.getOpcode();
4763 assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
4764
4765 const Register Dst = MI.getOperand(0).getReg();
4766 LLT Ty = MRI.getType(Dst);
4768 if (LI && !LI->isLegalOrCustom({TargetOpcode::G_UBFX, {Ty, ExtractTy}}))
4769 return false;
4770
4771 // Try to match shr (and x, c1), c2
4772 Register AndSrc;
4773 int64_t ShrAmt;
4774 int64_t SMask;
4775 if (!mi_match(Dst, MRI,
4776 m_BinOp(Opcode, m_OneUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
4777 m_ICst(ShrAmt))))
4778 return false;
4779
4780 const unsigned Size = Ty.getScalarSizeInBits();
4781 if (ShrAmt < 0 || ShrAmt >= Size)
4782 return false;
4783
4784 // If the shift subsumes the mask, emit the 0 directly.
4785 if (0 == (SMask >> ShrAmt)) {
4786 MatchInfo = [=](MachineIRBuilder &B) {
4787 B.buildConstant(Dst, 0);
4788 };
4789 return true;
4790 }
4791
4792 // Check that ubfx can do the extraction, with no holes in the mask.
4793 uint64_t UMask = SMask;
4794 UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
4796 if (!isMask_64(UMask))
4797 return false;
4798
4799 // Calculate start position and width of the extract.
4800 const int64_t Pos = ShrAmt;
4801 const int64_t Width = llvm::countr_one(UMask) - ShrAmt;
4802
4803 // It's preferable to keep the shift, rather than form G_SBFX.
4804 // TODO: remove the G_AND via demanded bits analysis.
4805 if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
4806 return false;
4807
4808 MatchInfo = [=](MachineIRBuilder &B) {
4809 auto WidthCst = B.buildConstant(ExtractTy, Width);
4810 auto PosCst = B.buildConstant(ExtractTy, Pos);
4811 B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
4812 };
4813 return true;
4814}
4815
4816bool CombinerHelper::reassociationCanBreakAddressingModePattern(
4817 MachineInstr &MI) const {
4818 auto &PtrAdd = cast<GPtrAdd>(MI);
4819
4820 Register Src1Reg = PtrAdd.getBaseReg();
4821 auto *Src1Def = getOpcodeDef<GPtrAdd>(Src1Reg, MRI);
4822 if (!Src1Def)
4823 return false;
4824
4825 Register Src2Reg = PtrAdd.getOffsetReg();
4826
4827 if (MRI.hasOneNonDBGUse(Src1Reg))
4828 return false;
4829
4830 auto C1 = getIConstantVRegVal(Src1Def->getOffsetReg(), MRI);
4831 if (!C1)
4832 return false;
4833 auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4834 if (!C2)
4835 return false;
4836
4837 const APInt &C1APIntVal = *C1;
4838 const APInt &C2APIntVal = *C2;
4839 const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
4840
4841 for (auto &UseMI : MRI.use_nodbg_instructions(PtrAdd.getReg(0))) {
4842 // This combine may end up running before ptrtoint/inttoptr combines
4843 // manage to eliminate redundant conversions, so try to look through them.
4844 MachineInstr *ConvUseMI = &UseMI;
4845 unsigned ConvUseOpc = ConvUseMI->getOpcode();
4846 while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
4847 ConvUseOpc == TargetOpcode::G_PTRTOINT) {
4848 Register DefReg = ConvUseMI->getOperand(0).getReg();
4849 if (!MRI.hasOneNonDBGUse(DefReg))
4850 break;
4851 ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
4852 ConvUseOpc = ConvUseMI->getOpcode();
4853 }
4854 auto *LdStMI = dyn_cast<GLoadStore>(ConvUseMI);
4855 if (!LdStMI)
4856 continue;
4857 // Is x[offset2] already not a legal addressing mode? If so then
4858 // reassociating the constants breaks nothing (we test offset2 because
4859 // that's the one we hope to fold into the load or store).
4860 TargetLoweringBase::AddrMode AM;
4861 AM.HasBaseReg = true;
4862 AM.BaseOffs = C2APIntVal.getSExtValue();
4863 unsigned AS = MRI.getType(LdStMI->getPointerReg()).getAddressSpace();
4864 Type *AccessTy = getTypeForLLT(LdStMI->getMMO().getMemoryType(),
4865 PtrAdd.getMF()->getFunction().getContext());
4866 const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
4867 if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4868 AccessTy, AS))
4869 continue;
4870
4871 // Would x[offset1+offset2] still be a legal addressing mode?
4872 AM.BaseOffs = CombinedValue;
4873 if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4874 AccessTy, AS))
4875 return true;
4876 }
4877
4878 return false;
4879}
4880
4882 MachineInstr *RHS,
4883 BuildFnTy &MatchInfo) const {
4884 // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4885 Register Src1Reg = MI.getOperand(1).getReg();
4886 if (RHS->getOpcode() != TargetOpcode::G_ADD)
4887 return false;
4888 auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
4889 if (!C2)
4890 return false;
4891
4892 // If both additions are nuw, the reassociated additions are also nuw.
4893 // If the original G_PTR_ADD is additionally nusw, X and C are both not
4894 // negative, so BASE+X is between BASE and BASE+(X+C). The new G_PTR_ADDs are
4895 // therefore also nusw.
4896 // If the original G_PTR_ADD is additionally inbounds (which implies nusw),
4897 // the new G_PTR_ADDs are then also inbounds.
4898 unsigned PtrAddFlags = MI.getFlags();
4899 unsigned AddFlags = RHS->getFlags();
4900 bool IsNoUWrap = PtrAddFlags & AddFlags & MachineInstr::MIFlag::NoUWrap;
4901 bool IsNoUSWrap = IsNoUWrap && (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap);
4902 bool IsInBounds = IsNoUWrap && (PtrAddFlags & MachineInstr::MIFlag::InBounds);
4903 unsigned Flags = 0;
4904 if (IsNoUWrap)
4906 if (IsNoUSWrap)
4908 if (IsInBounds)
4910
4911 MatchInfo = [=, &MI](MachineIRBuilder &B) {
4912 LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
4913
4914 auto NewBase =
4915 Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg(), Flags);
4916 Observer.changingInstr(MI);
4917 MI.getOperand(1).setReg(NewBase.getReg(0));
4918 MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
4919 MI.setFlags(Flags);
4920 Observer.changedInstr(MI);
4921 };
4922 return !reassociationCanBreakAddressingModePattern(MI);
4923}
4924
4926 MachineInstr *LHS,
4927 MachineInstr *RHS,
4928 BuildFnTy &MatchInfo) const {
4929 // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
4930 // if and only if (G_PTR_ADD X, C) has one use.
4931 Register LHSBase;
4932 std::optional<ValueAndVReg> LHSCstOff;
4933 if (!mi_match(MI.getBaseReg(), MRI,
4934 m_OneUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
4935 return false;
4936
4937 auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
4938
4939 // Reassociating nuw additions preserves nuw. If both original G_PTR_ADDs are
4940 // nuw and inbounds (which implies nusw), the offsets are both non-negative,
4941 // so the new G_PTR_ADDs are also inbounds.
4942 unsigned PtrAddFlags = MI.getFlags();
4943 unsigned LHSPtrAddFlags = LHSPtrAdd->getFlags();
4944 bool IsNoUWrap = PtrAddFlags & LHSPtrAddFlags & MachineInstr::MIFlag::NoUWrap;
4945 bool IsNoUSWrap = IsNoUWrap && (PtrAddFlags & LHSPtrAddFlags &
4947 bool IsInBounds = IsNoUWrap && (PtrAddFlags & LHSPtrAddFlags &
4949 unsigned Flags = 0;
4950 if (IsNoUWrap)
4952 if (IsNoUSWrap)
4954 if (IsInBounds)
4956
4957 MatchInfo = [=, &MI](MachineIRBuilder &B) {
4958 // When we change LHSPtrAdd's offset register we might cause it to use a reg
4959 // before its def. Sink the instruction so the outer PTR_ADD to ensure this
4960 // doesn't happen.
4961 LHSPtrAdd->moveBefore(&MI);
4962 Register RHSReg = MI.getOffsetReg();
4963 // set VReg will cause type mismatch if it comes from extend/trunc
4964 auto NewCst = B.buildConstant(MRI.getType(RHSReg), LHSCstOff->Value);
4965 Observer.changingInstr(MI);
4966 MI.getOperand(2).setReg(NewCst.getReg(0));
4967 MI.setFlags(Flags);
4968 Observer.changedInstr(MI);
4969 Observer.changingInstr(*LHSPtrAdd);
4970 LHSPtrAdd->getOperand(2).setReg(RHSReg);
4971 LHSPtrAdd->setFlags(Flags);
4972 Observer.changedInstr(*LHSPtrAdd);
4973 };
4974 return !reassociationCanBreakAddressingModePattern(MI);
4975}
4976
4978 GPtrAdd &MI, MachineInstr *LHS, MachineInstr *RHS,
4979 BuildFnTy &MatchInfo) const {
4980 // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4981 auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
4982 if (!LHSPtrAdd)
4983 return false;
4984
4985 Register Src2Reg = MI.getOperand(2).getReg();
4986 Register LHSSrc1 = LHSPtrAdd->getBaseReg();
4987 Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
4988 auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
4989 if (!C1)
4990 return false;
4991 auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4992 if (!C2)
4993 return false;
4994
4995 // Reassociating nuw additions preserves nuw. If both original G_PTR_ADDs are
4996 // inbounds, reaching the same result in one G_PTR_ADD is also inbounds.
4997 // The nusw constraints are satisfied because imm1+imm2 cannot exceed the
4998 // largest signed integer that fits into the index type, which is the maximum
4999 // size of allocated objects according to the IR Language Reference.
5000 unsigned PtrAddFlags = MI.getFlags();
5001 unsigned LHSPtrAddFlags = LHSPtrAdd->getFlags();
5002 bool IsNoUWrap = PtrAddFlags & LHSPtrAddFlags & MachineInstr::MIFlag::NoUWrap;
5003 bool IsInBounds =
5004 PtrAddFlags & LHSPtrAddFlags & MachineInstr::MIFlag::InBounds;
5005 unsigned Flags = 0;
5006 if (IsNoUWrap)
5008 if (IsInBounds) {
5011 }
5012
5013 MatchInfo = [=, &MI](MachineIRBuilder &B) {
5014 auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
5015 Observer.changingInstr(MI);
5016 MI.getOperand(1).setReg(LHSSrc1);
5017 MI.getOperand(2).setReg(NewCst.getReg(0));
5018 MI.setFlags(Flags);
5019 Observer.changedInstr(MI);
5020 };
5021 return !reassociationCanBreakAddressingModePattern(MI);
5022}
5023
5025 BuildFnTy &MatchInfo) const {
5026 auto &PtrAdd = cast<GPtrAdd>(MI);
5027 // We're trying to match a few pointer computation patterns here for
5028 // re-association opportunities.
5029 // 1) Isolating a constant operand to be on the RHS, e.g.:
5030 // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
5031 //
5032 // 2) Folding two constants in each sub-tree as long as such folding
5033 // doesn't break a legal addressing mode.
5034 // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
5035 //
5036 // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
5037 // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
5038 // iif (G_PTR_ADD X, C) has one use.
5039 MachineInstr *LHS, *RHS;
5040 if (!mi_match(PtrAdd.getBaseReg(), MRI, m_MInstr(LHS)) ||
5041 !mi_match(PtrAdd.getOffsetReg(), MRI, m_MInstr(RHS)))
5042 return false;
5043
5044 // Try to match example 2.
5045 if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
5046 return true;
5047
5048 // Try to match example 3.
5049 if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
5050 return true;
5051
5052 // Try to match example 1.
5053 if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
5054 return true;
5055
5056 return false;
5057}
5059 Register OpLHS, Register OpRHS,
5060 BuildFnTy &MatchInfo) const {
5061 LLT OpRHSTy = MRI.getType(OpRHS);
5062 MachineInstr *OpLHSDef;
5063 if (!mi_match(OpLHS, MRI, m_MInstr(OpLHSDef)) || OpLHSDef->getOpcode() != Opc)
5064 return false;
5065
5066 Register OpLHSLHS = OpLHSDef->getOperand(1).getReg();
5067 Register OpLHSRHS = OpLHSDef->getOperand(2).getReg();
5068
5069 // If the inner op is (X op C), pull the constant out so it can be folded with
5070 // other constants in the expression tree. Folding is not guaranteed so we
5071 // might have (C1 op C2). In that case do not pull a constant out because it
5072 // won't help and can lead to infinite loops.
5073 if (isConstantOrConstantSplatVector(OpLHSRHS, MRI) &&
5076 // (Opc (Opc X, C1), C2) -> (Opc X, (Opc C1, C2))
5077 MatchInfo = [=](MachineIRBuilder &B) {
5078 auto NewCst = B.buildInstr(Opc, {OpRHSTy}, {OpLHSRHS, OpRHS});
5079 B.buildInstr(Opc, {DstReg}, {OpLHSLHS, NewCst});
5080 };
5081 return true;
5082 }
5083 if (getTargetLowering().isReassocProfitable(MRI, OpLHS, OpRHS)) {
5084 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
5085 // iff (op x, c1) has one use
5086 MatchInfo = [=](MachineIRBuilder &B) {
5087 auto NewLHSLHS = B.buildInstr(Opc, {OpRHSTy}, {OpLHSLHS, OpRHS});
5088 B.buildInstr(Opc, {DstReg}, {NewLHSLHS, OpLHSRHS});
5089 };
5090 return true;
5091 }
5092 }
5093
5094 return false;
5095}
5096
5098 BuildFnTy &MatchInfo) const {
5099 // We don't check if the reassociation will break a legal addressing mode
5100 // here since pointer arithmetic is handled by G_PTR_ADD.
5101 unsigned Opc = MI.getOpcode();
5102 Register DstReg = MI.getOperand(0).getReg();
5103 Register LHSReg = MI.getOperand(1).getReg();
5104 Register RHSReg = MI.getOperand(2).getReg();
5105
5106 if (tryReassocBinOp(Opc, DstReg, LHSReg, RHSReg, MatchInfo))
5107 return true;
5108 if (tryReassocBinOp(Opc, DstReg, RHSReg, LHSReg, MatchInfo))
5109 return true;
5110 return false;
5111}
5112
5114 BuildFnTy &MatchInfo) const {
5115 Register Dst = MI.getOperand(0).getReg();
5116 Register SrcOp = MI.getOperand(1).getReg();
5117 LLT DstTy = MRI.getType(Dst);
5118 unsigned Opc = MI.getOpcode();
5119
5121 return false;
5122
5123 if (DstTy.isScalableVector())
5124 return false;
5125
5126 if (DstTy.isFixedVector()) {
5128 if (!BV)
5129 return false;
5130 SmallVector<APInt> Csts;
5131 for (unsigned I = 0, E = BV->getNumSources(); I != E; ++I) {
5132 auto MaybeCst = ConstantFoldCastOp(Opc, DstTy, BV->getSourceReg(I), MRI);
5133 if (!MaybeCst)
5134 return false;
5135 Csts.push_back(*MaybeCst);
5136 }
5137 MatchInfo = [Dst, Csts = std::move(Csts)](MachineIRBuilder &B) {
5138 B.buildBuildVectorConstant(Dst, Csts);
5139 };
5140 return true;
5141 }
5142
5143 if (auto MaybeCst = ConstantFoldCastOp(Opc, DstTy, SrcOp, MRI)) {
5144 MatchInfo = [Dst, Cst = *MaybeCst](MachineIRBuilder &B) {
5145 B.buildConstant(Dst, Cst);
5146 };
5147 return true;
5148 }
5149
5150 return false;
5151}
5152
5154 BuildFnTy &MatchInfo) const {
5155 Register Dst = MI.getOperand(0).getReg();
5156 LLT DstTy = MRI.getType(Dst);
5157
5159 MI.getOpcode(), DstTy, MI.getOperand(1).getReg(), MRI);
5160 if (Csts.empty())
5161 return false;
5162
5163 MatchInfo = [Dst, Csts = std::move(Csts)](MachineIRBuilder &B) {
5164 if (Csts.size() == 1)
5165 B.buildConstant(Dst, Csts[0]);
5166 else
5167 B.buildBuildVectorConstant(Dst, Csts);
5168 };
5169 return true;
5170}
5171
5173 BuildFnTy &MatchInfo) const {
5174 Register Dst = MI.getOperand(0).getReg();
5175 Register Op1 = MI.getOperand(1).getReg();
5176 Register Op2 = MI.getOperand(2).getReg();
5177 LLT DstTy = MRI.getType(Dst);
5178
5179 // Scalable and pointer-element vectors have no G_BUILD_VECTOR of
5180 // G_CONSTANT to fold to.
5181 if (DstTy.isScalableVector() ||
5182 (DstTy.isVector() && DstTy.getElementType().isPointer()))
5183 return false;
5184
5185 if (DstTy.isFixedVector()) {
5186 SmallVector<APInt> Csts =
5187 ConstantFoldVectorBinop(MI.getOpcode(), Op1, Op2, MRI);
5188 if (Csts.empty())
5189 return false;
5190 MatchInfo = [Dst, Csts = std::move(Csts)](MachineIRBuilder &B) {
5191 B.buildBuildVectorConstant(Dst, Csts);
5192 };
5193 return true;
5194 }
5195
5196 auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
5197 if (!MaybeCst)
5198 return false;
5199 MatchInfo = [Dst, Cst = *MaybeCst](MachineIRBuilder &B) {
5200 B.buildConstant(Dst, Cst);
5201 };
5202 return true;
5203}
5204
5205// Vector FP constant folding assumes IEEE denormal arithmetic. Flush-to-zero
5206// and dynamic modes can produce a different value, so skip those folds.
5207// Targets such as RISC-V represent FP values as untyped scalars
5208// (s16/s32/s64/s128). getFltSemanticForLLT maps those onto the IEEE formats.
5209//
5210// TODO: Honor non-IEEE and dynamic denormal modes instead of skipping the
5211// vector folds. Scalar folds have the same limitation and stay unchanged here.
5213 LLT ScalarTy = Ty.getScalarType();
5214 if (!ScalarTy.isFloat() && !ScalarTy.isAnyScalar())
5215 return true;
5216 return MF.getDenormalMode(getFltSemanticForLLT(ScalarTy)) ==
5218}
5219
5221 BuildFnTy &MatchInfo) const {
5222 Register Dst = MI.getOperand(0).getReg();
5223 Register Op1 = MI.getOperand(1).getReg();
5224 Register Op2 = MI.getOperand(2).getReg();
5225 LLT DstTy = MRI.getType(Dst);
5226
5227 if (DstTy.isScalableVector())
5228 return false;
5229
5230 if (DstTy.isFixedVector()) {
5232 return false;
5234 ConstantFoldVectorFPBinop(MI.getOpcode(), Op1, Op2, MRI);
5235 if (Csts.empty())
5236 return false;
5237 MatchInfo = [Dst, Csts = std::move(Csts)](MachineIRBuilder &B) {
5238 B.buildBuildVectorFConstant(Dst, Csts);
5239 };
5240 return true;
5241 }
5242
5243 auto MaybeCst = ConstantFoldFPBinOp(MI.getOpcode(), Op1, Op2, MRI);
5244 if (!MaybeCst)
5245 return false;
5246 MatchInfo = [Dst, Cst = *MaybeCst](MachineIRBuilder &B) {
5247 B.buildFConstant(Dst, Cst);
5248 };
5249 return true;
5250}
5251
5253 BuildFnTy &MatchInfo) const {
5254 Register Dst = MI.getOperand(0).getReg();
5255 Register Src = MI.getOperand(1).getReg();
5256 LLT DstTy = MRI.getType(Dst);
5257 LLT SrcTy = MRI.getType(Src);
5258
5260 return false;
5261
5262 // Source and destination element types can differ (G_FPEXT/G_FPTRUNC) and
5263 // can have different denormal modes.
5264 if (SrcTy.isVector() &&
5267 return false;
5268
5270 ConstantFoldUnaryFPOp(MI.getOpcode(), DstTy, Src, MRI);
5271 if (Csts.empty())
5272 return false;
5273 MatchInfo = [Dst, Csts = std::move(Csts)](MachineIRBuilder &B) {
5274 if (Csts.size() == 1)
5275 B.buildFConstant(Dst, Csts[0]);
5276 else
5277 B.buildBuildVectorFConstant(Dst, Csts);
5278 };
5279 return true;
5280}
5281
5283 BuildFnTy &MatchInfo) const {
5284 assert(MI.getOpcode() == TargetOpcode::G_FMA ||
5285 MI.getOpcode() == TargetOpcode::G_FMAD);
5286 Register Dst = MI.getOperand(0).getReg();
5287 auto [_, Op1, Op2, Op3] = MI.getFirst4Regs();
5288 LLT DstTy = MRI.getType(Dst);
5289
5290 auto FoldFMA = [](const APFloat &A, const APFloat &B,
5291 const APFloat &C) -> APFloat {
5292 APFloat Res(A);
5294 return Res;
5295 };
5296
5297 if (DstTy.isScalableVector())
5298 return false;
5299
5300 if (DstTy.isFixedVector()) {
5302 return false;
5303 auto *BV1 = getOpcodeDef<GBuildVector>(Op1, MRI);
5304 auto *BV2 = getOpcodeDef<GBuildVector>(Op2, MRI);
5305 auto *BV3 = getOpcodeDef<GBuildVector>(Op3, MRI);
5306 if (!BV1 || !BV2 || !BV3)
5307 return false;
5308 unsigned NumElts = BV1->getNumSources();
5309 if (BV2->getNumSources() != NumElts || BV3->getNumSources() != NumElts)
5310 return false;
5312 for (unsigned I = 0; I != NumElts; ++I) {
5313 const ConstantFP *C1 = getConstantFPVRegVal(BV1->getSourceReg(I), MRI);
5314 const ConstantFP *C2 = getConstantFPVRegVal(BV2->getSourceReg(I), MRI);
5315 const ConstantFP *C3 = getConstantFPVRegVal(BV3->getSourceReg(I), MRI);
5316 if (!C1 || !C2 || !C3)
5317 return false;
5318 Csts.push_back(
5319 FoldFMA(C1->getValueAPF(), C2->getValueAPF(), C3->getValueAPF()));
5320 }
5321 MatchInfo = [Dst, Csts = std::move(Csts)](MachineIRBuilder &B) {
5322 B.buildBuildVectorFConstant(Dst, Csts);
5323 };
5324 return true;
5325 }
5326
5327 const ConstantFP *Op3Cst = getConstantFPVRegVal(Op3, MRI);
5328 const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
5329 const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
5330 if (!Op1Cst || !Op2Cst || !Op3Cst)
5331 return false;
5332
5333 APFloat Res = FoldFMA(Op1Cst->getValueAPF(), Op2Cst->getValueAPF(),
5334 Op3Cst->getValueAPF());
5335 MatchInfo = [Dst, Res](MachineIRBuilder &B) { B.buildFConstant(Dst, Res); };
5336 return true;
5337}
5338
5341 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
5342 // Look for a binop feeding into an AND with a mask:
5343 //
5344 // %add = G_ADD %lhs, %rhs
5345 // %and = G_AND %add, 000...11111111
5346 //
5347 // Check if it's possible to perform the binop at a narrower width and zext
5348 // back to the original width like so:
5349 //
5350 // %narrow_lhs = G_TRUNC %lhs
5351 // %narrow_rhs = G_TRUNC %rhs
5352 // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
5353 // %new_add = G_ZEXT %narrow_add
5354 // %and = G_AND %new_add, 000...11111111
5355 //
5356 // This can allow later combines to eliminate the G_AND if it turns out
5357 // that the mask is irrelevant.
5358 assert(MI.getOpcode() == TargetOpcode::G_AND);
5359 Register Dst = MI.getOperand(0).getReg();
5360 Register AndLHS = MI.getOperand(1).getReg();
5361 Register AndRHS = MI.getOperand(2).getReg();
5362 LLT WideTy = MRI.getType(Dst);
5363
5364 // If the potential binop has more than one use, then it's possible that one
5365 // of those uses will need its full width.
5366 if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
5367 return false;
5368
5369 // Check if the LHS feeding the AND is impacted by the high bits that we're
5370 // masking out.
5371 //
5372 // e.g. for 64-bit x, y:
5373 //
5374 // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
5375 MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
5376 if (!LHSInst)
5377 return false;
5378 unsigned LHSOpc = LHSInst->getOpcode();
5379 switch (LHSOpc) {
5380 default:
5381 return false;
5382 case TargetOpcode::G_ADD:
5383 case TargetOpcode::G_SUB:
5384 case TargetOpcode::G_MUL:
5385 case TargetOpcode::G_AND:
5386 case TargetOpcode::G_OR:
5387 case TargetOpcode::G_XOR:
5388 break;
5389 }
5390
5391 // Find the mask on the RHS.
5392 auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
5393 if (!Cst)
5394 return false;
5395 auto Mask = Cst->Value;
5396 if (!Mask.isMask())
5397 return false;
5398
5399 // No point in combining if there's nothing to truncate.
5400 unsigned NarrowWidth = Mask.countr_one();
5401 if (NarrowWidth == WideTy.getSizeInBits())
5402 return false;
5403 LLT NarrowTy = LLT::integer(NarrowWidth);
5404
5405 // Check if adding the zext + truncates could be harmful.
5406 auto &MF = *MI.getMF();
5407 const auto &TLI = getTargetLowering();
5408 LLVMContext &Ctx = MF.getFunction().getContext();
5409 if (!TLI.isTruncateFree(WideTy, NarrowTy, Ctx) ||
5410 !TLI.isZExtFree(NarrowTy, WideTy, Ctx))
5411 return false;
5412 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
5413 !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
5414 return false;
5415 Register BinOpLHS = LHSInst->getOperand(1).getReg();
5416 Register BinOpRHS = LHSInst->getOperand(2).getReg();
5417 MatchInfo = [=, &MI](MachineIRBuilder &B) {
5418 auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
5419 auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
5420 auto NarrowBinOp =
5421 Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
5422 auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
5423 Observer.changingInstr(MI);
5424 MI.getOperand(1).setReg(Ext.getReg(0));
5425 Observer.changedInstr(MI);
5426 };
5427 return true;
5428}
5429
5431 BuildFnTy &MatchInfo) const {
5432 // (G_*MULO x, 0) -> 0 + no carry out
5433 assert(MI.getOpcode() == TargetOpcode::G_UMULO ||
5434 MI.getOpcode() == TargetOpcode::G_SMULO);
5435 if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
5436 return false;
5437 Register Dst = MI.getOperand(0).getReg();
5438 Register Carry = MI.getOperand(1).getReg();
5439 if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Dst)) ||
5440 !isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
5441 return false;
5442 MatchInfo = [=](MachineIRBuilder &B) {
5443 B.buildConstant(Dst, 0);
5444 B.buildConstant(Carry, 0);
5445 };
5446 return true;
5447}
5448
5452 if (SrcA.isValid() && SrcA == SrcB)
5453 return true;
5454 int64_t Cst;
5455 return mi_match(A, MRI, m_ICstOrSplat(Cst)) &&
5457}
5458
5460 unsigned Opcode = MI.getOpcode();
5461 assert(Opcode == TargetOpcode::G_UDIV || Opcode == TargetOpcode::G_UREM);
5462 auto &UDivorRem = cast<GenericMachineInstr>(MI);
5463 Register Dst = UDivorRem.getReg(0);
5464 Register LHS = UDivorRem.getReg(1);
5465 Register RHS = UDivorRem.getReg(2);
5466 LLT Ty = MRI.getType(Dst);
5467 LLT ScalarTy = Ty.getScalarType();
5468 const unsigned EltBits = ScalarTy.getScalarSizeInBits();
5470 LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
5471
5472 auto &MIB = Builder;
5473
5474 bool UseSRL = false;
5475 SmallVector<Register, 16> Shifts, Factors;
5476 auto *RHSDefInstr = cast<GenericMachineInstr>(getDefIgnoringCopies(RHS, MRI));
5477 bool IsSplat = getIConstantSplatVal(*RHSDefInstr, MRI).has_value();
5478
5479 auto BuildExactUDIVPattern = [&](const Constant *C) {
5480 // Don't recompute inverses for each splat element.
5481 if (IsSplat && !Factors.empty()) {
5482 Shifts.push_back(Shifts[0]);
5483 Factors.push_back(Factors[0]);
5484 return true;
5485 }
5486
5487 auto *CI = cast<ConstantInt>(C);
5488 APInt Divisor = CI->getValue();
5489 unsigned Shift = Divisor.countr_zero();
5490 if (Shift) {
5491 Divisor.lshrInPlace(Shift);
5492 UseSRL = true;
5493 }
5494
5495 // Calculate the multiplicative inverse modulo BW.
5496 APInt Factor = Divisor.multiplicativeInverse();
5497 Shifts.push_back(MIB.buildConstant(ScalarShiftAmtTy, Shift).getReg(0));
5498 Factors.push_back(MIB.buildConstant(ScalarTy, Factor).getReg(0));
5499 return true;
5500 };
5501
5502 if (MI.getFlag(MachineInstr::MIFlag::IsExact)) {
5503 // Collect all magic values from the build vector.
5504 if (!matchUnaryPredicate(MRI, RHS, BuildExactUDIVPattern))
5505 llvm_unreachable("Expected unary predicate match to succeed");
5506
5507 Register Shift, Factor;
5508 if (Ty.isVector()) {
5509 Shift = MIB.buildBuildVector(ShiftAmtTy, Shifts).getReg(0);
5510 Factor = MIB.buildBuildVector(Ty, Factors).getReg(0);
5511 } else {
5512 Shift = Shifts[0];
5513 Factor = Factors[0];
5514 }
5515
5516 Register Res = LHS;
5517
5518 if (UseSRL)
5519 Res = MIB.buildLShr(Ty, Res, Shift, MachineInstr::IsExact).getReg(0);
5520
5521 return MIB.buildMul(Ty, Res, Factor);
5522 }
5523
5524 unsigned KnownLeadingZeros =
5525 VT ? VT->getKnownBits(LHS).countMinLeadingZeros() : 0;
5526
5527 // Allow scalars to be widened to twice their size for divisors whose magic
5528 // number needs one more bit, if G_UMULH is legal for the wider type, as
5529 // SelectionDAG does. For even divisors, only do it if the zero-extension is
5530 // free.
5531 LLT WideTy = Ty.changeElementSize(EltBits * 2);
5532 LLVMContext &Ctx = MI.getMF()->getFunction().getContext();
5533 const bool AllowWiden =
5534 Ty.isScalar() && isLegal({TargetOpcode::G_UMULH, {WideTy}});
5535 const bool AllowEvenToWiden =
5536 AllowWiden && getTargetLowering().isZExtFree(Ty, WideTy, Ctx);
5537 bool UseWiden = false;
5538 APInt WideMagic;
5539
5540 bool UseNPQ = false;
5541 SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5542 auto BuildUDIVPattern = [&](const Constant *C) {
5543 auto *CI = cast<ConstantInt>(C);
5544 const APInt &Divisor = CI->getValue();
5545
5546 bool SelNPQ = false;
5547 APInt Magic(Divisor.getBitWidth(), 0);
5548 unsigned PreShift = 0, PostShift = 0;
5549
5550 // Magic algorithm doesn't work for division by 1. We need to emit a select
5551 // at the end.
5552 // TODO: Use undef values for divisor of 1.
5553 if (!Divisor.isOne()) {
5554
5555 // UnsignedDivisionByConstantInfo doesn't work correctly if leading zeros
5556 // in the dividend exceeds the leading zeros for the divisor.
5559 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
5560 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
5561 /*AllowWidenOptimization=*/AllowWiden);
5562
5563 // The widened magic number has the shift folded in, so the quotient is
5564 // just the high half of the 64-bit product.
5565 if (magics.Widen) {
5566 UseWiden = true;
5567 WideMagic = magics.Magic;
5568 return true;
5569 }
5570
5571 Magic = std::move(magics.Magic);
5572
5573 assert(magics.PreShift < Divisor.getBitWidth() &&
5574 "We shouldn't generate an undefined shift!");
5575 assert(magics.PostShift < Divisor.getBitWidth() &&
5576 "We shouldn't generate an undefined shift!");
5577 assert((!magics.IsAdd || magics.PreShift == 0) && "Unexpected pre-shift");
5578 PreShift = magics.PreShift;
5579 PostShift = magics.PostShift;
5580 SelNPQ = magics.IsAdd;
5581 }
5582
5583 PreShifts.push_back(
5584 MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
5585 MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
5586 NPQFactors.push_back(
5587 MIB.buildConstant(ScalarTy,
5588 SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5589 : APInt::getZero(EltBits))
5590 .getReg(0));
5591 PostShifts.push_back(
5592 MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
5593 UseNPQ |= SelNPQ;
5594 return true;
5595 };
5596
5597 // Collect the shifts/magic values from each element.
5598 bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
5599 (void)Matched;
5600 assert(Matched && "Expected unary predicate match to succeed");
5601
5602 if (UseWiden) {
5603 // Compute (s64(x) * WideMagic) >> 64, and truncate it back to s32.
5604 auto WideX = MIB.buildZExt(WideTy, LHS);
5605 auto High =
5606 MIB.buildUMulH(WideTy, WideX, MIB.buildConstant(WideTy, WideMagic));
5607 auto Quotient = MIB.buildTrunc(Ty, High);
5608 if (Opcode == TargetOpcode::G_UREM) {
5609 auto Prod = MIB.buildMul(Ty, Quotient, RHS);
5610 return MIB.buildSub(Ty, LHS, Prod);
5611 }
5612 return Quotient;
5613 }
5614
5615 Register PreShift, PostShift, MagicFactor, NPQFactor;
5616 auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
5617 if (RHSDef) {
5618 PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
5619 MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
5620 NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
5621 PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
5622 } else {
5623 assert(MRI.getType(RHS).isScalar() &&
5624 "Non-build_vector operation should have been a scalar");
5625 PreShift = PreShifts[0];
5626 MagicFactor = MagicFactors[0];
5627 PostShift = PostShifts[0];
5628 }
5629
5630 Register Q = LHS;
5631 Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
5632
5633 // Multiply the numerator (operand 0) by the magic value.
5634 Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
5635
5636 if (UseNPQ) {
5637 Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
5638
5639 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5640 // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
5641 if (Ty.isVector())
5642 NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
5643 else
5644 NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
5645
5646 Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
5647 }
5648
5649 Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
5650 auto One = MIB.buildConstant(Ty, 1);
5651 auto IsOne = MIB.buildICmp(
5653 Ty.isScalar() ? LLT::integer(1) : Ty.changeElementType(LLT::integer(1)),
5654 RHS, One);
5655 auto ret = MIB.buildSelect(Ty, IsOne, LHS, Q);
5656
5657 if (Opcode == TargetOpcode::G_UREM) {
5658 auto Prod = MIB.buildMul(Ty, ret, RHS);
5659 return MIB.buildSub(Ty, LHS, Prod);
5660 }
5661 return ret;
5662}
5663
5665 unsigned Opcode = MI.getOpcode();
5666 assert(Opcode == TargetOpcode::G_UDIV || Opcode == TargetOpcode::G_UREM);
5667 Register Dst = MI.getOperand(0).getReg();
5668 Register RHS = MI.getOperand(2).getReg();
5669 LLT DstTy = MRI.getType(Dst);
5670
5671 auto &MF = *MI.getMF();
5672 AttributeList Attr = MF.getFunction().getAttributes();
5673 const auto &TLI = getTargetLowering();
5674 LLVMContext &Ctx = MF.getFunction().getContext();
5675 if (DstTy.getScalarSizeInBits() == 1 ||
5676 TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, Ctx), Attr))
5677 return false;
5678
5679 // Don't do this for minsize because the instruction sequence is usually
5680 // larger.
5681 if (MF.getFunction().hasMinSize())
5682 return false;
5683
5684 if (Opcode == TargetOpcode::G_UDIV &&
5686 return matchUnaryPredicate(
5687 MRI, RHS, [](const Constant *C) { return C && !C->isNullValue(); });
5688 }
5689
5690 MachineInstr *RHSDef;
5691 if (!mi_match(RHS, MRI, m_MInstr(RHSDef)) ||
5693 return false;
5694
5695 // Don't do this if the types are not going to be legal.
5696 if (LI) {
5697 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
5698 return false;
5699 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
5700 return false;
5702 {TargetOpcode::G_ICMP,
5703 {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
5704 DstTy}}))
5705 return false;
5706 if (Opcode == TargetOpcode::G_UREM &&
5707 !isLegalOrBeforeLegalizer({TargetOpcode::G_SUB, {DstTy, DstTy}}))
5708 return false;
5709 }
5710
5711 return matchUnaryPredicate(
5712 MRI, RHS, [](const Constant *C) { return C && !C->isNullValue(); });
5713}
5714
5716 auto *NewMI = buildUDivOrURemUsingMul(MI);
5717 replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
5718}
5719
5721 unsigned Opcode = MI.getOpcode();
5722 assert(Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM);
5723 Register Dst = MI.getOperand(0).getReg();
5724 Register RHS = MI.getOperand(2).getReg();
5725 LLT DstTy = MRI.getType(Dst);
5726 auto SizeInBits = DstTy.getScalarSizeInBits();
5727 LLT WideTy = DstTy.changeElementSize(SizeInBits * 2);
5728
5729 auto &MF = *MI.getMF();
5730 AttributeList Attr = MF.getFunction().getAttributes();
5731 const auto &TLI = getTargetLowering();
5732 LLVMContext &Ctx = MF.getFunction().getContext();
5733 if (DstTy.getScalarSizeInBits() < 3 ||
5734 TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, Ctx), Attr))
5735 return false;
5736
5737 // Don't do this for minsize because the instruction sequence is usually
5738 // larger.
5739 if (MF.getFunction().hasMinSize())
5740 return false;
5741
5742 // If the sdiv has an 'exact' flag we can use a simpler lowering.
5743 if (Opcode == TargetOpcode::G_SDIV &&
5745 return matchUnaryPredicate(
5746 MRI, RHS, [](const Constant *C) { return C && !C->isNullValue(); });
5747 }
5748
5749 MachineInstr *RHSDef;
5750 if (!mi_match(RHS, MRI, m_MInstr(RHSDef)) ||
5752 return false;
5753
5754 // Don't do this if the types are not going to be legal.
5755 if (LI) {
5756 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
5757 return false;
5758 if (isPreLegalize()) {
5759 // The legalizer can still split a vector G_SMULH or lower it through a
5760 // wider G_MUL.
5761 if (!isLegalOrHasFewerElements({TargetOpcode::G_SMULH, {DstTy}}) &&
5762 !isLegalOrHasWidenScalar({TargetOpcode::G_MUL, {WideTy, WideTy}}))
5763 return false;
5764 } else if (!isLegal({TargetOpcode::G_SMULH, {DstTy}})) {
5765 // After legalization nothing will fix up an illegal G_SMULH.
5766 return false;
5767 }
5768 if (Opcode == TargetOpcode::G_SREM &&
5769 !isLegalOrBeforeLegalizer({TargetOpcode::G_SUB, {DstTy, DstTy}}))
5770 return false;
5771 }
5772
5773 return matchUnaryPredicate(
5774 MRI, RHS, [](const Constant *C) { return C && !C->isNullValue(); });
5775}
5776
5778 auto *NewMI = buildSDivOrSRemUsingMul(MI);
5779 replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
5780}
5781
5783 unsigned Opcode = MI.getOpcode();
5784 assert(MI.getOpcode() == TargetOpcode::G_SDIV ||
5785 Opcode == TargetOpcode::G_SREM);
5786 auto &SDivorRem = cast<GenericMachineInstr>(MI);
5787 Register Dst = SDivorRem.getReg(0);
5788 Register LHS = SDivorRem.getReg(1);
5789 Register RHS = SDivorRem.getReg(2);
5790 LLT Ty = MRI.getType(Dst);
5791 LLT ScalarTy = Ty.getScalarType();
5792 const unsigned EltBits = ScalarTy.getScalarSizeInBits();
5794 LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
5795 auto &MIB = Builder;
5796
5797 bool UseSRA = false;
5798 SmallVector<Register, 16> ExactShifts, ExactFactors;
5799
5800 auto *RHSDefInstr = cast<GenericMachineInstr>(getDefIgnoringCopies(RHS, MRI));
5801 bool IsSplat = getIConstantSplatVal(*RHSDefInstr, MRI).has_value();
5802
5803 auto BuildExactSDIVPattern = [&](const Constant *C) {
5804 // Don't recompute inverses for each splat element.
5805 if (IsSplat && !ExactFactors.empty()) {
5806 ExactShifts.push_back(ExactShifts[0]);
5807 ExactFactors.push_back(ExactFactors[0]);
5808 return true;
5809 }
5810
5811 auto *CI = cast<ConstantInt>(C);
5812 APInt Divisor = CI->getValue();
5813 unsigned Shift = Divisor.countr_zero();
5814 if (Shift) {
5815 Divisor.ashrInPlace(Shift);
5816 UseSRA = true;
5817 }
5818
5819 // Calculate the multiplicative inverse modulo BW.
5820 // 2^W requires W + 1 bits, so we have to extend and then truncate.
5821 APInt Factor = Divisor.multiplicativeInverse();
5822 ExactShifts.push_back(MIB.buildConstant(ScalarShiftAmtTy, Shift).getReg(0));
5823 ExactFactors.push_back(MIB.buildConstant(ScalarTy, Factor).getReg(0));
5824 return true;
5825 };
5826
5827 if (MI.getFlag(MachineInstr::MIFlag::IsExact)) {
5828 // Collect all magic values from the build vector.
5829 bool Matched = matchUnaryPredicate(MRI, RHS, BuildExactSDIVPattern);
5830 (void)Matched;
5831 assert(Matched && "Expected unary predicate match to succeed");
5832
5833 Register Shift, Factor;
5834 if (Ty.isVector()) {
5835 Shift = MIB.buildBuildVector(ShiftAmtTy, ExactShifts).getReg(0);
5836 Factor = MIB.buildBuildVector(Ty, ExactFactors).getReg(0);
5837 } else {
5838 Shift = ExactShifts[0];
5839 Factor = ExactFactors[0];
5840 }
5841
5842 Register Res = LHS;
5843
5844 if (UseSRA)
5845 Res = MIB.buildAShr(Ty, Res, Shift, MachineInstr::IsExact).getReg(0);
5846
5847 return MIB.buildMul(Ty, Res, Factor);
5848 }
5849
5850 SmallVector<Register, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5851
5852 auto BuildSDIVPattern = [&](const Constant *C) {
5853 auto *CI = cast<ConstantInt>(C);
5854 const APInt &Divisor = CI->getValue();
5855
5858 int NumeratorFactor = 0;
5859 int ShiftMask = -1;
5860
5861 if (Divisor.isOne() || Divisor.isAllOnes()) {
5862 // If d is +1/-1, we just multiply the numerator by +1/-1.
5863 NumeratorFactor = Divisor.getSExtValue();
5864 Magics.Magic = 0;
5865 Magics.ShiftAmount = 0;
5866 ShiftMask = 0;
5867 } else if (Divisor.isStrictlyPositive() && Magics.Magic.isNegative()) {
5868 // If d > 0 and m < 0, add the numerator.
5869 NumeratorFactor = 1;
5870 } else if (Divisor.isNegative() && Magics.Magic.isStrictlyPositive()) {
5871 // If d < 0 and m > 0, subtract the numerator.
5872 NumeratorFactor = -1;
5873 }
5874
5875 MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magics.Magic).getReg(0));
5876 Factors.push_back(MIB.buildConstant(ScalarTy, NumeratorFactor).getReg(0));
5877 Shifts.push_back(
5878 MIB.buildConstant(ScalarShiftAmtTy, Magics.ShiftAmount).getReg(0));
5879 ShiftMasks.push_back(MIB.buildConstant(ScalarTy, ShiftMask).getReg(0));
5880
5881 return true;
5882 };
5883
5884 // Collect the shifts/magic values from each element.
5885 bool Matched = matchUnaryPredicate(MRI, RHS, BuildSDIVPattern);
5886 (void)Matched;
5887 assert(Matched && "Expected unary predicate match to succeed");
5888
5889 Register MagicFactor, Factor, Shift, ShiftMask;
5890 auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
5891 if (RHSDef) {
5892 MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
5893 Factor = MIB.buildBuildVector(Ty, Factors).getReg(0);
5894 Shift = MIB.buildBuildVector(ShiftAmtTy, Shifts).getReg(0);
5895 ShiftMask = MIB.buildBuildVector(Ty, ShiftMasks).getReg(0);
5896 } else {
5897 assert(MRI.getType(RHS).isScalar() &&
5898 "Non-build_vector operation should have been a scalar");
5899 MagicFactor = MagicFactors[0];
5900 Factor = Factors[0];
5901 Shift = Shifts[0];
5902 ShiftMask = ShiftMasks[0];
5903 }
5904
5905 Register Q = LHS;
5906 Q = MIB.buildSMulH(Ty, LHS, MagicFactor).getReg(0);
5907
5908 // (Optionally) Add/subtract the numerator using Factor.
5909 Factor = MIB.buildMul(Ty, LHS, Factor).getReg(0);
5910 Q = MIB.buildAdd(Ty, Q, Factor).getReg(0);
5911
5912 // Shift right algebraic by shift value.
5913 Q = MIB.buildAShr(Ty, Q, Shift).getReg(0);
5914
5915 // Extract the sign bit, mask it and add it to the quotient.
5916 auto SignShift = MIB.buildConstant(ShiftAmtTy, EltBits - 1);
5917 auto T = MIB.buildLShr(Ty, Q, SignShift);
5918 T = MIB.buildAnd(Ty, T, ShiftMask);
5919 auto ret = MIB.buildAdd(Ty, Q, T);
5920
5921 if (Opcode == TargetOpcode::G_SREM) {
5922 auto Prod = MIB.buildMul(Ty, ret, RHS);
5923 return MIB.buildSub(Ty, LHS, Prod);
5924 }
5925 return ret;
5926}
5927
5929 assert((MI.getOpcode() == TargetOpcode::G_SDIV ||
5930 MI.getOpcode() == TargetOpcode::G_UDIV) &&
5931 "Expected SDIV or UDIV");
5933 Register RHS = Div.getReg(2);
5934 auto MatchPow2 = [&](const Constant *C) {
5935 auto *CI = dyn_cast<ConstantInt>(C);
5936 return CI && (CI->getValue().isPowerOf2() ||
5937 (IsSigned && CI->getValue().isNegatedPowerOf2()));
5938 };
5939 return matchUnaryPredicate(MRI, RHS, MatchPow2, /*AllowUndefs=*/false);
5940}
5941
5943 assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
5944 auto &SDiv = cast<GenericMachineInstr>(MI);
5945 Register Dst = SDiv.getReg(0);
5946 Register LHS = SDiv.getReg(1);
5947 Register RHS = SDiv.getReg(2);
5948 LLT Ty = MRI.getType(Dst);
5950 LLT CCVT = Ty.isVector() ? LLT::vector(Ty.getElementCount(), LLT::integer(1))
5951 : LLT::integer(1);
5952
5953 // Effectively we want to lower G_SDIV %lhs, %rhs, where %rhs is a power of 2,
5954 // to the following version:
5955 //
5956 // %c1 = G_CTTZ %rhs
5957 // %inexact = G_SUB $bitwidth, %c1
5958 // %sign = %G_ASHR %lhs, $(bitwidth - 1)
5959 // %lshr = G_LSHR %sign, %inexact
5960 // %add = G_ADD %lhs, %lshr
5961 // %ashr = G_ASHR %add, %c1
5962 // %ashr = G_SELECT, %isoneorallones, %lhs, %ashr
5963 // %zero = G_CONSTANT $0
5964 // %neg = G_NEG %ashr
5965 // %isneg = G_ICMP SLT %rhs, %zero
5966 // %res = G_SELECT %isneg, %neg, %ashr
5967
5968 unsigned BitWidth = Ty.getScalarSizeInBits();
5969 auto Zero = Builder.buildConstant(Ty, 0);
5970
5971 auto Bits = Builder.buildConstant(ShiftAmtTy, BitWidth);
5972 auto C1 = Builder.buildCTTZ(ShiftAmtTy, RHS);
5973 auto Inexact = Builder.buildSub(ShiftAmtTy, Bits, C1);
5974 // Splat the sign bit into the register
5975 auto Sign = Builder.buildAShr(
5976 Ty, LHS, Builder.buildConstant(ShiftAmtTy, BitWidth - 1));
5977
5978 // Add (LHS < 0) ? abs2 - 1 : 0;
5979 auto LSrl = Builder.buildLShr(Ty, Sign, Inexact);
5980 auto Add = Builder.buildAdd(Ty, LHS, LSrl);
5981 auto AShr = Builder.buildAShr(Ty, Add, C1);
5982
5983 // Special case: (sdiv X, 1) -> X
5984 // Special Case: (sdiv X, -1) -> 0-X
5985 auto One = Builder.buildConstant(Ty, 1);
5986 auto MinusOne = Builder.buildConstant(Ty, -1);
5987 auto IsOne = Builder.buildICmp(CmpInst::Predicate::ICMP_EQ, CCVT, RHS, One);
5988 auto IsMinusOne =
5989 Builder.buildICmp(CmpInst::Predicate::ICMP_EQ, CCVT, RHS, MinusOne);
5990 auto IsOneOrMinusOne = Builder.buildOr(CCVT, IsOne, IsMinusOne);
5991 AShr = Builder.buildSelect(Ty, IsOneOrMinusOne, LHS, AShr);
5992
5993 // If divided by a positive value, we're done. Otherwise, the result must be
5994 // negated.
5995 auto Neg = Builder.buildNeg(Ty, AShr);
5996 auto IsNeg = Builder.buildICmp(CmpInst::Predicate::ICMP_SLT, CCVT, RHS, Zero);
5997 Builder.buildSelect(MI.getOperand(0).getReg(), IsNeg, Neg, AShr);
5998 MI.eraseFromParent();
5999}
6000
6002 assert(MI.getOpcode() == TargetOpcode::G_UDIV && "Expected UDIV");
6003 auto &UDiv = cast<GenericMachineInstr>(MI);
6004 Register Dst = UDiv.getReg(0);
6005 Register LHS = UDiv.getReg(1);
6006 Register RHS = UDiv.getReg(2);
6007 LLT Ty = MRI.getType(Dst);
6009
6010 auto C1 = Builder.buildCTTZ(ShiftAmtTy, RHS);
6011 Builder.buildLShr(MI.getOperand(0).getReg(), LHS, C1);
6012 MI.eraseFromParent();
6013}
6014
6016 BuildFnTy &MatchInfo) const {
6017 Register Dst = MI.getOperand(0).getReg();
6018 Register LHS = MI.getOperand(1).getReg();
6019 Register RHS = MI.getOperand(2).getReg();
6020 Register Base, Shift;
6021 if (!mi_match(RHS, MRI, m_GShl(m_Reg(Base), m_Reg(Shift))))
6022 return false;
6023
6024 if (!matchUnaryPredicate(MRI, Base, [](const Constant *C) {
6026 return CI && CI->getValue().isPowerOf2();
6027 }))
6028 return false;
6029
6030 LLT Ty = MRI.getType(Dst);
6031 LLT ShiftTy = MRI.getType(Shift);
6032 // The shift type must be able to represent every valid shift amount.
6033 if (ShiftTy.getScalarSizeInBits() < Log2_64_Ceil(Ty.getScalarSizeInBits()))
6034 return false;
6035 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_CTTZ, {ShiftTy, Ty}}) ||
6036 !isLegalOrBeforeLegalizer({TargetOpcode::G_ADD, {ShiftTy, ShiftTy}}) ||
6037 !isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftTy}}))
6038 return false;
6039
6040 unsigned Flags =
6042 MatchInfo = [=](MachineIRBuilder &B) {
6043 auto Log2 = B.buildCTTZ(ShiftTy, Base);
6044 auto Amount = B.buildAdd(ShiftTy, Shift, Log2);
6045 B.buildLShr(Dst, LHS, Amount, Flags);
6046 };
6047 return true;
6048}
6049
6051 MachineInstr &MI, unsigned UnsignedOpcode) const {
6052 Register Dst = MI.getOperand(0).getReg();
6053 Register LHS = MI.getOperand(1).getReg();
6054 Register RHS = MI.getOperand(2).getReg();
6055 if (!VT || !VT->signBitIsZero(LHS) || !VT->signBitIsZero(RHS))
6056 return false;
6057
6058 LLT Ty = MRI.getType(Dst);
6059 return isLegalOrBeforeLegalizer({UnsignedOpcode, {Ty}});
6060}
6061
6063 assert(MI.getOpcode() == TargetOpcode::G_SREM && "Expected SREM");
6064 auto &SRem = cast<GBinOp>(MI);
6065 Register Dst = SRem.getReg(0);
6066 Register LHS = SRem.getLHSReg();
6067 Register RHS = SRem.getRHSReg();
6068 LLT Ty = MRI.getType(Dst);
6070
6071 // Effectively we want to lower G_SREM %lhs, %rhs, where %rhs is +/- a power
6072 // of 2, to the following branch-free bias-and-mask version:
6073 //
6074 // %abs = G_ABS %rhs
6075 // %mask = G_SUB %abs, 1
6076 // %sign = G_ASHR %lhs, $(bitwidth - 1)
6077 // %bias = G_AND %sign, %mask
6078 // %biased = G_ADD %lhs, %bias
6079 // %masked = G_AND %biased, %mask
6080 // %res = G_SUB %masked, %bias
6081 //
6082 // The bias adds (|%rhs| - 1) for negative %lhs, correcting rounding towards
6083 // zero (instead of towards -inf that a plain mask would give). Constant
6084 // divisors collapse %mask to a single G_CONSTANT via the CSEMIRBuilder folds
6085 // for G_ABS and G_SUB.
6086
6087 unsigned BitWidth = Ty.getScalarSizeInBits();
6088 auto AbsRHS = Builder.buildAbs(Ty, RHS);
6089 auto Mask = Builder.buildSub(Ty, AbsRHS, Builder.buildConstant(Ty, 1));
6090 auto BWMinusOne = Builder.buildConstant(ShiftAmtTy, BitWidth - 1);
6091 auto Sign = Builder.buildAShr(Ty, LHS, BWMinusOne);
6092 auto Bias = Builder.buildAnd(Ty, Sign, Mask);
6093 auto Biased = Builder.buildAdd(Ty, LHS, Bias);
6094 auto Masked = Builder.buildAnd(Ty, Biased, Mask);
6095 Builder.buildSub(Dst, Masked, Bias);
6096 MI.eraseFromParent();
6097}
6098
6100 assert(MI.getOpcode() == TargetOpcode::G_UMULH);
6101 Register RHS = MI.getOperand(2).getReg();
6102 Register Dst = MI.getOperand(0).getReg();
6103 LLT Ty = MRI.getType(Dst);
6104 LLT RHSTy = MRI.getType(RHS);
6106 auto MatchPow2ExceptOne = [&](const Constant *C) {
6107 if (auto *CI = dyn_cast<ConstantInt>(C))
6108 return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
6109 return false;
6110 };
6111 if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
6112 return false;
6113 // We need to check both G_LSHR and G_CTLZ because the combine uses G_CTLZ to
6114 // get log base 2, and it is not always legal for on a target.
6115 return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}}) &&
6116 isLegalOrBeforeLegalizer({TargetOpcode::G_CTLZ, {RHSTy, RHSTy}});
6117}
6118
6120 Register LHS = MI.getOperand(1).getReg();
6121 Register RHS = MI.getOperand(2).getReg();
6122 Register Dst = MI.getOperand(0).getReg();
6123 LLT Ty = MRI.getType(Dst);
6125 unsigned NumEltBits = Ty.getScalarSizeInBits();
6126
6127 auto LogBase2 = buildLogBase2(RHS, Builder);
6128 auto ShiftAmt =
6129 Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
6130 auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
6131 Builder.buildLShr(Dst, LHS, Trunc);
6132 MI.eraseFromParent();
6133}
6134
6136 Register &MatchInfo) const {
6137 Register Dst = MI.getOperand(0).getReg();
6138 Register Src = MI.getOperand(1).getReg();
6139 LLT DstTy = MRI.getType(Dst);
6140 LLT SrcTy = MRI.getType(Src);
6141 unsigned NumDstBits = DstTy.getScalarSizeInBits();
6142 unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
6143 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
6144
6146 {TargetOpcode::G_TRUNC_SSAT_S, {DstTy, SrcTy}}))
6147 return false;
6148
6149 APInt SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
6150 APInt SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
6151 if (mi_match(
6152 Src, MRI,
6153 m_GSMin(m_GSMax(m_Reg(MatchInfo), m_SpecificICstOrSplat(SignedMin)),
6154 m_SpecificICstOrSplat(SignedMax))))
6155 return true;
6156 if (mi_match(
6157 Src, MRI,
6158 m_GSMax(m_GSMin(m_Reg(MatchInfo), m_SpecificICstOrSplat(SignedMax)),
6159 m_SpecificICstOrSplat(SignedMin))))
6160 return true;
6161
6162 // CVP in the midend will often transform trunc(smin(smax(..)) into
6163 // trunc nsw(smin(..)) as the smax against INT_MIN never saturates.
6164 if (MI.getFlag(MachineInstr::MIFlag::NoSWrap) &&
6165 mi_match(Src, MRI,
6166 m_GSMin(m_Reg(MatchInfo), m_SpecificICstOrSplat(SignedMax))))
6167 return true;
6168
6169 return false;
6170}
6171
6173 Register &MatchInfo) const {
6174 Register Dst = MI.getOperand(0).getReg();
6175 Builder.buildTruncSSatS(Dst, MatchInfo);
6176 MI.eraseFromParent();
6177}
6178
6180 Register &MatchInfo) const {
6181 Register Dst = MI.getOperand(0).getReg();
6182 Register Src = MI.getOperand(1).getReg();
6183 LLT DstTy = MRI.getType(Dst);
6184 LLT SrcTy = MRI.getType(Src);
6185 unsigned NumDstBits = DstTy.getScalarSizeInBits();
6186 unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
6187 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
6188
6190 {TargetOpcode::G_TRUNC_SSAT_U, {DstTy, SrcTy}}))
6191 return false;
6192 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
6193 return mi_match(Src, MRI,
6195 m_SpecificICstOrSplat(UnsignedMax))) ||
6196 mi_match(Src, MRI,
6197 m_GSMax(m_GSMin(m_Reg(MatchInfo),
6198 m_SpecificICstOrSplat(UnsignedMax)),
6199 m_SpecificICstOrSplat(0))) ||
6200 mi_match(Src, MRI,
6202 m_SpecificICstOrSplat(UnsignedMax)));
6203}
6204
6206 Register &MatchInfo) const {
6207 Register Dst = MI.getOperand(0).getReg();
6208 Builder.buildTruncSSatU(Dst, MatchInfo);
6209 MI.eraseFromParent();
6210}
6211
6213 MachineInstr &MinMI) const {
6214 Register Min = MinMI.getOperand(2).getReg();
6215 Register Val = MinMI.getOperand(1).getReg();
6216 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6217 LLT SrcTy = MRI.getType(Val);
6218 unsigned NumDstBits = DstTy.getScalarSizeInBits();
6219 unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
6220 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
6221
6223 {TargetOpcode::G_TRUNC_SSAT_U, {DstTy, SrcTy}}))
6224 return false;
6225 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
6226 return mi_match(Min, MRI, m_SpecificICstOrSplat(UnsignedMax)) &&
6227 !mi_match(Val, MRI, m_GSMax(m_Reg(), m_Reg()));
6228}
6229
6231 MachineInstr &SrcMI) const {
6232 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6233 LLT SrcTy = MRI.getType(SrcMI.getOperand(1).getReg());
6234
6235 return LI &&
6236 isLegalOrBeforeLegalizer({TargetOpcode::G_FPTOUI_SAT, {DstTy, SrcTy}});
6237}
6238
6240 assert(MI.getOpcode() == TargetOpcode::G_FSUB);
6241
6242 Register LHS = MI.getOperand(1).getReg();
6243 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
6244
6245 const auto LHSCst = Ty.isVector()
6246 ? getFConstantSplat(LHS, MRI, /* allowUndef */ true)
6248 if (!LHSCst)
6249 return false;
6250
6251 // Skip fsub_to_fneg when both LHS and RHS are scalar constants (vector FP
6252 // binop constant folding is not supported yet), so constant_fold_fp_binop
6253 // folds these cases.
6254 if (!Ty.isVector() && getConstantFPVRegVal(LHS, MRI) &&
6255 getConstantFPVRegVal(MI.getOperand(2).getReg(), MRI))
6256 return false;
6257
6258 // -0.0 is always allowed
6259 if (LHSCst->Value.isNegZero())
6260 return true;
6261
6262 // +0.0 is only allowed if nsz is set.
6263 if (LHSCst->Value.isPosZero())
6264 return MI.getFlag(MachineInstr::FmNsz);
6265
6266 return false;
6267}
6268
6269/// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
6270/// due to global flags or MachineInstr flags.
6271static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
6272 if (MI.getOpcode() != TargetOpcode::G_FMUL)
6273 return false;
6274 return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
6275}
6276
6277static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
6278 const MachineRegisterInfo &MRI) {
6279 return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
6280 MRI.use_instr_nodbg_end()) >
6281 std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
6282 MRI.use_instr_nodbg_end());
6283}
6284
6286 bool &AllowFusionGlobally,
6287 bool &HasFMAD, bool &Aggressive,
6288 bool CanReassociate) const {
6289
6290 auto *MF = MI.getMF();
6291 const auto &TLI = *MF->getSubtarget().getTargetLowering();
6292 LLT DstType = MRI.getType(MI.getOperand(0).getReg());
6293
6294 if (CanReassociate && !MI.getFlag(MachineInstr::MIFlag::FmReassoc))
6295 return false;
6296
6297 // Floating-point multiply-add with intermediate rounding.
6298 HasFMAD = (!isPreLegalize() && TLI.isFMADLegal(MI, DstType));
6299 // Floating-point multiply-add without intermediate rounding.
6300 bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
6301 isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
6302 // No valid opcode, do not combine.
6303 if (!HasFMAD && !HasFMA)
6304 return false;
6305
6306 // FMAD (with intermediate rounding) is always safe to form; FMA requires the
6307 // contract fast-math flag.
6308 AllowFusionGlobally = HasFMAD;
6309 // If the addition is not contractable, do not combine.
6310 if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
6311 return false;
6312
6313 Aggressive = TLI.enableAggressiveFMAFusion(DstType);
6314 return true;
6315}
6316
6319 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6320 assert(MI.getOpcode() == TargetOpcode::G_FADD);
6321
6322 bool AllowFusionGlobally, HasFMAD, Aggressive;
6323 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6324 return false;
6325
6326 Register Op1 = MI.getOperand(1).getReg();
6327 Register Op2 = MI.getOperand(2).getReg();
6328 MachineInstr *Op1Def, *Op2Def;
6329 if (!mi_match(Op1, MRI, m_MInstr(Op1Def)) ||
6330 !mi_match(Op2, MRI, m_MInstr(Op2Def)))
6331 return false;
6332 DefinitionAndSourceRegister LHS = {Op1Def, Op1};
6333 DefinitionAndSourceRegister RHS = {Op2Def, Op2};
6334 unsigned PreferredFusedOpcode =
6335 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6336
6337 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
6338 // prefer to fold the multiply with fewer uses.
6339 if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
6340 isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
6341 if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
6342 std::swap(LHS, RHS);
6343 }
6344
6345 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6346 if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
6347 (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
6348 unsigned Flags = MI.getFlags() & LHS.MI->getFlags();
6349 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6350 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6351 {LHS.MI->getOperand(1).getReg(),
6352 LHS.MI->getOperand(2).getReg(), RHS.Reg},
6353 Flags);
6354 };
6355 return true;
6356 }
6357
6358 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6359 if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
6360 (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
6361 unsigned Flags = MI.getFlags() & RHS.MI->getFlags();
6362 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6363 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6364 {RHS.MI->getOperand(1).getReg(),
6365 RHS.MI->getOperand(2).getReg(), LHS.Reg},
6366 Flags);
6367 };
6368 return true;
6369 }
6370
6371 return false;
6372}
6373
6376 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6377 assert(MI.getOpcode() == TargetOpcode::G_FADD);
6378
6379 bool AllowFusionGlobally, HasFMAD, Aggressive;
6380 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6381 return false;
6382
6383 const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
6384 Register Op1 = MI.getOperand(1).getReg();
6385 Register Op2 = MI.getOperand(2).getReg();
6386 MachineInstr *Op1Def, *Op2Def;
6387 if (!mi_match(Op1, MRI, m_MInstr(Op1Def)) ||
6388 !mi_match(Op2, MRI, m_MInstr(Op2Def)))
6389 return false;
6390 DefinitionAndSourceRegister LHS = {Op1Def, Op1};
6391 DefinitionAndSourceRegister RHS = {Op2Def, Op2};
6392 LLT DstType = MRI.getType(MI.getOperand(0).getReg());
6393
6394 unsigned PreferredFusedOpcode =
6395 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6396
6397 MachineInstr *LHSFpExtSrc;
6398 bool LHSContractable =
6399 mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(LHSFpExtSrc))) &&
6400 isContractableFMul(*LHSFpExtSrc, AllowFusionGlobally) &&
6401 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
6402 MRI.getType(LHSFpExtSrc->getOperand(1).getReg()));
6403 MachineInstr *RHSFpExtSrc;
6404 bool RHSContractable =
6405 mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(RHSFpExtSrc))) &&
6406 isContractableFMul(*RHSFpExtSrc, AllowFusionGlobally) &&
6407 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
6408 MRI.getType(RHSFpExtSrc->getOperand(1).getReg()));
6409
6410 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
6411 if (LHSContractable || RHSContractable) {
6412 // Ensure that the contractable fmul with the fewest uses (if both are
6413 // contractable) is the LHS operand.
6414 if (!LHSContractable ||
6415 (RHSContractable && hasMoreUses(*LHSFpExtSrc, *RHSFpExtSrc, MRI))) {
6416 std::swap(LHS, RHS);
6417 LHSFpExtSrc = RHSFpExtSrc;
6418 }
6419
6420 unsigned Flags = MI.getFlags() & LHSFpExtSrc->getFlags();
6421 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6422 auto FpExtX = B.buildFPExt(DstType, LHSFpExtSrc->getOperand(1).getReg());
6423 auto FpExtY = B.buildFPExt(DstType, LHSFpExtSrc->getOperand(2).getReg());
6424 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6425 {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg}, Flags);
6426 };
6427 return true;
6428 }
6429
6430 return false;
6431}
6432
6435 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6436 assert(MI.getOpcode() == TargetOpcode::G_FADD);
6437
6438 bool AllowFusionGlobally, HasFMAD, Aggressive;
6439 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
6440 return false;
6441
6442 Register Op1 = MI.getOperand(1).getReg();
6443 Register Op2 = MI.getOperand(2).getReg();
6444 MachineInstr *Op1Def, *Op2Def;
6445 if (!mi_match(Op1, MRI, m_MInstr(Op1Def)) ||
6446 !mi_match(Op2, MRI, m_MInstr(Op2Def)))
6447 return false;
6448 DefinitionAndSourceRegister LHS = {Op1Def, Op1};
6449 DefinitionAndSourceRegister RHS = {Op2Def, Op2};
6450 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6451
6452 unsigned PreferredFusedOpcode =
6453 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6454
6455 MachineInstr *FMA = nullptr;
6456 Register Z;
6457 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
6458 if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
6459 mi_match(LHS.MI->getOperand(3).getReg(), MRI,
6460 m_GFMul(m_Reg(), m_Reg())) &&
6461 MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
6462 MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
6463 FMA = LHS.MI;
6464 Z = RHS.Reg;
6465 }
6466 // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
6467 else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
6468 mi_match(RHS.MI->getOperand(3).getReg(), MRI,
6469 m_GFMul(m_Reg(), m_Reg())) &&
6470 MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
6471 MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
6472 Z = LHS.Reg;
6473 FMA = RHS.MI;
6474 }
6475
6476 if (FMA) {
6477 MachineInstr *FMulMI;
6478 if (!mi_match(FMA->getOperand(3).getReg(), MRI, m_MInstr(FMulMI)))
6479 return false;
6480 Register X = FMA->getOperand(1).getReg();
6481 Register Y = FMA->getOperand(2).getReg();
6482 Register U = FMulMI->getOperand(1).getReg();
6483 Register V = FMulMI->getOperand(2).getReg();
6484 unsigned InnerFlags = MI.getFlags() & FMulMI->getFlags();
6485 unsigned OuterFlags = MI.getFlags() & FMA->getFlags();
6486
6487 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6488 Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
6489 B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z}, InnerFlags);
6490 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6491 {X, Y, InnerFMA}, OuterFlags);
6492 };
6493 return true;
6494 }
6495
6496 return false;
6497}
6498
6501 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6502 assert(MI.getOpcode() == TargetOpcode::G_FADD);
6503
6504 bool AllowFusionGlobally, HasFMAD, Aggressive;
6505 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6506 return false;
6507
6508 if (!Aggressive)
6509 return false;
6510
6511 const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
6512 LLT DstType = MRI.getType(MI.getOperand(0).getReg());
6513 Register Op1 = MI.getOperand(1).getReg();
6514 Register Op2 = MI.getOperand(2).getReg();
6515 MachineInstr *Op1Def, *Op2Def;
6516 if (!mi_match(Op1, MRI, m_MInstr(Op1Def)) ||
6517 !mi_match(Op2, MRI, m_MInstr(Op2Def)))
6518 return false;
6519 DefinitionAndSourceRegister LHS = {Op1Def, Op1};
6520 DefinitionAndSourceRegister RHS = {Op2Def, Op2};
6521
6522 unsigned PreferredFusedOpcode =
6523 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6524
6525 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
6526 // prefer to fold the multiply with fewer uses.
6527 if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
6528 isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
6529 if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
6530 std::swap(LHS, RHS);
6531 }
6532
6533 // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
6534 auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
6535 Register Y, unsigned InnerFlags,
6536 unsigned OuterFlags, MachineIRBuilder &B) {
6537 Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
6538 Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
6539 Register InnerFMA = B.buildInstr(PreferredFusedOpcode, {DstType},
6540 {FpExtU, FpExtV, Z}, InnerFlags)
6541 .getReg(0);
6542 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6543 {X, Y, InnerFMA}, OuterFlags);
6544 };
6545
6546 MachineInstr *FMulMI, *FMAMI;
6547 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
6548 // -> (fma x, y, (fma (fpext u), (fpext v), z))
6549 if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
6550 mi_match(LHS.MI->getOperand(3).getReg(), MRI,
6551 m_GFPExt(m_MInstr(FMulMI))) &&
6552 isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6553 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
6554 MRI.getType(FMulMI->getOperand(0).getReg()))) {
6555 unsigned InnerFlags = MI.getFlags() & FMulMI->getFlags();
6556 unsigned OuterFlags = MI.getFlags() & LHS.MI->getFlags();
6557 MatchInfo = [=](MachineIRBuilder &B) {
6558 buildMatchInfo(FMulMI->getOperand(1).getReg(),
6559 FMulMI->getOperand(2).getReg(), RHS.Reg,
6560 LHS.MI->getOperand(1).getReg(),
6561 LHS.MI->getOperand(2).getReg(), InnerFlags, OuterFlags, B);
6562 };
6563 return true;
6564 }
6565
6566 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
6567 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
6568 // FIXME: This turns two single-precision and one double-precision
6569 // operation into two double-precision operations, which might not be
6570 // interesting for all targets, especially GPUs.
6571 if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
6572 FMAMI->getOpcode() == PreferredFusedOpcode) {
6573 MachineInstr *FMulMI;
6574 if (!mi_match(FMAMI->getOperand(3).getReg(), MRI, m_MInstr(FMulMI)))
6575 return false;
6576 if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6577 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
6578 MRI.getType(FMAMI->getOperand(0).getReg()))) {
6579 unsigned InnerFlags = MI.getFlags() & FMulMI->getFlags();
6580 unsigned OuterFlags = MI.getFlags() & FMAMI->getFlags();
6581 MatchInfo = [=](MachineIRBuilder &B) {
6582 Register X = FMAMI->getOperand(1).getReg();
6583 Register Y = FMAMI->getOperand(2).getReg();
6584 X = B.buildFPExt(DstType, X).getReg(0);
6585 Y = B.buildFPExt(DstType, Y).getReg(0);
6586 buildMatchInfo(FMulMI->getOperand(1).getReg(),
6587 FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y,
6588 InnerFlags, OuterFlags, B);
6589 };
6590
6591 return true;
6592 }
6593 }
6594
6595 // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
6596 // -> (fma x, y, (fma (fpext u), (fpext v), z))
6597 if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
6598 mi_match(RHS.MI->getOperand(3).getReg(), MRI,
6599 m_GFPExt(m_MInstr(FMulMI))) &&
6600 isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6601 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
6602 MRI.getType(FMulMI->getOperand(0).getReg()))) {
6603 unsigned InnerFlags = MI.getFlags() & FMulMI->getFlags();
6604 unsigned OuterFlags = MI.getFlags() & RHS.MI->getFlags();
6605 MatchInfo = [=](MachineIRBuilder &B) {
6606 buildMatchInfo(FMulMI->getOperand(1).getReg(),
6607 FMulMI->getOperand(2).getReg(), LHS.Reg,
6608 RHS.MI->getOperand(1).getReg(),
6609 RHS.MI->getOperand(2).getReg(), InnerFlags, OuterFlags, B);
6610 };
6611 return true;
6612 }
6613
6614 // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
6615 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
6616 // FIXME: This turns two single-precision and one double-precision
6617 // operation into two double-precision operations, which might not be
6618 // interesting for all targets, especially GPUs.
6619 if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
6620 FMAMI->getOpcode() == PreferredFusedOpcode) {
6621 MachineInstr *FMulMI;
6622 if (!mi_match(FMAMI->getOperand(3).getReg(), MRI, m_MInstr(FMulMI)))
6623 return false;
6624 if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6625 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
6626 MRI.getType(FMAMI->getOperand(0).getReg()))) {
6627 unsigned InnerFlags = MI.getFlags() & FMulMI->getFlags();
6628 unsigned OuterFlags = MI.getFlags() & FMAMI->getFlags();
6629 MatchInfo = [=](MachineIRBuilder &B) {
6630 Register X = FMAMI->getOperand(1).getReg();
6631 Register Y = FMAMI->getOperand(2).getReg();
6632 X = B.buildFPExt(DstType, X).getReg(0);
6633 Y = B.buildFPExt(DstType, Y).getReg(0);
6634 buildMatchInfo(FMulMI->getOperand(1).getReg(),
6635 FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y,
6636 InnerFlags, OuterFlags, B);
6637 };
6638 return true;
6639 }
6640 }
6641
6642 return false;
6643}
6644
6647 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6648 assert(MI.getOpcode() == TargetOpcode::G_FSUB);
6649
6650 bool AllowFusionGlobally, HasFMAD, Aggressive;
6651 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6652 return false;
6653
6654 Register Op1 = MI.getOperand(1).getReg();
6655 Register Op2 = MI.getOperand(2).getReg();
6656 MachineInstr *Op1Def, *Op2Def;
6657 if (!mi_match(Op1, MRI, m_MInstr(Op1Def)) ||
6658 !mi_match(Op2, MRI, m_MInstr(Op2Def)))
6659 return false;
6660 DefinitionAndSourceRegister LHS = {Op1Def, Op1};
6661 DefinitionAndSourceRegister RHS = {Op2Def, Op2};
6662 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6663
6664 // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
6665 // prefer to fold the multiply with fewer uses.
6666 int FirstMulHasFewerUses = true;
6667 if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
6668 isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
6669 hasMoreUses(*LHS.MI, *RHS.MI, MRI))
6670 FirstMulHasFewerUses = false;
6671
6672 unsigned PreferredFusedOpcode =
6673 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6674
6675 // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
6676 if (FirstMulHasFewerUses &&
6677 (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
6678 (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
6679 unsigned Flags = MI.getFlags() & LHS.MI->getFlags();
6680 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6681 Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
6682 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6683 {LHS.MI->getOperand(1).getReg(),
6684 LHS.MI->getOperand(2).getReg(), NegZ},
6685 Flags);
6686 };
6687 return true;
6688 }
6689 // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
6690 else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
6691 (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
6692 unsigned Flags = MI.getFlags() & RHS.MI->getFlags();
6693 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6694 Register NegY =
6695 B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
6696 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6697 {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg}, Flags);
6698 };
6699 return true;
6700 }
6701
6702 return false;
6703}
6704
6707 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6708 assert(MI.getOpcode() == TargetOpcode::G_FSUB);
6709
6710 bool AllowFusionGlobally, HasFMAD, Aggressive;
6711 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6712 return false;
6713
6714 Register LHSReg = MI.getOperand(1).getReg();
6715 Register RHSReg = MI.getOperand(2).getReg();
6716 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6717
6718 unsigned PreferredFusedOpcode =
6719 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6720
6721 MachineInstr *FMulMI;
6722 // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
6723 if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
6724 (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
6725 MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
6726 isContractableFMul(*FMulMI, AllowFusionGlobally)) {
6727 unsigned Flags = MI.getFlags() & FMulMI->getFlags();
6728 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6729 Register NegX =
6730 B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
6731 Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
6732 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6733 {NegX, FMulMI->getOperand(2).getReg(), NegZ}, Flags);
6734 };
6735 return true;
6736 }
6737
6738 // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
6739 if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
6740 (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
6741 MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
6742 isContractableFMul(*FMulMI, AllowFusionGlobally)) {
6743 unsigned Flags = MI.getFlags() & FMulMI->getFlags();
6744 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6745 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6746 {FMulMI->getOperand(1).getReg(),
6747 FMulMI->getOperand(2).getReg(), LHSReg},
6748 Flags);
6749 };
6750 return true;
6751 }
6752
6753 return false;
6754}
6755
6758 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6759 assert(MI.getOpcode() == TargetOpcode::G_FSUB);
6760
6761 bool AllowFusionGlobally, HasFMAD, Aggressive;
6762 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6763 return false;
6764
6765 Register LHSReg = MI.getOperand(1).getReg();
6766 Register RHSReg = MI.getOperand(2).getReg();
6767 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6768
6769 unsigned PreferredFusedOpcode =
6770 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6771
6772 MachineInstr *FMulMI;
6773 // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
6774 if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
6775 isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6776 (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
6777 unsigned Flags = MI.getFlags() & FMulMI->getFlags();
6778 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6779 Register FpExtX =
6780 B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
6781 Register FpExtY =
6782 B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
6783 Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
6784 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6785 {FpExtX, FpExtY, NegZ}, Flags);
6786 };
6787 return true;
6788 }
6789
6790 // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
6791 if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
6792 isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6793 (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
6794 unsigned Flags = MI.getFlags() & FMulMI->getFlags();
6795 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6796 Register FpExtY =
6797 B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
6798 Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
6799 Register FpExtZ =
6800 B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
6801 B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
6802 {NegY, FpExtZ, LHSReg}, Flags);
6803 };
6804 return true;
6805 }
6806
6807 return false;
6808}
6809
6812 std::function<void(MachineIRBuilder &)> &MatchInfo) const {
6813 assert(MI.getOpcode() == TargetOpcode::G_FSUB);
6814
6815 bool AllowFusionGlobally, HasFMAD, Aggressive;
6816 if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
6817 return false;
6818
6819 const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
6820 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
6821 Register LHSReg = MI.getOperand(1).getReg();
6822 Register RHSReg = MI.getOperand(2).getReg();
6823
6824 unsigned PreferredFusedOpcode =
6825 HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
6826
6827 auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
6828 unsigned Flags, MachineIRBuilder &B) {
6829 Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
6830 Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
6831 B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z}, Flags);
6832 };
6833
6834 MachineInstr *FMulMI;
6835 // fold (fsub (fpext (fneg (fmul x, y))), z) ->
6836 // (fneg (fma (fpext x), (fpext y), z))
6837 // fold (fsub (fneg (fpext (fmul x, y))), z) ->
6838 // (fneg (fma (fpext x), (fpext y), z))
6839 if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
6840 mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
6841 isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6842 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
6843 MRI.getType(FMulMI->getOperand(0).getReg()))) {
6844 unsigned Flags = MI.getFlags() & FMulMI->getFlags();
6845 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6846 Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
6847 buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
6848 FMulMI->getOperand(2).getReg(), RHSReg, Flags, B);
6849 B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
6850 };
6851 return true;
6852 }
6853
6854 // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
6855 // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
6856 if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
6857 mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
6858 isContractableFMul(*FMulMI, AllowFusionGlobally) &&
6859 TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
6860 MRI.getType(FMulMI->getOperand(0).getReg()))) {
6861 unsigned Flags = MI.getFlags() & FMulMI->getFlags();
6862 MatchInfo = [=, &MI](MachineIRBuilder &B) {
6863 buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
6864 FMulMI->getOperand(2).getReg(), LHSReg, Flags, B);
6865 };
6866 return true;
6867 }
6868
6869 return false;
6870}
6871
6872// Combine multiple FDIVs with the same divisor into multiple FMULs by the
6873// reciprocal.
6874// E.g., (a / Y; b / Y;) -> (recip = 1.0 / Y; a * recip; b * recip)
6876 MachineInstr &MI, SmallVector<MachineInstr *> &MatchInfo) const {
6877 assert(MI.getOpcode() == TargetOpcode::G_FDIV);
6878
6879 Register X = MI.getOperand(1).getReg();
6880 Register Y = MI.getOperand(2).getReg();
6881
6882 if (!MI.getFlag(MachineInstr::MIFlag::FmArcp))
6883 return false;
6884
6885 auto IsOne = [this](Register X) {
6887 return N0CFP && (N0CFP->isOne() || N0CFP->isMinusOne());
6888 };
6889
6890 // Skip if current node is a reciprocal/fneg-reciprocal.
6891 if (IsOne(X))
6892 return false;
6893
6894 // Exit early if the target does not want this transform or if there can't
6895 // possibly be enough uses of the divisor to make the transform worthwhile.
6896 unsigned MinUses = getTargetLowering().combineRepeatedFPDivisors();
6897 if (!MinUses)
6898 return false;
6899
6900 // Find all FDIV users of the same divisor. For the moment we limit all
6901 // instructions to a single BB and use the first Instr in MatchInfo as the
6902 // dominating position.
6903 MatchInfo.push_back(&MI);
6904 for (auto &U : MRI.use_nodbg_instructions(Y)) {
6905 if (&U == &MI || U.getParent() != MI.getParent())
6906 continue;
6907 if (U.getOpcode() == TargetOpcode::G_FDIV &&
6908 U.getOperand(2).getReg() == Y && U.getOperand(1).getReg() != Y &&
6909 !IsOne(U.getOperand(1).getReg())) {
6910 // This division is eligible for optimization only if global unsafe math
6911 // is enabled or if this division allows reciprocal formation.
6912 if (U.getFlag(MachineInstr::MIFlag::FmArcp)) {
6913 MatchInfo.push_back(&U);
6914 if (dominates(U, *MatchInfo[0]))
6915 std::swap(MatchInfo[0], MatchInfo.back());
6916 }
6917 }
6918 }
6919
6920 // Now that we have the actual number of divisor uses, make sure it meets
6921 // the minimum threshold specified by the target.
6922 return MatchInfo.size() >= MinUses;
6923}
6924
6926 SmallVector<MachineInstr *> &MatchInfo) const {
6927 // Generate the new div at the position of the first instruction, that we have
6928 // ensured will dominate all other instructions.
6929 Builder.setInsertPt(*MatchInfo[0]->getParent(), MatchInfo[0]);
6930 LLT Ty = MRI.getType(MatchInfo[0]->getOperand(0).getReg());
6931 auto Div = Builder.buildFDiv(Ty, Builder.buildFConstant(Ty, 1.0),
6932 MatchInfo[0]->getOperand(2).getReg(),
6933 MatchInfo[0]->getFlags());
6934
6935 // Replace all found div's with fmul instructions.
6936 for (MachineInstr *MI : MatchInfo) {
6937 Builder.setInsertPt(*MI->getParent(), MI);
6938 Builder.buildFMul(MI->getOperand(0).getReg(), MI->getOperand(1).getReg(),
6939 Div->getOperand(0).getReg(), MI->getFlags());
6940 MI->eraseFromParent();
6941 }
6942}
6943
6945 Register &MatchInfo) const {
6946 // This combine folds the following patterns:
6947 //
6948 // G_BUILD_VECTOR_TRUNC (G_BITCAST(x), G_LSHR(G_BITCAST(x), k))
6949 // G_BUILD_VECTOR(G_TRUNC(G_BITCAST(x)), G_TRUNC(G_LSHR(G_BITCAST(x), k)))
6950 // into
6951 // x
6952 // if
6953 // k == sizeof(VecEltTy)/2
6954 // type(x) == type(dst)
6955 //
6956 // G_BUILD_VECTOR(G_TRUNC(G_BITCAST(x)), undef)
6957 // into
6958 // x
6959 // if
6960 // type(x) == type(dst)
6961
6962 LLT DstVecTy = MRI.getType(MI.getOperand(0).getReg());
6963 LLT DstEltTy = DstVecTy.getElementType();
6964
6965 Register Lo, Hi;
6966
6967 if (mi_match(
6968 MI, MRI,
6970 MatchInfo = Lo;
6971 return MRI.getType(MatchInfo) == DstVecTy;
6972 }
6973
6974 std::optional<ValueAndVReg> ShiftAmount;
6975 const auto LoPattern = m_GBitcast(m_Reg(Lo));
6976 const auto HiPattern = m_GLShr(m_GBitcast(m_Reg(Hi)), m_GCst(ShiftAmount));
6977 if (mi_match(
6978 MI, MRI,
6979 m_any_of(m_GBuildVectorTrunc(LoPattern, HiPattern),
6980 m_GBuildVector(m_GTrunc(LoPattern), m_GTrunc(HiPattern))))) {
6981 if (Lo == Hi && ShiftAmount->Value == DstEltTy.getSizeInBits()) {
6982 MatchInfo = Lo;
6983 return MRI.getType(MatchInfo) == DstVecTy;
6984 }
6985 }
6986
6987 return false;
6988}
6989
6991 Register &MatchInfo) const {
6992 // Replace (G_TRUNC (G_BITCAST (G_BUILD_VECTOR x, y)) with just x
6993 // if type(x) == type(G_TRUNC)
6994 if (!mi_match(MI.getOperand(1).getReg(), MRI,
6995 m_GBitcast(m_GBuildVector(m_Reg(MatchInfo), m_Reg()))))
6996 return false;
6997
6998 return MRI.getType(MatchInfo) == MRI.getType(MI.getOperand(0).getReg());
6999}
7000
7002 Register &MatchInfo) const {
7003 // Replace (G_TRUNC (G_LSHR (G_BITCAST (G_BUILD_VECTOR x, y)), K)) with
7004 // y if K == size of vector element type
7005 std::optional<ValueAndVReg> ShiftAmt;
7006 if (!mi_match(MI.getOperand(1).getReg(), MRI,
7008 m_GCst(ShiftAmt))))
7009 return false;
7010
7011 LLT MatchTy = MRI.getType(MatchInfo);
7012 return ShiftAmt->Value.getZExtValue() == MatchTy.getSizeInBits() &&
7013 MatchTy == MRI.getType(MI.getOperand(0).getReg());
7014}
7015
7016unsigned CombinerHelper::getFPMinMaxOpcForSelect(
7017 CmpInst::Predicate Pred, LLT DstTy,
7018 SelectPatternNaNBehaviour VsNaNRetVal) const {
7019 assert(VsNaNRetVal != SelectPatternNaNBehaviour::NOT_APPLICABLE &&
7020 "Expected a NaN behaviour?");
7021 // Choose an opcode based off of legality or the behaviour when one of the
7022 // LHS/RHS may be NaN.
7023 switch (Pred) {
7024 default:
7025 return 0;
7026 case CmpInst::FCMP_UGT:
7027 case CmpInst::FCMP_UGE:
7028 case CmpInst::FCMP_OGT:
7029 case CmpInst::FCMP_OGE:
7030 if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_OTHER)
7031 return TargetOpcode::G_FMAXNUM;
7032 if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_NAN)
7033 return TargetOpcode::G_FMAXIMUM;
7034 if (isLegal({TargetOpcode::G_FMAXNUM, {DstTy}}))
7035 return TargetOpcode::G_FMAXNUM;
7036 if (isLegal({TargetOpcode::G_FMAXIMUM, {DstTy}}))
7037 return TargetOpcode::G_FMAXIMUM;
7038 return 0;
7039 case CmpInst::FCMP_ULT:
7040 case CmpInst::FCMP_ULE:
7041 case CmpInst::FCMP_OLT:
7042 case CmpInst::FCMP_OLE:
7043 if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_OTHER)
7044 return TargetOpcode::G_FMINNUM;
7045 if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_NAN)
7046 return TargetOpcode::G_FMINIMUM;
7047 if (isLegal({TargetOpcode::G_FMINNUM, {DstTy}}))
7048 return TargetOpcode::G_FMINNUM;
7049 if (!isLegal({TargetOpcode::G_FMINIMUM, {DstTy}}))
7050 return 0;
7051 return TargetOpcode::G_FMINIMUM;
7052 }
7053}
7054
7055CombinerHelper::SelectPatternNaNBehaviour
7056CombinerHelper::computeRetValAgainstNaN(Register LHS, Register RHS,
7057 bool IsOrderedComparison) const {
7058 bool LHSSafe = VT->isKnownNeverNaN(LHS);
7059 bool RHSSafe = VT->isKnownNeverNaN(RHS);
7060 // Completely unsafe.
7061 if (!LHSSafe && !RHSSafe)
7062 return SelectPatternNaNBehaviour::NOT_APPLICABLE;
7063 if (LHSSafe && RHSSafe)
7064 return SelectPatternNaNBehaviour::RETURNS_ANY;
7065 // An ordered comparison will return false when given a NaN, so it
7066 // returns the RHS.
7067 if (IsOrderedComparison)
7068 return LHSSafe ? SelectPatternNaNBehaviour::RETURNS_NAN
7069 : SelectPatternNaNBehaviour::RETURNS_OTHER;
7070 // An unordered comparison will return true when given a NaN, so it
7071 // returns the LHS.
7072 return LHSSafe ? SelectPatternNaNBehaviour::RETURNS_OTHER
7073 : SelectPatternNaNBehaviour::RETURNS_NAN;
7074}
7075
7076bool CombinerHelper::matchFPSelectToMinMax(Register Dst, Register Cond,
7077 Register TrueVal, Register FalseVal,
7078 BuildFnTy &MatchInfo) const {
7079 // Match: select (fcmp cond x, y) x, y
7080 // select (fcmp cond x, y) y, x
7081 // And turn it into fminnum/fmaxnum or fmin/fmax based off of the condition.
7082 LLT DstTy = MRI.getType(Dst);
7083 // Bail out early on pointers, since we'll never want to fold to a min/max.
7084 if (DstTy.isPointer())
7085 return false;
7086 // Match a floating point compare with a less-than/greater-than predicate.
7087 // TODO: Allow multiple users of the compare if they are all selects.
7089 Register CmpLHS, CmpRHS;
7090 if (!mi_match(
7091 Cond, MRI,
7092 m_OneUse(m_GFCmp(m_Pred(Pred), m_Reg(CmpLHS), m_Reg(CmpRHS)))) ||
7094 return false;
7095 SelectPatternNaNBehaviour ResWithKnownNaNInfo =
7096 computeRetValAgainstNaN(CmpLHS, CmpRHS, CmpInst::isOrdered(Pred));
7097 if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::NOT_APPLICABLE)
7098 return false;
7099 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
7100 std::swap(CmpLHS, CmpRHS);
7102 if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::RETURNS_NAN)
7103 ResWithKnownNaNInfo = SelectPatternNaNBehaviour::RETURNS_OTHER;
7104 else if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::RETURNS_OTHER)
7105 ResWithKnownNaNInfo = SelectPatternNaNBehaviour::RETURNS_NAN;
7106 }
7107 if (TrueVal != CmpLHS || FalseVal != CmpRHS)
7108 return false;
7109 // Decide what type of max/min this should be based off of the predicate.
7110 unsigned Opc = getFPMinMaxOpcForSelect(Pred, DstTy, ResWithKnownNaNInfo);
7111 if (!Opc || !isLegal({Opc, {DstTy}}))
7112 return false;
7113 // Comparisons between signed zero and zero may have different results...
7114 // unless we have fmaximum/fminimum. In that case, we know -0 < 0.
7115 if (Opc != TargetOpcode::G_FMAXIMUM && Opc != TargetOpcode::G_FMINIMUM) {
7116 // We don't know if a comparison between two 0s will give us a consistent
7117 // result. Be conservative and only proceed if at least one side is
7118 // non-zero.
7119 auto KnownNonZeroSide = getFConstantVRegValWithLookThrough(CmpLHS, MRI);
7120 if (!KnownNonZeroSide || !KnownNonZeroSide->Value.isNonZero()) {
7121 KnownNonZeroSide = getFConstantVRegValWithLookThrough(CmpRHS, MRI);
7122 if (!KnownNonZeroSide || !KnownNonZeroSide->Value.isNonZero())
7123 return false;
7124 }
7125 }
7126 MatchInfo = [=](MachineIRBuilder &B) {
7127 B.buildInstr(Opc, {Dst}, {CmpLHS, CmpRHS});
7128 };
7129 return true;
7130}
7131
7133 BuildFnTy &MatchInfo) const {
7134 // TODO: Handle integer cases.
7135 assert(MI.getOpcode() == TargetOpcode::G_SELECT);
7136 // Condition may be fed by a truncated compare.
7137 Register Cond = MI.getOperand(1).getReg();
7138 Register MaybeTrunc;
7139 if (mi_match(Cond, MRI, m_OneUse(m_GTrunc(m_Reg(MaybeTrunc)))))
7140 Cond = MaybeTrunc;
7141 Register Dst = MI.getOperand(0).getReg();
7142 Register TrueVal = MI.getOperand(2).getReg();
7143 Register FalseVal = MI.getOperand(3).getReg();
7144 return matchFPSelectToMinMax(Dst, Cond, TrueVal, FalseVal, MatchInfo);
7145}
7146
7148 BuildFnTy &MatchInfo) const {
7149 assert(MI.getOpcode() == TargetOpcode::G_ICMP);
7150 // (X + Y) == X --> Y == 0
7151 // (X + Y) != X --> Y != 0
7152 // (X - Y) == X --> Y == 0
7153 // (X - Y) != X --> Y != 0
7154 // (X ^ Y) == X --> Y == 0
7155 // (X ^ Y) != X --> Y != 0
7156 Register Dst = MI.getOperand(0).getReg();
7157 CmpInst::Predicate Pred;
7158 Register X, Y, OpLHS, OpRHS;
7159 bool MatchedSub = mi_match(
7160 Dst, MRI,
7161 m_c_GICmp(m_Pred(Pred), m_Reg(X), m_GSub(m_Reg(OpLHS), m_Reg(Y))));
7162 if (MatchedSub && X != OpLHS)
7163 return false;
7164 if (!MatchedSub) {
7165 if (!mi_match(Dst, MRI,
7166 m_c_GICmp(m_Pred(Pred), m_Reg(X),
7167 m_any_of(m_GAdd(m_Reg(OpLHS), m_Reg(OpRHS)),
7168 m_GXor(m_Reg(OpLHS), m_Reg(OpRHS))))))
7169 return false;
7170 Y = X == OpLHS ? OpRHS : X == OpRHS ? OpLHS : Register();
7171 }
7172 MatchInfo = [=](MachineIRBuilder &B) {
7173 auto Zero = B.buildConstant(MRI.getType(Y), 0);
7174 B.buildICmp(Pred, Dst, Y, Zero);
7175 };
7176 return CmpInst::isEquality(Pred) && Y.isValid();
7177}
7178
7179/// Return the minimum useless shift amount that results in complete loss of the
7180/// source value. Return std::nullopt when it cannot determine a value.
7181static std::optional<unsigned>
7182getMinUselessShift(KnownBits ValueKB, unsigned Opcode,
7183 std::optional<int64_t> &Result) {
7184 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR ||
7185 Opcode == TargetOpcode::G_ASHR) &&
7186 "Expect G_SHL, G_LSHR or G_ASHR.");
7187 auto SignificantBits = 0;
7188 switch (Opcode) {
7189 case TargetOpcode::G_SHL:
7190 SignificantBits = ValueKB.countMinTrailingZeros();
7191 Result = 0;
7192 break;
7193 case TargetOpcode::G_LSHR:
7194 Result = 0;
7195 SignificantBits = ValueKB.countMinLeadingZeros();
7196 break;
7197 case TargetOpcode::G_ASHR:
7198 if (ValueKB.isNonNegative()) {
7199 SignificantBits = ValueKB.countMinLeadingZeros();
7200 Result = 0;
7201 } else if (ValueKB.isNegative()) {
7202 SignificantBits = ValueKB.countMinLeadingOnes();
7203 Result = -1;
7204 } else {
7205 // Cannot determine shift result.
7206 Result = std::nullopt;
7207 }
7208 break;
7209 default:
7210 break;
7211 }
7212 return ValueKB.getBitWidth() - SignificantBits;
7213}
7214
7216 BuildFnTy &MatchInfo) const {
7217 Register Dst = MI.getOperand(0).getReg();
7218 Register ShiftVal = MI.getOperand(1).getReg();
7219 Register ShiftReg = MI.getOperand(2).getReg();
7220 LLT ResTy = MRI.getType(Dst);
7221 std::optional<int64_t> Result;
7222 auto IsShiftTooBig = [&](const Constant *C) {
7223 auto *CI = dyn_cast<ConstantInt>(C);
7224 if (!CI)
7225 return false;
7226 if (CI->uge(ResTy.getScalarSizeInBits())) {
7227 Result = std::nullopt;
7228 return true;
7229 }
7230 auto OptMaxUsefulShift =
7231 getMinUselessShift(VT->getKnownBits(ShiftVal), MI.getOpcode(), Result);
7232 return OptMaxUsefulShift && CI->uge(*OptMaxUsefulShift);
7233 };
7234 if (!matchUnaryPredicate(MRI, ShiftReg, IsShiftTooBig))
7235 return false;
7236
7237 if (!Result) {
7238 MatchInfo = [Dst](MachineIRBuilder &B) { B.buildUndef(Dst); };
7239 return true;
7240 }
7241
7242 int64_t Val = *Result;
7243 MatchInfo = [Dst, Val](MachineIRBuilder &B) { B.buildConstant(Dst, Val); };
7244 return true;
7245}
7246
7248 unsigned LHSOpndIdx = 1;
7249 unsigned RHSOpndIdx = 2;
7250 switch (MI.getOpcode()) {
7251 case TargetOpcode::G_UADDO:
7252 case TargetOpcode::G_SADDO:
7253 case TargetOpcode::G_UMULO:
7254 case TargetOpcode::G_SMULO:
7255 LHSOpndIdx = 2;
7256 RHSOpndIdx = 3;
7257 break;
7258 default:
7259 break;
7260 }
7261 Register LHS = MI.getOperand(LHSOpndIdx).getReg();
7262 Register RHS = MI.getOperand(RHSOpndIdx).getReg();
7263 MachineInstr *LHSDef, *RHSDef;
7264 if (!mi_match(LHS, MRI, m_MInstr(LHSDef)) ||
7265 !mi_match(RHS, MRI, m_MInstr(RHSDef)))
7266 return false;
7267
7268 if (!isConstantOrConstantVector(*LHSDef, MRI, /*AllowFP=*/false,
7269 /*AllowOpaqueConstants=*/false)) {
7270 // Skip commuting if LHS is not a constant or a vector of constants. But,
7271 // LHS may be a G_CONSTANT_FOLD_BARRIER. If so we commute as long as we
7272 // don't already have a constant on the RHS.
7273 if (LHSDef->getOpcode() != TargetOpcode::G_CONSTANT_FOLD_BARRIER)
7274 return false;
7275 }
7276 // Commute as long as RHS is not a constant, a vector of constants or
7277 // G_CONSTANT_FOLD_BARRIER.
7278 return RHSDef->getOpcode() != TargetOpcode::G_CONSTANT_FOLD_BARRIER &&
7279 !isConstantOrConstantVector(*RHSDef, MRI, /*AllowFP=*/false,
7280 /*AllowOpaqueConstants=*/false);
7281}
7282
7284 Register LHS = MI.getOperand(1).getReg();
7285 Register RHS = MI.getOperand(2).getReg();
7286 std::optional<FPValueAndVReg> ValAndVReg;
7287 if (!mi_match(LHS, MRI, m_GFCstOrSplat(ValAndVReg)))
7288 return false;
7289 return !mi_match(RHS, MRI, m_GFCstOrSplat(ValAndVReg));
7290}
7291
7292bool CombinerHelper::isOneOrOneSplat(Register Src, bool AllowUndefs) const {
7293 LLT SrcTy = MRI.getType(Src);
7294 if (SrcTy.isFixedVector())
7295 return isConstantSplatVector(Src, 1, AllowUndefs);
7296 if (SrcTy.isScalar()) {
7297 if (AllowUndefs && getOpcodeDef<GImplicitDef>(Src, MRI) != nullptr)
7298 return true;
7299 auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
7300 return IConstant && IConstant->Value == 1;
7301 }
7302 return false; // scalable vector
7303}
7304
7305bool CombinerHelper::isZeroOrZeroSplat(Register Src, bool AllowUndefs) const {
7306 LLT SrcTy = MRI.getType(Src);
7307 if (SrcTy.isFixedVector())
7308 return isConstantSplatVector(Src, 0, AllowUndefs);
7309 if (SrcTy.isScalar()) {
7310 if (AllowUndefs && getOpcodeDef<GImplicitDef>(Src, MRI) != nullptr)
7311 return true;
7312 auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
7313 return IConstant && IConstant->Value == 0;
7314 }
7315 return false; // scalable vector
7316}
7317
7318// Ignores COPYs during conformance checks.
7319// FIXME scalable vectors.
7320bool CombinerHelper::isConstantSplatVector(Register Src, int64_t SplatValue,
7321 bool AllowUndefs) const {
7322 GBuildVector *BuildVector = getOpcodeDef<GBuildVector>(Src, MRI);
7323 if (!BuildVector)
7324 return false;
7325 unsigned NumSources = BuildVector->getNumSources();
7326
7327 for (unsigned I = 0; I < NumSources; ++I) {
7328 GImplicitDef *ImplicitDef =
7330 if (ImplicitDef && AllowUndefs)
7331 continue;
7332 if (ImplicitDef && !AllowUndefs)
7333 return false;
7334 std::optional<ValueAndVReg> IConstant =
7336 if (IConstant && IConstant->Value == SplatValue)
7337 continue;
7338 return false;
7339 }
7340 return true;
7341}
7342
7343// Ignores COPYs during lookups.
7344// FIXME scalable vectors
7345std::optional<APInt>
7346CombinerHelper::getConstantOrConstantSplatVector(Register Src) const {
7347 auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
7348 if (IConstant)
7349 return IConstant->Value;
7350
7351 GBuildVector *BuildVector = getOpcodeDef<GBuildVector>(Src, MRI);
7352 if (!BuildVector)
7353 return std::nullopt;
7354 unsigned NumSources = BuildVector->getNumSources();
7355
7356 std::optional<APInt> Value = std::nullopt;
7357 for (unsigned I = 0; I < NumSources; ++I) {
7358 std::optional<ValueAndVReg> IConstant =
7360 if (!IConstant)
7361 return std::nullopt;
7362 if (!Value)
7363 Value = IConstant->Value;
7364 else if (*Value != IConstant->Value)
7365 return std::nullopt;
7366 }
7367 return Value;
7368}
7369
7370// FIXME G_SPLAT_VECTOR
7371bool CombinerHelper::isConstantOrConstantVectorI(Register Src) const {
7372 auto IConstant = getIConstantVRegValWithLookThrough(Src, MRI);
7373 if (IConstant)
7374 return true;
7375
7376 GBuildVector *BuildVector = getOpcodeDef<GBuildVector>(Src, MRI);
7377 if (!BuildVector)
7378 return false;
7379
7380 unsigned NumSources = BuildVector->getNumSources();
7381 for (unsigned I = 0; I < NumSources; ++I) {
7382 std::optional<ValueAndVReg> IConstant =
7384 if (!IConstant)
7385 return false;
7386 }
7387 return true;
7388}
7389
7390// TODO: use knownbits to determine zeros
7391bool CombinerHelper::tryFoldSelectOfConstants(GSelect *Select,
7392 BuildFnTy &MatchInfo) const {
7393 uint32_t Flags = Select->getFlags();
7394 Register Dest = Select->getReg(0);
7395 Register Cond = Select->getCondReg();
7396 Register True = Select->getTrueReg();
7397 Register False = Select->getFalseReg();
7398 LLT CondTy = MRI.getType(Select->getCondReg());
7399 LLT TrueTy = MRI.getType(Select->getTrueReg());
7400
7401 // We only do this combine for scalar boolean conditions.
7402 if (CondTy != LLT::scalar(1))
7403 return false;
7404
7405 if (TrueTy.isPointer())
7406 return false;
7407
7408 // Both are scalars.
7409 std::optional<ValueAndVReg> TrueOpt =
7411 std::optional<ValueAndVReg> FalseOpt =
7413
7414 if (!TrueOpt || !FalseOpt)
7415 return false;
7416
7417 APInt TrueValue = TrueOpt->Value;
7418 APInt FalseValue = FalseOpt->Value;
7419
7420 // select Cond, 1, 0 --> zext (Cond)
7421 if (TrueValue.isOne() && FalseValue.isZero()) {
7422 MatchInfo = [=](MachineIRBuilder &B) {
7423 B.setInstrAndDebugLoc(*Select);
7424 B.buildZExtOrTrunc(Dest, Cond);
7425 };
7426 return true;
7427 }
7428
7429 // select Cond, -1, 0 --> sext (Cond)
7430 if (TrueValue.isAllOnes() && FalseValue.isZero()) {
7431 MatchInfo = [=](MachineIRBuilder &B) {
7432 B.setInstrAndDebugLoc(*Select);
7433 B.buildSExtOrTrunc(Dest, Cond);
7434 };
7435 return true;
7436 }
7437
7438 // select Cond, 0, 1 --> zext (!Cond)
7439 if (TrueValue.isZero() && FalseValue.isOne()) {
7440 MatchInfo = [=](MachineIRBuilder &B) {
7441 B.setInstrAndDebugLoc(*Select);
7442 Register Inner = MRI.createGenericVirtualRegister(CondTy);
7443 B.buildNot(Inner, Cond);
7444 B.buildZExtOrTrunc(Dest, Inner);
7445 };
7446 return true;
7447 }
7448
7449 // select Cond, 0, -1 --> sext (!Cond)
7450 if (TrueValue.isZero() && FalseValue.isAllOnes()) {
7451 MatchInfo = [=](MachineIRBuilder &B) {
7452 B.setInstrAndDebugLoc(*Select);
7453 Register Inner = MRI.createGenericVirtualRegister(CondTy);
7454 B.buildNot(Inner, Cond);
7455 B.buildSExtOrTrunc(Dest, Inner);
7456 };
7457 return true;
7458 }
7459
7460 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
7461 if (TrueValue - 1 == FalseValue) {
7462 MatchInfo = [=](MachineIRBuilder &B) {
7463 B.setInstrAndDebugLoc(*Select);
7464 Register Inner = MRI.createGenericVirtualRegister(TrueTy);
7465 B.buildZExtOrTrunc(Inner, Cond);
7466 B.buildAdd(Dest, Inner, False);
7467 };
7468 return true;
7469 }
7470
7471 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
7472 if (TrueValue + 1 == FalseValue) {
7473 MatchInfo = [=](MachineIRBuilder &B) {
7474 B.setInstrAndDebugLoc(*Select);
7475 Register Inner = MRI.createGenericVirtualRegister(TrueTy);
7476 B.buildSExtOrTrunc(Inner, Cond);
7477 B.buildAdd(Dest, Inner, False);
7478 };
7479 return true;
7480 }
7481
7482 // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
7483 if (TrueValue.isPowerOf2() && FalseValue.isZero()) {
7484 MatchInfo = [=](MachineIRBuilder &B) {
7485 B.setInstrAndDebugLoc(*Select);
7486 Register Inner = MRI.createGenericVirtualRegister(TrueTy);
7487 B.buildZExtOrTrunc(Inner, Cond);
7488 // The shift amount must be scalar.
7489 LLT ShiftTy = TrueTy.isVector() ? TrueTy.getElementType() : TrueTy;
7490 auto ShAmtC = B.buildConstant(ShiftTy, TrueValue.exactLogBase2());
7491 B.buildShl(Dest, Inner, ShAmtC, Flags);
7492 };
7493 return true;
7494 }
7495
7496 // select Cond, 0, Pow2 --> (zext (!Cond)) << log2(Pow2)
7497 if (FalseValue.isPowerOf2() && TrueValue.isZero()) {
7498 MatchInfo = [=](MachineIRBuilder &B) {
7499 B.setInstrAndDebugLoc(*Select);
7500 Register Not = MRI.createGenericVirtualRegister(CondTy);
7501 B.buildNot(Not, Cond);
7502 Register Inner = MRI.createGenericVirtualRegister(TrueTy);
7503 B.buildZExtOrTrunc(Inner, Not);
7504 // The shift amount must be scalar.
7505 LLT ShiftTy = TrueTy.isVector() ? TrueTy.getElementType() : TrueTy;
7506 auto ShAmtC = B.buildConstant(ShiftTy, FalseValue.exactLogBase2());
7507 B.buildShl(Dest, Inner, ShAmtC, Flags);
7508 };
7509 return true;
7510 }
7511
7512 // select Cond, -1, C --> or (sext Cond), C
7513 if (TrueValue.isAllOnes()) {
7514 MatchInfo = [=](MachineIRBuilder &B) {
7515 B.setInstrAndDebugLoc(*Select);
7516 Register Inner = MRI.createGenericVirtualRegister(TrueTy);
7517 B.buildSExtOrTrunc(Inner, Cond);
7518 B.buildOr(Dest, Inner, False, Flags);
7519 };
7520 return true;
7521 }
7522
7523 // select Cond, C, -1 --> or (sext (not Cond)), C
7524 if (FalseValue.isAllOnes()) {
7525 MatchInfo = [=](MachineIRBuilder &B) {
7526 B.setInstrAndDebugLoc(*Select);
7527 Register Not = MRI.createGenericVirtualRegister(CondTy);
7528 B.buildNot(Not, Cond);
7529 Register Inner = MRI.createGenericVirtualRegister(TrueTy);
7530 B.buildSExtOrTrunc(Inner, Not);
7531 B.buildOr(Dest, Inner, True, Flags);
7532 };
7533 return true;
7534 }
7535
7536 return false;
7537}
7538
7539// TODO: use knownbits to determine zeros
7540bool CombinerHelper::tryFoldBoolSelectToLogic(GSelect *Select,
7541 BuildFnTy &MatchInfo) const {
7542 uint32_t Flags = Select->getFlags();
7543 Register DstReg = Select->getReg(0);
7544 Register Cond = Select->getCondReg();
7545 Register True = Select->getTrueReg();
7546 Register False = Select->getFalseReg();
7547 LLT CondTy = MRI.getType(Select->getCondReg());
7548 LLT TrueTy = MRI.getType(Select->getTrueReg());
7549
7550 // Boolean or fixed vector of booleans.
7551 if (CondTy.isScalableVector() ||
7552 (CondTy.isFixedVector() &&
7553 CondTy.getElementType().getScalarSizeInBits() != 1) ||
7554 CondTy.getScalarSizeInBits() != 1)
7555 return false;
7556
7557 if (CondTy != TrueTy)
7558 return false;
7559
7560 // select Cond, Cond, F --> or Cond, F
7561 // select Cond, 1, F --> or Cond, F
7562 if ((Cond == True) || isOneOrOneSplat(True, /* AllowUndefs */ true)) {
7563 MatchInfo = [=](MachineIRBuilder &B) {
7564 B.setInstrAndDebugLoc(*Select);
7565 Register Ext = MRI.createGenericVirtualRegister(TrueTy);
7566 B.buildZExtOrTrunc(Ext, Cond);
7567 auto FreezeFalse = B.buildFreeze(TrueTy, False);
7568 B.buildOr(DstReg, Ext, FreezeFalse, Flags);
7569 };
7570 return true;
7571 }
7572
7573 // select Cond, T, Cond --> and Cond, T
7574 // select Cond, T, 0 --> and Cond, T
7575 if ((Cond == False) || isZeroOrZeroSplat(False, /* AllowUndefs */ true)) {
7576 MatchInfo = [=](MachineIRBuilder &B) {
7577 B.setInstrAndDebugLoc(*Select);
7578 Register Ext = MRI.createGenericVirtualRegister(TrueTy);
7579 B.buildZExtOrTrunc(Ext, Cond);
7580 auto FreezeTrue = B.buildFreeze(TrueTy, True);
7581 B.buildAnd(DstReg, Ext, FreezeTrue);
7582 };
7583 return true;
7584 }
7585
7586 // select Cond, T, 1 --> or (not Cond), T
7587 if (isOneOrOneSplat(False, /* AllowUndefs */ true)) {
7588 MatchInfo = [=](MachineIRBuilder &B) {
7589 B.setInstrAndDebugLoc(*Select);
7590 // First the not.
7591 Register Inner = MRI.createGenericVirtualRegister(CondTy);
7592 B.buildNot(Inner, Cond);
7593 // Then an ext to match the destination register.
7594 Register Ext = MRI.createGenericVirtualRegister(TrueTy);
7595 B.buildZExtOrTrunc(Ext, Inner);
7596 auto FreezeTrue = B.buildFreeze(TrueTy, True);
7597 B.buildOr(DstReg, Ext, FreezeTrue, Flags);
7598 };
7599 return true;
7600 }
7601
7602 // select Cond, 0, F --> and (not Cond), F
7603 if (isZeroOrZeroSplat(True, /* AllowUndefs */ true)) {
7604 MatchInfo = [=](MachineIRBuilder &B) {
7605 B.setInstrAndDebugLoc(*Select);
7606 // First the not.
7607 Register Inner = MRI.createGenericVirtualRegister(CondTy);
7608 B.buildNot(Inner, Cond);
7609 // Then an ext to match the destination register.
7610 Register Ext = MRI.createGenericVirtualRegister(TrueTy);
7611 B.buildZExtOrTrunc(Ext, Inner);
7612 auto FreezeFalse = B.buildFreeze(TrueTy, False);
7613 B.buildAnd(DstReg, Ext, FreezeFalse);
7614 };
7615 return true;
7616 }
7617
7618 return false;
7619}
7620
7622 BuildFnTy &MatchInfo) const {
7623 Register DstReg = MO.getReg();
7624 Register CondReg, True, False;
7625 if (!mi_match(DstReg, MRI,
7626 m_GISelect(m_Reg(CondReg), m_Reg(True), m_Reg(False))))
7627 return false;
7628
7629 CmpInst::Predicate Pred;
7630 Register CmpLHS, CmpRHS;
7631 if (!mi_match(CondReg, MRI,
7632 m_GICmp(m_Pred(Pred), m_Reg(CmpLHS), m_Reg(CmpRHS))))
7633 return false;
7634
7635 LLT DstTy = MRI.getType(DstReg);
7636 if (DstTy.isPointerOrPointerVector())
7637 return false;
7638
7639 // We want to fold the icmp and replace the select.
7640 if (!MRI.hasOneNonDBGUse(CondReg))
7641 return false;
7642
7643 // We need a larger or smaller predicate for
7644 // canonicalization.
7645 if (CmpInst::isEquality(Pred))
7646 return false;
7647
7648 // We can swap CmpLHS and CmpRHS for higher hitrate.
7649 if (True == CmpRHS && False == CmpLHS) {
7650 std::swap(CmpLHS, CmpRHS);
7651 Pred = CmpInst::getSwappedPredicate(Pred);
7652 }
7653
7654 // (icmp X, Y) ? X : Y -> integer minmax.
7655 // see matchSelectPattern in ValueTracking.
7656 // Legality between G_SELECT and integer minmax can differ.
7657 if (True != CmpLHS || False != CmpRHS)
7658 return false;
7659
7660 switch (Pred) {
7661 case ICmpInst::ICMP_UGT:
7662 case ICmpInst::ICMP_UGE: {
7663 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMAX, DstTy}))
7664 return false;
7665 MatchInfo = [=](MachineIRBuilder &B) { B.buildUMax(DstReg, True, False); };
7666 return true;
7667 }
7668 case ICmpInst::ICMP_SGT:
7669 case ICmpInst::ICMP_SGE: {
7670 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SMAX, DstTy}))
7671 return false;
7672 MatchInfo = [=](MachineIRBuilder &B) { B.buildSMax(DstReg, True, False); };
7673 return true;
7674 }
7675 case ICmpInst::ICMP_ULT:
7676 case ICmpInst::ICMP_ULE: {
7677 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMIN, DstTy}))
7678 return false;
7679 MatchInfo = [=](MachineIRBuilder &B) { B.buildUMin(DstReg, True, False); };
7680 return true;
7681 }
7682 case ICmpInst::ICMP_SLT:
7683 case ICmpInst::ICMP_SLE: {
7684 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SMIN, DstTy}))
7685 return false;
7686 MatchInfo = [=](MachineIRBuilder &B) { B.buildSMin(DstReg, True, False); };
7687 return true;
7688 }
7689 default:
7690 return false;
7691 }
7692}
7693
7694// (neg (min/max x, (neg x))) --> (max/min x, (neg x))
7696 BuildFnTy &MatchInfo) const {
7697 assert(MI.getOpcode() == TargetOpcode::G_SUB);
7698 Register DestReg = MI.getOperand(0).getReg();
7699 LLT DestTy = MRI.getType(DestReg);
7700
7701 Register X;
7702 Register Sub0;
7703 auto NegPattern = m_all_of(m_Neg(m_DeferredReg(X)), m_Reg(Sub0));
7704 if (mi_match(DestReg, MRI,
7705 m_Neg(m_OneUse(m_any_of(m_GSMin(m_Reg(X), NegPattern),
7706 m_GSMax(m_Reg(X), NegPattern),
7707 m_GUMin(m_Reg(X), NegPattern),
7708 m_GUMax(m_Reg(X), NegPattern)))))) {
7709 MachineInstr *MinMaxMI;
7710 if (!mi_match(MI.getOperand(2).getReg(), MRI, m_MInstr(MinMaxMI)))
7711 return false;
7712 unsigned NewOpc = getInverseGMinMaxOpcode(MinMaxMI->getOpcode());
7713 if (isLegal({NewOpc, {DestTy}})) {
7714 MatchInfo = [=](MachineIRBuilder &B) {
7715 B.buildInstr(NewOpc, {DestReg}, {X, Sub0});
7716 };
7717 return true;
7718 }
7719 }
7720
7721 return false;
7722}
7723
7726
7727 if (tryFoldSelectOfConstants(Select, MatchInfo))
7728 return true;
7729
7730 if (tryFoldBoolSelectToLogic(Select, MatchInfo))
7731 return true;
7732
7733 return false;
7734}
7735
7736/// Fold (icmp Pred1 V1, C1) && (icmp Pred2 V2, C2)
7737/// or (icmp Pred1 V1, C1) || (icmp Pred2 V2, C2)
7738/// into a single comparison using range-based reasoning.
7739/// see InstCombinerImpl::foldAndOrOfICmpsUsingRanges.
7740bool CombinerHelper::tryFoldAndOrOrICmpsUsingRanges(
7741 GLogicalBinOp *Logic, BuildFnTy &MatchInfo) const {
7742 assert(Logic->getOpcode() != TargetOpcode::G_XOR && "unexpected xor");
7743 bool IsAnd = Logic->getOpcode() == TargetOpcode::G_AND;
7744 Register DstReg = Logic->getReg(0);
7745 Register LHS = Logic->getLHSReg();
7746 Register RHS = Logic->getRHSReg();
7747 unsigned Flags = Logic->getFlags();
7748
7749 // We need an G_ICMP on the LHS register.
7750 GICmp *Cmp1 = getOpcodeDef<GICmp>(LHS, MRI);
7751 if (!Cmp1)
7752 return false;
7753
7754 // We need an G_ICMP on the RHS register.
7755 GICmp *Cmp2 = getOpcodeDef<GICmp>(RHS, MRI);
7756 if (!Cmp2)
7757 return false;
7758
7759 // We want to fold the icmps.
7760 if (!MRI.hasOneNonDBGUse(Cmp1->getReg(0)) ||
7761 !MRI.hasOneNonDBGUse(Cmp2->getReg(0)))
7762 return false;
7763
7764 APInt C1;
7765 APInt C2;
7766 std::optional<ValueAndVReg> MaybeC1 =
7768 if (!MaybeC1)
7769 return false;
7770 C1 = MaybeC1->Value;
7771
7772 std::optional<ValueAndVReg> MaybeC2 =
7774 if (!MaybeC2)
7775 return false;
7776 C2 = MaybeC2->Value;
7777
7778 Register R1 = Cmp1->getLHSReg();
7779 Register R2 = Cmp2->getLHSReg();
7780 CmpInst::Predicate Pred1 = Cmp1->getCond();
7781 CmpInst::Predicate Pred2 = Cmp2->getCond();
7782 LLT CmpTy = MRI.getType(Cmp1->getReg(0));
7783 LLT CmpOperandTy = MRI.getType(R1);
7784
7785 if (CmpOperandTy.isPointer())
7786 return false;
7787
7788 // We build ands, adds, and constants of type CmpOperandTy.
7789 // They must be legal to build.
7790 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_AND, CmpOperandTy}) ||
7791 !isLegalOrBeforeLegalizer({TargetOpcode::G_ADD, CmpOperandTy}) ||
7792 !isConstantLegalOrBeforeLegalizer(CmpOperandTy))
7793 return false;
7794
7795 // Look through add of a constant offset on R1, R2, or both operands. This
7796 // allows us to interpret the R + C' < C'' range idiom into a proper range.
7797 std::optional<APInt> Offset1;
7798 std::optional<APInt> Offset2;
7799 if (R1 != R2) {
7800 if (GAdd *Add = getOpcodeDef<GAdd>(R1, MRI)) {
7801 std::optional<ValueAndVReg> MaybeOffset1 =
7803 if (MaybeOffset1) {
7804 R1 = Add->getLHSReg();
7805 Offset1 = MaybeOffset1->Value;
7806 }
7807 }
7808 if (GAdd *Add = getOpcodeDef<GAdd>(R2, MRI)) {
7809 std::optional<ValueAndVReg> MaybeOffset2 =
7811 if (MaybeOffset2) {
7812 R2 = Add->getLHSReg();
7813 Offset2 = MaybeOffset2->Value;
7814 }
7815 }
7816 }
7817
7818 if (R1 != R2)
7819 return false;
7820
7821 // We calculate the icmp ranges including maybe offsets.
7822 ConstantRange CR1 = ConstantRange::makeExactICmpRegion(
7823 IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, C1);
7824 if (Offset1)
7825 CR1 = CR1.subtract(*Offset1);
7826
7827 ConstantRange CR2 = ConstantRange::makeExactICmpRegion(
7828 IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, C2);
7829 if (Offset2)
7830 CR2 = CR2.subtract(*Offset2);
7831
7832 bool CreateMask = false;
7833 APInt LowerDiff;
7834 std::optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
7835 if (!CR) {
7836 // We need non-wrapping ranges.
7837 if (CR1.isWrappedSet() || CR2.isWrappedSet())
7838 return false;
7839
7840 // Check whether we have equal-size ranges that only differ by one bit.
7841 // In that case we can apply a mask to map one range onto the other.
7842 LowerDiff = CR1.getLower() ^ CR2.getLower();
7843 APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
7844 APInt CR1Size = CR1.getUpper() - CR1.getLower();
7845 if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
7846 CR1Size != CR2.getUpper() - CR2.getLower())
7847 return false;
7848
7849 CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
7850 CreateMask = true;
7851 }
7852
7853 if (IsAnd)
7854 CR = CR->inverse();
7855
7856 CmpInst::Predicate NewPred;
7857 APInt NewC, Offset;
7858 CR->getEquivalentICmp(NewPred, NewC, Offset);
7859
7860 // We take the result type of one of the original icmps, CmpTy, for
7861 // the to be build icmp. The operand type, CmpOperandTy, is used for
7862 // the other instructions and constants to be build. The types of
7863 // the parameters and output are the same for add and and. CmpTy
7864 // and the type of DstReg might differ. That is why we zext or trunc
7865 // the icmp into the destination register.
7866
7867 MatchInfo = [=](MachineIRBuilder &B) {
7868 if (CreateMask && Offset != 0) {
7869 auto TildeLowerDiff = B.buildConstant(CmpOperandTy, ~LowerDiff);
7870 auto And = B.buildAnd(CmpOperandTy, R1, TildeLowerDiff); // the mask.
7871 auto OffsetC = B.buildConstant(CmpOperandTy, Offset);
7872 auto Add = B.buildAdd(CmpOperandTy, And, OffsetC, Flags);
7873 auto NewCon = B.buildConstant(CmpOperandTy, NewC);
7874 auto ICmp = B.buildICmp(NewPred, CmpTy, Add, NewCon);
7875 B.buildZExtOrTrunc(DstReg, ICmp);
7876 } else if (CreateMask && Offset == 0) {
7877 auto TildeLowerDiff = B.buildConstant(CmpOperandTy, ~LowerDiff);
7878 auto And = B.buildAnd(CmpOperandTy, R1, TildeLowerDiff); // the mask.
7879 auto NewCon = B.buildConstant(CmpOperandTy, NewC);
7880 auto ICmp = B.buildICmp(NewPred, CmpTy, And, NewCon);
7881 B.buildZExtOrTrunc(DstReg, ICmp);
7882 } else if (!CreateMask && Offset != 0) {
7883 auto OffsetC = B.buildConstant(CmpOperandTy, Offset);
7884 auto Add = B.buildAdd(CmpOperandTy, R1, OffsetC, Flags);
7885 auto NewCon = B.buildConstant(CmpOperandTy, NewC);
7886 auto ICmp = B.buildICmp(NewPred, CmpTy, Add, NewCon);
7887 B.buildZExtOrTrunc(DstReg, ICmp);
7888 } else if (!CreateMask && Offset == 0) {
7889 auto NewCon = B.buildConstant(CmpOperandTy, NewC);
7890 auto ICmp = B.buildICmp(NewPred, CmpTy, R1, NewCon);
7891 B.buildZExtOrTrunc(DstReg, ICmp);
7892 } else {
7893 llvm_unreachable("unexpected configuration of CreateMask and Offset");
7894 }
7895 };
7896 return true;
7897}
7898
7899bool CombinerHelper::tryFoldLogicOfFCmps(GLogicalBinOp *Logic,
7900 BuildFnTy &MatchInfo) const {
7901 assert(Logic->getOpcode() != TargetOpcode::G_XOR && "unexpecte xor");
7902 Register DestReg = Logic->getReg(0);
7903 Register LHS = Logic->getLHSReg();
7904 Register RHS = Logic->getRHSReg();
7905 bool IsAnd = Logic->getOpcode() == TargetOpcode::G_AND;
7906
7907 // We need a compare on the LHS register.
7908 GFCmp *Cmp1 = getOpcodeDef<GFCmp>(LHS, MRI);
7909 if (!Cmp1)
7910 return false;
7911
7912 // We need a compare on the RHS register.
7913 GFCmp *Cmp2 = getOpcodeDef<GFCmp>(RHS, MRI);
7914 if (!Cmp2)
7915 return false;
7916
7917 LLT CmpTy = MRI.getType(Cmp1->getReg(0));
7918 LLT CmpOperandTy = MRI.getType(Cmp1->getLHSReg());
7919
7920 // We build one fcmp, want to fold the fcmps, replace the logic op,
7921 // and the fcmps must have the same shape.
7923 {TargetOpcode::G_FCMP, {CmpTy, CmpOperandTy}}) ||
7924 !MRI.hasOneNonDBGUse(Logic->getReg(0)) ||
7925 !MRI.hasOneNonDBGUse(Cmp1->getReg(0)) ||
7926 !MRI.hasOneNonDBGUse(Cmp2->getReg(0)) ||
7927 MRI.getType(Cmp1->getLHSReg()) != MRI.getType(Cmp2->getLHSReg()))
7928 return false;
7929
7930 CmpInst::Predicate PredL = Cmp1->getCond();
7931 CmpInst::Predicate PredR = Cmp2->getCond();
7932 Register LHS0 = Cmp1->getLHSReg();
7933 Register LHS1 = Cmp1->getRHSReg();
7934 Register RHS0 = Cmp2->getLHSReg();
7935 Register RHS1 = Cmp2->getRHSReg();
7936
7937 if (LHS0 == RHS1 && LHS1 == RHS0) {
7938 // Swap RHS operands to match LHS.
7939 PredR = CmpInst::getSwappedPredicate(PredR);
7940 std::swap(RHS0, RHS1);
7941 }
7942
7943 if (LHS0 == RHS0 && LHS1 == RHS1) {
7944 // We determine the new predicate.
7945 unsigned CmpCodeL = getFCmpCode(PredL);
7946 unsigned CmpCodeR = getFCmpCode(PredR);
7947 unsigned NewPred = IsAnd ? CmpCodeL & CmpCodeR : CmpCodeL | CmpCodeR;
7948 unsigned Flags = Cmp1->getFlags() | Cmp2->getFlags();
7949 MatchInfo = [=](MachineIRBuilder &B) {
7950 // The fcmp predicates fill the lower part of the enum.
7951 FCmpInst::Predicate Pred = static_cast<FCmpInst::Predicate>(NewPred);
7952 if (Pred == FCmpInst::FCMP_FALSE &&
7954 auto False = B.buildConstant(CmpTy, 0);
7955 B.buildZExtOrTrunc(DestReg, False);
7956 } else if (Pred == FCmpInst::FCMP_TRUE &&
7958 auto True = B.buildConstant(
7959 CmpTy,
7960 getICmpTrueVal(getTargetLowering(), CmpTy.isVector() /*isVector*/));
7961 B.buildZExtOrTrunc(DestReg, True);
7962 } else { // We take the predicate without predicate optimizations.
7963 auto Cmp = B.buildFCmp(Pred, CmpTy, LHS0, LHS1, Flags);
7964 B.buildZExtOrTrunc(DestReg, Cmp);
7965 }
7966 };
7967 return true;
7968 }
7969
7970 return false;
7971}
7972
7974 GAnd *And = cast<GAnd>(&MI);
7975
7976 if (tryFoldAndOrOrICmpsUsingRanges(And, MatchInfo))
7977 return true;
7978
7979 if (tryFoldLogicOfFCmps(And, MatchInfo))
7980 return true;
7981
7982 return false;
7983}
7984
7986 GOr *Or = cast<GOr>(&MI);
7987
7988 if (tryFoldAndOrOrICmpsUsingRanges(Or, MatchInfo))
7989 return true;
7990
7991 if (tryFoldLogicOfFCmps(Or, MatchInfo))
7992 return true;
7993
7994 return false;
7995}
7996
7998 BuildFnTy &MatchInfo) const {
8000
8001 // Addo has no flags
8002 Register Dst = Add->getReg(0);
8003 Register Carry = Add->getReg(1);
8004 Register LHS = Add->getLHSReg();
8005 Register RHS = Add->getRHSReg();
8006 bool IsSigned = Add->isSigned();
8007 LLT DstTy = MRI.getType(Dst);
8008 LLT CarryTy = MRI.getType(Carry);
8009
8010 // Canonicalize constant to RHS.
8011 if (isConstantOrConstantVectorI(LHS) && !isConstantOrConstantVectorI(RHS)) {
8012 if (IsSigned) {
8013 MatchInfo = [=](MachineIRBuilder &B) {
8014 B.buildSAddo(Dst, Carry, RHS, LHS);
8015 };
8016 return true;
8017 }
8018 // !IsSigned
8019 MatchInfo = [=](MachineIRBuilder &B) {
8020 B.buildUAddo(Dst, Carry, RHS, LHS);
8021 };
8022 return true;
8023 }
8024
8025 std::optional<APInt> MaybeLHS = getConstantOrConstantSplatVector(LHS);
8026 std::optional<APInt> MaybeRHS = getConstantOrConstantSplatVector(RHS);
8027
8028 // Fold addo(c1, c2) -> c3, carry.
8029 if (MaybeLHS && MaybeRHS && isConstantLegalOrBeforeLegalizer(DstTy) &&
8031 bool Overflow;
8032 APInt Result = IsSigned ? MaybeLHS->sadd_ov(*MaybeRHS, Overflow)
8033 : MaybeLHS->uadd_ov(*MaybeRHS, Overflow);
8034 MatchInfo = [=](MachineIRBuilder &B) {
8035 B.buildConstant(Dst, Result);
8036 B.buildConstant(Carry, Overflow);
8037 };
8038 return true;
8039 }
8040
8041 // Fold (addo x, 0) -> x, no carry
8042 if (MaybeRHS && *MaybeRHS == 0 && isConstantLegalOrBeforeLegalizer(CarryTy)) {
8043 MatchInfo = [=](MachineIRBuilder &B) {
8044 B.buildCopy(Dst, LHS);
8045 B.buildConstant(Carry, 0);
8046 };
8047 return true;
8048 }
8049
8050 // Given 2 constant operands whose sum does not overflow:
8051 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
8052 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
8053 GAdd *AddLHS = getOpcodeDef<GAdd>(LHS, MRI);
8054 if (MaybeRHS && AddLHS && MRI.hasOneNonDBGUse(Add->getReg(0)) &&
8055 ((IsSigned && AddLHS->getFlag(MachineInstr::MIFlag::NoSWrap)) ||
8056 (!IsSigned && AddLHS->getFlag(MachineInstr::MIFlag::NoUWrap)))) {
8057 std::optional<APInt> MaybeAddRHS =
8058 getConstantOrConstantSplatVector(AddLHS->getRHSReg());
8059 if (MaybeAddRHS) {
8060 bool Overflow;
8061 APInt NewC = IsSigned ? MaybeAddRHS->sadd_ov(*MaybeRHS, Overflow)
8062 : MaybeAddRHS->uadd_ov(*MaybeRHS, Overflow);
8063 if (!Overflow && isConstantLegalOrBeforeLegalizer(DstTy)) {
8064 if (IsSigned) {
8065 MatchInfo = [=](MachineIRBuilder &B) {
8066 auto ConstRHS = B.buildConstant(DstTy, NewC);
8067 B.buildSAddo(Dst, Carry, AddLHS->getLHSReg(), ConstRHS);
8068 };
8069 return true;
8070 }
8071 // !IsSigned
8072 MatchInfo = [=](MachineIRBuilder &B) {
8073 auto ConstRHS = B.buildConstant(DstTy, NewC);
8074 B.buildUAddo(Dst, Carry, AddLHS->getLHSReg(), ConstRHS);
8075 };
8076 return true;
8077 }
8078 }
8079 };
8080
8081 // We try to combine addo to non-overflowing add.
8082 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_ADD, {DstTy}}) ||
8084 return false;
8085
8086 // We try to combine uaddo to non-overflowing add.
8087 if (!IsSigned) {
8088 ConstantRange CRLHS =
8089 ConstantRange::fromKnownBits(VT->getKnownBits(LHS), /*IsSigned=*/false);
8090 ConstantRange CRRHS =
8091 ConstantRange::fromKnownBits(VT->getKnownBits(RHS), /*IsSigned=*/false);
8092
8093 switch (CRLHS.unsignedAddMayOverflow(CRRHS)) {
8095 return false;
8097 MatchInfo = [=](MachineIRBuilder &B) {
8098 B.buildAdd(Dst, LHS, RHS, MachineInstr::MIFlag::NoUWrap);
8099 B.buildConstant(Carry, 0);
8100 };
8101 return true;
8102 }
8105 MatchInfo = [=](MachineIRBuilder &B) {
8106 B.buildAdd(Dst, LHS, RHS);
8107 B.buildConstant(Carry, 1);
8108 };
8109 return true;
8110 }
8111 }
8112 return false;
8113 }
8114
8115 // We try to combine saddo to non-overflowing add.
8116
8117 // If LHS and RHS each have at least two sign bits, then there is no signed
8118 // overflow.
8119 if (VT->computeNumSignBits(RHS) > 1 && VT->computeNumSignBits(LHS) > 1) {
8120 MatchInfo = [=](MachineIRBuilder &B) {
8121 B.buildAdd(Dst, LHS, RHS, MachineInstr::MIFlag::NoSWrap);
8122 B.buildConstant(Carry, 0);
8123 };
8124 return true;
8125 }
8126
8127 ConstantRange CRLHS =
8128 ConstantRange::fromKnownBits(VT->getKnownBits(LHS), /*IsSigned=*/true);
8129 ConstantRange CRRHS =
8130 ConstantRange::fromKnownBits(VT->getKnownBits(RHS), /*IsSigned=*/true);
8131
8132 switch (CRLHS.signedAddMayOverflow(CRRHS)) {
8134 return false;
8136 MatchInfo = [=](MachineIRBuilder &B) {
8137 B.buildAdd(Dst, LHS, RHS, MachineInstr::MIFlag::NoSWrap);
8138 B.buildConstant(Carry, 0);
8139 };
8140 return true;
8141 }
8144 MatchInfo = [=](MachineIRBuilder &B) {
8145 B.buildAdd(Dst, LHS, RHS);
8146 B.buildConstant(Carry, 1);
8147 };
8148 return true;
8149 }
8150 }
8151
8152 return false;
8153}
8154
8156 BuildFnTy &MatchInfo) const {
8158 MatchInfo(Builder);
8159 Root->eraseFromParent();
8160}
8161
8163 int64_t Exponent) const {
8164 bool OptForSize = MI.getMF()->getFunction().hasOptSize();
8166}
8167
8169 int64_t Exponent) const {
8170 auto [Dst, Base] = MI.getFirst2Regs();
8171 LLT Ty = MRI.getType(Dst);
8172 int64_t ExpVal = Exponent;
8173
8174 if (ExpVal == 0) {
8175 Builder.buildFConstant(Dst, 1.0);
8176 MI.removeFromParent();
8177 return;
8178 }
8179
8180 if (ExpVal < 0)
8181 ExpVal = -ExpVal;
8182
8183 // We use the simple binary decomposition method from SelectionDAG ExpandPowI
8184 // to generate the multiply sequence. There are more optimal ways to do this
8185 // (for example, powi(x,15) generates one more multiply than it should), but
8186 // this has the benefit of being both really simple and much better than a
8187 // libcall.
8188 std::optional<SrcOp> Res;
8189 SrcOp CurSquare = Base;
8190 while (ExpVal > 0) {
8191 if (ExpVal & 1) {
8192 if (!Res)
8193 Res = CurSquare;
8194 else
8195 Res = Builder.buildFMul(Ty, *Res, CurSquare);
8196 }
8197
8198 CurSquare = Builder.buildFMul(Ty, CurSquare, CurSquare);
8199 ExpVal >>= 1;
8200 }
8201
8202 // If the original exponent was negative, invert the result, producing
8203 // 1/(x*x*x).
8204 if (Exponent < 0)
8205 Res = Builder.buildFDiv(Ty, Builder.buildFConstant(Ty, 1.0), *Res,
8206 MI.getFlags());
8207
8208 Builder.buildCopy(Dst, *Res);
8209 MI.eraseFromParent();
8210}
8211
8213 BuildFnTy &MatchInfo) const {
8214 // fold (A+C1)-C2 -> A+(C1-C2)
8215 const GSub *Sub = cast<GSub>(&MI);
8216 Register A, C1Reg;
8217 if (!mi_match(Sub->getLHSReg(), MRI, m_GAdd(m_Reg(A), m_Reg(C1Reg))))
8218 return false;
8219
8220 if (!MRI.hasOneNonDBGUse(Sub->getLHSReg()))
8221 return false;
8222
8223 APInt C2 = getIConstantFromReg(Sub->getRHSReg(), MRI);
8224 APInt C1 = getIConstantFromReg(C1Reg, MRI);
8225
8226 Register Dst = Sub->getReg(0);
8227 LLT DstTy = MRI.getType(Dst);
8228
8229 MatchInfo = [=](MachineIRBuilder &B) {
8230 auto Const = B.buildConstant(DstTy, C1 - C2);
8231 B.buildAdd(Dst, A, Const);
8232 };
8233
8234 return true;
8235}
8236
8238 BuildFnTy &MatchInfo) const {
8239 // fold C2-(A+C1) -> (C2-C1)-A
8240 const GSub *Sub = cast<GSub>(&MI);
8241 Register A, C1Reg;
8242 if (!mi_match(Sub->getRHSReg(), MRI, m_GAdd(m_Reg(A), m_Reg(C1Reg))))
8243 return false;
8244
8245 if (!MRI.hasOneNonDBGUse(Sub->getRHSReg()))
8246 return false;
8247
8248 APInt C2 = getIConstantFromReg(Sub->getLHSReg(), MRI);
8249 APInt C1 = getIConstantFromReg(C1Reg, MRI);
8250
8251 Register Dst = Sub->getReg(0);
8252 LLT DstTy = MRI.getType(Dst);
8253
8254 MatchInfo = [=](MachineIRBuilder &B) {
8255 auto Const = B.buildConstant(DstTy, C2 - C1);
8256 B.buildSub(Dst, Const, A);
8257 };
8258
8259 return true;
8260}
8261
8263 BuildFnTy &MatchInfo) const {
8264 // fold (A-C1)-C2 -> A-(C1+C2)
8265 const GSub *Sub1 = cast<GSub>(&MI);
8266 Register A, C1Reg;
8267 if (!mi_match(Sub1->getLHSReg(), MRI, m_GSub(m_Reg(A), m_Reg(C1Reg))))
8268 return false;
8269
8270 if (!MRI.hasOneNonDBGUse(Sub1->getLHSReg()))
8271 return false;
8272
8273 APInt C2 = getIConstantFromReg(Sub1->getRHSReg(), MRI);
8274 APInt C1 = getIConstantFromReg(C1Reg, MRI);
8275
8276 Register Dst = Sub1->getReg(0);
8277 LLT DstTy = MRI.getType(Dst);
8278
8279 MatchInfo = [=](MachineIRBuilder &B) {
8280 auto Const = B.buildConstant(DstTy, C1 + C2);
8281 B.buildSub(Dst, A, Const);
8282 };
8283
8284 return true;
8285}
8286
8288 BuildFnTy &MatchInfo) const {
8289 // fold (C1-A)-C2 -> (C1-C2)-A
8290 const GSub *Sub1 = cast<GSub>(&MI);
8291 Register C1Reg, A;
8292 if (!mi_match(Sub1->getLHSReg(), MRI, m_GSub(m_Reg(C1Reg), m_Reg(A))))
8293 return false;
8294
8295 if (!MRI.hasOneNonDBGUse(Sub1->getLHSReg()))
8296 return false;
8297
8298 APInt C2 = getIConstantFromReg(Sub1->getRHSReg(), MRI);
8299 APInt C1 = getIConstantFromReg(C1Reg, MRI);
8300
8301 Register Dst = Sub1->getReg(0);
8302 LLT DstTy = MRI.getType(Dst);
8303
8304 MatchInfo = [=](MachineIRBuilder &B) {
8305 auto Const = B.buildConstant(DstTy, C1 - C2);
8306 B.buildSub(Dst, Const, A);
8307 };
8308
8309 return true;
8310}
8311
8313 BuildFnTy &MatchInfo) const {
8314 // fold ((A-C1)+C2) -> (A+(C2-C1))
8315 const GAdd *Add = cast<GAdd>(&MI);
8316 Register A, C1Reg;
8317 if (!mi_match(Add->getLHSReg(), MRI, m_GSub(m_Reg(A), m_Reg(C1Reg))))
8318 return false;
8319
8320 if (!MRI.hasOneNonDBGUse(Add->getLHSReg()))
8321 return false;
8322
8323 APInt C2 = getIConstantFromReg(Add->getRHSReg(), MRI);
8324 APInt C1 = getIConstantFromReg(C1Reg, MRI);
8325
8326 Register Dst = Add->getReg(0);
8327 LLT DstTy = MRI.getType(Dst);
8328
8329 MatchInfo = [=](MachineIRBuilder &B) {
8330 auto Const = B.buildConstant(DstTy, C2 - C1);
8331 B.buildAdd(Dst, A, Const);
8332 };
8333
8334 return true;
8335}
8336
8338 const MachineInstr &MI, BuildFnTy &MatchInfo) const {
8339 const GUnmerge *Unmerge = cast<GUnmerge>(&MI);
8340
8341 if (!MRI.hasOneNonDBGUse(Unmerge->getSourceReg()))
8342 return false;
8343
8344 LLT DstTy = MRI.getType(Unmerge->getReg(0));
8345
8346 // $bv:_(<8 x s8>) = G_BUILD_VECTOR ....
8347 // $any:_(<8 x s16>) = G_ANYEXT $bv
8348 // $uv:_(<4 x s16>), $uv1:_(<4 x s16>) = G_UNMERGE_VALUES $any
8349 //
8350 // ->
8351 //
8352 // $any:_(s16) = G_ANYEXT $bv[0]
8353 // $any1:_(s16) = G_ANYEXT $bv[1]
8354 // $any2:_(s16) = G_ANYEXT $bv[2]
8355 // $any3:_(s16) = G_ANYEXT $bv[3]
8356 // $any4:_(s16) = G_ANYEXT $bv[4]
8357 // $any5:_(s16) = G_ANYEXT $bv[5]
8358 // $any6:_(s16) = G_ANYEXT $bv[6]
8359 // $any7:_(s16) = G_ANYEXT $bv[7]
8360 // $uv:_(<4 x s16>) = G_BUILD_VECTOR $any, $any1, $any2, $any3
8361 // $uv1:_(<4 x s16>) = G_BUILD_VECTOR $any4, $any5, $any6, $any7
8362
8363 // We want to unmerge into vectors.
8364 if (!DstTy.isFixedVector())
8365 return false;
8366
8367 Register AnySrcReg;
8368 if (!mi_match(Unmerge->getSourceReg(), MRI, m_GAnyExt(m_Reg(AnySrcReg))))
8369 return false;
8370
8371 GBuildVector *BV;
8372 if (mi_match(AnySrcReg, MRI, m_GBuildVector(BV))) {
8373 // G_UNMERGE_VALUES G_ANYEXT G_BUILD_VECTOR
8374
8375 if (!MRI.hasOneNonDBGUse(BV->getReg(0)))
8376 return false;
8377
8378 // FIXME: check element types?
8379 if (BV->getNumSources() % Unmerge->getNumDefs() != 0)
8380 return false;
8381
8382 LLT BigBvTy = MRI.getType(BV->getReg(0));
8383 LLT SmallBvTy = DstTy;
8384 LLT SmallBvElemenTy = SmallBvTy.getElementType();
8385
8387 {TargetOpcode::G_BUILD_VECTOR, {SmallBvTy, SmallBvElemenTy}}))
8388 return false;
8389
8390 // We check the legality of scalar anyext.
8392 {TargetOpcode::G_ANYEXT,
8393 {SmallBvElemenTy, BigBvTy.getElementType()}}))
8394 return false;
8395
8396 MatchInfo = [=](MachineIRBuilder &B) {
8397 // Build into each G_UNMERGE_VALUES def
8398 // a small build vector with anyext from the source build vector.
8399 for (unsigned I = 0; I < Unmerge->getNumDefs(); ++I) {
8401 for (unsigned J = 0; J < SmallBvTy.getNumElements(); ++J) {
8402 Register SourceArray =
8403 BV->getSourceReg(I * SmallBvTy.getNumElements() + J);
8404 auto AnyExt = B.buildAnyExt(SmallBvElemenTy, SourceArray);
8405 Ops.push_back(AnyExt.getReg(0));
8406 }
8407 B.buildBuildVector(Unmerge->getOperand(I).getReg(), Ops);
8408 };
8409 };
8410 return true;
8411 };
8412
8413 return false;
8414}
8415
8417 BuildFnTy &MatchInfo) const {
8418
8419 bool Changed = false;
8420 auto &Shuffle = cast<GShuffleVector>(MI);
8421 ArrayRef<int> OrigMask = Shuffle.getMask();
8422 SmallVector<int, 16> NewMask;
8423 const LLT SrcTy = MRI.getType(Shuffle.getSrc1Reg());
8424 const unsigned NumSrcElems = SrcTy.isVector() ? SrcTy.getNumElements() : 1;
8425 const unsigned NumDstElts = OrigMask.size();
8426 for (unsigned i = 0; i != NumDstElts; ++i) {
8427 int Idx = OrigMask[i];
8428 if (Idx >= (int)NumSrcElems) {
8429 Idx = -1;
8430 Changed = true;
8431 }
8432 NewMask.push_back(Idx);
8433 }
8434
8435 if (!Changed)
8436 return false;
8437
8438 MatchInfo = [&, NewMask = std::move(NewMask)](MachineIRBuilder &B) {
8439 B.buildShuffleVector(MI.getOperand(0), MI.getOperand(1), MI.getOperand(2),
8440 std::move(NewMask));
8441 };
8442
8443 return true;
8444}
8445
8446static void commuteMask(MutableArrayRef<int> Mask, const unsigned NumElems) {
8447 const unsigned MaskSize = Mask.size();
8448 for (unsigned I = 0; I < MaskSize; ++I) {
8449 int Idx = Mask[I];
8450 if (Idx < 0)
8451 continue;
8452
8453 if (Idx < (int)NumElems)
8454 Mask[I] = Idx + NumElems;
8455 else
8456 Mask[I] = Idx - NumElems;
8457 }
8458}
8459
8461 if (!MRI.getType(Reg).isFixedVector())
8462 return false;
8463 return matchUnaryPredicate(MRI, Reg, [](const Constant *C) {
8464 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8465 return CI && (CI->isZero() || CI->isOne());
8466 });
8467}
8468
8470 BuildFnTy &MatchInfo) const {
8471
8472 auto &Shuffle = cast<GShuffleVector>(MI);
8473 // If any of the two inputs is already undef, don't check the mask again to
8474 // prevent infinite loop
8475 if (getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, Shuffle.getSrc1Reg(), MRI))
8476 return false;
8477
8478 if (getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, Shuffle.getSrc2Reg(), MRI))
8479 return false;
8480
8481 const LLT DstTy = MRI.getType(Shuffle.getReg(0));
8482 const LLT Src1Ty = MRI.getType(Shuffle.getSrc1Reg());
8484 {TargetOpcode::G_SHUFFLE_VECTOR, {DstTy, Src1Ty}}))
8485 return false;
8486
8487 ArrayRef<int> Mask = Shuffle.getMask();
8488 const unsigned NumSrcElems = Src1Ty.getNumElements();
8489
8490 bool TouchesSrc1 = false;
8491 bool TouchesSrc2 = false;
8492 const unsigned NumElems = Mask.size();
8493 for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
8494 if (Mask[Idx] < 0)
8495 continue;
8496
8497 if (Mask[Idx] < (int)NumSrcElems)
8498 TouchesSrc1 = true;
8499 else
8500 TouchesSrc2 = true;
8501 }
8502
8503 if (TouchesSrc1 == TouchesSrc2)
8504 return false;
8505
8506 Register NewSrc1 = Shuffle.getSrc1Reg();
8507 SmallVector<int, 16> NewMask(Mask);
8508 if (TouchesSrc2) {
8509 NewSrc1 = Shuffle.getSrc2Reg();
8510 commuteMask(NewMask, NumSrcElems);
8511 }
8512
8513 MatchInfo = [=, &Shuffle](MachineIRBuilder &B) {
8514 auto Undef = B.buildUndef(Src1Ty);
8515 B.buildShuffleVector(Shuffle.getReg(0), NewSrc1, Undef, NewMask);
8516 };
8517
8518 return true;
8519}
8520
8522 BuildFnTy &MatchInfo) const {
8523 const GSubCarryOut *Subo = cast<GSubCarryOut>(&MI);
8524
8525 Register Dst = Subo->getReg(0);
8526 Register LHS = Subo->getLHSReg();
8527 Register RHS = Subo->getRHSReg();
8528 Register Carry = Subo->getCarryOutReg();
8529 LLT DstTy = MRI.getType(Dst);
8530 LLT CarryTy = MRI.getType(Carry);
8531
8532 // Check legality before known bits.
8533 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SUB, {DstTy}}) ||
8535 return false;
8536
8537 ConstantRange KBLHS =
8538 ConstantRange::fromKnownBits(VT->getKnownBits(LHS),
8539 /* IsSigned=*/Subo->isSigned());
8540 ConstantRange KBRHS =
8541 ConstantRange::fromKnownBits(VT->getKnownBits(RHS),
8542 /* IsSigned=*/Subo->isSigned());
8543
8544 if (Subo->isSigned()) {
8545 // G_SSUBO
8546 switch (KBLHS.signedSubMayOverflow(KBRHS)) {
8548 return false;
8550 MatchInfo = [=](MachineIRBuilder &B) {
8551 B.buildSub(Dst, LHS, RHS, MachineInstr::MIFlag::NoSWrap);
8552 B.buildConstant(Carry, 0);
8553 };
8554 return true;
8555 }
8558 MatchInfo = [=](MachineIRBuilder &B) {
8559 B.buildSub(Dst, LHS, RHS);
8560 B.buildConstant(Carry, getICmpTrueVal(getTargetLowering(),
8561 /*isVector=*/CarryTy.isVector()));
8562 };
8563 return true;
8564 }
8565 }
8566 return false;
8567 }
8568
8569 // G_USUBO
8570 switch (KBLHS.unsignedSubMayOverflow(KBRHS)) {
8572 return false;
8574 MatchInfo = [=](MachineIRBuilder &B) {
8575 B.buildSub(Dst, LHS, RHS, MachineInstr::MIFlag::NoUWrap);
8576 B.buildConstant(Carry, 0);
8577 };
8578 return true;
8579 }
8582 MatchInfo = [=](MachineIRBuilder &B) {
8583 B.buildSub(Dst, LHS, RHS);
8584 B.buildConstant(Carry, getICmpTrueVal(getTargetLowering(),
8585 /*isVector=*/CarryTy.isVector()));
8586 };
8587 return true;
8588 }
8589 }
8590
8591 return false;
8592}
8593
8594// Fold (ctlz (xor x, (sra x, bitwidth-1))) -> (add (ctls x), 1).
8595// Fold (ctlz (or (shl (xor x, (sra x, bitwidth-1)), 1), 1) -> (ctls x)
8597 BuildFnTy &MatchInfo) const {
8598 assert((CtlzMI.getOpcode() == TargetOpcode::G_CTLZ ||
8599 CtlzMI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_POISON) &&
8600 "Expected G_CTLZ variant");
8601
8602 const Register Dst = CtlzMI.getOperand(0).getReg();
8603 Register Src = CtlzMI.getOperand(1).getReg();
8604
8605 LLT Ty = MRI.getType(Dst);
8606 LLT SrcTy = MRI.getType(Src);
8607
8608 if (!(Ty.isValid() && Ty.isScalar()))
8609 return false;
8610
8611 if (!LI)
8612 return false;
8613
8614 SmallVector<LLT, 2> QueryTypes = {Ty, SrcTy};
8615 LegalityQuery Query(TargetOpcode::G_CTLS, QueryTypes);
8616
8617 switch (LI->getAction(Query).Action) {
8618 default:
8619 return false;
8623 break;
8624 }
8625
8626 // Src = or(shl(V, 1), 1) -> Src=V; NeedAdd = False
8627 Register V;
8628 bool NeedAdd = true;
8629 if (mi_match(Src, MRI,
8631 m_SpecificICst(1))))) {
8632 NeedAdd = false;
8633 Src = V;
8634 }
8635
8636 unsigned BitWidth = Ty.getScalarSizeInBits();
8637
8638 Register X;
8639 if (!mi_match(Src, MRI,
8642 m_SpecificICst(BitWidth - 1)))))))
8643 return false;
8644
8645 MatchInfo = [=](MachineIRBuilder &B) {
8646 if (!NeedAdd) {
8647 B.buildCTLS(Dst, X);
8648 return;
8649 }
8650
8651 auto Ctls = B.buildCTLS(Ty, X);
8652 auto One = B.buildConstant(Ty, 1);
8653
8654 B.buildAdd(Dst, Ctls, One);
8655 };
8656
8657 return true;
8658}
8659
8661 const ConstantFP *C = getConstantFPVRegVal(Reg, MRI);
8662 return C && C->getValueAPF().isNaN();
8663}
8664
8666 unsigned ZeroPoisonOpc) const {
8667 const bool IsCtlzPair = Opc == TargetOpcode::G_CTLZ &&
8668 ZeroPoisonOpc == TargetOpcode::G_CTLZ_ZERO_POISON;
8669 const bool IsCttzPair = Opc == TargetOpcode::G_CTTZ &&
8670 ZeroPoisonOpc == TargetOpcode::G_CTTZ_ZERO_POISON;
8671 if (MI.getOpcode() != Opc || (!IsCtlzPair && !IsCttzPair))
8672 return false;
8673 if (!VT)
8674 return false;
8675
8676 Register Src = MI.getOperand(1).getReg();
8677 if (!VT->isKnownNeverZero(Src))
8678 return false;
8679
8680 LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
8681 LLT SrcTy = MRI.getType(Src);
8682 return isLegalOrBeforeLegalizer({ZeroPoisonOpc, {DstTy, SrcTy}});
8683}
8684
8685static APInt getDemandedBitsForLogicalOp(unsigned Opcode, const APInt &Demanded,
8686 const KnownBits &OtherKnown) {
8687 assert((Opcode == TargetOpcode::G_AND || Opcode == TargetOpcode::G_OR) &&
8688 "Expected G_AND or G_OR");
8689 return Demanded &
8690 ~(Opcode == TargetOpcode::G_AND ? OtherKnown.Zero : OtherKnown.One);
8691}
8692
8693static std::optional<unsigned>
8694getValidConstShiftAmt(const std::optional<APInt> &Amt, unsigned BW) {
8695 if (!Amt || Amt->uge(BW))
8696 return std::nullopt;
8697 return Amt->getZExtValue();
8698}
8699
8701 const APInt &DemandedBits,
8702 unsigned ShAmt) {
8703 assert(ShAmt < DemandedBits.getBitWidth() &&
8704 "shift amount must be less than the bit width");
8705 switch (Opcode) {
8706 case TargetOpcode::G_SHL:
8707 return DemandedBits.lshr(ShAmt);
8708 case TargetOpcode::G_LSHR:
8709 return DemandedBits.shl(ShAmt);
8710 case TargetOpcode::G_ASHR: {
8711 APInt Src = DemandedBits.shl(ShAmt);
8712 if (DemandedBits.countLeadingZeros() < ShAmt)
8713 Src.setSignBit();
8714 return Src;
8715 }
8716 default:
8717 llvm_unreachable("not a shift opcode");
8718 }
8719}
8720
8721Register CombinerHelper::simplifyMultipleUseDemandedBits(
8722 Register R, const APInt &DemandedBits, unsigned Depth) const {
8723 assert(R.isVirtual() && "Expected a virtual register");
8724 assert(!DemandedBits.isZero() && "Zero demand is handled by the caller");
8726 return Register();
8727
8728 [[maybe_unused]] LLT Ty = MRI.getType(R);
8729 assert(Ty.isValid() && "Expected a typed register");
8730 assert(DemandedBits.getBitWidth() == Ty.getScalarSizeInBits() &&
8731 "DemandedBits width must match the register scalar type");
8732
8733 MachineInstr *DefMI = MRI.getVRegDef(R);
8734 assert(DefMI && "Expected a definition in generic SSA MIR");
8735 if (!isa<GAnd>(DefMI) && !isa<GOr>(DefMI))
8736 return Register();
8737
8738 unsigned Opcode = DefMI->getOpcode();
8739 auto *Logic = cast<GLogicalBinOp>(DefMI);
8740 Register LHS = Logic->getLHSReg();
8741 Register RHS = Logic->getRHSReg();
8742 assert(MRI.getType(LHS) == Ty && MRI.getType(RHS) == Ty &&
8743 "Logical operands must match the result type");
8744
8745 auto LookThrough = [&](Register X, Register CReg) -> Register {
8746 std::optional<APInt> C = getConstantOrConstantSplatVector(CReg);
8747 if (!C || C->getBitWidth() != DemandedBits.getBitWidth())
8748 return Register();
8749 bool BypassToX = Opcode == TargetOpcode::G_AND
8750 ? DemandedBits.isSubsetOf(*C)
8751 : DemandedBits.isSubsetOf(~*C);
8752 if (BypassToX) {
8753 if (Register Deeper =
8754 simplifyMultipleUseDemandedBits(X, DemandedBits, Depth + 1))
8755 return Deeper;
8756 return X;
8757 }
8758 bool BypassToC = Opcode == TargetOpcode::G_AND
8759 ? DemandedBits.isSubsetOf(~*C)
8760 : DemandedBits.isSubsetOf(*C);
8761 if (BypassToC)
8762 return CReg;
8763 return Register();
8764 };
8765
8766 if (Register Repl = LookThrough(LHS, RHS))
8767 return Repl;
8768 return LookThrough(RHS, LHS);
8769}
8770
8771bool CombinerHelper::simplifyDemandedBitsImpl(MachineInstr &MI, unsigned OpNo,
8772 const APInt &DemandedBits,
8773 KnownBits &Known, unsigned Depth,
8774 bool DoRewrite) const {
8775 Known = KnownBits(DemandedBits.getBitWidth());
8776 assert(MI.getOperand(OpNo).isReg() && !MI.getOperand(OpNo).isDef() &&
8777 "Expected a register use");
8778 Register OpReg = MI.getOperand(OpNo).getReg();
8779 assert(OpReg.isVirtual() && "Expected a virtual register");
8780 LLT OpTy = MRI.getType(OpReg);
8781 assert(OpTy.isValid() && "Expected a typed register");
8782 assert(DemandedBits.getBitWidth() == OpTy.getScalarSizeInBits() &&
8783 "DemandedBits width must match the operand scalar type");
8784
8785 MachineInstr *DefMI = MRI.getVRegDef(OpReg);
8786 assert(DefMI && "Expected a definition in generic SSA MIR");
8787 // Undemanded bits can still affect poison-generating flags in the user.
8788 auto DropPoisonFlags = [&]() {
8789 if (!DoRewrite ||
8791 return;
8792 Observer.changingInstr(MI);
8794 Observer.changedInstr(MI);
8795 };
8796 // Debug users can observe bits that are not demanded by other users.
8797 auto InvalidateDebugUses = [&](const APInt &Demanded) {
8798 if (DoRewrite && !Demanded.isAllOnes())
8799 MRI.markUsesInDebugValueAsUndef(OpReg);
8800 };
8801 auto Rewrite = [&](Register Repl) {
8802 if (!DoRewrite || Repl == OpReg)
8803 return Repl != OpReg;
8804 DropPoisonFlags();
8805 if (DefMI->getNumExplicitDefs() == 1 && MRI.hasOneNonDBGUse(OpReg)) {
8806 InvalidateDebugUses(DemandedBits);
8807 replaceRegWith(MRI, OpReg, Repl);
8808 eraseInst(*DefMI);
8809 } else {
8810 replaceRegOpWith(MRI, MI.getOperand(OpNo), Repl);
8811 }
8812 return true;
8813 };
8814
8815 if (DemandedBits.isZero()) {
8816 if (DefMI->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
8817 return false;
8818 if (!DoRewrite)
8819 return true;
8820 MachineBasicBlock &SaveMBB = Builder.getMBB();
8821 MachineBasicBlock::iterator SavePt = Builder.getInsertPt();
8822 DebugLoc SaveDL = Builder.getDL();
8823 Builder.setInstrAndDebugLoc(MI);
8824 Register Undef = Builder.buildUndef(OpTy).getReg(0);
8825 Builder.setInsertPt(SaveMBB, SavePt);
8826 Builder.setDebugLoc(SaveDL);
8827 // The producer may have side effects; replace only this use.
8828 DropPoisonFlags();
8829 replaceRegOpWith(MRI, MI.getOperand(OpNo), Undef);
8830 return true;
8831 }
8832
8833 if (!VT)
8834 return false;
8835
8836 unsigned BW = DemandedBits.getBitWidth();
8837 auto GiveUp = [&]() {
8838 APInt DemandedElts = OpTy.isFixedVector()
8840 : APInt(1, 1);
8841 Known = VT->getKnownBits(OpReg, DemandedElts, Depth);
8842 return false;
8843 };
8844
8846 return GiveUp();
8847
8848 // Shared defs require full demand unless this use can be rerouted to an
8849 // existing value that agrees on its demanded bits.
8850 APInt Demanded = DemandedBits;
8851 if (!MRI.hasOneNonDBGUse(OpReg) && !Demanded.isAllOnes()) {
8852 if (Register Repl =
8853 simplifyMultipleUseDemandedBits(OpReg, Demanded, Depth)) {
8854 Known = VT->getKnownBits(Repl);
8855 if (Rewrite(Repl))
8856 return true;
8857 }
8858 Demanded = APInt::getAllOnes(BW);
8859 }
8860
8861 unsigned Opcode = DefMI->getOpcode();
8862 switch (Opcode) {
8863 case TargetOpcode::G_AND:
8864 case TargetOpcode::G_OR: {
8865 auto *Logic = cast<GLogicalBinOp>(DefMI);
8866 Register LHS = Logic->getLHSReg();
8867 Register RHS = Logic->getRHSReg();
8868 assert(MRI.getType(LHS) == OpTy && MRI.getType(RHS) == OpTy &&
8869 "Logical operands must match the result type");
8870 auto SimplifyWithConst = [&](Register X,
8871 Register CReg) -> std::optional<Register> {
8872 std::optional<APInt> C = getConstantOrConstantSplatVector(CReg);
8873 if (!C)
8874 return std::nullopt;
8875 assert(C->getBitWidth() == BW && "Constant width must match its type");
8876 // Check redundancy before rewriting X can change its known bits.
8877 if (Opcode == TargetOpcode::G_AND) {
8878 if (Demanded.isSubsetOf(*C | VT->getKnownBits(X).Zero))
8879 return X;
8880 if (Demanded.isSubsetOf(~*C))
8881 return CReg;
8882 return std::nullopt;
8883 }
8884 if (Demanded.isSubsetOf(~*C | VT->getKnownBits(X).One))
8885 return X;
8886 if (Demanded.isSubsetOf(*C))
8887 return CReg;
8888 return std::nullopt;
8889 };
8890
8891 // Compute known bits before a rewrite can erase the def.
8892 if (std::optional<Register> Repl = SimplifyWithConst(LHS, RHS)) {
8893 Known = VT->getKnownBits(*Repl);
8894 if (Rewrite(*Repl))
8895 return true;
8896 }
8897 if (std::optional<Register> Repl = SimplifyWithConst(RHS, LHS)) {
8898 Known = VT->getKnownBits(*Repl);
8899 if (Rewrite(*Repl))
8900 return true;
8901 }
8902
8903 KnownBits RHSKnown(BW);
8904 bool Changed = simplifyDemandedBitsImpl(*DefMI, /*OpNo=*/2, Demanded,
8905 RHSKnown, Depth + 1, DoRewrite);
8906 APInt LHSDemand = getDemandedBitsForLogicalOp(Opcode, Demanded, RHSKnown);
8907 KnownBits LHSKnown(BW);
8908 Changed |= simplifyDemandedBitsImpl(*DefMI, /*OpNo=*/1, LHSDemand, LHSKnown,
8909 Depth + 1, DoRewrite);
8910 if (!Changed && MRI.hasOneNonDBGUse(RHS) &&
8911 !getConstantOrConstantSplatVector(RHS)) {
8912 // Reduced-demand LHS facts cannot justify reducing the RHS demand.
8913 APInt RHSDemand =
8914 LHSDemand == Demanded
8915 ? getDemandedBitsForLogicalOp(Opcode, Demanded, LHSKnown)
8917 Opcode, Demanded,
8918 VT->getKnownBits(
8919 LHS,
8920 OpTy.isFixedVector()
8921 ? APInt::getAllOnes(OpTy.getNumElements())
8922 : APInt(1, 1),
8923 Depth + 1));
8924 if (RHSDemand != Demanded) {
8925 // Keep full-demand RHS facts if the reduced-demand retry fails.
8926 KnownBits RetryKnown(BW);
8927 Changed = simplifyDemandedBitsImpl(*DefMI, /*OpNo=*/2, RHSDemand,
8928 RetryKnown, Depth + 1, DoRewrite);
8929 }
8930 }
8931 if (Changed) {
8932 DropPoisonFlags();
8933 InvalidateDebugUses(Demanded);
8934 }
8935 Known = Opcode == TargetOpcode::G_AND ? LHSKnown & RHSKnown
8936 : LHSKnown | RHSKnown;
8937 return Changed;
8938 }
8939
8940 case TargetOpcode::G_ADD:
8941 case TargetOpcode::G_SUB: {
8942 // The low bits of a sum or a difference only depend on the low bits of the
8943 // operands, as carries and borrows only propagate upwards.
8944 APInt OpDemand = APInt::getLowBitsSet(BW, Demanded.getActiveBits());
8945 KnownBits LHSKnown(BW), RHSKnown(BW);
8946 bool Changed = simplifyDemandedBitsImpl(*DefMI, /*OpNo=*/1, OpDemand,
8947 LHSKnown, Depth + 1, DoRewrite);
8948 Changed |= simplifyDemandedBitsImpl(*DefMI, /*OpNo=*/2, OpDemand, RHSKnown,
8949 Depth + 1, DoRewrite);
8950 if (Changed) {
8951 DropPoisonFlags();
8952 InvalidateDebugUses(Demanded);
8953 }
8954 // Changing an operand drops the flags, so only use them if nothing changed.
8955 bool NSW = !Changed && DefMI->getFlag(MachineInstr::NoSWrap);
8956 bool NUW = !Changed && DefMI->getFlag(MachineInstr::NoUWrap);
8957 Known = Opcode == TargetOpcode::G_ADD
8958 ? KnownBits::add(LHSKnown, RHSKnown, NSW, NUW)
8959 : KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
8960 return Changed;
8961 }
8962
8963 case TargetOpcode::G_SHL:
8964 case TargetOpcode::G_LSHR:
8965 case TargetOpcode::G_ASHR: {
8966 std::optional<unsigned> ShAmt = getValidConstShiftAmt(
8967 getConstantOrConstantSplatVector(DefMI->getOperand(2).getReg()), BW);
8968 if (!ShAmt)
8969 return GiveUp();
8970
8971 APInt SrcDemand = getDemandedSrcBitsForShiftConst(Opcode, Demanded, *ShAmt);
8972 KnownBits SrcKnown(BW);
8973 bool Changed = simplifyDemandedBitsImpl(*DefMI, /*OpNo=*/1, SrcDemand,
8974 SrcKnown, Depth + 1, DoRewrite);
8975 if (Changed) {
8976 DropPoisonFlags();
8977 InvalidateDebugUses(Demanded);
8978 }
8979 KnownBits AmtKnown = KnownBits::makeConstant(APInt(BW, *ShAmt));
8980 switch (Opcode) {
8981 case TargetOpcode::G_SHL:
8982 Known = KnownBits::shl(SrcKnown, AmtKnown);
8983 break;
8984 case TargetOpcode::G_LSHR:
8985 Known = KnownBits::lshr(SrcKnown, AmtKnown);
8986 break;
8987 case TargetOpcode::G_ASHR: {
8988 // ASHR and LSHR agree outside sign fill or for nonnegative inputs.
8989 LLT AmtTy = MRI.getType(DefMI->getOperand(2).getReg());
8990 bool LShrLegal = isPreLegalize() || !LI ||
8991 isLegal({TargetOpcode::G_LSHR, {OpTy, AmtTy}});
8992 if ((Demanded.countLeadingZeros() >= *ShAmt ||
8993 SrcKnown.isNonNegative()) &&
8994 LShrLegal) {
8995 if (DoRewrite) {
8996 MachineBasicBlock &SaveMBB = Builder.getMBB();
8997 MachineBasicBlock::iterator SavePt = Builder.getInsertPt();
8998 DebugLoc SaveDL = Builder.getDL();
8999 Builder.setInstrAndDebugLoc(*DefMI);
9000 auto Lshr = Builder.buildLShr(OpTy, DefMI->getOperand(1).getReg(),
9001 DefMI->getOperand(2).getReg());
9002 Builder.setInsertPt(SaveMBB, SavePt);
9003 Builder.setDebugLoc(SaveDL);
9004 Rewrite(Lshr.getReg(0));
9005 Known = KnownBits::lshr(SrcKnown, AmtKnown);
9006 }
9007 return true;
9008 }
9009 Known = KnownBits::ashr(SrcKnown, AmtKnown);
9010 break;
9011 }
9012 }
9013 return Changed;
9014 }
9015 default:
9016 return GiveUp();
9017 }
9018}
9019
9021 const APInt &DemandedBits,
9023 unsigned Depth) const {
9024 return simplifyDemandedBitsImpl(MI, OpNo, DemandedBits, Known, Depth,
9025 /*DoRewrite=*/true);
9026}
9027
9029 BuildFnTy &MatchInfo) const {
9030 Register Dst = MI.getOperand(0).getReg();
9031 LLT Ty = MRI.getType(Dst);
9032 assert(Ty.isValid() && "Expected a typed generic result");
9033 if (!VT || Ty.isVector())
9034 return false;
9035
9036 APInt RootDemand = APInt::getAllOnes(Ty.getScalarSizeInBits());
9037 auto Probe = [&](unsigned OpNo, const APInt &OpDemand, KnownBits &Known) {
9038 if (!simplifyDemandedBitsImpl(MI, OpNo, OpDemand, Known, /*Depth=*/0,
9039 /*DoRewrite=*/false))
9040 return false;
9041
9042 MatchInfo = [this, &MI, OpNo, OpDemand](MachineIRBuilder &) {
9043 KnownBits K(OpDemand.getBitWidth());
9044 simplifyDemandedBits(MI, OpNo, OpDemand, K);
9045 };
9046 return true;
9047 };
9048
9049 unsigned Opcode = MI.getOpcode();
9050 switch (Opcode) {
9051 case TargetOpcode::G_SHL:
9052 case TargetOpcode::G_LSHR:
9053 case TargetOpcode::G_ASHR: {
9054 std::optional<unsigned> ShAmt = getValidConstShiftAmt(
9055 getConstantOrConstantSplatVector(MI.getOperand(2).getReg()),
9056 RootDemand.getBitWidth());
9057 if (!ShAmt)
9058 return false;
9059 APInt SrcDemand =
9060 getDemandedSrcBitsForShiftConst(Opcode, RootDemand, *ShAmt);
9061 KnownBits SrcKnown(RootDemand.getBitWidth());
9062 return Probe(/*OpNo=*/1, SrcDemand, SrcKnown);
9063 }
9064 default:
9065 return false;
9066 case TargetOpcode::G_AND:
9067 case TargetOpcode::G_OR: {
9068 // Let redundant_and/redundant_or fold the root before operand rewrites can
9069 // discard the known bits that make it redundant.
9070 KnownBits L = VT->getKnownBits(MI.getOperand(1).getReg());
9071 KnownBits R = VT->getKnownBits(MI.getOperand(2).getReg());
9072 bool RootRedundant = Opcode == TargetOpcode::G_AND
9073 ? RootDemand.isSubsetOf(L.Zero | R.One) ||
9074 RootDemand.isSubsetOf(R.Zero | L.One)
9075 : RootDemand.isSubsetOf(L.One | R.Zero) ||
9076 RootDemand.isSubsetOf(R.One | L.Zero);
9077 if (RootRedundant)
9078 return false;
9079
9080 KnownBits RHSKnown(RootDemand.getBitWidth());
9081 if (Probe(/*OpNo=*/2, RootDemand, RHSKnown))
9082 return true;
9083
9084 APInt LHSDemand = getDemandedBitsForLogicalOp(Opcode, RootDemand, RHSKnown);
9085
9086 KnownBits LHSKnown(RootDemand.getBitWidth());
9087 if (Probe(/*OpNo=*/1, LHSDemand, LHSKnown))
9088 return true;
9089
9090 Register RHS = MI.getOperand(2).getReg();
9091 if (!MRI.hasOneNonDBGUse(RHS) || getConstantOrConstantSplatVector(RHS))
9092 return false;
9093
9094 APInt RHSDemand =
9095 LHSDemand == RootDemand
9096 ? getDemandedBitsForLogicalOp(Opcode, RootDemand, LHSKnown)
9098 Opcode, RootDemand,
9099 VT->getKnownBits(MI.getOperand(1).getReg()));
9100 KnownBits RetryKnown(RootDemand.getBitWidth());
9101 return RHSDemand != RootDemand && Probe(/*OpNo=*/2, RHSDemand, RetryKnown);
9102 }
9103 }
9104}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const TargetLowering & TLI
SDValue Pred
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
uint64_t uint64_t
uint64_t Imm
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static APInt getDemandedBitsForLogicalOp(unsigned Opcode, const APInt &Demanded, const KnownBits &OtherKnown)
static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits, int64_t Cst, bool IsVector)
static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1, const MachineRegisterInfo &MRI)
static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally)
Checks if MI is TargetOpcode::G_FMUL and contractable either due to global flags or MachineInstr flag...
static unsigned getIndexedOpc(unsigned LdStOpc)
static std::optional< unsigned > getValidConstShiftAmt(const std::optional< APInt > &Amt, unsigned BW)
static APInt getDemandedSrcBitsForShiftConst(unsigned Opcode, const APInt &DemandedBits, unsigned ShAmt)
static std::optional< std::pair< GZExtLoad *, int64_t > > matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits, const MachineRegisterInfo &MRI)
Helper function for findLoadOffsetsForLoadOrCombine.
static std::optional< unsigned > getMinUselessShift(KnownBits ValueKB, unsigned Opcode, std::optional< int64_t > &Result)
Return the minimum useless shift amount that results in complete loss of the source value.
static Register peekThroughBitcast(Register Reg, const MachineRegisterInfo &MRI)
static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I)
static cl::opt< bool > ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false), cl::desc("Force all indexed operations to be " "legal for the GlobalISel combiner"))
static void commuteMask(MutableArrayRef< int > Mask, const unsigned NumElems)
static cl::opt< unsigned > PostIndexUseThreshold("post-index-use-threshold", cl::Hidden, cl::init(32), cl::desc("Number of uses of a base pointer to check before it is no longer " "considered for post-indexing."))
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
static bool vectorFPFoldUsesIEEEDenormals(const MachineFunction &MF, LLT Ty)
static unsigned getExtLoadOpcForExtend(unsigned ExtOpc)
static LLT getMidVTForTruncRightShiftCombine(LLT ShiftTy, LLT TruncTy)
static bool canFoldInAddressingMode(GLoadStore *MI, const TargetLowering &TLI, MachineRegisterInfo &MRI)
Return true if 'MI' is a load or a store that may be fold it's address operand into the load / store ...
static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I)
static Register buildLogBase2(Register V, MachineIRBuilder &MIB)
Determines the LogBase2 value for a non-null input value using the transform: LogBase2(V) = (EltBits ...
This contains common combine transformations that may be used in a combine pass,or by the target else...
Utilities for dealing with flags related to floating point properties and mode controls.
This contains common code to allow clients to notify changes to machine instr.
Provides analysis for querying information about KnownBits during GISel passes.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
#define _
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Interface for Targets to specify which operations they can successfully select and how the others sho...
static bool isConstantSplatVector(SDValue N, APInt &SplatValue, unsigned MinSizeInBits)
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
Implement a low-level type suitable for MachineInstr level instruction selection.
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
Register Reg
#define R2(n)
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t High
uint64_t IntrinsicInst * II
int64_t C1
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file implements the SmallBitVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Value * RHS
Value * LHS
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1372
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
int32_t exactLogBase2() const
Definition APInt.h:1803
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned countLeadingZeros() const
Definition APInt.h:1626
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:550
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isMask(unsigned numBits) const
Definition APInt.h:484
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
LLVM_ABI void applyCombineBuildVectorOfBitcast(MachineInstr &MI, SmallVector< Register > &Ops) const
LLVM_ABI void applyCombineExtendingLoads(MachineInstr &MI, PreferredTuple &MatchInfo) const
LLVM_ABI bool matchRepeatedFPDivisor(MachineInstr &MI, SmallVector< MachineInstr * > &MatchInfo) const
LLVM_ABI bool isFPConstantLegalOrBeforeLegalizer(const LLT Ty) const
LLVM_ABI bool matchFoldC2MinusAPlusC1(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchLoadOrCombine(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match expression trees of the form.
LLVM_ABI const RegisterBank * getRegBank(Register Reg) const
Get the register bank of Reg.
LLVM_ABI bool matchEqualDefs(const MachineOperand &MOP1, const MachineOperand &MOP2) const
Return true if MOP1 and MOP2 are register operands are defined by equivalent instructions.
LLVM_ABI void applyUDivOrURemByConst(MachineInstr &MI) const
LLVM_ABI void applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) const
LLVM_ABI bool matchUnmergeValuesAnyExtBuildVector(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchFsubToFneg(MachineInstr &MI) const
LLVM_ABI bool matchCtls(MachineInstr &CtlzMI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchSelectSameVal(MachineInstr &MI) const
Optimize (cond ? x : x) -> x.
LLVM_ABI bool matchReassocConstantInnerRHS(GPtrAdd &MI, MachineInstr *RHS, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchBitfieldExtractFromShr(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match: shr (shl x, n), k -> sbfx/ubfx x, pos, width.
LLVM_ABI bool matchFoldAMinusC1PlusC2(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchTruncSSatU(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI void applySimplifyURemByPow2(MachineInstr &MI) const
Combine G_UREM x, (known power of 2) to an add and bitmasking.
LLVM_ABI bool matchCombineUnmergeZExtToZExt(MachineInstr &MI) const
Transform X, Y = G_UNMERGE(G_ZEXT(Z)) -> X = G_ZEXT(Z); Y = G_CONSTANT 0.
LLVM_ABI bool matchSimplifyDemandedBits(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match demanded-bits simplification of a root's register use.
const TargetInstrInfo * TII
LLVM_ABI void applyCombineConcatVectors(MachineInstr &MI, SmallVector< Register > &Ops) const
Replace MI with a flattened build_vector with Ops or an implicit_def if Ops is empty.
LLVM_ABI void applyXorOfAndWithSameReg(MachineInstr &MI, std::pair< Register, Register > &MatchInfo) const
LLVM_ABI bool canCombineFMadOrFMA(MachineInstr &MI, bool &AllowFusionGlobally, bool &HasFMAD, bool &Aggressive, bool CanReassociate=false) const
LLVM_ABI bool matchFoldAPlusC1MinusC2(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchExtractVecEltBuildVec(MachineInstr &MI, Register &Reg) const
LLVM_ABI void applyCombineUnmergeConstant(MachineInstr &MI, SmallVectorImpl< APInt > &Csts) const
LLVM_ABI bool matchCombineFAddFpExtFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) (fadd (fpext (fmul x,...
LLVM_ABI bool matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) const
LLVM_ABI void applyCombineShuffleConcat(MachineInstr &MI, SmallVector< Register > &Ops) const
Replace MI with a flattened build_vector with Ops or an implicit_def if Ops is empty.
LLVM_ABI void replaceSingleDefInstWithReg(MachineInstr &MI, Register Replacement) const
Delete MI and replace all of its uses with Replacement.
LLVM_ABI void applyCombineShuffleToBuildVector(MachineInstr &MI) const
Replace shuffle MI with a build_vector.
LLVM_ABI bool matchCombineExtractedVectorLoad(MachineInstr &MI, BuildFnTy &MatchInfo) const
Combine a G_EXTRACT_VECTOR_ELT of a load into a narrowed load.
LLVM_ABI void replaceRegWith(MachineRegisterInfo &MRI, Register FromReg, Register ToReg) const
MachineRegisterInfo::replaceRegWith() and inform the observer of the changes.
LLVM_ABI void replaceRegOpWith(MachineRegisterInfo &MRI, MachineOperand &FromRegOp, Register ToReg) const
Replace a single register operand with a new register and inform the observer of the changes.
LLVM_ABI void applyCombineMemCpyFamily(MachineInstr &MI, MemCpyFamilyLoweringInfo &MatchInfo) const
LLVM_ABI bool matchReassocCommBinOp(MachineInstr &MI, BuildFnTy &MatchInfo) const
Reassociate commutative binary operations like G_ADD.
LLVM_ABI void applyBuildFnMO(const MachineOperand &MO, BuildFnTy &MatchInfo) const
Use a function which takes in a MachineIRBuilder to perform a combine.
LLVM_ABI bool matchCommuteConstantToRHS(MachineInstr &MI) const
Match constant LHS ops that should be commuted.
LLVM_ABI bool matchSimplifyNegMinMax(MachineInstr &MI, BuildFnTy &MatchInfo) const
Tranform (neg (min/max x, (neg x))) into (max/min x, (neg x)).
LLVM_ABI bool matchCombineDivRem(MachineInstr &MI, MachineInstr *&OtherMI) const
Try to combine G_[SU]DIV and G_[SU]REM into a single G_[SU]DIVREM when their source operands are iden...
LLVM_ABI void applyUMulHToLShr(MachineInstr &MI) const
LLVM_ABI void applyNotCmp(MachineInstr &MI, SmallVectorImpl< Register > &RegsToNegate) const
LLVM_ABI bool isLegalOrHasFewerElements(const LegalityQuery &Query) const
LLVM_ABI bool matchShiftImmedChain(MachineInstr &MI, RegisterImmPair &MatchInfo) const
Fold (shift (shift base, x), y) -> (shift base (x+y))
LLVM_ABI bool matchTruncLshrBuildVectorFold(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI bool matchAllExplicitUsesAreUndef(MachineInstr &MI) const
Return true if all register explicit use operands on MI are defined by a G_IMPLICIT_DEF.
LLVM_ABI bool isPredecessor(const MachineInstr &DefMI, const MachineInstr &UseMI) const
Returns true if DefMI precedes UseMI or they are the same instruction.
LLVM_ABI bool matchPtrAddImmedChain(MachineInstr &MI, PtrAddChain &MatchInfo) const
LLVM_ABI bool matchTruncSSatS(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI const TargetLowering & getTargetLowering() const
LLVM_ABI bool matchShuffleUndefRHS(MachineInstr &MI, BuildFnTy &MatchInfo) const
Remove references to rhs if it is undef.
LLVM_ABI void applyBuildInstructionSteps(MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) const
Replace MI with a series of instructions described in MatchInfo.
LLVM_ABI void applySDivByPow2(MachineInstr &MI) const
LLVM_ABI bool matchConstantFoldFPBinOp(MachineInstr &MI, BuildFnTy &MatchInfo) const
Do constant FP folding when opportunities are exposed after MIR building.
LLVM_ABI void applyUDivByPow2(MachineInstr &MI) const
Given an G_UDIV MI expressing an unsigned divided by a pow2 constant, return expressions that impleme...
LLVM_ABI bool matchOr(MachineInstr &MI, BuildFnTy &MatchInfo) const
Combine ors.
LLVM_ABI bool matchLshrOfTruncOfLshr(MachineInstr &MI, LshrOfTruncOfLshr &MatchInfo, MachineInstr &ShiftMI) const
Fold (lshr (trunc (lshr x, C1)), C2) -> trunc (shift x, (C1 + C2))
LLVM_ABI void replaceInstWithConstant(MachineInstr &MI, int64_t C) const
Replace an instruction with a G_CONSTANT with value C.
LLVM_ABI bool matchCombineFSubFpExtFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z)) (fsub (fpext (fmul x,...
LLVM_ABI bool matchConstantLargerBitWidth(MachineInstr &MI, unsigned ConstIdx) const
Checks if constant at ConstIdx is larger than MI 's bitwidth.
LLVM_ABI void applyCombineCopy(MachineInstr &MI) const
LLVM_ABI bool matchCombineShlOfExtend(MachineInstr &MI, RegisterImmPair &MatchData) const
LLVM_ABI bool matchCombineFSubFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fsub (fmul x, y), z) -> (fma x, y, -z) (fsub (fmul x, y), z) -> (fmad x,...
LLVM_ABI bool matchCombineFAddFMAFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z)) (fadd (fmad x,...
LLVM_ABI bool matchSextTruncSextLoad(MachineInstr &MI) const
LLVM_ABI bool matchCombineInsertVecElts(MachineInstr &MI, SmallVectorImpl< Register > &MatchInfo) const
LLVM_ABI bool matchCombineBuildUnmerge(MachineInstr &MI, MachineRegisterInfo &MRI, Register &UnmergeSrc) const
LLVM_ABI bool matchDivByPow2(MachineInstr &MI, bool IsSigned) const
Given an G_SDIV MI expressing a signed divided by a pow2 constant, return expressions that implements...
LLVM_ABI bool matchNarrowBinopFeedingAnd(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchCombineLoadWithAndMask(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match (and (load x), mask) -> zextload x.
LLVM_ABI bool matchCombineFAddFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fadd (fmul x, y), z) -> (fma x, y, z) (fadd (fmul x, y), z) -> (fmad x,...
LLVM_ABI bool matchCombineCopy(MachineInstr &MI) const
LLVM_ABI bool matchExtendThroughPhis(MachineInstr &MI, MachineInstr *&ExtMI) const
LLVM_ABI void applyShiftImmedChain(MachineInstr &MI, RegisterImmPair &MatchInfo) const
LLVM_ABI bool matchXorOfAndWithSameReg(MachineInstr &MI, std::pair< Register, Register > &MatchInfo) const
Fold (xor (and x, y), y) -> (and (not x), y) {.
LLVM_ABI bool matchCombineShuffleVector(MachineInstr &MI, SmallVectorImpl< Register > &Ops) const
Check if the G_SHUFFLE_VECTOR MI can be replaced by a concat_vectors.
LLVM_ABI void replaceInstWithFConstant(MachineInstr &MI, double C) const
Replace an instruction with a G_FCONSTANT with value C.
LLVM_ABI bool matchOrShiftToFunnelShift(MachineInstr &MI, bool AllowScalarConstants, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchRedundantSExtInReg(MachineInstr &MI) const
LLVM_ABI void replaceOpcodeWith(MachineInstr &FromMI, unsigned ToOpcode) const
Replace the opcode in instruction with a new opcode and inform the observer of the changes.
LLVM_ABI void applyFunnelShiftConstantModulo(MachineInstr &MI) const
Replaces the shift amount in MI with ShiftAmt % BW.
LLVM_ABI bool matchFoldC1Minus2MinusC2(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI void applyCombineShlOfExtend(MachineInstr &MI, const RegisterImmPair &MatchData) const
LLVM_ABI void applyUseVectorTruncate(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI CombinerHelper(GISelChangeObserver &Observer, MachineIRBuilder &B, bool IsPreLegalize, GISelValueTracking *VT=nullptr, MachineDominatorTree *MDT=nullptr, const LegalizerInfo *LI=nullptr)
LLVM_ABI bool matchShuffleDisjointMask(MachineInstr &MI, BuildFnTy &MatchInfo) const
Turn shuffle a, b, mask -> shuffle undef, b, mask iff mask does not reference a.
LLVM_ABI bool matchCombineMulToShl(MachineInstr &MI, unsigned &ShiftVal) const
Transform a multiply by a power-of-2 value to a left shift.
LLVM_ABI void applyCombineShuffleVector(MachineInstr &MI, ArrayRef< Register > Ops) const
Replace MI with a concat_vectors with Ops.
LLVM_ABI bool matchCombineUnmergeUndef(MachineInstr &MI, std::function< void(MachineIRBuilder &)> &MatchInfo) const
Transform G_UNMERGE G_IMPLICIT_DEF -> G_IMPLICIT_DEF, G_IMPLICIT_DEF, ...
LLVM_ABI void applyFoldBinOpIntoSelect(MachineInstr &MI, const unsigned &SelectOpNo) const
SelectOperand is the operand in binary operator MI that is the select to fold.
LLVM_ABI bool matchFoldAMinusC1MinusC2(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI void applyCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) const
LLVM_ABI bool matchCombineShuffleConcat(MachineInstr &MI, SmallVector< Register > &Ops) const
LLVM_ABI void applySextInRegOfLoad(MachineInstr &MI, std::tuple< Register, unsigned > &MatchInfo) const
LLVM_ABI bool matchTruncUSatU(MachineInstr &MI, MachineInstr &MinMI) const
LLVM_ABI bool matchICmpToLHSKnownBits(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchReassocPtrAdd(MachineInstr &MI, BuildFnTy &MatchInfo) const
Reassociate pointer calculations with G_ADD involved, to allow better addressing mode usage.
LLVM_ABI bool isPreLegalize() const
LLVM_ABI bool matchUndefShuffleVectorMask(MachineInstr &MI) const
Return true if a G_SHUFFLE_VECTOR instruction MI has an undef mask.
LLVM_ABI bool matchCombineSubToAdd(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchShiftOfShiftedLogic(MachineInstr &MI, ShiftOfShiftedLogic &MatchInfo) const
If we have a shift-by-constant of a bitwise logic op that itself has a shift-by-constant operand with...
LLVM_ABI bool matchCombineConcatVectors(MachineInstr &MI, SmallVector< Register > &Ops) const
If MI is G_CONCAT_VECTORS, try to combine it.
LLVM_ABI bool matchInsertExtractVecEltOutOfBounds(MachineInstr &MI) const
Return true if a G_{EXTRACT,INSERT}_VECTOR_ELT has an out of range index.
LLVM_ABI bool matchOperandIsKnownToBeAPowerOfTwo(const MachineOperand &MO, bool OrNegative=false, bool OrZero=false) const
Check if operand MO is known to be a power of 2.
LLVM_ABI bool matchExtractAllEltsFromBuildVector(MachineInstr &MI, SmallVectorImpl< std::pair< Register, MachineInstr * > > &MatchInfo) const
LLVM_ABI LLVMContext & getContext() const
LLVM_ABI void applyPtrAddImmedChain(MachineInstr &MI, PtrAddChain &MatchInfo) const
LLVM_ABI bool isConstantLegalOrBeforeLegalizer(const LLT Ty) const
LLVM_ABI bool matchNotCmp(MachineInstr &MI, SmallVectorImpl< Register > &RegsToNegate) const
Combine inverting a result of a compare into the opposite cond code.
LLVM_ABI bool matchSextInRegOfLoad(MachineInstr &MI, std::tuple< Register, unsigned > &MatchInfo) const
Match sext_inreg(load p), imm -> sextload p.
LLVM_ABI bool matchSelectIMinMax(const MachineOperand &MO, BuildFnTy &MatchInfo) const
Combine select to integer min/max.
LLVM_ABI bool simplifyDemandedBits(MachineInstr &MI, unsigned OpNo, const APInt &DemandedBits, KnownBits &Known, unsigned Depth=0) const
Simplify a register use under DemandedBits and compute Known in the same walk.
LLVM_ABI bool matchConstantFoldUnaryIntOp(MachineInstr &MI, BuildFnTy &MatchInfo) const
Constant fold a unary integer op (G_CTLZ, G_CTTZ, G_CTPOP and their _ZERO_POISON variants,...
LLVM_ABI bool isLegal(const LegalityQuery &Query) const
LLVM_ABI bool matchShiftsTooBig(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match shifts greater or equal to the range (the bitwidth of the result datatype, or the effective bit...
LLVM_ABI void applyCombineShuffleOfBuildVector(MachineInstr &MI) const
Replace shuffle of build_vector with a build_vector.
LLVM_ABI bool matchICmpToTrueFalseKnownBits(MachineInstr &MI, int64_t &MatchInfo) const
LLVM_ABI bool tryReassocBinOp(unsigned Opc, Register DstReg, Register Op0, Register Op1, BuildFnTy &MatchInfo) const
Try to reassociate to reassociate operands of a commutative binop.
LLVM_ABI void eraseInst(MachineInstr &MI) const
Erase MI.
LLVM_ABI void applyBuildFnNoErase(MachineInstr &MI, BuildFnTy &MatchInfo) const
Use a function which takes in a MachineIRBuilder to perform a combine.
LLVM_ABI bool matchUseVectorTruncate(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI bool matchConstantFoldBinOp(MachineInstr &MI, BuildFnTy &MatchInfo) const
Do constant folding when opportunities are exposed after MIR building.
MachineRegisterInfo & MRI
LLVM_ABI void applyExtendThroughPhis(MachineInstr &MI, MachineInstr *&ExtMI) const
LLVM_ABI bool matchConstantFPOp(const MachineOperand &MOP, double C) const
Return true if MOP is defined by a G_FCONSTANT or splat with a value exactly equal to C.
LLVM_ABI MachineInstr * buildUDivOrURemUsingMul(MachineInstr &MI) const
Given an G_UDIV MI or G_UREM MI expressing a divide by constant, return an expression that implements...
LLVM_ABI void applyExtractVecEltBuildVec(MachineInstr &MI, Register &Reg) const
LLVM_ABI bool matchFoldBinOpIntoSelect(MachineInstr &MI, unsigned &SelectOpNo) const
Push a binary operator through a select on constants.
LLVM_ABI bool tryCombineShiftToUnmerge(MachineInstr &MI, unsigned TargetShiftAmount) const
LLVM_ABI bool isConstantNaN(Register Reg) const
LLVM_ABI bool matchPtrAddZeroVector(MachineInstr &MI) const
}
LLVM_ABI bool tryCombineExtendingLoads(MachineInstr &MI) const
If MI is extend that consumes the result of a load, try to combine it.
LLVM_ABI bool isLegalOrBeforeLegalizer(const LegalityQuery &Query) const
LLVM_ABI bool matchBuildVectorIdentityFold(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI bool matchBitfieldExtractFromShrAnd(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match: shr (and x, n), k -> ubfx x, pos, width.
LLVM_ABI void applyTruncSSatS(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI void applyRotateOutOfRange(MachineInstr &MI) const
LLVM_ABI bool matchReassocFoldConstantsInSubTree(GPtrAdd &MI, MachineInstr *LHS, MachineInstr *RHS, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchHoistLogicOpWithSameOpcodeHands(MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) const
Match (logic_op (op x...), (op y...)) -> (op (logic_op x, y))
LLVM_ABI bool matchBitfieldExtractFromAnd(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match: and (lshr x, cst), mask -> ubfx x, cst, width.
LLVM_ABI bool matchBitfieldExtractFromSExtInReg(MachineInstr &MI, BuildFnTy &MatchInfo) const
Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
LLVM_ABI bool matchAndOrDisjointMask(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI void replaceInstWithUndef(MachineInstr &MI) const
Replace an instruction with a G_IMPLICIT_DEF.
LLVM_ABI bool isDesirableToCommuteWithShift(const MachineInstr &MI) const
LLVM_ABI bool matchRedundantBinOpInEquality(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform: (X + Y) == X -> Y == 0 (X - Y) == X -> Y == 0 (X ^ Y) == X -> Y == 0 (X + Y) !...
LLVM_ABI bool matchConstantFoldFPUnary(MachineInstr &MI, BuildFnTy &MatchInfo) const
Constant fold a unary FP operation when the source is constant.
LLVM_ABI bool matchOptBrCondByInvertingCond(MachineInstr &MI, MachineInstr *&BrCond) const
If a brcond's true block is not the fallthrough, make it so by inverting the condition and swapping o...
LLVM_ABI bool matchAddOverflow(MachineInstr &MI, BuildFnTy &MatchInfo) const
Combine addos.
LLVM_ABI void applyAshShlToSextInreg(MachineInstr &MI, std::tuple< Register, int64_t > &MatchInfo) const
LLVM_ABI bool matchSelect(MachineInstr &MI, BuildFnTy &MatchInfo) const
Combine selects.
LLVM_ABI bool matchCombineExtendingLoads(MachineInstr &MI, PreferredTuple &MatchInfo) const
LLVM_ABI bool matchConstantFoldCastOp(MachineInstr &MI, BuildFnTy &MatchInfo) const
Do constant folding when opportunities are exposed after MIR building.
LLVM_ABI bool matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) const
Transform X, Y<dead> = G_UNMERGE Z -> X = G_TRUNC Z.
LLVM_ABI bool matchRotateOutOfRange(MachineInstr &MI) const
LLVM_ABI void applyExpandFPowI(MachineInstr &MI, int64_t Exponent) const
Expands FPOWI into a series of multiplications and a division if the exponent is negative.
LLVM_ABI void setRegBank(Register Reg, const RegisterBank *RegBank) const
Set the register bank of Reg.
LLVM_ABI bool matchCommuteFPConstantToRHS(MachineInstr &MI) const
Match constant LHS FP ops that should be commuted.
LLVM_ABI void applyCombineDivRem(MachineInstr &MI, MachineInstr *&OtherMI) const
LLVM_ABI bool matchRedundantOr(MachineInstr &MI, Register &Replacement) const
LLVM_ABI void applyTruncSSatU(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI void applySimplifySRemByPow2(MachineInstr &MI) const
Combine G_SREM x, (+/-2^k) to a bias-and-mask sequence.
LLVM_ABI bool matchCombineFSubFpExtFNegFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fsub (fpext (fneg (fmul x, y))), z) -> (fneg (fma (fpext x), (fpext y),...
LLVM_ABI bool matchTruncBuildVectorFold(MachineInstr &MI, Register &MatchInfo) const
LLVM_ABI void applyCombineTruncOfShift(MachineInstr &MI, std::pair< MachineInstr *, LLT > &MatchInfo) const
LLVM_ABI bool matchConstantOp(const MachineOperand &MOP, int64_t C) const
Return true if MOP is defined by a G_CONSTANT or splat with a value equal to C.
const LegalizerInfo * LI
LLVM_ABI void applyCombineMulToShl(MachineInstr &MI, unsigned &ShiftVal) const
LLVM_ABI void applyCombineBuildUnmerge(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B, Register &UnmergeSrc) const
LLVM_ABI bool matchUMulHToLShr(MachineInstr &MI) const
MachineDominatorTree * MDT
LLVM_ABI bool matchSimplifySelectToMinMax(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI void applyRepeatedFPDivisor(SmallVector< MachineInstr * > &MatchInfo) const
LLVM_ABI bool matchTruncUSatUToFPTOUISat(MachineInstr &MI, MachineInstr &SrcMI) const
const RegisterBankInfo * RBI
LLVM_ABI bool matchMulOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) const
Match: (G_*MULO x, 0) -> 0 + no carry out.
GISelValueTracking * VT
LLVM_ABI bool matchBinopWithNeg(MachineInstr &MI, BuildFnTy &MatchInfo) const
Fold a bitwiseop (~b +/- c) -> a bitwiseop ~(b -/+ c)
LLVM_ABI bool matchCombineUnmergeConstant(MachineInstr &MI, SmallVectorImpl< APInt > &Csts) const
Transform G_UNMERGE Constant -> Constant1, Constant2, ...
LLVM_ABI bool matchCountZeroToZeroPoison(MachineInstr &MI, unsigned Opc, unsigned ZeroPoisonOpc) const
LLVM_ABI void applyShiftOfShiftedLogic(MachineInstr &MI, ShiftOfShiftedLogic &MatchInfo) const
const TargetRegisterInfo * TRI
LLVM_ABI bool matchRedundantAnd(MachineInstr &MI, Register &Replacement) const
LLVM_ABI bool dominates(const MachineInstr &DefMI, const MachineInstr &UseMI) const
Returns true if DefMI dominates UseMI.
GISelChangeObserver & Observer
LLVM_ABI void applyBuildFn(MachineInstr &MI, BuildFnTy &MatchInfo) const
Use a function which takes in a MachineIRBuilder to perform a combine.
LLVM_ABI bool matchCombineTruncOfShift(MachineInstr &MI, std::pair< MachineInstr *, LLT > &MatchInfo) const
Transform trunc (shl x, K) to shl (trunc x), K if K < VT.getScalarSizeInBits().
LLVM_ABI bool matchCombineShiftToUnmerge(MachineInstr &MI, unsigned TargetShiftSize, unsigned &ShiftVal) const
Reduce a shift by a constant to an unmerge and a shift on a half sized type.
LLVM_ABI bool matchUDivOrURemByConst(MachineInstr &MI) const
Combine G_UDIV or G_UREM by constant into a multiply by magic constant.
LLVM_ABI bool matchAnd(MachineInstr &MI, BuildFnTy &MatchInfo) const
Combine ands.
LLVM_ABI bool matchSuboCarryOut(const MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchCombineFSubFNegFMulToFMadOrFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Transform (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) (fsub (fneg (fmul,...
LLVM_ABI bool matchCombineZextTrunc(MachineInstr &MI, Register &Reg) const
Transform zext(trunc(x)) to x.
LLVM_ABI bool matchUDivByShiftedPow2(MachineInstr &MI, BuildFnTy &MatchInfo) const
Combine unsigned division by a shifted power of two into a right shift.
LLVM_ABI bool matchSameRegOrICstOrSplat(Register A, Register B) const
True when A and B are the same register, including through copies, or different registers holding the...
LLVM_ABI void applyLshrOfTruncOfLshr(MachineInstr &MI, LshrOfTruncOfLshr &MatchInfo) const
LLVM_ABI bool tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen=0) const
Optimize memcpy intrinsics et al, e.g.
LLVM_ABI bool matchFreezeOfSingleMaybePoisonOperand(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI void applySDivOrSRemByConst(MachineInstr &MI) const
LLVM_ABI bool matchCombineMemCpyFamily(MachineInstr &MI, MemCpyFamilyLoweringInfo &MatchInfo, unsigned MaxLen=0) const
LLVM_ABI MachineInstr * buildSDivOrSRemUsingMul(MachineInstr &MI) const
Given an G_SDIV MI or G_SREM MI expressing a signed divide by constant, return an expression that imp...
LLVM_ABI bool isLegalOrHasWidenScalar(const LegalityQuery &Query) const
LLVM_ABI bool matchSignedDivRemToUnsigned(MachineInstr &MI, unsigned UnsignedOpcode) const
Convert signed division or remainder of nonnegative operands to unsigned.
LLVM_ABI bool matchReassocConstantInnerLHS(GPtrAdd &MI, MachineInstr *LHS, MachineInstr *RHS, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchOverlappingAnd(MachineInstr &MI, BuildFnTy &MatchInfo) const
Fold and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0.
LLVM_ABI bool matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) const
Transform anyext(trunc(x)) to x.
LLVM_ABI void applyExtractAllEltsFromBuildVector(MachineInstr &MI, SmallVectorImpl< std::pair< Register, MachineInstr * > > &MatchInfo) const
MachineIRBuilder & Builder
LLVM_ABI bool isZeroOrOneVector(Register Reg) const
LLVM_ABI void replaceSingleDefInstWithOperand(MachineInstr &MI, unsigned OpIdx) const
Delete MI and replace all of its uses with its OpIdx-th operand.
LLVM_ABI const MachineFunction & getMachineFunction() const
LLVM_ABI bool matchCombineBuildVectorOfBitcast(MachineInstr &MI, SmallVector< Register > &Ops) const
Combine G_BUILD_VECTOR(G_UNMERGE(G_BITCAST), Undef) to G_BITCAST(G_BUILD_VECTOR(.....
LLVM_ABI bool matchCombineFAddFpExtFMulToFMadOrFMAAggressive(MachineInstr &MI, BuildFnTy &MatchInfo) const
LLVM_ABI bool matchConstantFoldFMA(MachineInstr &MI, BuildFnTy &MatchInfo) const
Constant fold G_FMA/G_FMAD.
LLVM_ABI bool matchSDivOrSRemByConst(MachineInstr &MI) const
Combine G_SDIV or G_SREM by constant into a multiply by magic constant.
LLVM_ABI void applyOptBrCondByInvertingCond(MachineInstr &MI, MachineInstr *&BrCond) const
LLVM_ABI void applyCombineShiftToUnmerge(MachineInstr &MI, const unsigned &ShiftVal) const
LLVM_ABI bool matchFPowIExpansion(MachineInstr &MI, int64_t Exponent) const
Match FPOWI if it's safe to extend it into a series of multiplications.
LLVM_ABI void applyCombineInsertVecElts(MachineInstr &MI, SmallVectorImpl< Register > &MatchInfo) const
LLVM_ABI bool matchCombineUnmergeMergeToPlainValues(MachineInstr &MI, SmallVectorImpl< Register > &Operands) const
Transform <ty,...> G_UNMERGE(G_MERGE ty X, Y, Z) -> ty X, Y, Z.
LLVM_ABI void applyCombineUnmergeMergeToPlainValues(MachineInstr &MI, SmallVectorImpl< Register > &Operands) const
LLVM_ABI bool matchAshrShlToSextInreg(MachineInstr &MI, std::tuple< Register, int64_t > &MatchInfo) const
Match ashr (shl x, C), C -> sext_inreg (C)
LLVM_ABI void applyCombineUnmergeZExtToZExt(MachineInstr &MI) const
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This class represents a range of values.
LLVM_ABI std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
const APInt & getUpper() const
Return the upper value for this range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool isBigEndian() const
Definition DataLayout.h:220
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
Represents overflowing add operations.
Represents an integer addition.
Represents a logical and.
CmpInst::Predicate getCond() const
Register getLHSReg() const
Register getRHSReg() const
Represents any generic load, including sign/zero extending variants.
Register getDstReg() const
Get the definition register of the loaded value.
Register getCarryOutReg() const
Register getLHSReg() const
Register getRHSReg() const
Represents a G_BUILD_VECTOR.
Register getSrcReg() const
Represents a G_CONCAT_VECTORS.
Represent a G_ICMP.
Abstract class that contains various methods for clients to notify about changes.
Simple wrapper observer that takes several observers, and calls each one for each event.
Represents any type of generic load or store.
Register getPointerReg() const
Get the source register of the pointer value.
Represents a G_LOAD.
Represents a logical binary operation.
MachineMemOperand & getMMO() const
Get the MachineMemOperand on this instruction.
bool isAtomic() const
Returns true if the attached MachineMemOperand has the atomic flag set.
LocationSize getMemSizeInBits() const
Returns the size in bits of the memory access.
Register getSourceReg(unsigned I) const
Returns the I'th source register.
unsigned getNumSources() const
Returns the number of source registers.
Represents a logical or.
Represents a G_PTR_ADD.
Represents a G_SELECT.
Represents overflowing sub operations.
Represents an integer subtraction.
Represents a G_UNMERGE_VALUES.
unsigned getNumDefs() const
Returns the number of def registers.
Register getSourceReg() const
Get the unmerge source register.
Represents a G_ZEXTLOAD.
Represents a zext.
Register getReg(unsigned Idx) const
Access the Idx'th operand as a register and return it.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
constexpr bool isScalar() const
constexpr LLT changeElementType(LLT NewEltTy) const
If this type is a vector, return a vector with the same number of elements but the new element type.
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
LLT getScalarType() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isFloat() const
constexpr bool isVector() const
constexpr bool isByteSized() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr bool isPointer() const
constexpr bool isAnyScalar() const
constexpr ElementCount getElementCount() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr bool isPointerOrPointerVector() const
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
static LLT integer(unsigned SizeInBits)
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
LLT changeElementSize(unsigned NewEltSize) const
If this type is a vector, return a vector with the same number of elements but the new element size.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI LegalizeResult lowerMemCpyFamily(MachineInstr &MI, Register Dst, Register Src, uint64_t KnownLen, Align Alignment, bool DstAlignCanChange, ArrayRef< LLT > MemOps)
@ Legalized
Instruction has been legalized and the MachineFunction changed.
LLVM_ABI Register getVectorElementPointer(Register VecPtr, LLT VecTy, Register Index)
Get a pointer to vector element Index located in memory for a vector of type VecTy starting at a base...
TypeSize getValue() const
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
Helper class to build MachineInstr.
const TargetInstrInfo & getTII()
MachineInstrBuilder buildSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_SUB Op0, Op1.
MachineInstrBuilder buildCTLZ(const DstOp &Dst, const SrcOp &Src0)
Build and insert Res = G_CTLZ Op0, Src0.
MachineFunction & getMF()
Getter for the function we currently build.
MachineRegisterInfo * getMRI()
Getter for MRI.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
LLVM_ABI bool isDereferenceableInvariantLoad() const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
unsigned getNumOperands() const
Retuns the total number of operands.
static constexpr uint32_t getPoisonGeneratingFlags()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
mop_range uses()
Returns all operands which may be register uses.
MachineOperand * findRegisterUseOperand(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false)
Wrapper for findRegisterUseOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
LLT getMemoryType() const
Return the memory type of the memory reference.
unsigned getAddrSpace() const
bool isAtomic() const
Returns true if this operation has an atomic ordering requirement of unordered or higher,...
const MachinePointerInfo & getPointerInfo() const
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
LocationSize getSizeInBits() const
Return the size in bits of the memory reference.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setMBB(MachineBasicBlock *MBB)
void setPredicate(unsigned Predicate)
Register getReg() const
getReg - Returns the register number.
unsigned getPredicate() const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool all() const
Returns true if all bits are set.
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
virtual LLVM_READONLY LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const
Return the preferred type to use for a shift opcode, given the shifted amount type is ShiftValueTy.
bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const
Return true if it is beneficial to expand an @llvm.powi.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset, bool IsPre, MachineRegisterInfo &MRI) const
Returns true if the specified base+offset is a legal indexed addressing mode for this target.
virtual bool isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const
Return true if it is profitable to move this shift by a constant amount through its operand,...
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:181
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
self_iterator getIterator()
Definition ilist_node.h:123
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FewerElements
The (vector) operation should be implemented by splitting it into sub-vectors where the operation is ...
@ Legal
The operation is expected to be selectable directly by the target, and no transformation is necessary...
@ WidenScalar
The operation should be implemented in terms of a wider scalar base-type.
@ Custom
The target wants to do something special with this combination of operand and type.
operand_type_match m_Reg()
SpecificConstantMatch m_SpecificICst(const APInt &RequestedValue)
Matches a constant equal to RequestedValue.
GInstrBind< GBuildVector > m_GBuildVector(GBuildVector *&Inst)
GCstAndRegMatch m_GCst(std::optional< ValueAndVReg > &ValReg)
LoadOp_match< GLoad, PtrP > m_GLoad(const PtrP &Ptr)
MIFlagsRef m_MIFlags(uint32_t &Flags)
operand_type_match m_Pred()
BinaryOp_match< LHS, RHS, TargetOpcode::G_UMIN, true > m_GUMin(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_ZEXT > m_GZExt(const SrcTy &Src)
BinaryOp_match< LHS, RHS, TargetOpcode::G_XOR, true > m_GXor(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_SEXT > m_GSExt(const SrcTy &Src)
UnaryOp_match< SrcTy, TargetOpcode::G_FPEXT > m_GFPExt(const SrcTy &Src)
ConstantMatch< APInt > m_ICst(APInt &Cst)
BinaryOp_match< LHS, RHS, TargetOpcode::G_ADD, true > m_GAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_OR, true > m_GOr(const LHS &L, const RHS &R)
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
ICstOrSplatMatch< APInt > m_ICstOrSplat(APInt &Cst)
ImplicitDefMatch m_GImplicitDef()
GInstrBind< GConcatVectors > m_GConcatVectors(GConcatVectors *&Inst)
GConstantBitsMatch m_GConstantOrFConstantBits(APInt &Bits)
CheckType m_SpecificType(LLT Ty)
deferred_ty< Register > m_DeferredReg(Register &R)
Similar to m_SpecificReg/Type, but the specific value to match originated from an earlier sub-pattern...
BinaryOp_match< LHS, RHS, TargetOpcode::G_UMAX, true > m_GUMax(const LHS &L, const RHS &R)
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
CompareOp_match< Pred, LHS, RHS, TargetOpcode::G_ICMP > m_GICmp(const Pred &P, const LHS &L, const RHS &R)
GInstrBind< GUnmerge > m_GUnmerge(GUnmerge *&Inst)
Instruction binders for ops with no operand-form matcher (constant-immediate or variadic-source ops).
MMORef m_MMO(const MachineMemOperand *&MMO)
BinaryOp_match< LHS, RHS, TargetOpcode::G_SUB > m_GSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_ASHR, false > m_GAShr(const LHS &L, const RHS &R)
TernaryOp_match< Src0Ty, Src1Ty, Src2Ty, TargetOpcode::G_SELECT > m_GISelect(const Src0Ty &Src0, const Src1Ty &Src1, const Src2Ty &Src2)
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
BinaryOp_match< LHS, RHS, TargetOpcode::G_PTR_ADD, false > m_GPtrAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_SHL, false > m_GShl(const LHS &L, const RHS &R)
Or< Preds... > m_any_of(Preds &&... preds)
SpecificConstantOrSplatMatch m_SpecificICstOrSplat(const APInt &RequestedValue)
Matches a RequestedValue constant or a constant splat of RequestedValue.
BinaryOp_match< LHS, RHS, TargetOpcode::G_AND, true > m_GAnd(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_BITCAST > m_GBitcast(const SrcTy &Src)
BinaryOp_match< LHS, RHS, TargetOpcode::G_BUILD_VECTOR_TRUNC, false > m_GBuildVectorTrunc(const LHS &L, const RHS &R)
bind_ty< MachineInstr * > m_MInstr(MachineInstr *&MI)
UnaryOp_match< SrcTy, TargetOpcode::G_FNEG > m_GFNeg(const SrcTy &Src)
CompareOp_match< Pred, LHS, RHS, TargetOpcode::G_ICMP, true > m_c_GICmp(const Pred &P, const LHS &L, const RHS &R)
G_ICMP matcher that also matches commuted compares.
LoadOp_match< GAnyLoad, PtrP > m_GAnyLoad(const PtrP &Ptr)
TernaryOp_match< Src0Ty, Src1Ty, Src2Ty, TargetOpcode::G_INSERT_VECTOR_ELT > m_GInsertVecElt(const Src0Ty &Src0, const Src1Ty &Src1, const Src2Ty &Src2)
GFCstOrSplatGFCstMatch m_GFCstOrSplat(std::optional< FPValueAndVReg > &FPValReg)
And< Preds... > m_all_of(Preds &&... preds)
BinaryOp_match< LHS, RHS, TargetOpcode::G_SMIN, true > m_GSMin(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_LSHR, false > m_GLShr(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_ANYEXT > m_GAnyExt(const SrcTy &Src)
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, TargetOpcode::G_FMUL, true > m_GFMul(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_TRUNC > m_GTrunc(const SrcTy &Src)
BinaryOp_match< LHS, RHS, TargetOpcode::G_SMAX, true > m_GSMax(const LHS &L, const RHS &R)
CompareOp_match< Pred, LHS, RHS, TargetOpcode::G_FCMP > m_GFCmp(const Pred &P, const LHS &L, const RHS &R)
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
Not(const Pred &P) -> Not< Pred >
initializer< Ty > init(const Ty &Val)
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI std::optional< APInt > isConstantOrConstantSplatVector(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a constant integer or a splat vector of constant integers.
Definition Utils.cpp:1678
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool isBuildVectorAllZeros(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndef=false)
Return true if the specified instruction is a G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all of the...
Definition Utils.cpp:1594
LLVM_ABI Type * getTypeForLLT(LLT Ty, LLVMContext &C)
Get the type back from LLT.
Definition Utils.cpp:2138
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI MachineInstr * getOpcodeDef(unsigned Opcode, Register Reg, const MachineRegisterInfo &MRI)
See if Reg is defined by an single def instruction that is Opcode.
Definition Utils.cpp:679
LLVM_ABI std::optional< APFloat > isConstantOrConstantSplatVectorFP(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a float constant integer or a splat vector of float constant integers.
Definition Utils.cpp:1690
LLVM_ABI const ConstantFP * getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:487
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI std::optional< APInt > getIConstantVRegVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:301
LLVM_ABI std::optional< APInt > getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:1554
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1716
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:345
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
std::function< void(MachineIRBuilder &)> BuildFnTy
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
LLVM_ABI std::optional< APFloat > ConstantFoldFPBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:754
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool matchUnaryPredicate(const MachineRegisterInfo &MRI, Register Reg, llvm::function_ref< bool(const Constant *ConstVal)> Match, bool AllowUndefs=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant G_B...
Definition Utils.cpp:1729
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI MVT getMVTForLLT(LLT Ty)
Get a rough equivalent of an MVT for a given LLT.
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1700
LLVM_ABI MachineInstr * getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, folding away any trivial copies.
Definition Utils.cpp:520
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI std::optional< APInt > ConstantFoldBinOp(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Definition Utils.cpp:685
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI const APInt & getIConstantFromReg(Register VReg, const MachineRegisterInfo &MRI)
VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:312
LLVM_ABI bool isConstantOrConstantVector(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowFP=true, bool AllowOpaqueConstants=true)
Return true if the specified instruction is known to be a constant, or a vector of constants.
Definition Utils.cpp:1658
constexpr unsigned MaxAnalysisRecursionDepth
SmallVector< std::function< void(MachineInstrBuilder &)>, 4 > OperandBuildSteps
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool canReplaceReg(Register DstReg, Register SrcReg, MachineRegisterInfo &MRI)
Check if DstReg can be replaced with SrcReg depending on the register constraints.
Definition Utils.cpp:207
LLVM_ABI bool isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector)
Returns true if given the TargetLowering's boolean contents information, the value Val contains a tru...
Definition Utils.cpp:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
std::tuple< Register, Register, uint64_t, Align, bool, std::vector< LLT > > MemCpyFamilyLoweringInfo
Definition Utils.h:208
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:262
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI SmallVector< APInt > ConstantFoldVectorBinop(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Tries to constant fold a vector binop with sources Op1 and Op2.
Definition Utils.cpp:832
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI std::optional< FPValueAndVReg > getFConstantSplat(Register VReg, const MachineRegisterInfo &MRI, bool AllowUndef=true)
Returns a floating point scalar constant of a build vector splat if it exists.
Definition Utils.cpp:1587
LLVM_ABI EVT getApproximateEVTForLLT(LLT Ty, LLVMContext &Ctx)
LLVM_ABI std::optional< APInt > ConstantFoldCastOp(unsigned Opcode, LLT DstTy, const Register Op0, const MachineRegisterInfo &MRI)
Definition Utils.cpp:946
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI bool canLowerMemCpyFamily(const MachineInstr &MI, const MachineRegisterInfo &MRI, unsigned MaxLen, Register &Dst, Register &Src, uint64_t &KnownLen, Align &Alignment, bool &DstAlignCanChange, std::vector< LLT > &MemOps)
Matcher for memcpy-like instructions.
Definition Utils.cpp:2305
LLVM_ABI SmallVector< APFloat > ConstantFoldUnaryFPOp(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Tries to constant fold a unary floating-point operation on Src.
Definition Utils.cpp:1031
LLVM_ABI unsigned getInverseGMinMaxOpcode(unsigned MinMaxOpc)
Returns the inverse opcode of MinMaxOpc, which is a generic min/max opcode like G_SMIN.
Definition Utils.cpp:286
LLVM_ABI SmallVector< APFloat > ConstantFoldVectorFPBinop(unsigned Opcode, const Register Op1, const Register Op2, const MachineRegisterInfo &MRI)
Tries to constant fold a vector floating-point binop with sources Op1 and Op2.
Definition Utils.cpp:855
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI std::optional< FPValueAndVReg > getFConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_FCONSTANT returns it...
Definition Utils.cpp:454
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:440
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI std::optional< DefinitionAndSourceRegister > getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, and underlying value Register folding away any copies.
Definition Utils.cpp:495
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI SmallVector< APInt > ConstantFoldUnaryIntOp(unsigned Opcode, LLT DstTy, Register Src, const MachineRegisterInfo &MRI)
Tries to constant fold a unary integer operation (G_CTLZ, G_CTTZ, G_CTPOP and their _ZERO_POISON vari...
Definition Utils.cpp:983
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI int64_t getICmpTrueVal(const TargetLowering &TLI, bool IsVector)
Returns an integer representing true, as defined by the TargetBooleanContents.
Definition Utils.cpp:1787
LLVM_ABI Register getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the source register for Reg, folding away any trivial copies.
Definition Utils.cpp:527
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
unsigned getFCmpCode(CmpInst::Predicate CC)
Similar to getICmpCode but for FCmpInst.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Simple struct used to hold a Register value and the instruction which defines it.
Definition Utils.h:245
static constexpr DenormalMode getIEEE()
Extended Value Type.
Definition ValueTypes.h:35
SmallVector< InstructionBuildSteps, 2 > InstrsToBuild
Describes instructions to be built during a combine.
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
The LegalityQuery object bundles together all the information that's needed to decide whether a given...
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
MachinePointerInfo getWithOffset(int64_t O) const
const RegisterBank * Bank
Magic data for optimising signed division by a constant.
static LLVM_ABI SignedDivisionByConstantInfo get(const APInt &D)
Calculate the magic numbers required to implement a signed integer division by a constant as a sequen...
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
Magic data for optimising unsigned division by a constant.
static LLVM_ABI UnsignedDivisionByConstantInfo get(const APInt &D, unsigned LeadingZeros=0, bool AllowEvenDivisorOptimization=true, bool AllowWidenOptimization=false)
Calculate the magic numbers required to implement an unsigned integer division by a constant as a seq...