LLVM 23.0.0git
RISCVVectorPeephole.cpp
Go to the documentation of this file.
1//===- RISCVVectorPeephole.cpp - MI Vector Pseudo Peepholes ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs various vector pseudo peephole optimisations after
10// instruction selection.
11//
12// Currently it converts vmerge.vvm to vmv.v.v
13// PseudoVMERGE_VVM %false, %false, %true, %allonesmask, %vl, %sew
14// ->
15// PseudoVMV_V_V %false, %true, %vl, %sew
16//
17// And masked pseudos to unmasked pseudos
18// PseudoVADD_V_V_MASK %passthru, %a, %b, %allonesmask, %vl, sew, policy
19// ->
20// PseudoVADD_V_V %passthru %a, %b, %vl, sew, policy
21//
22// It also converts AVLs to VLMAX where possible
23// %vl = VLENB * something
24// PseudoVADD_V_V %passthru, %a, %b, %vl, sew, policy
25// ->
26// PseudoVADD_V_V %passthru, %a, %b, -1, sew, policy
27//
28//===----------------------------------------------------------------------===//
29
30#include "RISCV.h"
31#include "RISCVSubtarget.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "riscv-vector-peephole"
40
41namespace {
42
43class RISCVVectorPeephole : public MachineFunctionPass {
44public:
45 static char ID;
46 const TargetInstrInfo *TII;
49 const RISCVSubtarget *ST;
50 RISCVVectorPeephole() : MachineFunctionPass(ID) {}
51
52 bool runOnMachineFunction(MachineFunction &MF) override;
53 MachineFunctionProperties getRequiredProperties() const override {
54 return MachineFunctionProperties().setIsSSA();
55 }
56
57 StringRef getPassName() const override {
58 return "RISC-V Vector Peephole Optimization";
59 }
60
61private:
62 bool convertToVLMAX(MachineInstr &MI) const;
63 bool convertToWholeRegister(MachineInstr &MI) const;
64 bool convertToUnmasked(MachineInstr &MI) const;
65 bool convertAllOnesVMergeToVMv(MachineInstr &MI) const;
66 bool convertSameMaskVMergeToVMv(MachineInstr &MI);
67 bool foldUndefPassthruVMV_V_V(MachineInstr &MI);
68 bool foldVMV_V_V(MachineInstr &MI);
69 bool foldVMergeToMask(MachineInstr &MI) const;
70
71 bool hasSameEEW(const MachineInstr &User, const MachineInstr &Src) const;
72 bool isAllOnesMask(const MachineInstr *MaskDef) const;
73 std::optional<unsigned> getConstant(const MachineOperand &VL) const;
74 bool ensureDominates(ArrayRef<const MachineOperand *> Defs,
75 MachineInstr &Use) const;
77 lookThruCopies(Register Reg, bool OneUseOnly = false,
79};
80
81} // namespace
82
83char RISCVVectorPeephole::ID = 0;
84
85INITIALIZE_PASS(RISCVVectorPeephole, DEBUG_TYPE, "RISC-V Fold Masks", false,
86 false)
87
88/// Given \p User that has an input operand with EEW=SEW, which uses the dest
89/// operand of \p Src with an unknown EEW, return true if their EEWs match.
90bool RISCVVectorPeephole::hasSameEEW(const MachineInstr &User,
91 const MachineInstr &Src) const {
92 unsigned UserLog2SEW =
93 User.getOperand(RISCVII::getSEWOpNum(User.getDesc())).getImm();
94 unsigned SrcLog2SEW =
95 Src.getOperand(RISCVII::getSEWOpNum(Src.getDesc())).getImm();
96 unsigned SrcLog2EEW = RISCV::getDestLog2EEW(
97 TII->get(RISCV::getRVVMCOpcode(Src.getOpcode())), SrcLog2SEW);
98 return SrcLog2EEW == UserLog2SEW;
99}
100
101/// Check if an operand is an immediate or a materialized ADDI $x0, imm.
102std::optional<unsigned>
103RISCVVectorPeephole::getConstant(const MachineOperand &VL) const {
104 if (VL.isImm())
105 return VL.getImm();
106
107 MachineInstr *Def = MRI->getVRegDef(VL.getReg());
108 if (!Def || Def->getOpcode() != RISCV::ADDI ||
109 Def->getOperand(1).getReg() != RISCV::X0)
110 return std::nullopt;
111 return Def->getOperand(2).getImm();
112}
113
114/// Convert AVLs that are known to be VLMAX to the VLMAX sentinel.
115bool RISCVVectorPeephole::convertToVLMAX(MachineInstr &MI) const {
116 if (!RISCVII::hasVLOp(MI.getDesc().TSFlags) ||
117 !RISCVII::hasSEWOp(MI.getDesc().TSFlags))
118 return false;
119
120 auto LMUL = RISCVVType::decodeVLMUL(RISCVII::getLMul(MI.getDesc().TSFlags));
121 // Fixed-point value, denominator=8
122 unsigned LMULFixed = LMUL.second ? (8 / LMUL.first) : 8 * LMUL.first;
123 unsigned Log2SEW = MI.getOperand(RISCVII::getSEWOpNum(MI.getDesc())).getImm();
124 // A Log2SEW of 0 is an operation on mask registers only
125 unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
126 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
127 assert(8 * LMULFixed / SEW > 0);
128
129 // If the exact VLEN is known then we know VLMAX, check if the AVL == VLMAX.
130 MachineOperand &VL = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
131 if (auto VLen = ST->getRealVLen(), AVL = getConstant(VL);
132 VLen && AVL && (*VLen * LMULFixed) / SEW == *AVL * 8) {
134 return true;
135 }
136
137 // If an AVL is a VLENB that's possibly scaled to be equal to VLMAX, convert
138 // it to the VLMAX sentinel value.
139 if (!VL.isReg())
140 return false;
141 MachineInstr *Def = MRI->getVRegDef(VL.getReg());
142 if (!Def)
143 return false;
144
145 // Fixed-point value, denominator=8
146 uint64_t ScaleFixed = 8;
147 // Check if the VLENB was potentially scaled with slli/srli
148 if (Def->getOpcode() == RISCV::SLLI) {
149 assert(Def->getOperand(2).getImm() < 64);
150 ScaleFixed <<= Def->getOperand(2).getImm();
151 Def = MRI->getVRegDef(Def->getOperand(1).getReg());
152 } else if (Def->getOpcode() == RISCV::SRLI) {
153 assert(Def->getOperand(2).getImm() < 64);
154 ScaleFixed >>= Def->getOperand(2).getImm();
155 Def = MRI->getVRegDef(Def->getOperand(1).getReg());
156 }
157
158 if (!Def || Def->getOpcode() != RISCV::PseudoReadVLENB)
159 return false;
160
161 // AVL = (VLENB * Scale)
162 //
163 // VLMAX = (VLENB * 8 * LMUL) / SEW
164 //
165 // AVL == VLMAX
166 // -> VLENB * Scale == (VLENB * 8 * LMUL) / SEW
167 // -> Scale == (8 * LMUL) / SEW
168 if (ScaleFixed != 8 * LMULFixed / SEW)
169 return false;
170
172
173 return true;
174}
175
176bool RISCVVectorPeephole::isAllOnesMask(const MachineInstr *MaskDef) const {
177 while (MaskDef->isCopy() && MaskDef->getOperand(1).getReg().isVirtual())
178 MaskDef = MRI->getVRegDef(MaskDef->getOperand(1).getReg());
179
180 // TODO: Check that the VMSET is the expected bitwidth? The pseudo has
181 // undefined behaviour if it's the wrong bitwidth, so we could choose to
182 // assume that it's all-ones? Same applies to its VL.
183 switch (MaskDef->getOpcode()) {
184 case RISCV::PseudoVMSET_M_B1:
185 case RISCV::PseudoVMSET_M_B2:
186 case RISCV::PseudoVMSET_M_B4:
187 case RISCV::PseudoVMSET_M_B8:
188 case RISCV::PseudoVMSET_M_B16:
189 case RISCV::PseudoVMSET_M_B32:
190 case RISCV::PseudoVMSET_M_B64:
191 return true;
192 default:
193 return false;
194 }
195}
196
197/// Convert unit strided unmasked loads and stores to whole-register equivalents
198/// to avoid the dependency on $vl and $vtype.
199///
200/// %x = PseudoVLE8_V_M1 %passthru, %ptr, %vlmax, policy
201/// PseudoVSE8_V_M1 %v, %ptr, %vlmax
202///
203/// ->
204///
205/// %x = VL1RE8_V %ptr
206/// VS1R_V %v, %ptr
207bool RISCVVectorPeephole::convertToWholeRegister(MachineInstr &MI) const {
208#define CASE_WHOLE_REGISTER_LMUL_SEW(lmul, sew) \
209 case RISCV::PseudoVLE##sew##_V_M##lmul: \
210 NewOpc = RISCV::VL##lmul##RE##sew##_V; \
211 break; \
212 case RISCV::PseudoVSE##sew##_V_M##lmul: \
213 NewOpc = RISCV::VS##lmul##R_V; \
214 break;
215#define CASE_WHOLE_REGISTER_LMUL(lmul) \
216 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 8) \
217 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 16) \
218 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 32) \
219 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 64)
220
221 unsigned NewOpc;
222 switch (MI.getOpcode()) {
227 default:
228 return false;
229 }
230
231 MachineOperand &VLOp = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
232 if (!VLOp.isImm() || VLOp.getImm() != RISCV::VLMaxSentinel)
233 return false;
234
235 // Whole register instructions aren't pseudos so they don't have
236 // policy/SEW/AVL ops, and they don't have passthrus.
237 if (RISCVII::hasVecPolicyOp(MI.getDesc().TSFlags))
238 MI.removeOperand(RISCVII::getVecPolicyOpNum(MI.getDesc()));
239 MI.removeOperand(RISCVII::getSEWOpNum(MI.getDesc()));
240 MI.removeOperand(RISCVII::getVLOpNum(MI.getDesc()));
241 if (RISCVII::isFirstDefTiedToFirstUse(MI.getDesc()))
242 MI.removeOperand(1);
243
244 MI.setDesc(TII->get(NewOpc));
245
246 return true;
247}
248
249static unsigned getVMV_V_VOpcodeForVMERGE_VVM(const MachineInstr &MI) {
250#define CASE_VMERGE_TO_VMV(lmul) \
251 case RISCV::PseudoVMERGE_VVM_##lmul: \
252 return RISCV::PseudoVMV_V_V_##lmul;
253 switch (MI.getOpcode()) {
254 default:
255 return 0;
256 CASE_VMERGE_TO_VMV(MF8)
257 CASE_VMERGE_TO_VMV(MF4)
258 CASE_VMERGE_TO_VMV(MF2)
259 CASE_VMERGE_TO_VMV(M1)
260 CASE_VMERGE_TO_VMV(M2)
261 CASE_VMERGE_TO_VMV(M4)
262 CASE_VMERGE_TO_VMV(M8)
263 }
264}
265
266/// Convert a PseudoVMERGE_VVM with an all ones mask to a PseudoVMV_V_V.
267///
268/// %x = PseudoVMERGE_VVM %passthru, %false, %true, %allones, sew, vl
269/// ->
270/// %x = PseudoVMV_V_V %passthru, %true, vl, sew, tu_mu
271bool RISCVVectorPeephole::convertAllOnesVMergeToVMv(MachineInstr &MI) const {
272 unsigned NewOpc = getVMV_V_VOpcodeForVMERGE_VVM(MI);
273 if (!NewOpc)
274 return false;
275 if (!isAllOnesMask(MRI->getVRegDef(MI.getOperand(4).getReg())))
276 return false;
277
278 MI.setDesc(TII->get(NewOpc));
279 MI.removeOperand(2); // False operand
280 MI.removeOperand(3); // Mask operand
281 MI.addOperand(
283
284 // vmv.v.v doesn't have a mask operand, so we may be able to inflate the
285 // register class for the destination and passthru operands e.g. VRNoV0 -> VR
286 MRI->recomputeRegClass(MI.getOperand(0).getReg());
287 if (MI.getOperand(1).getReg().isValid())
288 MRI->recomputeRegClass(MI.getOperand(1).getReg());
289 return true;
290}
291
292// If \p Reg is defined by one or more COPYs of virtual registers, traverses
293// the chain and returns the root non-COPY source.
294Register RISCVVectorPeephole::lookThruCopies(
295 Register Reg, bool OneUseOnly,
296 SmallVectorImpl<MachineInstr *> *Copies) const {
297 while (MachineInstr *Def = MRI->getUniqueVRegDef(Reg)) {
298 if (!Def->isFullCopy())
299 break;
300 Register Src = Def->getOperand(1).getReg();
301 if (!Src.isVirtual())
302 break;
303 if (OneUseOnly && !MRI->hasOneNonDBGUse(Reg))
304 break;
305 if (Copies)
306 Copies->push_back(Def);
307 Reg = Src;
308 }
309 return Reg;
310}
311
312/// If a PseudoVMERGE_VVM's true operand is a masked pseudo and both have the
313/// same mask, and the masked pseudo's passthru is the same as the false
314/// operand, we can convert the PseudoVMERGE_VVM to a PseudoVMV_V_V.
315///
316/// %true = PseudoVADD_VV_M1_MASK %false, %x, %y, %mask, vl1, sew, policy
317/// %x = PseudoVMERGE_VVM %passthru, %false, %true, %mask, vl2, sew
318/// ->
319/// %true = PseudoVADD_VV_M1_MASK %false, %x, %y, %mask, vl1, sew, policy
320/// %x = PseudoVMV_V_V %passthru, %true, vl2, sew, tu_mu
321bool RISCVVectorPeephole::convertSameMaskVMergeToVMv(MachineInstr &MI) {
322 unsigned NewOpc = getVMV_V_VOpcodeForVMERGE_VVM(MI);
323 if (!NewOpc)
324 return false;
325 MachineInstr *True = MRI->getVRegDef(MI.getOperand(3).getReg());
326
327 if (!True || True->getParent() != MI.getParent())
328 return false;
329
330 auto *TrueMaskedInfo = RISCV::getMaskedPseudoInfo(True->getOpcode());
331 if (!TrueMaskedInfo || !hasSameEEW(MI, *True))
332 return false;
333
334 Register TrueMaskReg = lookThruCopies(
335 True->getOperand(TrueMaskedInfo->MaskOpIdx + True->getNumExplicitDefs())
336 .getReg());
337 Register MIMaskReg = lookThruCopies(MI.getOperand(4).getReg());
338 if (!TrueMaskReg.isVirtual() || TrueMaskReg != MIMaskReg)
339 return false;
340
341 // Masked off lanes past TrueVL will come from False, and converting to vmv
342 // will lose these lanes unless MIVL <= TrueVL.
343 // We can relax this when False == Passthru and True's tail policy is TU,
344 // because True's tail lanes will preserve its passthru (= False = Passthru).
345 const MachineOperand &MIVL = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
346 const MachineOperand &TrueVL =
347 True->getOperand(RISCVII::getVLOpNum(True->getDesc()));
348 Register FalseReg = MI.getOperand(2).getReg();
349 if (!RISCV::isVLKnownLE(MIVL, TrueVL)) {
350 Register PassthruReg = MI.getOperand(1).getReg();
351 if (FalseReg.isValid() && FalseReg != PassthruReg)
352 return false;
354 return false;
355 uint64_t TruePolicy =
357 if (TruePolicy & RISCVVType::TAIL_AGNOSTIC)
358 return false;
359 }
360
361 // True's passthru needs to be equivalent to False
362 Register TruePassthruReg = True->getOperand(1).getReg();
363 if (TruePassthruReg != FalseReg) {
364 // If True's passthru is undef see if we can change it to False
365 if (TruePassthruReg.isValid() ||
366 !MRI->hasOneUse(MI.getOperand(3).getReg()) ||
367 !ensureDominates(&MI.getOperand(2), *True))
368 return false;
369 True->getOperand(1).setReg(MI.getOperand(2).getReg());
370 // If True is masked then its passthru needs to be in VRNoV0.
371 MRI->constrainRegClass(True->getOperand(1).getReg(),
372 TII->getRegClass(True->getDesc(), 1));
373 }
374
375 // If True is mask agnostic, we need to make it mask undisturbed.
377 MachineOperand &PolicyOp =
379 PolicyOp.setImm(PolicyOp.getImm() & ~RISCVVType::MASK_AGNOSTIC);
380 }
381
382 MI.setDesc(TII->get(NewOpc));
383 MI.removeOperand(2); // False operand
384 MI.removeOperand(3); // Mask operand
385 MI.addOperand(
387
388 // vmv.v.v doesn't have a mask operand, so we may be able to inflate the
389 // register class for the destination and passthru operands e.g. VRNoV0 -> VR
390 MRI->recomputeRegClass(MI.getOperand(0).getReg());
391 if (MI.getOperand(1).getReg().isValid())
392 MRI->recomputeRegClass(MI.getOperand(1).getReg());
393 return true;
394}
395
396bool RISCVVectorPeephole::convertToUnmasked(MachineInstr &MI) const {
397 const RISCV::RISCVMaskedPseudoInfo *I =
398 RISCV::getMaskedPseudoInfo(MI.getOpcode());
399 if (!I)
400 return false;
401
402 if (!isAllOnesMask(MRI->getVRegDef(
403 MI.getOperand(I->MaskOpIdx + MI.getNumExplicitDefs()).getReg())))
404 return false;
405
406 // There are two classes of pseudos in the table - compares and
407 // everything else. See the comment on RISCVMaskedPseudo for details.
408 const unsigned Opc = I->UnmaskedPseudo;
409 const MCInstrDesc &MCID = TII->get(Opc);
410 [[maybe_unused]] const bool HasPolicyOp =
412 const bool HasPassthru = RISCVII::isFirstDefTiedToFirstUse(MCID);
413 const MCInstrDesc &MaskedMCID = TII->get(MI.getOpcode());
416 "Unmasked pseudo has policy but masked pseudo doesn't?");
417 assert(HasPolicyOp == HasPassthru && "Unexpected pseudo structure");
418 assert(!(HasPassthru && !RISCVII::isFirstDefTiedToFirstUse(MaskedMCID)) &&
419 "Unmasked with passthru but masked with no passthru?");
420 (void)HasPolicyOp;
421
422 MI.setDesc(MCID);
423
424 // Drop the policy operand if unmasked doesn't need it.
425 if (RISCVII::hasVecPolicyOp(MaskedMCID.TSFlags) &&
427 MI.removeOperand(RISCVII::getVecPolicyOpNum(MaskedMCID));
428
429 // TODO: Increment all MaskOpIdxs in tablegen by num of explicit defs?
430 unsigned MaskOpIdx = I->MaskOpIdx + MI.getNumExplicitDefs();
431 MI.removeOperand(MaskOpIdx);
432
433 // The unmasked pseudo will no longer be constrained to the vrnov0 reg class,
434 // so try and relax it to vr.
435 MRI->recomputeRegClass(MI.getOperand(0).getReg());
436
437 // If the original masked pseudo had a passthru, relax it or remove it.
438 if (RISCVII::isFirstDefTiedToFirstUse(MaskedMCID)) {
439 unsigned PassthruOpIdx = MI.getNumExplicitDefs();
440 if (HasPassthru) {
441 if (MI.getOperand(PassthruOpIdx).getReg())
442 MRI->recomputeRegClass(MI.getOperand(PassthruOpIdx).getReg());
443 } else
444 MI.removeOperand(PassthruOpIdx);
445 }
446
447 return true;
448}
449
450/// Given A and B are in the same MBB, returns true if A comes before B.
453 assert(A->getParent() == B->getParent());
454 const MachineBasicBlock *MBB = A->getParent();
455 auto MBBEnd = MBB->end();
456 if (B == MBBEnd)
457 return true;
458
460 for (; &*I != A && &*I != B; ++I)
461 ;
462
463 return &*I == A;
464}
465
466/// If a register in \p Defs doesn't dominate \p Use, try to move Use so it
467/// does. Returns false if any def doesn't dominate and we can't move Use. Each
468/// def must be in the same block as Use.
469bool RISCVVectorPeephole::ensureDominates(ArrayRef<const MachineOperand *> Defs,
470 MachineInstr &Use) const {
471 MachineInstr *Dest = &Use;
472
473 for (const MachineOperand *MO : Defs) {
474 assert(MO->getParent()->getParent() == Use.getParent());
475 if (!MO->isReg() || !MO->getReg().isValid())
476 continue;
477
478 MachineInstr *Def = MRI->getVRegDef(MO->getReg());
479 if (Def->getParent() == Dest->getParent() && !dominates(Def, *Dest)) {
480 if (!RISCVInstrInfo::isSafeToMove(*Dest, *Def->getNextNode()))
481 return false;
482 Dest = Def->getNextNode();
483 }
484 }
485
486 if (Dest != &Use)
487 Use.moveBefore(Dest);
488
489 return true;
490}
491
492/// If a PseudoVMV_V_V's passthru is undef then we can replace it with its input
493bool RISCVVectorPeephole::foldUndefPassthruVMV_V_V(MachineInstr &MI) {
494 if (RISCV::getRVVMCOpcode(MI.getOpcode()) != RISCV::VMV_V_V)
495 return false;
496 if (MI.getOperand(1).getReg().isValid())
497 return false;
498
499 // If the input was a pseudo with a policy operand, we can give it a tail
500 // agnostic policy if MI's undef tail subsumes the input's.
501 MachineInstr *Src = MRI->getVRegDef(MI.getOperand(2).getReg());
502 if (Src && !Src->hasUnmodeledSideEffects() &&
503 MRI->hasOneUse(MI.getOperand(2).getReg()) &&
504 RISCVII::hasVLOp(Src->getDesc().TSFlags) &&
505 RISCVII::hasVecPolicyOp(Src->getDesc().TSFlags) && hasSameEEW(MI, *Src)) {
506 const MachineOperand &MIVL = MI.getOperand(3);
507 const MachineOperand &SrcVL =
508 Src->getOperand(RISCVII::getVLOpNum(Src->getDesc()));
509
510 MachineOperand &SrcPolicy =
511 Src->getOperand(RISCVII::getVecPolicyOpNum(Src->getDesc()));
512
513 if (RISCV::isVLKnownLE(MIVL, SrcVL))
514 SrcPolicy.setImm(SrcPolicy.getImm() | RISCVVType::TAIL_AGNOSTIC);
515 }
516
517 MRI->constrainRegClass(MI.getOperand(2).getReg(),
518 MRI->getRegClass(MI.getOperand(0).getReg()));
519 MRI->replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(2).getReg());
520 MRI->clearKillFlags(MI.getOperand(2).getReg());
521 MI.eraseFromParent();
522 return true;
523}
524
525/// If a PseudoVMV_V_V is the only user of its input, fold its passthru and VL
526/// into it.
527///
528/// %x = PseudoVADD_V_V_M1 %passthru, %a, %b, %vl1, sew, policy
529/// %y = PseudoVMV_V_V_M1 %passthru, %x, %vl2, sew, policy
530/// (where %vl1 <= %vl2)
531///
532/// ->
533///
534/// %y = PseudoVADD_V_V_M1 %passthru, %a, %b, vl1, sew, policy
535bool RISCVVectorPeephole::foldVMV_V_V(MachineInstr &MI) {
536 if (RISCV::getRVVMCOpcode(MI.getOpcode()) != RISCV::VMV_V_V)
537 return false;
538
539 MachineOperand &Passthru = MI.getOperand(1);
540
541 if (!MRI->hasOneUse(MI.getOperand(2).getReg()))
542 return false;
543
544 MachineInstr *Src = MRI->getVRegDef(MI.getOperand(2).getReg());
545 if (!Src || Src->hasUnmodeledSideEffects() ||
546 Src->getParent() != MI.getParent() ||
547 !RISCVII::isFirstDefTiedToFirstUse(Src->getDesc()) ||
548 !RISCVII::hasVLOp(Src->getDesc().TSFlags))
549 return false;
550
551 // Src's dest needs to have the same EEW as MI's input.
552 if (!hasSameEEW(MI, *Src))
553 return false;
554
555 std::optional<std::pair<unsigned, unsigned>> NeedsCommute;
556
557 // Src needs to have the same passthru as VMV_V_V
558 MachineOperand &SrcPassthru = Src->getOperand(Src->getNumExplicitDefs());
559 if (SrcPassthru.getReg().isValid() &&
560 SrcPassthru.getReg() != Passthru.getReg()) {
561 // If Src's passthru != Passthru, check if it uses Passthru in another
562 // operand and try to commute it.
563 int OtherIdx = Src->findRegisterUseOperandIdx(Passthru.getReg(), TRI);
564 if (OtherIdx == -1)
565 return false;
566 unsigned OpIdx1 = OtherIdx;
567 unsigned OpIdx2 = Src->getNumExplicitDefs();
568 if (!TII->findCommutedOpIndices(*Src, OpIdx1, OpIdx2))
569 return false;
570 NeedsCommute = {OpIdx1, OpIdx2};
571 }
572
573 // Src VL will have already been reduced if legal by RISCVVLOptimizer,
574 // so we don't need to handle a smaller source VL here. However, the
575 // user's VL may be larger
576 MachineOperand &SrcVL = Src->getOperand(RISCVII::getVLOpNum(Src->getDesc()));
577 if (!RISCV::isVLKnownLE(SrcVL, MI.getOperand(3)))
578 return false;
579
580 // If the new passthru doesn't dominate Src, try to move Src so it does.
581 if (!ensureDominates(&Passthru, *Src))
582 return false;
583
584 if (NeedsCommute) {
585 auto [OpIdx1, OpIdx2] = *NeedsCommute;
586 [[maybe_unused]] bool Commuted =
587 TII->commuteInstruction(*Src, /*NewMI=*/false, OpIdx1, OpIdx2);
588 assert(Commuted && "Failed to commute Src?");
589 }
590
591 if (SrcPassthru.getReg() != Passthru.getReg()) {
592 SrcPassthru.setReg(Passthru.getReg());
593 // If Src is masked then its passthru needs to be in VRNoV0.
594 if (Passthru.getReg().isValid())
596 Passthru.getReg(),
597 TII->getRegClass(Src->getDesc(), SrcPassthru.getOperandNo()));
598 }
599
600 if (RISCVII::hasVecPolicyOp(Src->getDesc().TSFlags)) {
601 // If MI was tail agnostic and the VL didn't increase, preserve it.
603 if ((MI.getOperand(5).getImm() & RISCVVType::TAIL_AGNOSTIC) &&
604 RISCV::isVLKnownLE(MI.getOperand(3), SrcVL))
606 Src->getOperand(RISCVII::getVecPolicyOpNum(Src->getDesc())).setImm(Policy);
607 }
608
609 MRI->constrainRegClass(Src->getOperand(0).getReg(),
610 MRI->getRegClass(MI.getOperand(0).getReg()));
611 MRI->replaceRegWith(MI.getOperand(0).getReg(), Src->getOperand(0).getReg());
612 MI.eraseFromParent();
613
614 return true;
615}
616
617/// Try to fold away VMERGE_VVM instructions into their operands:
618///
619/// %true = PseudoVADD_VV ...
620/// %x = PseudoVMERGE_VVM_M1 %false, %false, %true, %mask
621/// ->
622/// %x = PseudoVADD_VV_M1_MASK %false, ..., %mask
623///
624/// We can only fold if vmerge's passthru operand, vmerge's false operand and
625/// %true's passthru operand (if it has one) are the same. This is because we
626/// have to consolidate them into one passthru operand in the result.
627///
628/// If %true is masked, then we can use its mask instead of vmerge's if vmerge's
629/// mask is all ones.
630///
631/// The resulting VL is the minimum of the two VLs.
632///
633/// The resulting policy is the effective policy the vmerge would have had,
634/// i.e. whether or not it's passthru operand was implicit-def.
635bool RISCVVectorPeephole::foldVMergeToMask(MachineInstr &MI) const {
636 if (RISCV::getRVVMCOpcode(MI.getOpcode()) != RISCV::VMERGE_VVM)
637 return false;
638
639 // Collect chain of COPYs on True's result for later cleanup.
640 SmallVector<MachineInstr *, 4> TrueCopies;
641 Register PassthruReg = lookThruCopies(MI.getOperand(1).getReg());
642 const MachineOperand &FalseOp = MI.getOperand(2);
643 Register FalseReg = lookThruCopies(FalseOp.getReg());
644 Register TrueReg = lookThruCopies(MI.getOperand(3).getReg(),
645 /*OneUseOnly=*/true, &TrueCopies);
646 if (!TrueReg.isVirtual() || !MRI->hasOneUse(TrueReg))
647 return false;
648 MachineInstr &True = *MRI->getUniqueVRegDef(TrueReg);
649 if (True.getParent() != MI.getParent())
650 return false;
651 const MachineOperand &MaskOp = MI.getOperand(4);
652 MachineInstr *Mask = MRI->getUniqueVRegDef(MaskOp.getReg());
653 assert(Mask);
654
655 const RISCV::RISCVMaskedPseudoInfo *Info =
656 RISCV::lookupMaskedIntrinsicByUnmasked(True.getOpcode());
657 if (!Info)
658 return false;
659
660 // If the EEW of True is different from vmerge's SEW, then we can't fold.
661 if (!hasSameEEW(MI, True))
662 return false;
663
664 // We require that either passthru and false are the same, or that passthru
665 // is undefined.
666 if (PassthruReg && !(PassthruReg.isVirtual() && PassthruReg == FalseReg))
667 return false;
668
669 std::optional<std::pair<unsigned, unsigned>> NeedsCommute;
670
671 // If True has a passthru operand then it needs to be the same as vmerge's
672 // False, since False will be used for the result's passthru operand.
673 Register TruePassthru;
675 TruePassthru =
676 lookThruCopies(True.getOperand(True.getNumExplicitDefs()).getReg());
677 if (TruePassthru && !(TruePassthru.isVirtual() && TruePassthru == FalseReg)) {
678 // If True's passthru != False, check if it uses False in another operand
679 // and try to commute it.
680 int OtherIdx = True.findRegisterUseOperandIdx(FalseReg, TRI);
681 if (OtherIdx == -1)
682 return false;
683 unsigned OpIdx1 = OtherIdx;
684 unsigned OpIdx2 = True.getNumExplicitDefs();
685 if (!TII->findCommutedOpIndices(True, OpIdx1, OpIdx2))
686 return false;
687 NeedsCommute = {OpIdx1, OpIdx2};
688 }
689
690 // Make sure it doesn't raise any observable fp exceptions, since changing the
691 // active elements will affect how fflags is set.
692 if (True.hasUnmodeledSideEffects() || True.mayRaiseFPException())
693 return false;
694
695 const MachineOperand &VMergeVL =
696 MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
697 const MachineOperand &TrueVL =
699
700 MachineOperand MinVL = MachineOperand::CreateImm(0);
701 if (RISCV::isVLKnownLE(TrueVL, VMergeVL))
702 MinVL = TrueVL;
703 else if (RISCV::isVLKnownLE(VMergeVL, TrueVL))
704 MinVL = VMergeVL;
705 else if (!TruePassthru && !True.mayLoadOrStore())
706 // If True's passthru is undef, we can use vmerge's vl.
707 MinVL = VMergeVL;
708 else
709 return false;
710
711 unsigned RVVTSFlags =
712 TII->get(RISCV::getRVVMCOpcode(True.getOpcode())).TSFlags;
713 if (RISCVII::elementsDependOnVL(RVVTSFlags) && !TrueVL.isIdenticalTo(MinVL))
714 return false;
715 if (RISCVII::elementsDependOnMask(RVVTSFlags) && !isAllOnesMask(Mask))
716 return false;
717
718 // Use a tumu policy, relaxing it to tail agnostic provided that the passthru
719 // operand is undefined.
720 //
721 // However, if the VL became smaller than what the vmerge had originally, then
722 // elements past VL that were previously in the vmerge's body will have moved
723 // to the tail. In that case we always need to use tail undisturbed to
724 // preserve them.
726 if (!PassthruReg && RISCV::isVLKnownLE(VMergeVL, MinVL))
728
730 "Foldable unmasked pseudo should have a policy op already");
731
732 // Make sure Mask, False and MinVL dominate True and its copies, otherwise
733 // move down True so it does.
734 if (!ensureDominates({&MaskOp, &FalseOp, &MinVL}, True))
735 return false;
736
737 if (NeedsCommute) {
738 auto [OpIdx1, OpIdx2] = *NeedsCommute;
739 [[maybe_unused]] bool Commuted =
740 TII->commuteInstruction(True, /*NewMI=*/false, OpIdx1, OpIdx2);
741 assert(Commuted && "Failed to commute True?");
742 Info = RISCV::lookupMaskedIntrinsicByUnmasked(True.getOpcode());
743 }
744
745 True.setDesc(TII->get(Info->MaskedPseudo));
746
747 // Insert the mask operand.
748 // TODO: Increment MaskOpIdx by number of explicit defs?
749 True.insert(True.operands_begin() + Info->MaskOpIdx +
750 True.getNumExplicitDefs(),
751 MachineOperand::CreateReg(MaskOp.getReg(), false));
752
753 // Update the passthru, AVL and policy.
754 True.getOperand(True.getNumExplicitDefs()).setReg(FalseReg);
756 True.insert(True.operands_begin() + RISCVII::getVLOpNum(True.getDesc()),
757 MinVL);
759
760 MRI->replaceRegWith(True.getOperand(0).getReg(), MI.getOperand(0).getReg());
761 // Now that True is masked, constrain its operands from vr -> vrnov0.
762 for (MachineOperand &MO : True.explicit_operands()) {
763 if (!MO.isReg() || !MO.getReg().isVirtual())
764 continue;
766 MO.getReg(), True.getRegClassConstraint(MO.getOperandNo(), TII, TRI));
767 }
768 // We should clear the IsKill flag since we have a new use now.
769 MRI->clearKillFlags(FalseReg);
770 MI.eraseFromParent();
771
772 // Cleanup all the COPYs on True's value. We have to manually do this because
773 // sometimes sinking True causes these COPY to be invalid (use before define).
774 for (MachineInstr *TrueCopy : TrueCopies)
775 TrueCopy->eraseFromParent();
776
777 return true;
778}
779
780bool RISCVVectorPeephole::runOnMachineFunction(MachineFunction &MF) {
781 if (skipFunction(MF.getFunction()))
782 return false;
783
784 // Skip if the vector extension is not enabled.
785 ST = &MF.getSubtarget<RISCVSubtarget>();
786 if (!ST->hasVInstructions())
787 return false;
788
789 TII = ST->getInstrInfo();
790 MRI = &MF.getRegInfo();
791 TRI = MRI->getTargetRegisterInfo();
792
793 bool Changed = false;
794
795 for (MachineBasicBlock &MBB : MF) {
796 for (MachineInstr &MI : make_early_inc_range(MBB))
797 Changed |= foldVMergeToMask(MI);
798
799 for (MachineInstr &MI : make_early_inc_range(MBB)) {
800 Changed |= convertToVLMAX(MI);
801 Changed |= convertToUnmasked(MI);
802 Changed |= convertToWholeRegister(MI);
803 Changed |= convertAllOnesVMergeToVMv(MI);
804 Changed |= convertSameMaskVMergeToVMv(MI);
805 if (foldUndefPassthruVMV_V_V(MI)) {
806 Changed |= true;
807 continue; // MI is erased
808 }
809 Changed |= foldVMV_V_V(MI);
810 }
811 }
812
813 return Changed;
814}
815
817 return new RISCVVectorPeephole();
818}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
static uint64_t getConstant(const Value *IndexValue)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define CASE_WHOLE_REGISTER_LMUL(lmul)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
SI Lower i1 Copies
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
mop_iterator operands_begin()
bool mayRaiseFPException() const
Return true if this instruction could possibly raise a floating-point exception.
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.
bool isCopy() const
const MachineBasicBlock * getParent() const
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
LLVM_ABI void insert(mop_iterator InsertBefore, ArrayRef< MachineOperand > Ops)
Inserts Ops BEFORE It. Can untie/retie tied operands.
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 explicit_operands()
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI const TargetRegisterClass * getRegClassConstraint(unsigned OpIdx, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Compute the static register class constraint for operand OpIdx.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
static MachineOperand CreateImm(int64_t Val)
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI bool recomputeRegClass(Register Reg)
recomputeRegClass - Try to find a legal super-class of Reg's register class that still satisfies the ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static bool isSafeToMove(const MachineInstr &From, const MachineBasicBlock::iterator &To)
Return true if moving From down to To won't cause any physical register reads or writes to be clobber...
bool hasVInstructions() const
std::optional< unsigned > getRealVLen() const
const RISCVInstrInfo * getInstrInfo() const override
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
Changed
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
static unsigned getVecPolicyOpNum(const MCInstrDesc &Desc)
static RISCVVType::VLMUL getLMul(uint64_t TSFlags)
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool hasVLOp(uint64_t TSFlags)
static bool elementsDependOnMask(uint64_t TSFlags)
static bool hasVecPolicyOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool elementsDependOnVL(uint64_t TSFlags)
static bool hasSEWOp(uint64_t TSFlags)
static bool isFirstDefTiedToFirstUse(const MCInstrDesc &Desc)
LLVM_ABI std::pair< unsigned, bool > decodeVLMUL(VLMUL VLMul)
static bool isValidSEW(unsigned SEW)
bool isVLKnownLE(const MachineOperand &LHS, const MachineOperand &RHS)
Given two VL operands, do we know that LHS <= RHS?
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
unsigned getDestLog2EEW(const MCInstrDesc &Desc, unsigned Log2SEW)
static constexpr int64_t VLMaxSentinel
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
ArrayRef(const T &OneElt) -> ArrayRef< T >
FunctionPass * createRISCVVectorPeepholePass()