LLVM 22.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 tryToReduceVL(MachineInstr &MI) const;
63 bool convertToVLMAX(MachineInstr &MI) const;
64 bool convertToWholeRegister(MachineInstr &MI) const;
65 bool convertToUnmasked(MachineInstr &MI) const;
66 bool convertAllOnesVMergeToVMv(MachineInstr &MI) const;
67 bool convertSameMaskVMergeToVMv(MachineInstr &MI);
68 bool foldUndefPassthruVMV_V_V(MachineInstr &MI);
69 bool foldVMV_V_V(MachineInstr &MI);
70 bool foldVMergeToMask(MachineInstr &MI) const;
71
72 bool hasSameEEW(const MachineInstr &User, const MachineInstr &Src) const;
73 bool isAllOnesMask(const MachineInstr *MaskDef) const;
74 std::optional<unsigned> getConstant(const MachineOperand &VL) const;
75 bool ensureDominates(const MachineOperand &Use, MachineInstr &Src) const;
76 Register lookThruCopies(Register Reg, bool OneUseOnly = false) const;
77};
78
79} // namespace
80
81char RISCVVectorPeephole::ID = 0;
82
83INITIALIZE_PASS(RISCVVectorPeephole, DEBUG_TYPE, "RISC-V Fold Masks", false,
84 false)
85
86/// Given \p User that has an input operand with EEW=SEW, which uses the dest
87/// operand of \p Src with an unknown EEW, return true if their EEWs match.
88bool RISCVVectorPeephole::hasSameEEW(const MachineInstr &User,
89 const MachineInstr &Src) const {
90 unsigned UserLog2SEW =
91 User.getOperand(RISCVII::getSEWOpNum(User.getDesc())).getImm();
92 unsigned SrcLog2SEW =
93 Src.getOperand(RISCVII::getSEWOpNum(Src.getDesc())).getImm();
94 unsigned SrcLog2EEW = RISCV::getDestLog2EEW(
95 TII->get(RISCV::getRVVMCOpcode(Src.getOpcode())), SrcLog2SEW);
96 return SrcLog2EEW == UserLog2SEW;
97}
98
99// Attempt to reduce the VL of an instruction whose sole use is feeding a
100// instruction with a narrower VL. This currently works backwards from the
101// user instruction (which might have a smaller VL).
102bool RISCVVectorPeephole::tryToReduceVL(MachineInstr &MI) const {
103 // Note that the goal here is a bit multifaceted.
104 // 1) For store's reducing the VL of the value being stored may help to
105 // reduce VL toggles. This is somewhat of an artifact of the fact we
106 // promote arithmetic instructions but VL predicate stores.
107 // 2) For vmv.v.v reducing VL eagerly on the source instruction allows us
108 // to share code with the foldVMV_V_V transform below.
109 //
110 // Note that to the best of our knowledge, reducing VL is generally not
111 // a significant win on real hardware unless we can also reduce LMUL which
112 // this code doesn't try to do.
113 //
114 // TODO: We can handle a bunch more instructions here, and probably
115 // recurse backwards through operands too.
116 SmallVector<unsigned, 2> SrcIndices = {0};
117 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
118 default:
119 return false;
120 case RISCV::VSE8_V:
121 case RISCV::VSE16_V:
122 case RISCV::VSE32_V:
123 case RISCV::VSE64_V:
124 break;
125 case RISCV::VMV_V_V:
126 SrcIndices[0] = 2;
127 break;
128 case RISCV::VMERGE_VVM:
129 SrcIndices.assign({2, 3});
130 break;
131 case RISCV::VREDSUM_VS:
132 case RISCV::VREDMAXU_VS:
133 case RISCV::VREDMAX_VS:
134 case RISCV::VREDMINU_VS:
135 case RISCV::VREDMIN_VS:
136 case RISCV::VREDAND_VS:
137 case RISCV::VREDOR_VS:
138 case RISCV::VREDXOR_VS:
139 case RISCV::VWREDSUM_VS:
140 case RISCV::VWREDSUMU_VS:
141 case RISCV::VFREDUSUM_VS:
142 case RISCV::VFREDOSUM_VS:
143 case RISCV::VFREDMAX_VS:
144 case RISCV::VFREDMIN_VS:
145 case RISCV::VFWREDUSUM_VS:
146 case RISCV::VFWREDOSUM_VS:
147 SrcIndices[0] = 2;
148 break;
149 }
150
151 MachineOperand &VL = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
152 if (VL.isImm() && VL.getImm() == RISCV::VLMaxSentinel)
153 return false;
154
155 bool Changed = false;
156 for (unsigned SrcIdx : SrcIndices) {
157 Register SrcReg = MI.getOperand(SrcIdx).getReg();
158 // Note: one *use*, not one *user*.
159 if (!MRI->hasOneUse(SrcReg))
160 continue;
161
162 MachineInstr *Src = MRI->getVRegDef(SrcReg);
163 if (!Src || Src->hasUnmodeledSideEffects() ||
164 Src->getParent() != MI.getParent() || Src->getNumDefs() != 1 ||
165 !RISCVII::hasVLOp(Src->getDesc().TSFlags) ||
166 !RISCVII::hasSEWOp(Src->getDesc().TSFlags))
167 continue;
168
169 // Src's dest needs to have the same EEW as MI's input.
170 if (!hasSameEEW(MI, *Src))
171 continue;
172
173 bool ElementsDependOnVL = RISCVII::elementsDependOnVL(
174 TII->get(RISCV::getRVVMCOpcode(Src->getOpcode())).TSFlags);
175 if (ElementsDependOnVL || Src->mayRaiseFPException())
176 continue;
177
178 MachineOperand &SrcVL =
179 Src->getOperand(RISCVII::getVLOpNum(Src->getDesc()));
180 if (VL.isIdenticalTo(SrcVL) || !RISCV::isVLKnownLE(VL, SrcVL))
181 continue;
182
183 if (!ensureDominates(VL, *Src))
184 continue;
185
186 if (VL.isImm())
187 SrcVL.ChangeToImmediate(VL.getImm());
188 else if (VL.isReg())
189 SrcVL.ChangeToRegister(VL.getReg(), false);
190
191 Changed = true;
192 }
193
194 // TODO: For instructions with a passthru, we could clear the passthru
195 // and tail policy since we've just proven the tail is not demanded.
196 return Changed;
197}
198
199/// Check if an operand is an immediate or a materialized ADDI $x0, imm.
200std::optional<unsigned>
201RISCVVectorPeephole::getConstant(const MachineOperand &VL) const {
202 if (VL.isImm())
203 return VL.getImm();
204
205 MachineInstr *Def = MRI->getVRegDef(VL.getReg());
206 if (!Def || Def->getOpcode() != RISCV::ADDI ||
207 Def->getOperand(1).getReg() != RISCV::X0)
208 return std::nullopt;
209 return Def->getOperand(2).getImm();
210}
211
212/// Convert AVLs that are known to be VLMAX to the VLMAX sentinel.
213bool RISCVVectorPeephole::convertToVLMAX(MachineInstr &MI) const {
214 if (!RISCVII::hasVLOp(MI.getDesc().TSFlags) ||
215 !RISCVII::hasSEWOp(MI.getDesc().TSFlags))
216 return false;
217
218 auto LMUL = RISCVVType::decodeVLMUL(RISCVII::getLMul(MI.getDesc().TSFlags));
219 // Fixed-point value, denominator=8
220 unsigned LMULFixed = LMUL.second ? (8 / LMUL.first) : 8 * LMUL.first;
221 unsigned Log2SEW = MI.getOperand(RISCVII::getSEWOpNum(MI.getDesc())).getImm();
222 // A Log2SEW of 0 is an operation on mask registers only
223 unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
224 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
225 assert(8 * LMULFixed / SEW > 0);
226
227 // If the exact VLEN is known then we know VLMAX, check if the AVL == VLMAX.
228 MachineOperand &VL = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
229 if (auto VLen = ST->getRealVLen(), AVL = getConstant(VL);
230 VLen && AVL && (*VLen * LMULFixed) / SEW == *AVL * 8) {
232 return true;
233 }
234
235 // If an AVL is a VLENB that's possibly scaled to be equal to VLMAX, convert
236 // it to the VLMAX sentinel value.
237 if (!VL.isReg())
238 return false;
239 MachineInstr *Def = MRI->getVRegDef(VL.getReg());
240 if (!Def)
241 return false;
242
243 // Fixed-point value, denominator=8
244 uint64_t ScaleFixed = 8;
245 // Check if the VLENB was potentially scaled with slli/srli
246 if (Def->getOpcode() == RISCV::SLLI) {
247 assert(Def->getOperand(2).getImm() < 64);
248 ScaleFixed <<= Def->getOperand(2).getImm();
249 Def = MRI->getVRegDef(Def->getOperand(1).getReg());
250 } else if (Def->getOpcode() == RISCV::SRLI) {
251 assert(Def->getOperand(2).getImm() < 64);
252 ScaleFixed >>= Def->getOperand(2).getImm();
253 Def = MRI->getVRegDef(Def->getOperand(1).getReg());
254 }
255
256 if (!Def || Def->getOpcode() != RISCV::PseudoReadVLENB)
257 return false;
258
259 // AVL = (VLENB * Scale)
260 //
261 // VLMAX = (VLENB * 8 * LMUL) / SEW
262 //
263 // AVL == VLMAX
264 // -> VLENB * Scale == (VLENB * 8 * LMUL) / SEW
265 // -> Scale == (8 * LMUL) / SEW
266 if (ScaleFixed != 8 * LMULFixed / SEW)
267 return false;
268
270
271 return true;
272}
273
274bool RISCVVectorPeephole::isAllOnesMask(const MachineInstr *MaskDef) const {
275 while (MaskDef->isCopy() && MaskDef->getOperand(1).getReg().isVirtual())
276 MaskDef = MRI->getVRegDef(MaskDef->getOperand(1).getReg());
277
278 // TODO: Check that the VMSET is the expected bitwidth? The pseudo has
279 // undefined behaviour if it's the wrong bitwidth, so we could choose to
280 // assume that it's all-ones? Same applies to its VL.
281 switch (MaskDef->getOpcode()) {
282 case RISCV::PseudoVMSET_M_B1:
283 case RISCV::PseudoVMSET_M_B2:
284 case RISCV::PseudoVMSET_M_B4:
285 case RISCV::PseudoVMSET_M_B8:
286 case RISCV::PseudoVMSET_M_B16:
287 case RISCV::PseudoVMSET_M_B32:
288 case RISCV::PseudoVMSET_M_B64:
289 return true;
290 default:
291 return false;
292 }
293}
294
295/// Convert unit strided unmasked loads and stores to whole-register equivalents
296/// to avoid the dependency on $vl and $vtype.
297///
298/// %x = PseudoVLE8_V_M1 %passthru, %ptr, %vlmax, policy
299/// PseudoVSE8_V_M1 %v, %ptr, %vlmax
300///
301/// ->
302///
303/// %x = VL1RE8_V %ptr
304/// VS1R_V %v, %ptr
305bool RISCVVectorPeephole::convertToWholeRegister(MachineInstr &MI) const {
306#define CASE_WHOLE_REGISTER_LMUL_SEW(lmul, sew) \
307 case RISCV::PseudoVLE##sew##_V_M##lmul: \
308 NewOpc = RISCV::VL##lmul##RE##sew##_V; \
309 break; \
310 case RISCV::PseudoVSE##sew##_V_M##lmul: \
311 NewOpc = RISCV::VS##lmul##R_V; \
312 break;
313#define CASE_WHOLE_REGISTER_LMUL(lmul) \
314 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 8) \
315 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 16) \
316 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 32) \
317 CASE_WHOLE_REGISTER_LMUL_SEW(lmul, 64)
318
319 unsigned NewOpc;
320 switch (MI.getOpcode()) {
325 default:
326 return false;
327 }
328
329 MachineOperand &VLOp = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
330 if (!VLOp.isImm() || VLOp.getImm() != RISCV::VLMaxSentinel)
331 return false;
332
333 // Whole register instructions aren't pseudos so they don't have
334 // policy/SEW/AVL ops, and they don't have passthrus.
335 if (RISCVII::hasVecPolicyOp(MI.getDesc().TSFlags))
336 MI.removeOperand(RISCVII::getVecPolicyOpNum(MI.getDesc()));
337 MI.removeOperand(RISCVII::getSEWOpNum(MI.getDesc()));
338 MI.removeOperand(RISCVII::getVLOpNum(MI.getDesc()));
339 if (RISCVII::isFirstDefTiedToFirstUse(MI.getDesc()))
340 MI.removeOperand(1);
341
342 MI.setDesc(TII->get(NewOpc));
343
344 return true;
345}
346
347static unsigned getVMV_V_VOpcodeForVMERGE_VVM(const MachineInstr &MI) {
348#define CASE_VMERGE_TO_VMV(lmul) \
349 case RISCV::PseudoVMERGE_VVM_##lmul: \
350 return RISCV::PseudoVMV_V_V_##lmul;
351 switch (MI.getOpcode()) {
352 default:
353 return 0;
354 CASE_VMERGE_TO_VMV(MF8)
355 CASE_VMERGE_TO_VMV(MF4)
356 CASE_VMERGE_TO_VMV(MF2)
357 CASE_VMERGE_TO_VMV(M1)
358 CASE_VMERGE_TO_VMV(M2)
359 CASE_VMERGE_TO_VMV(M4)
360 CASE_VMERGE_TO_VMV(M8)
361 }
362}
363
364/// Convert a PseudoVMERGE_VVM with an all ones mask to a PseudoVMV_V_V.
365///
366/// %x = PseudoVMERGE_VVM %passthru, %false, %true, %allones, sew, vl
367/// ->
368/// %x = PseudoVMV_V_V %passthru, %true, vl, sew, tu_mu
369bool RISCVVectorPeephole::convertAllOnesVMergeToVMv(MachineInstr &MI) const {
370 unsigned NewOpc = getVMV_V_VOpcodeForVMERGE_VVM(MI);
371 if (!NewOpc)
372 return false;
373 if (!isAllOnesMask(MRI->getVRegDef(MI.getOperand(4).getReg())))
374 return false;
375
376 MI.setDesc(TII->get(NewOpc));
377 MI.removeOperand(2); // False operand
378 MI.removeOperand(3); // Mask operand
379 MI.addOperand(
381
382 // vmv.v.v doesn't have a mask operand, so we may be able to inflate the
383 // register class for the destination and passthru operands e.g. VRNoV0 -> VR
384 MRI->recomputeRegClass(MI.getOperand(0).getReg());
385 if (MI.getOperand(1).getReg().isValid())
386 MRI->recomputeRegClass(MI.getOperand(1).getReg());
387 return true;
388}
389
390// If \p Reg is defined by one or more COPYs of virtual registers, traverses
391// the chain and returns the root non-COPY source.
392Register RISCVVectorPeephole::lookThruCopies(Register Reg,
393 bool OneUseOnly) const {
394 while (MachineInstr *Def = MRI->getUniqueVRegDef(Reg)) {
395 if (!Def->isFullCopy())
396 break;
397 Register Src = Def->getOperand(1).getReg();
398 if (!Src.isVirtual())
399 break;
400 if (OneUseOnly && !MRI->hasOneNonDBGUse(Reg))
401 break;
402 Reg = Src;
403 }
404 return Reg;
405}
406
407/// If a PseudoVMERGE_VVM's true operand is a masked pseudo and both have the
408/// same mask, and the masked pseudo's passthru is the same as the false
409/// operand, we can convert the PseudoVMERGE_VVM to a PseudoVMV_V_V.
410///
411/// %true = PseudoVADD_VV_M1_MASK %false, %x, %y, %mask, vl1, sew, policy
412/// %x = PseudoVMERGE_VVM %passthru, %false, %true, %mask, vl2, sew
413/// ->
414/// %true = PseudoVADD_VV_M1_MASK %false, %x, %y, %mask, vl1, sew, policy
415/// %x = PseudoVMV_V_V %passthru, %true, vl2, sew, tu_mu
416bool RISCVVectorPeephole::convertSameMaskVMergeToVMv(MachineInstr &MI) {
417 unsigned NewOpc = getVMV_V_VOpcodeForVMERGE_VVM(MI);
418 if (!NewOpc)
419 return false;
420 MachineInstr *True = MRI->getVRegDef(MI.getOperand(3).getReg());
421
422 if (!True || True->getParent() != MI.getParent())
423 return false;
424
425 auto *TrueMaskedInfo = RISCV::getMaskedPseudoInfo(True->getOpcode());
426 if (!TrueMaskedInfo || !hasSameEEW(MI, *True))
427 return false;
428
429 Register TrueMaskReg = lookThruCopies(
430 True->getOperand(TrueMaskedInfo->MaskOpIdx + True->getNumExplicitDefs())
431 .getReg());
432 Register MIMaskReg = lookThruCopies(MI.getOperand(4).getReg());
433 if (!TrueMaskReg.isVirtual() || TrueMaskReg != MIMaskReg)
434 return false;
435
436 // Masked off lanes past TrueVL will come from False, and converting to vmv
437 // will lose these lanes unless MIVL <= TrueVL.
438 // TODO: We could relax this for False == Passthru and True policy == TU
439 const MachineOperand &MIVL = MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
440 const MachineOperand &TrueVL =
441 True->getOperand(RISCVII::getVLOpNum(True->getDesc()));
442 if (!RISCV::isVLKnownLE(MIVL, TrueVL))
443 return false;
444
445 // True's passthru needs to be equivalent to False
446 Register TruePassthruReg = True->getOperand(1).getReg();
447 Register FalseReg = MI.getOperand(2).getReg();
448 if (TruePassthruReg != FalseReg) {
449 // If True's passthru is undef see if we can change it to False
450 if (TruePassthruReg.isValid() ||
451 !MRI->hasOneUse(MI.getOperand(3).getReg()) ||
452 !ensureDominates(MI.getOperand(2), *True))
453 return false;
454 True->getOperand(1).setReg(MI.getOperand(2).getReg());
455 // If True is masked then its passthru needs to be in VRNoV0.
456 MRI->constrainRegClass(True->getOperand(1).getReg(),
457 TII->getRegClass(True->getDesc(), 1));
458 }
459
460 MI.setDesc(TII->get(NewOpc));
461 MI.removeOperand(2); // False operand
462 MI.removeOperand(3); // Mask operand
463 MI.addOperand(
465
466 // vmv.v.v doesn't have a mask operand, so we may be able to inflate the
467 // register class for the destination and passthru operands e.g. VRNoV0 -> VR
468 MRI->recomputeRegClass(MI.getOperand(0).getReg());
469 if (MI.getOperand(1).getReg().isValid())
470 MRI->recomputeRegClass(MI.getOperand(1).getReg());
471 return true;
472}
473
474bool RISCVVectorPeephole::convertToUnmasked(MachineInstr &MI) const {
475 const RISCV::RISCVMaskedPseudoInfo *I =
476 RISCV::getMaskedPseudoInfo(MI.getOpcode());
477 if (!I)
478 return false;
479
480 if (!isAllOnesMask(MRI->getVRegDef(
481 MI.getOperand(I->MaskOpIdx + MI.getNumExplicitDefs()).getReg())))
482 return false;
483
484 // There are two classes of pseudos in the table - compares and
485 // everything else. See the comment on RISCVMaskedPseudo for details.
486 const unsigned Opc = I->UnmaskedPseudo;
487 const MCInstrDesc &MCID = TII->get(Opc);
488 [[maybe_unused]] const bool HasPolicyOp =
490 const bool HasPassthru = RISCVII::isFirstDefTiedToFirstUse(MCID);
491 const MCInstrDesc &MaskedMCID = TII->get(MI.getOpcode());
494 "Unmasked pseudo has policy but masked pseudo doesn't?");
495 assert(HasPolicyOp == HasPassthru && "Unexpected pseudo structure");
496 assert(!(HasPassthru && !RISCVII::isFirstDefTiedToFirstUse(MaskedMCID)) &&
497 "Unmasked with passthru but masked with no passthru?");
498 (void)HasPolicyOp;
499
500 MI.setDesc(MCID);
501
502 // Drop the policy operand if unmasked doesn't need it.
503 if (RISCVII::hasVecPolicyOp(MaskedMCID.TSFlags) &&
505 MI.removeOperand(RISCVII::getVecPolicyOpNum(MaskedMCID));
506
507 // TODO: Increment all MaskOpIdxs in tablegen by num of explicit defs?
508 unsigned MaskOpIdx = I->MaskOpIdx + MI.getNumExplicitDefs();
509 MI.removeOperand(MaskOpIdx);
510
511 // The unmasked pseudo will no longer be constrained to the vrnov0 reg class,
512 // so try and relax it to vr.
513 MRI->recomputeRegClass(MI.getOperand(0).getReg());
514
515 // If the original masked pseudo had a passthru, relax it or remove it.
516 if (RISCVII::isFirstDefTiedToFirstUse(MaskedMCID)) {
517 unsigned PassthruOpIdx = MI.getNumExplicitDefs();
518 if (HasPassthru) {
519 if (MI.getOperand(PassthruOpIdx).getReg())
520 MRI->recomputeRegClass(MI.getOperand(PassthruOpIdx).getReg());
521 } else
522 MI.removeOperand(PassthruOpIdx);
523 }
524
525 return true;
526}
527
528/// Check if it's safe to move From down to To, checking that no physical
529/// registers are clobbered.
530static bool isSafeToMove(const MachineInstr &From, const MachineInstr &To) {
531 assert(From.getParent() == To.getParent());
532 SmallVector<Register> PhysUses, PhysDefs;
533 for (const MachineOperand &MO : From.all_uses())
534 if (MO.getReg().isPhysical())
535 PhysUses.push_back(MO.getReg());
536 for (const MachineOperand &MO : From.all_defs())
537 if (MO.getReg().isPhysical())
538 PhysDefs.push_back(MO.getReg());
539 bool SawStore = false;
540 for (auto II = std::next(From.getIterator()); II != To.getIterator(); II++) {
541 for (Register PhysReg : PhysUses)
542 if (II->definesRegister(PhysReg, nullptr))
543 return false;
544 for (Register PhysReg : PhysDefs)
545 if (II->definesRegister(PhysReg, nullptr) ||
546 II->readsRegister(PhysReg, nullptr))
547 return false;
548 if (II->mayStore()) {
549 SawStore = true;
550 break;
551 }
552 }
553 return From.isSafeToMove(SawStore);
554}
555
556/// Given A and B are in the same MBB, returns true if A comes before B.
559 assert(A->getParent() == B->getParent());
560 const MachineBasicBlock *MBB = A->getParent();
561 auto MBBEnd = MBB->end();
562 if (B == MBBEnd)
563 return true;
564
566 for (; &*I != A && &*I != B; ++I)
567 ;
568
569 return &*I == A;
570}
571
572/// If the register in \p MO doesn't dominate \p Src, try to move \p Src so it
573/// does. Returns false if doesn't dominate and we can't move. \p MO must be in
574/// the same basic block as \Src.
575bool RISCVVectorPeephole::ensureDominates(const MachineOperand &MO,
576 MachineInstr &Src) const {
577 assert(MO.getParent()->getParent() == Src.getParent());
578 if (!MO.isReg() || !MO.getReg().isValid())
579 return true;
580
581 MachineInstr *Def = MRI->getVRegDef(MO.getReg());
582 if (Def->getParent() == Src.getParent() && !dominates(Def, Src)) {
583 if (!isSafeToMove(Src, *Def->getNextNode()))
584 return false;
585 Src.moveBefore(Def->getNextNode());
586 }
587
588 return true;
589}
590
591/// If a PseudoVMV_V_V's passthru is undef then we can replace it with its input
592bool RISCVVectorPeephole::foldUndefPassthruVMV_V_V(MachineInstr &MI) {
593 if (RISCV::getRVVMCOpcode(MI.getOpcode()) != RISCV::VMV_V_V)
594 return false;
595 if (MI.getOperand(1).getReg().isValid())
596 return false;
597
598 // If the input was a pseudo with a policy operand, we can give it a tail
599 // agnostic policy if MI's undef tail subsumes the input's.
600 MachineInstr *Src = MRI->getVRegDef(MI.getOperand(2).getReg());
601 if (Src && !Src->hasUnmodeledSideEffects() &&
602 MRI->hasOneUse(MI.getOperand(2).getReg()) &&
603 RISCVII::hasVLOp(Src->getDesc().TSFlags) &&
604 RISCVII::hasVecPolicyOp(Src->getDesc().TSFlags) && hasSameEEW(MI, *Src)) {
605 const MachineOperand &MIVL = MI.getOperand(3);
606 const MachineOperand &SrcVL =
607 Src->getOperand(RISCVII::getVLOpNum(Src->getDesc()));
608
609 MachineOperand &SrcPolicy =
610 Src->getOperand(RISCVII::getVecPolicyOpNum(Src->getDesc()));
611
612 if (RISCV::isVLKnownLE(MIVL, SrcVL))
613 SrcPolicy.setImm(SrcPolicy.getImm() | RISCVVType::TAIL_AGNOSTIC);
614 }
615
616 MRI->constrainRegClass(MI.getOperand(2).getReg(),
617 MRI->getRegClass(MI.getOperand(0).getReg()));
618 MRI->replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(2).getReg());
619 MRI->clearKillFlags(MI.getOperand(2).getReg());
620 MI.eraseFromParent();
621 return true;
622}
623
624/// If a PseudoVMV_V_V is the only user of its input, fold its passthru and VL
625/// into it.
626///
627/// %x = PseudoVADD_V_V_M1 %passthru, %a, %b, %vl1, sew, policy
628/// %y = PseudoVMV_V_V_M1 %passthru, %x, %vl2, sew, policy
629/// (where %vl1 <= %vl2, see related tryToReduceVL)
630///
631/// ->
632///
633/// %y = PseudoVADD_V_V_M1 %passthru, %a, %b, vl1, sew, policy
634bool RISCVVectorPeephole::foldVMV_V_V(MachineInstr &MI) {
635 if (RISCV::getRVVMCOpcode(MI.getOpcode()) != RISCV::VMV_V_V)
636 return false;
637
638 MachineOperand &Passthru = MI.getOperand(1);
639
640 if (!MRI->hasOneUse(MI.getOperand(2).getReg()))
641 return false;
642
643 MachineInstr *Src = MRI->getVRegDef(MI.getOperand(2).getReg());
644 if (!Src || Src->hasUnmodeledSideEffects() ||
645 Src->getParent() != MI.getParent() ||
646 !RISCVII::isFirstDefTiedToFirstUse(Src->getDesc()) ||
647 !RISCVII::hasVLOp(Src->getDesc().TSFlags))
648 return false;
649
650 // Src's dest needs to have the same EEW as MI's input.
651 if (!hasSameEEW(MI, *Src))
652 return false;
653
654 std::optional<std::pair<unsigned, unsigned>> NeedsCommute;
655
656 // Src needs to have the same passthru as VMV_V_V
657 MachineOperand &SrcPassthru = Src->getOperand(Src->getNumExplicitDefs());
658 if (SrcPassthru.getReg().isValid() &&
659 SrcPassthru.getReg() != Passthru.getReg()) {
660 // If Src's passthru != Passthru, check if it uses Passthru in another
661 // operand and try to commute it.
662 int OtherIdx = Src->findRegisterUseOperandIdx(Passthru.getReg(), TRI);
663 if (OtherIdx == -1)
664 return false;
665 unsigned OpIdx1 = OtherIdx;
666 unsigned OpIdx2 = Src->getNumExplicitDefs();
667 if (!TII->findCommutedOpIndices(*Src, OpIdx1, OpIdx2))
668 return false;
669 NeedsCommute = {OpIdx1, OpIdx2};
670 }
671
672 // Src VL will have already been reduced if legal (see tryToReduceVL),
673 // so we don't need to handle a smaller source VL here. However, the
674 // user's VL may be larger
675 MachineOperand &SrcVL = Src->getOperand(RISCVII::getVLOpNum(Src->getDesc()));
676 if (!RISCV::isVLKnownLE(SrcVL, MI.getOperand(3)))
677 return false;
678
679 // If the new passthru doesn't dominate Src, try to move Src so it does.
680 if (!ensureDominates(Passthru, *Src))
681 return false;
682
683 if (NeedsCommute) {
684 auto [OpIdx1, OpIdx2] = *NeedsCommute;
685 [[maybe_unused]] bool Commuted =
686 TII->commuteInstruction(*Src, /*NewMI=*/false, OpIdx1, OpIdx2);
687 assert(Commuted && "Failed to commute Src?");
688 }
689
690 if (SrcPassthru.getReg() != Passthru.getReg()) {
691 SrcPassthru.setReg(Passthru.getReg());
692 // If Src is masked then its passthru needs to be in VRNoV0.
693 if (Passthru.getReg().isValid())
694 MRI->constrainRegClass(
695 Passthru.getReg(),
696 TII->getRegClass(Src->getDesc(), SrcPassthru.getOperandNo()));
697 }
698
699 if (RISCVII::hasVecPolicyOp(Src->getDesc().TSFlags)) {
700 // If MI was tail agnostic and the VL didn't increase, preserve it.
702 if ((MI.getOperand(5).getImm() & RISCVVType::TAIL_AGNOSTIC) &&
703 RISCV::isVLKnownLE(MI.getOperand(3), SrcVL))
705 Src->getOperand(RISCVII::getVecPolicyOpNum(Src->getDesc())).setImm(Policy);
706 }
707
708 MRI->constrainRegClass(Src->getOperand(0).getReg(),
709 MRI->getRegClass(MI.getOperand(0).getReg()));
710 MRI->replaceRegWith(MI.getOperand(0).getReg(), Src->getOperand(0).getReg());
711 MI.eraseFromParent();
712
713 return true;
714}
715
716/// Try to fold away VMERGE_VVM instructions into their operands:
717///
718/// %true = PseudoVADD_VV ...
719/// %x = PseudoVMERGE_VVM_M1 %false, %false, %true, %mask
720/// ->
721/// %x = PseudoVADD_VV_M1_MASK %false, ..., %mask
722///
723/// We can only fold if vmerge's passthru operand, vmerge's false operand and
724/// %true's passthru operand (if it has one) are the same. This is because we
725/// have to consolidate them into one passthru operand in the result.
726///
727/// If %true is masked, then we can use its mask instead of vmerge's if vmerge's
728/// mask is all ones.
729///
730/// The resulting VL is the minimum of the two VLs.
731///
732/// The resulting policy is the effective policy the vmerge would have had,
733/// i.e. whether or not it's passthru operand was implicit-def.
734bool RISCVVectorPeephole::foldVMergeToMask(MachineInstr &MI) const {
735 if (RISCV::getRVVMCOpcode(MI.getOpcode()) != RISCV::VMERGE_VVM)
736 return false;
737
738 Register PassthruReg = lookThruCopies(MI.getOperand(1).getReg());
739 Register FalseReg = lookThruCopies(MI.getOperand(2).getReg());
740 Register TrueReg =
741 lookThruCopies(MI.getOperand(3).getReg(), /*OneUseOnly=*/true);
742 if (!TrueReg.isVirtual() || !MRI->hasOneUse(TrueReg))
743 return false;
744 MachineInstr &True = *MRI->getUniqueVRegDef(TrueReg);
745 if (True.getParent() != MI.getParent())
746 return false;
747 const MachineOperand &MaskOp = MI.getOperand(4);
748 MachineInstr *Mask = MRI->getUniqueVRegDef(MaskOp.getReg());
749 assert(Mask);
750
751 const RISCV::RISCVMaskedPseudoInfo *Info =
752 RISCV::lookupMaskedIntrinsicByUnmasked(True.getOpcode());
753 if (!Info)
754 return false;
755
756 // If the EEW of True is different from vmerge's SEW, then we can't fold.
757 if (!hasSameEEW(MI, True))
758 return false;
759
760 // We require that either passthru and false are the same, or that passthru
761 // is undefined.
762 if (PassthruReg && !(PassthruReg.isVirtual() && PassthruReg == FalseReg))
763 return false;
764
765 std::optional<std::pair<unsigned, unsigned>> NeedsCommute;
766
767 // If True has a passthru operand then it needs to be the same as vmerge's
768 // False, since False will be used for the result's passthru operand.
769 Register TruePassthru =
770 lookThruCopies(True.getOperand(True.getNumExplicitDefs()).getReg());
771 if (RISCVII::isFirstDefTiedToFirstUse(True.getDesc()) && TruePassthru &&
772 !(TruePassthru.isVirtual() && TruePassthru == FalseReg)) {
773 // If True's passthru != False, check if it uses False in another operand
774 // and try to commute it.
775 int OtherIdx = True.findRegisterUseOperandIdx(FalseReg, TRI);
776 if (OtherIdx == -1)
777 return false;
778 unsigned OpIdx1 = OtherIdx;
779 unsigned OpIdx2 = True.getNumExplicitDefs();
780 if (!TII->findCommutedOpIndices(True, OpIdx1, OpIdx2))
781 return false;
782 NeedsCommute = {OpIdx1, OpIdx2};
783 }
784
785 // Make sure it doesn't raise any observable fp exceptions, since changing the
786 // active elements will affect how fflags is set.
787 if (True.hasUnmodeledSideEffects() || True.mayRaiseFPException())
788 return false;
789
790 const MachineOperand &VMergeVL =
791 MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
792 const MachineOperand &TrueVL =
794
795 MachineOperand MinVL = MachineOperand::CreateImm(0);
796 if (RISCV::isVLKnownLE(TrueVL, VMergeVL))
797 MinVL = TrueVL;
798 else if (RISCV::isVLKnownLE(VMergeVL, TrueVL))
799 MinVL = VMergeVL;
800 else
801 return false;
802
803 unsigned RVVTSFlags =
805 if (RISCVII::elementsDependOnVL(RVVTSFlags) && !TrueVL.isIdenticalTo(MinVL))
806 return false;
807 if (RISCVII::elementsDependOnMask(RVVTSFlags) && !isAllOnesMask(Mask))
808 return false;
809
810 // Use a tumu policy, relaxing it to tail agnostic provided that the passthru
811 // operand is undefined.
812 //
813 // However, if the VL became smaller than what the vmerge had originally, then
814 // elements past VL that were previously in the vmerge's body will have moved
815 // to the tail. In that case we always need to use tail undisturbed to
816 // preserve them.
818 if (!PassthruReg && RISCV::isVLKnownLE(VMergeVL, MinVL))
820
822 "Foldable unmasked pseudo should have a policy op already");
823
824 // Make sure the mask dominates True, otherwise move down True so it does.
825 // VL will always dominate since if it's a register they need to be the same.
826 if (!ensureDominates(MaskOp, True))
827 return false;
828
829 if (NeedsCommute) {
830 auto [OpIdx1, OpIdx2] = *NeedsCommute;
831 [[maybe_unused]] bool Commuted =
832 TII->commuteInstruction(True, /*NewMI=*/false, OpIdx1, OpIdx2);
833 assert(Commuted && "Failed to commute True?");
834 Info = RISCV::lookupMaskedIntrinsicByUnmasked(True.getOpcode());
835 }
836
837 True.setDesc(TII->get(Info->MaskedPseudo));
838
839 // Insert the mask operand.
840 // TODO: Increment MaskOpIdx by number of explicit defs?
841 True.insert(True.operands_begin() + Info->MaskOpIdx +
842 True.getNumExplicitDefs(),
843 MachineOperand::CreateReg(MaskOp.getReg(), false));
844
845 // Update the passthru, AVL and policy.
846 True.getOperand(True.getNumExplicitDefs()).setReg(FalseReg);
848 True.insert(True.operands_begin() + RISCVII::getVLOpNum(True.getDesc()),
849 MinVL);
851
852 MRI->replaceRegWith(True.getOperand(0).getReg(), MI.getOperand(0).getReg());
853 // Now that True is masked, constrain its operands from vr -> vrnov0.
854 for (MachineOperand &MO : True.explicit_operands()) {
855 if (!MO.isReg() || !MO.getReg().isVirtual())
856 continue;
857 MRI->constrainRegClass(
858 MO.getReg(), True.getRegClassConstraint(MO.getOperandNo(), TII, TRI));
859 }
860 // We should clear the IsKill flag since we have a new use now.
861 MRI->clearKillFlags(FalseReg);
862 MI.eraseFromParent();
863
864 return true;
865}
866
867bool RISCVVectorPeephole::runOnMachineFunction(MachineFunction &MF) {
868 if (skipFunction(MF.getFunction()))
869 return false;
870
871 // Skip if the vector extension is not enabled.
872 ST = &MF.getSubtarget<RISCVSubtarget>();
873 if (!ST->hasVInstructions())
874 return false;
875
876 TII = ST->getInstrInfo();
877 MRI = &MF.getRegInfo();
878 TRI = MRI->getTargetRegisterInfo();
879
880 bool Changed = false;
881
882 for (MachineBasicBlock &MBB : MF) {
883 for (MachineInstr &MI : make_early_inc_range(MBB))
884 Changed |= foldVMergeToMask(MI);
885
886 for (MachineInstr &MI : make_early_inc_range(MBB)) {
887 Changed |= convertToVLMAX(MI);
888 Changed |= tryToReduceVL(MI);
889 Changed |= convertToUnmasked(MI);
890 Changed |= convertToWholeRegister(MI);
891 Changed |= convertAllOnesVMergeToVMv(MI);
892 Changed |= convertSameMaskVMergeToVMv(MI);
893 if (foldUndefPassthruVMV_V_V(MI)) {
894 Changed |= true;
895 continue; // MI is erased
896 }
897 Changed |= foldVMV_V_V(MI);
898 }
899 }
900
901 return Changed;
902}
903
905 return new RISCVVectorPeephole();
906}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const TargetInstrInfo & TII
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")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define DEBUG_TYPE
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
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define CASE_WHOLE_REGISTER_LMUL(lmul)
static bool isSafeToMove(const MachineInstr &From, const MachineInstr &To)
Check if it's safe to move From down to To, checking that no physical registers are clobbered.
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:90
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 isCopy() const
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
LLVM_ABI bool isSafeToMove(bool &SawStore) const
Return true if it is safe to move this instruction.
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.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
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.
LLVM_ABI void ChangeToRegister(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isDebug=false)
ChangeToRegister - Replace this operand with a new register operand of the specified value.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
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,...
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
void assign(size_type NumElts, ValueParamT Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
TargetInstrInfo - Interface to description of machine instruction set.
virtual const TargetRegisterClass * getRegClass(const MCInstrDesc &MCID, unsigned OpNum) const
Given a machine instruction descriptor, returns the register class constraint for OpNum,...
virtual bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction.
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
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:232
self_iterator getIterator()
Definition ilist_node.h:123
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
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:632
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
FunctionPass * createRISCVVectorPeepholePass()