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