1//===-------------- RISCVVLOptimizer.cpp - VL Optimizer -------------------===//
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 reduces the VL where possible at the MI level, before VSETVLI
10// instructions are inserted.
11//
12// The purpose of this optimization is to make the VL argument, for instructions
13// that have a VL argument, as small as possible.
14//
15// This is split into a sparse dataflow analysis where we determine what VL is
16// demanded by each instruction first, and then afterwards try to reduce the VL
17// of each instruction if it demands less than its VL operand.
18//
19// The analysis is explained in more detail in the 2025 EuroLLVM Developers'
20// Meeting talk "Accidental Dataflow Analysis: Extending the RISC-V VL
21// Optimizer", which is available on YouTube at
22// https://www.youtube.com/watch?v=Mfb5fRSdJAc
23//
24// The slides for the talk are available at
25// https://llvm.org/devmtg/2025-04/slides/technical_talk/lau_accidental_dataflow.pdf
26//
27//===---------------------------------------------------------------------===//
28
29#include "RISCV.h"
30#include "RISCVSubtarget.h"
31#include "llvm/ADT/PostOrderIterator.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/CodeGen/MachineDominators.h"
34#include "llvm/CodeGen/MachineFunctionPass.h"
35#include "llvm/InitializePasses.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "riscv-vl-optimizer"
40#define PASS_NAME "RISC-V VL Optimizer"
41
42namespace {
43
44/// Wrapper around MachineOperand that defaults to immediate 0.
45struct DemandedVL {
46 MachineOperand VL;
47 DemandedVL() : VL(MachineOperand::CreateImm(Val: 0)) {}
48 DemandedVL(MachineOperand VL) : VL(VL) {}
49 static DemandedVL vlmax() {
50 return DemandedVL(MachineOperand::CreateImm(Val: RISCV::VLMaxSentinel));
51 }
52 bool operator!=(const DemandedVL &Other) const {
53 return !VL.isIdenticalTo(Other: Other.VL);
54 }
55
56 DemandedVL max(const DemandedVL &X) const {
57 if (RISCV::isVLKnownLE(LHS: VL, RHS: X.VL))
58 return X;
59 if (RISCV::isVLKnownLE(LHS: X.VL, RHS: VL))
60 return *this;
61 return DemandedVL::vlmax();
62 }
63};
64
65class RISCVVLOptimizer : public MachineFunctionPass {
66 MachineRegisterInfo *MRI;
67 const MachineDominatorTree *MDT;
68 const TargetInstrInfo *TII;
69
70public:
71 static char ID;
72
73 RISCVVLOptimizer() : MachineFunctionPass(ID) {}
74
75 bool runOnMachineFunction(MachineFunction &MF) override;
76
77 void getAnalysisUsage(AnalysisUsage &AU) const override {
78 AU.setPreservesCFG();
79 AU.addRequired<MachineDominatorTreeWrapperPass>();
80 MachineFunctionPass::getAnalysisUsage(AU);
81 }
82
83 StringRef getPassName() const override { return PASS_NAME; }
84
85private:
86 DemandedVL getMinimumVLForUser(const MachineOperand &UserOp) const;
87 /// Returns true if the users of \p MI have compatible EEWs and SEWs.
88 bool checkUsers(const MachineInstr &MI) const;
89 bool tryReduceVL(MachineInstr &MI, MachineOperand VL) const;
90 bool isSupportedInstr(const MachineInstr &MI) const;
91 bool isCandidate(const MachineInstr &MI) const;
92 void transfer(const MachineInstr &MI);
93
94 /// For a given instruction, records what elements of it are demanded by
95 /// downstream users.
96 MapVector<const MachineInstr *, DemandedVL> DemandedVLs;
97 SetVector<const MachineInstr *> Worklist;
98
99 /// \returns all vector virtual registers that \p MI uses.
100 auto virtual_vec_uses(const MachineInstr &MI) const {
101 return make_filter_range(Range: MI.uses(), Pred: [this](const MachineOperand &MO) {
102 return MO.isReg() && MO.getReg().isVirtual() &&
103 RISCVRegisterInfo::isRVVRegClass(RC: MRI->getRegClass(Reg: MO.getReg()));
104 });
105 }
106};
107
108/// Represents the EMUL and EEW of a MachineOperand.
109struct OperandInfo {
110 // Represent as 1,2,4,8, ... and fractional indicator. This is because
111 // EMUL can take on values that don't map to RISCVVType::VLMUL values exactly.
112 // For example, a mask operand can have an EMUL less than MF8.
113 // If nullopt, then EMUL isn't used (i.e. only a single scalar is read).
114 std::optional<std::pair<unsigned, bool>> EMUL;
115
116 unsigned Log2EEW;
117
118 OperandInfo(RISCVVType::VLMUL EMUL, unsigned Log2EEW)
119 : EMUL(RISCVVType::decodeVLMUL(VLMul: EMUL)), Log2EEW(Log2EEW) {}
120
121 OperandInfo(std::pair<unsigned, bool> EMUL, unsigned Log2EEW)
122 : EMUL(EMUL), Log2EEW(Log2EEW) {}
123
124 OperandInfo(unsigned Log2EEW) : Log2EEW(Log2EEW) {}
125
126 OperandInfo() = delete;
127
128 /// Return true if the EMUL and EEW produced by \p Def is compatible with the
129 /// EMUL and EEW used by \p User.
130 static bool areCompatible(const OperandInfo &Def, const OperandInfo &User) {
131 if (Def.Log2EEW != User.Log2EEW)
132 return false;
133 if (User.EMUL && Def.EMUL != User.EMUL)
134 return false;
135 return true;
136 }
137
138 void print(raw_ostream &OS) const {
139 if (EMUL) {
140 OS << "EMUL: m";
141 if (EMUL->second)
142 OS << "f";
143 OS << EMUL->first;
144 } else
145 OS << "EMUL: none\n";
146 OS << ", EEW: " << (1 << Log2EEW);
147 }
148};
149
150} // end anonymous namespace
151
152char RISCVVLOptimizer::ID = 0;
153INITIALIZE_PASS_BEGIN(RISCVVLOptimizer, DEBUG_TYPE, PASS_NAME, false, false)
154INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
155INITIALIZE_PASS_END(RISCVVLOptimizer, DEBUG_TYPE, PASS_NAME, false, false)
156
157FunctionPass *llvm::createRISCVVLOptimizerPass() {
158 return new RISCVVLOptimizer();
159}
160
161[[maybe_unused]]
162static raw_ostream &operator<<(raw_ostream &OS, const OperandInfo &OI) {
163 OI.print(OS);
164 return OS;
165}
166
167[[maybe_unused]]
168static raw_ostream &operator<<(raw_ostream &OS,
169 const std::optional<OperandInfo> &OI) {
170 if (OI)
171 OI->print(OS);
172 else
173 OS << "nullopt";
174 return OS;
175}
176
177/// Return EMUL = (EEW / SEW) * LMUL where EEW comes from Log2EEW and LMUL and
178/// SEW are from the TSFlags of MI.
179static std::pair<unsigned, bool>
180getEMULEqualsEEWDivSEWTimesLMUL(unsigned Log2EEW, const MachineInstr &MI) {
181 RISCVVType::VLMUL MIVLMUL = RISCVII::getLMul(TSFlags: MI.getDesc().TSFlags);
182 auto [MILMUL, MILMULIsFractional] = RISCVVType::decodeVLMUL(VLMul: MIVLMUL);
183 unsigned MILog2SEW =
184 MI.getOperand(i: RISCVII::getSEWOpNum(Desc: MI.getDesc())).getImm();
185
186 // Mask instructions will have 0 as the SEW operand. But the LMUL of these
187 // instructions is calculated is as if the SEW operand was 3 (e8).
188 if (MILog2SEW == 0)
189 MILog2SEW = 3;
190
191 unsigned MISEW = 1 << MILog2SEW;
192
193 unsigned EEW = 1 << Log2EEW;
194 // Calculate (EEW/SEW)*LMUL preserving fractions less than 1. Use GCD
195 // to put fraction in simplest form.
196 unsigned Num = EEW, Denom = MISEW;
197 int GCD = MILMULIsFractional ? std::gcd(m: Num, n: Denom * MILMUL)
198 : std::gcd(m: Num * MILMUL, n: Denom);
199 Num = MILMULIsFractional ? Num / GCD : Num * MILMUL / GCD;
200 Denom = MILMULIsFractional ? Denom * MILMUL / GCD : Denom / GCD;
201 return std::make_pair(x&: Num > Denom ? Num : Denom, y: Denom > Num);
202}
203
204/// Dest has EEW=SEW. Source EEW=SEW/Factor (i.e. F2 => EEW/2).
205/// SEW comes from TSFlags of MI.
206static unsigned getIntegerExtensionOperandEEW(unsigned Factor,
207 const MachineInstr &MI,
208 const MachineOperand &MO) {
209 unsigned MILog2SEW =
210 MI.getOperand(i: RISCVII::getSEWOpNum(Desc: MI.getDesc())).getImm();
211
212 if (MO.getOperandNo() == 0)
213 return MILog2SEW;
214
215 unsigned MISEW = 1 << MILog2SEW;
216 unsigned EEW = MISEW / Factor;
217 unsigned Log2EEW = Log2_32(Value: EEW);
218
219 return Log2EEW;
220}
221
222#define VSEG_CASES(Prefix, EEW) \
223 RISCV::Prefix##SEG2E##EEW##_V: \
224 case RISCV::Prefix##SEG3E##EEW##_V: \
225 case RISCV::Prefix##SEG4E##EEW##_V: \
226 case RISCV::Prefix##SEG5E##EEW##_V: \
227 case RISCV::Prefix##SEG6E##EEW##_V: \
228 case RISCV::Prefix##SEG7E##EEW##_V: \
229 case RISCV::Prefix##SEG8E##EEW##_V
230#define VSSEG_CASES(EEW) VSEG_CASES(VS, EEW)
231#define VSSSEG_CASES(EEW) VSEG_CASES(VSS, EEW)
232#define VSUXSEG_CASES(EEW) VSEG_CASES(VSUX, I##EEW)
233#define VSOXSEG_CASES(EEW) VSEG_CASES(VSOX, I##EEW)
234
235static std::optional<unsigned> getOperandLog2EEW(const MachineOperand &MO) {
236 const MachineInstr &MI = *MO.getParent();
237 const MCInstrDesc &Desc = MI.getDesc();
238 const RISCVVPseudosTable::PseudoInfo *RVV =
239 RISCVVPseudosTable::getPseudoInfo(Pseudo: MI.getOpcode());
240 assert(RVV && "Could not find MI in PseudoTable");
241
242 // MI has a SEW associated with it. The RVV specification defines
243 // the EEW of each operand and definition in relation to MI.SEW.
244 unsigned MILog2SEW = MI.getOperand(i: RISCVII::getSEWOpNum(Desc)).getImm();
245
246 const bool HasPassthru = RISCVII::isFirstDefTiedToFirstUse(Desc);
247 const bool IsTied = RISCVII::isTiedPseudo(TSFlags: Desc.TSFlags);
248
249 bool IsMODef = MO.getOperandNo() == 0 ||
250 (HasPassthru && MO.getOperandNo() == MI.getNumExplicitDefs());
251
252 // All mask operands have EEW=1
253 const MCOperandInfo &Info = Desc.operands()[MO.getOperandNo()];
254 if (Info.OperandType == MCOI::OPERAND_REGISTER &&
255 Info.RegClass == RISCV::VMV0RegClassID)
256 return 0;
257
258 // switch against BaseInstr to reduce number of cases that need to be
259 // considered.
260 switch (RVV->BaseInstr) {
261
262 // 6. Configuration-Setting Instructions
263 // Configuration setting instructions do not read or write vector registers
264 case RISCV::VSETIVLI:
265 case RISCV::VSETVL:
266 case RISCV::VSETVLI:
267 llvm_unreachable("Configuration setting instructions do not read or write "
268 "vector registers");
269
270 // Vector Loads and Stores
271 // Vector Unit-Stride Instructions
272 // Vector Strided Instructions
273 /// Dest EEW encoded in the instruction
274 case RISCV::VLM_V:
275 case RISCV::VSM_V:
276 return 0;
277 case RISCV::VLE8_V:
278 case RISCV::VSE8_V:
279 case RISCV::VLSE8_V:
280 case RISCV::VSSE8_V:
281 case VSSEG_CASES(8):
282 case VSSSEG_CASES(8):
283 return 3;
284 case RISCV::VLE16_V:
285 case RISCV::VSE16_V:
286 case RISCV::VLSE16_V:
287 case RISCV::VSSE16_V:
288 case VSSEG_CASES(16):
289 case VSSSEG_CASES(16):
290 return 4;
291 case RISCV::VLE32_V:
292 case RISCV::VSE32_V:
293 case RISCV::VLSE32_V:
294 case RISCV::VSSE32_V:
295 case VSSEG_CASES(32):
296 case VSSSEG_CASES(32):
297 return 5;
298 case RISCV::VLE64_V:
299 case RISCV::VSE64_V:
300 case RISCV::VLSE64_V:
301 case RISCV::VSSE64_V:
302 case VSSEG_CASES(64):
303 case VSSSEG_CASES(64):
304 return 6;
305
306 // Vector Indexed Instructions
307 // vs(o|u)xei<eew>.v
308 // Dest/Data (operand 0) EEW=SEW. Source EEW=<eew>.
309 case RISCV::VLUXEI8_V:
310 case RISCV::VLOXEI8_V:
311 case RISCV::VSUXEI8_V:
312 case RISCV::VSOXEI8_V:
313 case VSUXSEG_CASES(8):
314 case VSOXSEG_CASES(8): {
315 if (MO.getOperandNo() == 0)
316 return MILog2SEW;
317 return 3;
318 }
319 case RISCV::VLUXEI16_V:
320 case RISCV::VLOXEI16_V:
321 case RISCV::VSUXEI16_V:
322 case RISCV::VSOXEI16_V:
323 case VSUXSEG_CASES(16):
324 case VSOXSEG_CASES(16): {
325 if (MO.getOperandNo() == 0)
326 return MILog2SEW;
327 return 4;
328 }
329 case RISCV::VLUXEI32_V:
330 case RISCV::VLOXEI32_V:
331 case RISCV::VSUXEI32_V:
332 case RISCV::VSOXEI32_V:
333 case VSUXSEG_CASES(32):
334 case VSOXSEG_CASES(32): {
335 if (MO.getOperandNo() == 0)
336 return MILog2SEW;
337 return 5;
338 }
339 case RISCV::VLUXEI64_V:
340 case RISCV::VLOXEI64_V:
341 case RISCV::VSUXEI64_V:
342 case RISCV::VSOXEI64_V:
343 case VSUXSEG_CASES(64):
344 case VSOXSEG_CASES(64): {
345 if (MO.getOperandNo() == 0)
346 return MILog2SEW;
347 return 6;
348 }
349
350 // Vector Integer Arithmetic Instructions
351 // Vector Single-Width Integer Add and Subtract
352 case RISCV::VADD_VI:
353 case RISCV::VADD_VV:
354 case RISCV::VADD_VX:
355 case RISCV::VSUB_VV:
356 case RISCV::VSUB_VX:
357 case RISCV::VRSUB_VI:
358 case RISCV::VRSUB_VX:
359 // Vector Bitwise Logical Instructions
360 // Vector Single-Width Shift Instructions
361 // EEW=SEW.
362 case RISCV::VAND_VI:
363 case RISCV::VAND_VV:
364 case RISCV::VAND_VX:
365 case RISCV::VOR_VI:
366 case RISCV::VOR_VV:
367 case RISCV::VOR_VX:
368 case RISCV::VXOR_VI:
369 case RISCV::VXOR_VV:
370 case RISCV::VXOR_VX:
371 case RISCV::VSLL_VI:
372 case RISCV::VSLL_VV:
373 case RISCV::VSLL_VX:
374 case RISCV::VSRL_VI:
375 case RISCV::VSRL_VV:
376 case RISCV::VSRL_VX:
377 case RISCV::VSRA_VI:
378 case RISCV::VSRA_VV:
379 case RISCV::VSRA_VX:
380 // Vector Integer Min/Max Instructions
381 // EEW=SEW.
382 case RISCV::VMINU_VV:
383 case RISCV::VMINU_VX:
384 case RISCV::VMIN_VV:
385 case RISCV::VMIN_VX:
386 case RISCV::VMAXU_VV:
387 case RISCV::VMAXU_VX:
388 case RISCV::VMAX_VV:
389 case RISCV::VMAX_VX:
390 // Vector Single-Width Integer Multiply Instructions
391 // Source and Dest EEW=SEW.
392 case RISCV::VMUL_VV:
393 case RISCV::VMUL_VX:
394 case RISCV::VMULH_VV:
395 case RISCV::VMULH_VX:
396 case RISCV::VMULHU_VV:
397 case RISCV::VMULHU_VX:
398 case RISCV::VMULHSU_VV:
399 case RISCV::VMULHSU_VX:
400 // Vector Integer Divide Instructions
401 // EEW=SEW.
402 case RISCV::VDIVU_VV:
403 case RISCV::VDIVU_VX:
404 case RISCV::VDIV_VV:
405 case RISCV::VDIV_VX:
406 case RISCV::VREMU_VV:
407 case RISCV::VREMU_VX:
408 case RISCV::VREM_VV:
409 case RISCV::VREM_VX:
410 // Vector Single-Width Integer Multiply-Add Instructions
411 // EEW=SEW.
412 case RISCV::VMACC_VV:
413 case RISCV::VMACC_VX:
414 case RISCV::VNMSAC_VV:
415 case RISCV::VNMSAC_VX:
416 case RISCV::VMADD_VV:
417 case RISCV::VMADD_VX:
418 case RISCV::VNMSUB_VV:
419 case RISCV::VNMSUB_VX:
420 // Vector Integer Merge Instructions
421 // Vector Integer Add-with-Carry / Subtract-with-Borrow Instructions
422 // EEW=SEW, except the mask operand has EEW=1. Mask operand is handled
423 // before this switch.
424 case RISCV::VMERGE_VIM:
425 case RISCV::VMERGE_VVM:
426 case RISCV::VMERGE_VXM:
427 case RISCV::VADC_VIM:
428 case RISCV::VADC_VVM:
429 case RISCV::VADC_VXM:
430 case RISCV::VSBC_VVM:
431 case RISCV::VSBC_VXM:
432 // Vector Integer Move Instructions
433 // Vector Fixed-Point Arithmetic Instructions
434 // Vector Single-Width Saturating Add and Subtract
435 // Vector Single-Width Averaging Add and Subtract
436 // EEW=SEW.
437 case RISCV::VMV_V_I:
438 case RISCV::VMV_V_V:
439 case RISCV::VMV_V_X:
440 case RISCV::VSADDU_VI:
441 case RISCV::VSADDU_VV:
442 case RISCV::VSADDU_VX:
443 case RISCV::VSADD_VI:
444 case RISCV::VSADD_VV:
445 case RISCV::VSADD_VX:
446 case RISCV::VSSUBU_VV:
447 case RISCV::VSSUBU_VX:
448 case RISCV::VSSUB_VV:
449 case RISCV::VSSUB_VX:
450 case RISCV::VAADDU_VV:
451 case RISCV::VAADDU_VX:
452 case RISCV::VAADD_VV:
453 case RISCV::VAADD_VX:
454 case RISCV::VASUBU_VV:
455 case RISCV::VASUBU_VX:
456 case RISCV::VASUB_VV:
457 case RISCV::VASUB_VX:
458 // Vector Single-Width Fractional Multiply with Rounding and Saturation
459 // EEW=SEW. The instruction produces 2*SEW product internally but
460 // saturates to fit into SEW bits.
461 case RISCV::VSMUL_VV:
462 case RISCV::VSMUL_VX:
463 // Vector Single-Width Scaling Shift Instructions
464 // EEW=SEW.
465 case RISCV::VSSRL_VI:
466 case RISCV::VSSRL_VV:
467 case RISCV::VSSRL_VX:
468 case RISCV::VSSRA_VI:
469 case RISCV::VSSRA_VV:
470 case RISCV::VSSRA_VX:
471 // Vector Permutation Instructions
472 // Integer Scalar Move Instructions
473 // Floating-Point Scalar Move Instructions
474 // EEW=SEW.
475 case RISCV::VMV_X_S:
476 case RISCV::VMV_S_X:
477 case RISCV::VFMV_F_S:
478 case RISCV::VFMV_S_F:
479 // Vector Slide Instructions
480 // EEW=SEW.
481 case RISCV::VSLIDEUP_VI:
482 case RISCV::VSLIDEUP_VX:
483 case RISCV::VSLIDEDOWN_VI:
484 case RISCV::VSLIDEDOWN_VX:
485 case RISCV::VSLIDE1UP_VX:
486 case RISCV::VFSLIDE1UP_VF:
487 case RISCV::VSLIDE1DOWN_VX:
488 case RISCV::VFSLIDE1DOWN_VF:
489 // Vector Register Gather Instructions
490 // EEW=SEW. For mask operand, EEW=1.
491 case RISCV::VRGATHER_VI:
492 case RISCV::VRGATHER_VV:
493 case RISCV::VRGATHER_VX:
494 // Vector Element Index Instruction
495 case RISCV::VID_V:
496 // Vector Single-Width Floating-Point Add/Subtract Instructions
497 case RISCV::VFADD_VF:
498 case RISCV::VFADD_VV:
499 case RISCV::VFSUB_VF:
500 case RISCV::VFSUB_VV:
501 case RISCV::VFRSUB_VF:
502 // Vector Single-Width Floating-Point Multiply/Divide Instructions
503 case RISCV::VFMUL_VF:
504 case RISCV::VFMUL_VV:
505 case RISCV::VFDIV_VF:
506 case RISCV::VFDIV_VV:
507 case RISCV::VFRDIV_VF:
508 // Vector Single-Width Floating-Point Fused Multiply-Add Instructions
509 case RISCV::VFMACC_VV:
510 case RISCV::VFMACC_VF:
511 case RISCV::VFNMACC_VV:
512 case RISCV::VFNMACC_VF:
513 case RISCV::VFMSAC_VV:
514 case RISCV::VFMSAC_VF:
515 case RISCV::VFNMSAC_VV:
516 case RISCV::VFNMSAC_VF:
517 case RISCV::VFMADD_VV:
518 case RISCV::VFMADD_VF:
519 case RISCV::VFNMADD_VV:
520 case RISCV::VFNMADD_VF:
521 case RISCV::VFMSUB_VV:
522 case RISCV::VFMSUB_VF:
523 case RISCV::VFNMSUB_VV:
524 case RISCV::VFNMSUB_VF:
525 // Vector Floating-Point Square-Root Instruction
526 case RISCV::VFSQRT_V:
527 // Vector Floating-Point Reciprocal Square-Root Estimate Instruction
528 case RISCV::VFRSQRT7_V:
529 // Vector Floating-Point Reciprocal Estimate Instruction
530 case RISCV::VFREC7_V:
531 // Vector Floating-Point MIN/MAX Instructions
532 case RISCV::VFMIN_VF:
533 case RISCV::VFMIN_VV:
534 case RISCV::VFMAX_VF:
535 case RISCV::VFMAX_VV:
536 // Vector Floating-Point Sign-Injection Instructions
537 case RISCV::VFSGNJ_VF:
538 case RISCV::VFSGNJ_VV:
539 case RISCV::VFSGNJN_VV:
540 case RISCV::VFSGNJN_VF:
541 case RISCV::VFSGNJX_VF:
542 case RISCV::VFSGNJX_VV:
543 // Vector Floating-Point Classify Instruction
544 case RISCV::VFCLASS_V:
545 // Vector Floating-Point Move Instruction
546 case RISCV::VFMV_V_F:
547 // Single-Width Floating-Point/Integer Type-Convert Instructions
548 case RISCV::VFCVT_XU_F_V:
549 case RISCV::VFCVT_X_F_V:
550 case RISCV::VFCVT_RTZ_XU_F_V:
551 case RISCV::VFCVT_RTZ_X_F_V:
552 case RISCV::VFCVT_F_XU_V:
553 case RISCV::VFCVT_F_X_V:
554 // Vector Floating-Point Merge Instruction
555 case RISCV::VFMERGE_VFM:
556 // Vector count population in mask vcpop.m
557 // vfirst find-first-set mask bit
558 case RISCV::VCPOP_M:
559 case RISCV::VFIRST_M:
560 // Vector Bit-manipulation Instructions (Zvbb)
561 // Vector And-Not
562 case RISCV::VANDN_VV:
563 case RISCV::VANDN_VX:
564 // Vector Reverse Bits in Elements
565 case RISCV::VBREV_V:
566 // Vector Reverse Bits in Bytes
567 case RISCV::VBREV8_V:
568 // Vector Reverse Bytes
569 case RISCV::VREV8_V:
570 // Vector Count Leading Zeros
571 case RISCV::VCLZ_V:
572 // Vector Count Trailing Zeros
573 case RISCV::VCTZ_V:
574 // Vector Population Count
575 case RISCV::VCPOP_V:
576 // Vector Rotate Left
577 case RISCV::VROL_VV:
578 case RISCV::VROL_VX:
579 // Vector Rotate Right
580 case RISCV::VROR_VI:
581 case RISCV::VROR_VV:
582 case RISCV::VROR_VX:
583 // Vector Carry-less Multiplication Instructions (Zvbc)
584 // Vector Carry-less Multiply
585 case RISCV::VCLMUL_VV:
586 case RISCV::VCLMUL_VX:
587 // Vector Carry-less Multiply Return High Half
588 case RISCV::VCLMULH_VV:
589 case RISCV::VCLMULH_VX:
590
591 // Zvabd
592 case RISCV::VABS_V:
593 case RISCV::VABD_VV:
594 case RISCV::VABDU_VV:
595 return MILog2SEW;
596
597 // Vector Widening Shift Left Logical (Zvbb)
598 case RISCV::VWSLL_VI:
599 case RISCV::VWSLL_VX:
600 case RISCV::VWSLL_VV:
601 // Vector Widening Integer Add/Subtract
602 // Def uses EEW=2*SEW . Operands use EEW=SEW.
603 case RISCV::VWADDU_VV:
604 case RISCV::VWADDU_VX:
605 case RISCV::VWSUBU_VV:
606 case RISCV::VWSUBU_VX:
607 case RISCV::VWADD_VV:
608 case RISCV::VWADD_VX:
609 case RISCV::VWSUB_VV:
610 case RISCV::VWSUB_VX:
611 // Vector Widening Integer Multiply Instructions
612 // Destination EEW=2*SEW. Source EEW=SEW.
613 case RISCV::VWMUL_VV:
614 case RISCV::VWMUL_VX:
615 case RISCV::VWMULSU_VV:
616 case RISCV::VWMULSU_VX:
617 case RISCV::VWMULU_VV:
618 case RISCV::VWMULU_VX:
619 // Vector Widening Integer Multiply-Add Instructions
620 // Destination EEW=2*SEW. Source EEW=SEW.
621 // A SEW-bit*SEW-bit multiply of the sources forms a 2*SEW-bit value, which
622 // is then added to the 2*SEW-bit Dest. These instructions never have a
623 // passthru operand.
624 case RISCV::VWMACCU_VV:
625 case RISCV::VWMACCU_VX:
626 case RISCV::VWMACC_VV:
627 case RISCV::VWMACC_VX:
628 case RISCV::VWMACCSU_VV:
629 case RISCV::VWMACCSU_VX:
630 case RISCV::VWMACCUS_VX:
631 // Vector Widening Floating-Point Fused Multiply-Add Instructions
632 case RISCV::VFWMACC_VF:
633 case RISCV::VFWMACC_VV:
634 case RISCV::VFWNMACC_VF:
635 case RISCV::VFWNMACC_VV:
636 case RISCV::VFWMSAC_VF:
637 case RISCV::VFWMSAC_VV:
638 case RISCV::VFWNMSAC_VF:
639 case RISCV::VFWNMSAC_VV:
640 case RISCV::VFWMACCBF16_VV:
641 case RISCV::VFWMACCBF16_VF:
642 // Vector Widening Floating-Point Add/Subtract Instructions
643 // Dest EEW=2*SEW. Source EEW=SEW.
644 case RISCV::VFWADD_VV:
645 case RISCV::VFWADD_VF:
646 case RISCV::VFWSUB_VV:
647 case RISCV::VFWSUB_VF:
648 // Vector Widening Floating-Point Multiply
649 case RISCV::VFWMUL_VF:
650 case RISCV::VFWMUL_VV:
651 // Widening Floating-Point/Integer Type-Convert Instructions
652 case RISCV::VFWCVT_XU_F_V:
653 case RISCV::VFWCVT_X_F_V:
654 case RISCV::VFWCVT_RTZ_XU_F_V:
655 case RISCV::VFWCVT_RTZ_X_F_V:
656 case RISCV::VFWCVT_F_XU_V:
657 case RISCV::VFWCVT_F_X_V:
658 case RISCV::VFWCVT_F_F_V:
659 case RISCV::VFWCVTBF16_F_F_V:
660 // Zvabd
661 case RISCV::VWABDA_VV:
662 case RISCV::VWABDAU_VV:
663 return IsMODef ? MILog2SEW + 1 : MILog2SEW;
664
665 // Def and Op1 uses EEW=2*SEW. Op2 uses EEW=SEW.
666 case RISCV::VWADDU_WV:
667 case RISCV::VWADDU_WX:
668 case RISCV::VWSUBU_WV:
669 case RISCV::VWSUBU_WX:
670 case RISCV::VWADD_WV:
671 case RISCV::VWADD_WX:
672 case RISCV::VWSUB_WV:
673 case RISCV::VWSUB_WX:
674 // Vector Widening Floating-Point Add/Subtract Instructions
675 case RISCV::VFWADD_WF:
676 case RISCV::VFWADD_WV:
677 case RISCV::VFWSUB_WF:
678 case RISCV::VFWSUB_WV: {
679 bool IsOp1 = (HasPassthru && !IsTied) ? MO.getOperandNo() == 2
680 : MO.getOperandNo() == 1;
681 bool TwoTimes = IsMODef || IsOp1;
682 return TwoTimes ? MILog2SEW + 1 : MILog2SEW;
683 }
684
685 // Vector Integer Extension
686 case RISCV::VZEXT_VF2:
687 case RISCV::VSEXT_VF2:
688 return getIntegerExtensionOperandEEW(Factor: 2, MI, MO);
689 case RISCV::VZEXT_VF4:
690 case RISCV::VSEXT_VF4:
691 return getIntegerExtensionOperandEEW(Factor: 4, MI, MO);
692 case RISCV::VZEXT_VF8:
693 case RISCV::VSEXT_VF8:
694 return getIntegerExtensionOperandEEW(Factor: 8, MI, MO);
695
696 // Vector Narrowing Integer Right Shift Instructions
697 // Destination EEW=SEW, Op 1 has EEW=2*SEW. Op2 has EEW=SEW
698 case RISCV::VNSRL_WX:
699 case RISCV::VNSRL_WI:
700 case RISCV::VNSRL_WV:
701 case RISCV::VNSRA_WI:
702 case RISCV::VNSRA_WV:
703 case RISCV::VNSRA_WX:
704 // Vector Narrowing Fixed-Point Clip Instructions
705 // Destination and Op1 EEW=SEW. Op2 EEW=2*SEW.
706 case RISCV::VNCLIPU_WI:
707 case RISCV::VNCLIPU_WV:
708 case RISCV::VNCLIPU_WX:
709 case RISCV::VNCLIP_WI:
710 case RISCV::VNCLIP_WV:
711 case RISCV::VNCLIP_WX:
712 // Narrowing Floating-Point/Integer Type-Convert Instructions
713 case RISCV::VFNCVT_XU_F_W:
714 case RISCV::VFNCVT_X_F_W:
715 case RISCV::VFNCVT_RTZ_XU_F_W:
716 case RISCV::VFNCVT_RTZ_X_F_W:
717 case RISCV::VFNCVT_F_XU_W:
718 case RISCV::VFNCVT_F_X_W:
719 case RISCV::VFNCVT_F_F_W:
720 case RISCV::VFNCVT_ROD_F_F_W:
721 case RISCV::VFNCVTBF16_F_F_W: {
722 assert(!IsTied);
723 bool IsOp1 = HasPassthru ? MO.getOperandNo() == 2 : MO.getOperandNo() == 1;
724 bool TwoTimes = IsOp1;
725 return TwoTimes ? MILog2SEW + 1 : MILog2SEW;
726 }
727
728 // Vector Mask Instructions
729 // Vector Mask-Register Logical Instructions
730 // vmsbf.m set-before-first mask bit
731 // vmsif.m set-including-first mask bit
732 // vmsof.m set-only-first mask bit
733 // EEW=1
734 // We handle the cases when operand is a v0 mask operand above the switch,
735 // but these instructions may use non-v0 mask operands and need to be handled
736 // specifically.
737 case RISCV::VMAND_MM:
738 case RISCV::VMNAND_MM:
739 case RISCV::VMANDN_MM:
740 case RISCV::VMXOR_MM:
741 case RISCV::VMOR_MM:
742 case RISCV::VMNOR_MM:
743 case RISCV::VMORN_MM:
744 case RISCV::VMXNOR_MM:
745 case RISCV::VMSBF_M:
746 case RISCV::VMSIF_M:
747 case RISCV::VMSOF_M: {
748 return MILog2SEW;
749 }
750
751 // Vector Compress Instruction
752 // EEW=SEW, except the mask operand has EEW=1. Mask operand is not handled
753 // before this switch.
754 case RISCV::VCOMPRESS_VM:
755 return MO.getOperandNo() == 3 ? 0 : MILog2SEW;
756
757 // Vector Iota Instruction
758 // EEW=SEW, except the mask operand has EEW=1. Mask operand is not handled
759 // before this switch.
760 case RISCV::VIOTA_M: {
761 if (IsMODef || MO.getOperandNo() == 1)
762 return MILog2SEW;
763 return 0;
764 }
765
766 // Vector Integer Compare Instructions
767 // Dest EEW=1. Source EEW=SEW.
768 case RISCV::VMSEQ_VI:
769 case RISCV::VMSEQ_VV:
770 case RISCV::VMSEQ_VX:
771 case RISCV::VMSNE_VI:
772 case RISCV::VMSNE_VV:
773 case RISCV::VMSNE_VX:
774 case RISCV::VMSLTU_VV:
775 case RISCV::VMSLTU_VX:
776 case RISCV::VMSLT_VV:
777 case RISCV::VMSLT_VX:
778 case RISCV::VMSLEU_VV:
779 case RISCV::VMSLEU_VI:
780 case RISCV::VMSLEU_VX:
781 case RISCV::VMSLE_VV:
782 case RISCV::VMSLE_VI:
783 case RISCV::VMSLE_VX:
784 case RISCV::VMSGTU_VI:
785 case RISCV::VMSGTU_VX:
786 case RISCV::VMSGT_VI:
787 case RISCV::VMSGT_VX:
788 // Vector Integer Add-with-Carry / Subtract-with-Borrow Instructions
789 // Dest EEW=1. Source EEW=SEW. Mask source operand handled above this switch.
790 case RISCV::VMADC_VIM:
791 case RISCV::VMADC_VVM:
792 case RISCV::VMADC_VXM:
793 case RISCV::VMSBC_VVM:
794 case RISCV::VMSBC_VXM:
795 // Dest EEW=1. Source EEW=SEW.
796 case RISCV::VMADC_VV:
797 case RISCV::VMADC_VI:
798 case RISCV::VMADC_VX:
799 case RISCV::VMSBC_VV:
800 case RISCV::VMSBC_VX:
801 // 13.13. Vector Floating-Point Compare Instructions
802 // Dest EEW=1. Source EEW=SEW
803 case RISCV::VMFEQ_VF:
804 case RISCV::VMFEQ_VV:
805 case RISCV::VMFNE_VF:
806 case RISCV::VMFNE_VV:
807 case RISCV::VMFLT_VF:
808 case RISCV::VMFLT_VV:
809 case RISCV::VMFLE_VF:
810 case RISCV::VMFLE_VV:
811 case RISCV::VMFGT_VF:
812 case RISCV::VMFGE_VF: {
813 if (IsMODef)
814 return 0;
815 return MILog2SEW;
816 }
817
818 // Vector Reduction Operations
819 // Vector Single-Width Integer Reduction Instructions
820 case RISCV::VREDAND_VS:
821 case RISCV::VREDMAX_VS:
822 case RISCV::VREDMAXU_VS:
823 case RISCV::VREDMIN_VS:
824 case RISCV::VREDMINU_VS:
825 case RISCV::VREDOR_VS:
826 case RISCV::VREDSUM_VS:
827 case RISCV::VREDXOR_VS:
828 // Vector Single-Width Floating-Point Reduction Instructions
829 case RISCV::VFREDMAX_VS:
830 case RISCV::VFREDMIN_VS:
831 case RISCV::VFREDOSUM_VS:
832 case RISCV::VFREDUSUM_VS: {
833 return MILog2SEW;
834 }
835
836 // Vector Widening Integer Reduction Instructions
837 // The Dest and VS1 read only element 0 for the vector register. Return
838 // 2*EEW for these. VS2 has EEW=SEW and EMUL=LMUL.
839 case RISCV::VWREDSUM_VS:
840 case RISCV::VWREDSUMU_VS:
841 // Vector Widening Floating-Point Reduction Instructions
842 case RISCV::VFWREDOSUM_VS:
843 case RISCV::VFWREDUSUM_VS: {
844 bool TwoTimes = IsMODef || MO.getOperandNo() == 3;
845 return TwoTimes ? MILog2SEW + 1 : MILog2SEW;
846 }
847
848 // Vector Register Gather with 16-bit Index Elements Instruction
849 // Dest and source data EEW=SEW. Index vector EEW=16.
850 case RISCV::VRGATHEREI16_VV: {
851 if (MO.getOperandNo() == 2)
852 return 4;
853 return MILog2SEW;
854 }
855
856 default:
857 return std::nullopt;
858 }
859}
860
861static std::optional<OperandInfo> getOperandInfo(const MachineOperand &MO) {
862 const MachineInstr &MI = *MO.getParent();
863 const RISCVVPseudosTable::PseudoInfo *RVV =
864 RISCVVPseudosTable::getPseudoInfo(Pseudo: MI.getOpcode());
865 assert(RVV && "Could not find MI in PseudoTable");
866
867 std::optional<unsigned> Log2EEW = getOperandLog2EEW(MO);
868 if (!Log2EEW)
869 return std::nullopt;
870
871 switch (RVV->BaseInstr) {
872 // Vector Reduction Operations
873 // Vector Single-Width Integer Reduction Instructions
874 // Vector Widening Integer Reduction Instructions
875 // Vector Widening Floating-Point Reduction Instructions
876 // The Dest and VS1 only read element 0 of the vector register. Return just
877 // the EEW for these.
878 case RISCV::VREDAND_VS:
879 case RISCV::VREDMAX_VS:
880 case RISCV::VREDMAXU_VS:
881 case RISCV::VREDMIN_VS:
882 case RISCV::VREDMINU_VS:
883 case RISCV::VREDOR_VS:
884 case RISCV::VREDSUM_VS:
885 case RISCV::VREDXOR_VS:
886 case RISCV::VWREDSUM_VS:
887 case RISCV::VWREDSUMU_VS:
888 case RISCV::VFWREDOSUM_VS:
889 case RISCV::VFWREDUSUM_VS:
890 if (MO.getOperandNo() != 2)
891 return OperandInfo(*Log2EEW);
892 break;
893 };
894
895 // All others have EMUL=EEW/SEW*LMUL
896 return OperandInfo(getEMULEqualsEEWDivSEWTimesLMUL(Log2EEW: *Log2EEW, MI), *Log2EEW);
897}
898
899static bool isTupleInsertInstr(const MachineInstr &MI);
900
901/// Return true if we can reason about demanded VLs elementwise for \p MI.
902bool RISCVVLOptimizer::isSupportedInstr(const MachineInstr &MI) const {
903 if (MI.isPHI() || MI.isFullCopy() || isTupleInsertInstr(MI))
904 return true;
905
906 unsigned RVVOpc = RISCV::getRVVMCOpcode(RVVPseudoOpcode: MI.getOpcode());
907 if (!RVVOpc)
908 return false;
909
910 assert(!(MI.getNumExplicitDefs() == 0 && !MI.mayStore() &&
911 !RISCVII::elementsDependOnVL(TII->get(RVVOpc).TSFlags)) &&
912 "No defs but elements don't depend on VL?");
913
914 // TODO: Reduce vl for vmv.s.x and vfmv.s.f. Currently this introduces more vl
915 // toggles, we need to extend PRE in RISCVInsertVSETVLI first.
916 if (RVVOpc == RISCV::VMV_S_X || RVVOpc == RISCV::VFMV_S_F)
917 return false;
918
919 if (RISCVII::elementsDependOnVL(TSFlags: TII->get(Opcode: RVVOpc).TSFlags))
920 return false;
921
922 if (MI.mayStore())
923 return false;
924
925 return true;
926}
927
928/// Return true if MO is a vector operand but is used as a scalar operand.
929static bool isVectorOpUsedAsScalarOp(const MachineOperand &MO) {
930 const MachineInstr *MI = MO.getParent();
931 const RISCVVPseudosTable::PseudoInfo *RVV =
932 RISCVVPseudosTable::getPseudoInfo(Pseudo: MI->getOpcode());
933
934 if (!RVV)
935 return false;
936
937 switch (RVV->BaseInstr) {
938 // Reductions only use vs1[0] of vs1
939 case RISCV::VREDAND_VS:
940 case RISCV::VREDMAX_VS:
941 case RISCV::VREDMAXU_VS:
942 case RISCV::VREDMIN_VS:
943 case RISCV::VREDMINU_VS:
944 case RISCV::VREDOR_VS:
945 case RISCV::VREDSUM_VS:
946 case RISCV::VREDXOR_VS:
947 case RISCV::VWREDSUM_VS:
948 case RISCV::VWREDSUMU_VS:
949 case RISCV::VFREDMAX_VS:
950 case RISCV::VFREDMIN_VS:
951 case RISCV::VFREDOSUM_VS:
952 case RISCV::VFREDUSUM_VS:
953 case RISCV::VFWREDOSUM_VS:
954 case RISCV::VFWREDUSUM_VS:
955 return MO.getOperandNo() == 3;
956 case RISCV::VMV_X_S:
957 case RISCV::VFMV_F_S:
958 return MO.getOperandNo() == 1;
959 default:
960 return false;
961 }
962}
963
964bool RISCVVLOptimizer::isCandidate(const MachineInstr &MI) const {
965 const MCInstrDesc &Desc = MI.getDesc();
966 if (!RISCVII::hasVLOp(TSFlags: Desc.TSFlags) || !RISCVII::hasSEWOp(TSFlags: Desc.TSFlags))
967 return false;
968
969 if (MI.getNumExplicitDefs() != 1)
970 return false;
971
972 // Some instructions have implicit defs e.g. $vxsat. If they might be read
973 // later then we can't reduce VL.
974 if (!MI.allImplicitDefsAreDead()) {
975 LLVM_DEBUG(dbgs() << "Not a candidate because has non-dead implicit def\n");
976 return false;
977 }
978
979 if (MI.mayRaiseFPException()) {
980 LLVM_DEBUG(dbgs() << "Not a candidate because may raise FP exception\n");
981 return false;
982 }
983
984 for (const MachineMemOperand *MMO : MI.memoperands()) {
985 if (MMO->isVolatile()) {
986 LLVM_DEBUG(dbgs() << "Not a candidate because contains volatile MMO\n");
987 return false;
988 }
989 }
990
991 if (!isSupportedInstr(MI)) {
992 LLVM_DEBUG(dbgs() << "Not a candidate due to unsupported instruction: "
993 << MI);
994 return false;
995 }
996
997 assert(!RISCVII::elementsDependOnVL(
998 TII->get(RISCV::getRVVMCOpcode(MI.getOpcode())).TSFlags) &&
999 "Instruction shouldn't be supported if elements depend on VL");
1000
1001 assert(RISCVRI::isVRegClass(
1002 MRI->getRegClass(MI.getOperand(0).getReg())->TSFlags) &&
1003 "All supported instructions produce a vector register result");
1004
1005 LLVM_DEBUG(dbgs() << "Found a candidate for VL reduction: " << MI << "\n");
1006 return true;
1007}
1008
1009/// Given a vslidedown.vx like:
1010///
1011/// %slideamt = ADDI %x, -1
1012/// %v = PseudoVSLIDEDOWN_VX %passthru, %src, %slideamt, avl=1
1013///
1014/// %v will only read the first %slideamt + 1 lanes of %src, which = %x.
1015/// This is a common case when lowering extractelement.
1016///
1017/// Note that if %x is 0, %slideamt will be all ones. In this case %src will be
1018/// completely slid down and none of its lanes will be read (since %slideamt is
1019/// greater than the largest VLMAX of 65536) so we can demand any minimum VL.
1020static std::optional<DemandedVL>
1021getMinimumVLForVSLIDEDOWN_VX(const MachineOperand &UserOp,
1022 const MachineRegisterInfo *MRI) {
1023 const MachineInstr &MI = *UserOp.getParent();
1024 if (RISCV::getRVVMCOpcode(RVVPseudoOpcode: MI.getOpcode()) != RISCV::VSLIDEDOWN_VX)
1025 return std::nullopt;
1026 // We're looking at what lanes are used from the src operand.
1027 if (UserOp.getOperandNo() != 2)
1028 return std::nullopt;
1029 // For now, the AVL must be 1.
1030 const MachineOperand &AVL = MI.getOperand(i: 4);
1031 if (!AVL.isImm() || AVL.getImm() != 1)
1032 return std::nullopt;
1033 // The slide amount must be %x - 1.
1034 const MachineOperand &SlideAmt = MI.getOperand(i: 3);
1035 if (!SlideAmt.getReg().isVirtual())
1036 return std::nullopt;
1037 MachineInstr *SlideAmtDef = MRI->getUniqueVRegDef(Reg: SlideAmt.getReg());
1038 if (SlideAmtDef->getOpcode() != RISCV::ADDI ||
1039 SlideAmtDef->getOperand(i: 2).getImm() != -AVL.getImm() ||
1040 !SlideAmtDef->getOperand(i: 1).getReg().isVirtual())
1041 return std::nullopt;
1042 return SlideAmtDef->getOperand(i: 1);
1043}
1044
1045DemandedVL
1046RISCVVLOptimizer::getMinimumVLForUser(const MachineOperand &UserOp) const {
1047 const MachineInstr &UserMI = *UserOp.getParent();
1048 const MCInstrDesc &Desc = UserMI.getDesc();
1049
1050 if (UserMI.isPHI() || UserMI.isFullCopy() || isTupleInsertInstr(MI: UserMI))
1051 return DemandedVLs.lookup(Key: &UserMI);
1052
1053 if (!RISCVII::hasVLOp(TSFlags: Desc.TSFlags) || !RISCVII::hasSEWOp(TSFlags: Desc.TSFlags)) {
1054 LLVM_DEBUG(dbgs() << " Abort due to lack of VL, assume that"
1055 " use VLMAX\n");
1056 return DemandedVL::vlmax();
1057 }
1058
1059 if (auto VL = getMinimumVLForVSLIDEDOWN_VX(UserOp, MRI))
1060 return *VL;
1061
1062 if (RISCVII::readsPastVL(
1063 TSFlags: TII->get(Opcode: RISCV::getRVVMCOpcode(RVVPseudoOpcode: UserMI.getOpcode())).TSFlags)) {
1064 LLVM_DEBUG(dbgs() << " Abort because used by unsafe instruction\n");
1065 return DemandedVL::vlmax();
1066 }
1067
1068 unsigned VLOpNum = RISCVII::getVLOpNum(Desc);
1069 const MachineOperand &VLOp = UserMI.getOperand(i: VLOpNum);
1070 // Looking for an immediate or a register VL that isn't X0.
1071 assert((!VLOp.isReg() || VLOp.getReg() != RISCV::X0) &&
1072 "Did not expect X0 VL");
1073
1074 // If the user is a passthru it will read the elements past VL, so
1075 // abort if any of the elements past VL are demanded.
1076 if (UserOp.isTied()) {
1077 assert(UserOp.getOperandNo() == UserMI.getNumExplicitDefs() &&
1078 RISCVII::isFirstDefTiedToFirstUse(UserMI.getDesc()));
1079 if (!RISCV::isVLKnownLE(LHS: DemandedVLs.lookup(Key: &UserMI).VL, RHS: VLOp)) {
1080 LLVM_DEBUG(dbgs() << " Abort because user is passthru in "
1081 "instruction with demanded tail\n");
1082 return DemandedVL::vlmax();
1083 }
1084 }
1085
1086 // Instructions like reductions may use a vector register as a scalar
1087 // register. In this case, we should treat it as only reading the first lane.
1088 if (isVectorOpUsedAsScalarOp(MO: UserOp)) {
1089 LLVM_DEBUG(dbgs() << " Used this operand as a scalar operand\n");
1090 return MachineOperand::CreateImm(Val: 1);
1091 }
1092
1093 // If we know the demanded VL of UserMI, then we can reduce the VL it
1094 // requires.
1095 if (RISCV::isVLKnownLE(LHS: DemandedVLs.lookup(Key: &UserMI).VL, RHS: VLOp))
1096 return DemandedVLs.lookup(Key: &UserMI);
1097
1098 return VLOp;
1099}
1100
1101/// Return true if MI is an instruction used for assembling registers
1102/// for segmented store instructions, namely, RISCVISD::TUPLE_INSERT.
1103/// Currently it's lowered to INSERT_SUBREG.
1104static bool isTupleInsertInstr(const MachineInstr &MI) {
1105 if (!MI.isInsertSubreg())
1106 return false;
1107
1108 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1109 const TargetRegisterClass *DstRC = MRI.getRegClass(Reg: MI.getOperand(i: 0).getReg());
1110 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1111 if (!RISCVRI::isVRegClass(TSFlags: DstRC->TSFlags))
1112 return false;
1113 unsigned NF = RISCVRI::getNF(TSFlags: DstRC->TSFlags);
1114 if (NF < 2)
1115 return false;
1116
1117 // Check whether INSERT_SUBREG has the correct subreg index for tuple inserts.
1118 auto VLMul = RISCVRI::getLMul(TSFlags: DstRC->TSFlags);
1119 unsigned SubRegIdx = MI.getOperand(i: 3).getImm();
1120 [[maybe_unused]] auto [LMul, IsFractional] = RISCVVType::decodeVLMUL(VLMul);
1121 assert(!IsFractional && "unexpected LMUL for tuple register classes");
1122 return TRI->getSubRegIdxSize(Idx: SubRegIdx) == RISCV::RVVBitsPerBlock * LMul;
1123}
1124
1125static bool isSegmentedStoreInstr(const MachineInstr &MI) {
1126 switch (RISCV::getRVVMCOpcode(RVVPseudoOpcode: MI.getOpcode())) {
1127 case VSSEG_CASES(8):
1128 case VSSSEG_CASES(8):
1129 case VSUXSEG_CASES(8):
1130 case VSOXSEG_CASES(8):
1131 case VSSEG_CASES(16):
1132 case VSSSEG_CASES(16):
1133 case VSUXSEG_CASES(16):
1134 case VSOXSEG_CASES(16):
1135 case VSSEG_CASES(32):
1136 case VSSSEG_CASES(32):
1137 case VSUXSEG_CASES(32):
1138 case VSOXSEG_CASES(32):
1139 case VSSEG_CASES(64):
1140 case VSSSEG_CASES(64):
1141 case VSUXSEG_CASES(64):
1142 case VSOXSEG_CASES(64):
1143 return true;
1144 default:
1145 return false;
1146 }
1147}
1148
1149bool RISCVVLOptimizer::checkUsers(const MachineInstr &MI) const {
1150 if (MI.isPHI() || MI.isFullCopy() || isTupleInsertInstr(MI))
1151 return true;
1152
1153 SmallSetVector<MachineOperand *, 8> OpWorklist;
1154 SmallPtrSet<const MachineInstr *, 4> PHISeen;
1155 for (auto &UserOp : MRI->use_operands(Reg: MI.getOperand(i: 0).getReg()))
1156 OpWorklist.insert(X: &UserOp);
1157
1158 while (!OpWorklist.empty()) {
1159 MachineOperand &UserOp = *OpWorklist.pop_back_val();
1160 const MachineInstr &UserMI = *UserOp.getParent();
1161 LLVM_DEBUG(dbgs() << " Checking user: " << UserMI << "\n");
1162
1163 if (UserMI.isFullCopy() && UserMI.getOperand(i: 0).getReg().isVirtual()) {
1164 LLVM_DEBUG(dbgs() << " Peeking through uses of COPY\n");
1165 OpWorklist.insert_range(R: llvm::make_pointer_range(
1166 Range: MRI->use_operands(Reg: UserMI.getOperand(i: 0).getReg())));
1167 continue;
1168 }
1169
1170 if (isTupleInsertInstr(MI: UserMI)) {
1171 LLVM_DEBUG(dbgs().indent(4) << "Peeking through uses of INSERT_SUBREG\n");
1172 for (MachineOperand &UseOp :
1173 MRI->use_operands(Reg: UserMI.getOperand(i: 0).getReg())) {
1174 const MachineInstr &CandidateMI = *UseOp.getParent();
1175 // We should not propagate the VL if the user is not a segmented store
1176 // or another INSERT_SUBREG, since VL just works differently
1177 // between segmented operations (per-field) v.s. other RVV ops (on the
1178 // whole register group).
1179 if (!isTupleInsertInstr(MI: CandidateMI) &&
1180 !isSegmentedStoreInstr(MI: CandidateMI))
1181 return false;
1182 OpWorklist.insert(X: &UseOp);
1183 }
1184 continue;
1185 }
1186
1187 if (UserMI.isPHI()) {
1188 // Don't follow PHI cycles
1189 if (!PHISeen.insert(Ptr: &UserMI).second)
1190 continue;
1191 LLVM_DEBUG(dbgs() << " Peeking through uses of PHI\n");
1192 OpWorklist.insert_range(R: llvm::make_pointer_range(
1193 Range: MRI->use_operands(Reg: UserMI.getOperand(i: 0).getReg())));
1194 continue;
1195 }
1196
1197 if (!RISCVII::hasSEWOp(TSFlags: UserMI.getDesc().TSFlags)) {
1198 LLVM_DEBUG(dbgs() << " Abort due to lack of SEW operand\n");
1199 return false;
1200 }
1201
1202 std::optional<OperandInfo> ConsumerInfo = getOperandInfo(MO: UserOp);
1203 std::optional<OperandInfo> ProducerInfo = getOperandInfo(MO: MI.getOperand(i: 0));
1204 if (!ConsumerInfo || !ProducerInfo) {
1205 LLVM_DEBUG(dbgs() << " Abort due to unknown operand information.\n");
1206 LLVM_DEBUG(dbgs() << " ConsumerInfo is: " << ConsumerInfo << "\n");
1207 LLVM_DEBUG(dbgs() << " ProducerInfo is: " << ProducerInfo << "\n");
1208 return false;
1209 }
1210
1211 if (!OperandInfo::areCompatible(Def: *ProducerInfo, User: *ConsumerInfo)) {
1212 LLVM_DEBUG(
1213 dbgs()
1214 << " Abort due to incompatible information for EMUL or EEW.\n");
1215 LLVM_DEBUG(dbgs() << " ConsumerInfo is: " << ConsumerInfo << "\n");
1216 LLVM_DEBUG(dbgs() << " ProducerInfo is: " << ProducerInfo << "\n");
1217 return false;
1218 }
1219 }
1220
1221 return true;
1222}
1223
1224bool RISCVVLOptimizer::tryReduceVL(MachineInstr &MI,
1225 MachineOperand CommonVL) const {
1226 LLVM_DEBUG(dbgs() << "Trying to reduce VL for " << MI);
1227
1228 unsigned VLOpNum = RISCVII::getVLOpNum(Desc: MI.getDesc());
1229 MachineOperand &VLOp = MI.getOperand(i: VLOpNum);
1230
1231 assert((CommonVL.isImm() || CommonVL.getReg().isVirtual()) &&
1232 "Expected VL to be an Imm or virtual Reg");
1233
1234 // If the VL is defined by a vleff that doesn't dominate MI, try using the
1235 // vleff's AVL. It will be greater than or equal to the output VL.
1236 if (CommonVL.isReg()) {
1237 const MachineInstr *VLMI = MRI->getVRegDef(Reg: CommonVL.getReg());
1238 if (RISCVInstrInfo::isFaultOnlyFirstLoad(MI: *VLMI) &&
1239 !MDT->dominates(A: VLMI, B: &MI))
1240 CommonVL = VLMI->getOperand(i: RISCVII::getVLOpNum(Desc: VLMI->getDesc()));
1241 }
1242
1243 if (!RISCV::isVLKnownLE(LHS: CommonVL, RHS: VLOp)) {
1244 LLVM_DEBUG(dbgs() << " Abort due to CommonVL not <= VLOp.\n");
1245 return false;
1246 }
1247
1248 if (CommonVL.isIdenticalTo(Other: VLOp)) {
1249 LLVM_DEBUG(
1250 dbgs() << " Abort due to CommonVL == VLOp, no point in reducing.\n");
1251 return false;
1252 }
1253
1254 if (CommonVL.isImm()) {
1255 LLVM_DEBUG(dbgs() << " Reduce VL from " << VLOp << " to "
1256 << CommonVL.getImm() << " for " << MI << "\n");
1257 VLOp.ChangeToImmediate(ImmVal: CommonVL.getImm());
1258 return true;
1259 }
1260 MachineInstr *VLMI = MRI->getVRegDef(Reg: CommonVL.getReg());
1261 auto VLDominates = [this, &VLMI](const MachineInstr &MI) {
1262 return MDT->dominates(A: VLMI, B: &MI);
1263 };
1264 if (!VLDominates(MI)) {
1265 assert(MI.getNumExplicitDefs() == 1);
1266 auto Uses = MRI->use_instructions(Reg: MI.getOperand(i: 0).getReg());
1267 auto UsesSameBB = make_filter_range(Range&: Uses, Pred: [&MI](const MachineInstr &Use) {
1268 return Use.getParent() == MI.getParent();
1269 });
1270 if (VLMI->getParent() == MI.getParent() &&
1271 all_of(Range&: UsesSameBB, P: VLDominates) &&
1272 RISCVInstrInfo::isSafeToMove(From: MI, To: std::next(x: VLMI->getIterator()))) {
1273 VLMI->getParent()->splice(Where: std::next(x: VLMI->getIterator()), Other: MI.getParent(),
1274 From: MI.getIterator());
1275 } else {
1276 LLVM_DEBUG(dbgs() << " Abort due to VL not dominating.\n");
1277 return false;
1278 }
1279 }
1280 LLVM_DEBUG(dbgs() << " Reduce VL from " << VLOp << " to "
1281 << printReg(CommonVL.getReg(), MRI->getTargetRegisterInfo())
1282 << " for " << MI << "\n");
1283
1284 // All our checks passed. We can reduce VL.
1285 VLOp.ChangeToRegister(Reg: CommonVL.getReg(), isDef: false);
1286 MRI->constrainRegClass(Reg: CommonVL.getReg(), RC: &RISCV::GPRNoX0RegClass);
1287 return true;
1288}
1289
1290static bool isPhysical(const MachineOperand &MO) {
1291 return MO.isReg() && MO.getReg().isPhysical();
1292}
1293
1294/// Look through \p MI's operands and propagate what it demands to its uses.
1295void RISCVVLOptimizer::transfer(const MachineInstr &MI) {
1296 if (!isSupportedInstr(MI) || !checkUsers(MI) || any_of(Range: MI.defs(), P: isPhysical))
1297 DemandedVLs[&MI] = DemandedVL::vlmax();
1298
1299 for (const MachineOperand &MO : virtual_vec_uses(MI)) {
1300 const MachineInstr *Def = MRI->getVRegDef(Reg: MO.getReg());
1301 DemandedVL Prev = DemandedVLs[Def];
1302 DemandedVLs[Def] = DemandedVLs[Def].max(X: getMinimumVLForUser(UserOp: MO));
1303 if (DemandedVLs[Def] != Prev)
1304 Worklist.insert(X: Def);
1305 }
1306}
1307
1308bool RISCVVLOptimizer::runOnMachineFunction(MachineFunction &MF) {
1309 if (skipFunction(F: MF.getFunction()))
1310 return false;
1311
1312 MRI = &MF.getRegInfo();
1313 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1314
1315 const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1316 if (!ST.hasVInstructions())
1317 return false;
1318
1319 TII = ST.getInstrInfo();
1320
1321 assert(DemandedVLs.empty());
1322
1323 // For each instruction that defines a vector, propagate the VL it
1324 // uses to its inputs.
1325 for (MachineBasicBlock *MBB : post_order(G: &MF)) {
1326 assert(MDT->isReachableFromEntry(MBB));
1327 for (MachineInstr &MI : reverse(C&: *MBB))
1328 if (!MI.isDebugInstr())
1329 Worklist.insert(X: &MI);
1330 }
1331
1332 while (!Worklist.empty()) {
1333 const MachineInstr *MI = Worklist.front();
1334 Worklist.remove(X: MI);
1335 transfer(MI: *MI);
1336 }
1337
1338 // Then go through and see if we can reduce the VL of any instructions to
1339 // only what's demanded.
1340 bool MadeChange = false;
1341 for (auto &[MI, VL] : DemandedVLs) {
1342 assert(MDT->isReachableFromEntry(MI->getParent()));
1343 if (!isCandidate(MI: *MI))
1344 continue;
1345 if (!tryReduceVL(MI&: *const_cast<MachineInstr *>(MI), CommonVL: VL.VL))
1346 continue;
1347 MadeChange = true;
1348 }
1349
1350 DemandedVLs.clear();
1351 return MadeChange;
1352}
1353