LLVM 19.0.0git
RISCVInsertVSETVLI.cpp
Go to the documentation of this file.
1//===- RISCVInsertVSETVLI.cpp - Insert VSETVLI instructions ---------------===//
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 file implements a function pass that inserts VSETVLI instructions where
10// needed and expands the vl outputs of VLEFF/VLSEGFF to PseudoReadVL
11// instructions.
12//
13// This pass consists of 3 phases:
14//
15// Phase 1 collects how each basic block affects VL/VTYPE.
16//
17// Phase 2 uses the information from phase 1 to do a data flow analysis to
18// propagate the VL/VTYPE changes through the function. This gives us the
19// VL/VTYPE at the start of each basic block.
20//
21// Phase 3 inserts VSETVLI instructions in each basic block. Information from
22// phase 2 is used to prevent inserting a VSETVLI before the first vector
23// instruction in the block if possible.
24//
25//===----------------------------------------------------------------------===//
26
27#include "RISCV.h"
28#include "RISCVSubtarget.h"
29#include "llvm/ADT/Statistic.h"
34#include <queue>
35using namespace llvm;
36
37#define DEBUG_TYPE "riscv-insert-vsetvli"
38#define RISCV_INSERT_VSETVLI_NAME "RISC-V Insert VSETVLI pass"
39#define RISCV_COALESCE_VSETVLI_NAME "RISC-V Coalesce VSETVLI pass"
40
41STATISTIC(NumInsertedVSETVL, "Number of VSETVL inst inserted");
42STATISTIC(NumCoalescedVSETVL, "Number of VSETVL inst coalesced");
43
45 "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
46 cl::desc("Disable looking through phis when inserting vsetvlis."));
47
49 "riscv-insert-vsetvl-strict-asserts", cl::init(true), cl::Hidden,
50 cl::desc("Enable strict assertion checking for the dataflow algorithm"));
51
52namespace {
53
54static unsigned getVLOpNum(const MachineInstr &MI) {
55 return RISCVII::getVLOpNum(MI.getDesc());
56}
57
58static unsigned getSEWOpNum(const MachineInstr &MI) {
59 return RISCVII::getSEWOpNum(MI.getDesc());
60}
61
62static bool isVectorConfigInstr(const MachineInstr &MI) {
63 return MI.getOpcode() == RISCV::PseudoVSETVLI ||
64 MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
65 MI.getOpcode() == RISCV::PseudoVSETIVLI;
66}
67
68/// Return true if this is 'vsetvli x0, x0, vtype' which preserves
69/// VL and only sets VTYPE.
70static bool isVLPreservingConfig(const MachineInstr &MI) {
71 if (MI.getOpcode() != RISCV::PseudoVSETVLIX0)
72 return false;
73 assert(RISCV::X0 == MI.getOperand(1).getReg());
74 return RISCV::X0 == MI.getOperand(0).getReg();
75}
76
77static bool isFloatScalarMoveOrScalarSplatInstr(const MachineInstr &MI) {
78 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
79 default:
80 return false;
81 case RISCV::VFMV_S_F:
82 case RISCV::VFMV_V_F:
83 return true;
84 }
85}
86
87static bool isScalarExtractInstr(const MachineInstr &MI) {
88 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
89 default:
90 return false;
91 case RISCV::VMV_X_S:
92 case RISCV::VFMV_F_S:
93 return true;
94 }
95}
96
97static bool isScalarInsertInstr(const MachineInstr &MI) {
98 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
99 default:
100 return false;
101 case RISCV::VMV_S_X:
102 case RISCV::VFMV_S_F:
103 return true;
104 }
105}
106
107static bool isScalarSplatInstr(const MachineInstr &MI) {
108 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
109 default:
110 return false;
111 case RISCV::VMV_V_I:
112 case RISCV::VMV_V_X:
113 case RISCV::VFMV_V_F:
114 return true;
115 }
116}
117
118static bool isVSlideInstr(const MachineInstr &MI) {
119 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
120 default:
121 return false;
122 case RISCV::VSLIDEDOWN_VX:
123 case RISCV::VSLIDEDOWN_VI:
124 case RISCV::VSLIDEUP_VX:
125 case RISCV::VSLIDEUP_VI:
126 return true;
127 }
128}
129
130/// Get the EEW for a load or store instruction. Return std::nullopt if MI is
131/// not a load or store which ignores SEW.
132static std::optional<unsigned> getEEWForLoadStore(const MachineInstr &MI) {
133 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
134 default:
135 return std::nullopt;
136 case RISCV::VLE8_V:
137 case RISCV::VLSE8_V:
138 case RISCV::VSE8_V:
139 case RISCV::VSSE8_V:
140 return 8;
141 case RISCV::VLE16_V:
142 case RISCV::VLSE16_V:
143 case RISCV::VSE16_V:
144 case RISCV::VSSE16_V:
145 return 16;
146 case RISCV::VLE32_V:
147 case RISCV::VLSE32_V:
148 case RISCV::VSE32_V:
149 case RISCV::VSSE32_V:
150 return 32;
151 case RISCV::VLE64_V:
152 case RISCV::VLSE64_V:
153 case RISCV::VSE64_V:
154 case RISCV::VSSE64_V:
155 return 64;
156 }
157}
158
159static bool isNonZeroLoadImmediate(MachineInstr &MI) {
160 return MI.getOpcode() == RISCV::ADDI &&
161 MI.getOperand(1).isReg() && MI.getOperand(2).isImm() &&
162 MI.getOperand(1).getReg() == RISCV::X0 &&
163 MI.getOperand(2).getImm() != 0;
164}
165
166/// Return true if this is an operation on mask registers. Note that
167/// this includes both arithmetic/logical ops and load/store (vlm/vsm).
168static bool isMaskRegOp(const MachineInstr &MI) {
169 if (!RISCVII::hasSEWOp(MI.getDesc().TSFlags))
170 return false;
171 const unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
172 // A Log2SEW of 0 is an operation on mask registers only.
173 return Log2SEW == 0;
174}
175
176/// Return true if the inactive elements in the result are entirely undefined.
177/// Note that this is different from "agnostic" as defined by the vector
178/// specification. Agnostic requires each lane to either be undisturbed, or
179/// take the value -1; no other value is allowed.
180static bool hasUndefinedMergeOp(const MachineInstr &MI,
181 const MachineRegisterInfo &MRI) {
182
183 unsigned UseOpIdx;
184 if (!MI.isRegTiedToUseOperand(0, &UseOpIdx))
185 // If there is no passthrough operand, then the pass through
186 // lanes are undefined.
187 return true;
188
189 // If the tied operand is NoReg, an IMPLICIT_DEF, or a REG_SEQEUENCE whose
190 // operands are solely IMPLICIT_DEFS, then the pass through lanes are
191 // undefined.
192 const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
193 if (UseMO.getReg() == RISCV::NoRegister)
194 return true;
195
196 if (UseMO.isUndef())
197 return true;
198 if (UseMO.getReg().isPhysical())
199 return false;
200
201 if (MachineInstr *UseMI = MRI.getVRegDef(UseMO.getReg())) {
202 if (UseMI->isImplicitDef())
203 return true;
204
205 if (UseMI->isRegSequence()) {
206 for (unsigned i = 1, e = UseMI->getNumOperands(); i < e; i += 2) {
207 MachineInstr *SourceMI = MRI.getVRegDef(UseMI->getOperand(i).getReg());
208 if (!SourceMI || !SourceMI->isImplicitDef())
209 return false;
210 }
211 return true;
212 }
213 }
214 return false;
215}
216
217/// Which subfields of VL or VTYPE have values we need to preserve?
218struct DemandedFields {
219 // Some unknown property of VL is used. If demanded, must preserve entire
220 // value.
221 bool VLAny = false;
222 // Only zero vs non-zero is used. If demanded, can change non-zero values.
223 bool VLZeroness = false;
224 // What properties of SEW we need to preserve.
225 enum : uint8_t {
226 SEWEqual = 3, // The exact value of SEW needs to be preserved.
227 SEWGreaterThanOrEqual = 2, // SEW can be changed as long as it's greater
228 // than or equal to the original value.
229 SEWGreaterThanOrEqualAndLessThan64 =
230 1, // SEW can be changed as long as it's greater
231 // than or equal to the original value, but must be less
232 // than 64.
233 SEWNone = 0 // We don't need to preserve SEW at all.
234 } SEW = SEWNone;
235 bool LMUL = false;
236 bool SEWLMULRatio = false;
237 bool TailPolicy = false;
238 bool MaskPolicy = false;
239
240 // Return true if any part of VTYPE was used
241 bool usedVTYPE() const {
242 return SEW || LMUL || SEWLMULRatio || TailPolicy || MaskPolicy;
243 }
244
245 // Return true if any property of VL was used
246 bool usedVL() {
247 return VLAny || VLZeroness;
248 }
249
250 // Mark all VTYPE subfields and properties as demanded
251 void demandVTYPE() {
252 SEW = SEWEqual;
253 LMUL = true;
254 SEWLMULRatio = true;
255 TailPolicy = true;
256 MaskPolicy = true;
257 }
258
259 // Mark all VL properties as demanded
260 void demandVL() {
261 VLAny = true;
262 VLZeroness = true;
263 }
264
265 // Make this the result of demanding both the fields in this and B.
266 void doUnion(const DemandedFields &B) {
267 VLAny |= B.VLAny;
268 VLZeroness |= B.VLZeroness;
269 SEW = std::max(SEW, B.SEW);
270 LMUL |= B.LMUL;
271 SEWLMULRatio |= B.SEWLMULRatio;
272 TailPolicy |= B.TailPolicy;
273 MaskPolicy |= B.MaskPolicy;
274 }
275
276#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
277 /// Support for debugging, callable in GDB: V->dump()
278 LLVM_DUMP_METHOD void dump() const {
279 print(dbgs());
280 dbgs() << "\n";
281 }
282
283 /// Implement operator<<.
284 void print(raw_ostream &OS) const {
285 OS << "{";
286 OS << "VLAny=" << VLAny << ", ";
287 OS << "VLZeroness=" << VLZeroness << ", ";
288 OS << "SEW=";
289 switch (SEW) {
290 case SEWEqual:
291 OS << "SEWEqual";
292 break;
293 case SEWGreaterThanOrEqual:
294 OS << "SEWGreaterThanOrEqual";
295 break;
296 case SEWGreaterThanOrEqualAndLessThan64:
297 OS << "SEWGreaterThanOrEqualAndLessThan64";
298 break;
299 case SEWNone:
300 OS << "SEWNone";
301 break;
302 };
303 OS << ", ";
304 OS << "LMUL=" << LMUL << ", ";
305 OS << "SEWLMULRatio=" << SEWLMULRatio << ", ";
306 OS << "TailPolicy=" << TailPolicy << ", ";
307 OS << "MaskPolicy=" << MaskPolicy;
308 OS << "}";
309 }
310#endif
311};
312
313#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
315inline raw_ostream &operator<<(raw_ostream &OS, const DemandedFields &DF) {
316 DF.print(OS);
317 return OS;
318}
319#endif
320
321/// Return true if moving from CurVType to NewVType is
322/// indistinguishable from the perspective of an instruction (or set
323/// of instructions) which use only the Used subfields and properties.
324static bool areCompatibleVTYPEs(uint64_t CurVType, uint64_t NewVType,
325 const DemandedFields &Used) {
326 switch (Used.SEW) {
327 case DemandedFields::SEWNone:
328 break;
329 case DemandedFields::SEWEqual:
330 if (RISCVVType::getSEW(CurVType) != RISCVVType::getSEW(NewVType))
331 return false;
332 break;
333 case DemandedFields::SEWGreaterThanOrEqual:
334 if (RISCVVType::getSEW(NewVType) < RISCVVType::getSEW(CurVType))
335 return false;
336 break;
337 case DemandedFields::SEWGreaterThanOrEqualAndLessThan64:
338 if (RISCVVType::getSEW(NewVType) < RISCVVType::getSEW(CurVType) ||
339 RISCVVType::getSEW(NewVType) >= 64)
340 return false;
341 break;
342 }
343
344 if (Used.LMUL &&
345 RISCVVType::getVLMUL(CurVType) != RISCVVType::getVLMUL(NewVType))
346 return false;
347
348 if (Used.SEWLMULRatio) {
349 auto Ratio1 = RISCVVType::getSEWLMULRatio(RISCVVType::getSEW(CurVType),
350 RISCVVType::getVLMUL(CurVType));
351 auto Ratio2 = RISCVVType::getSEWLMULRatio(RISCVVType::getSEW(NewVType),
352 RISCVVType::getVLMUL(NewVType));
353 if (Ratio1 != Ratio2)
354 return false;
355 }
356
357 if (Used.TailPolicy && RISCVVType::isTailAgnostic(CurVType) !=
359 return false;
360 if (Used.MaskPolicy && RISCVVType::isMaskAgnostic(CurVType) !=
362 return false;
363 return true;
364}
365
366/// Return the fields and properties demanded by the provided instruction.
367DemandedFields getDemanded(const MachineInstr &MI,
369 const RISCVSubtarget *ST) {
370 // Warning: This function has to work on both the lowered (i.e. post
371 // emitVSETVLIs) and pre-lowering forms. The main implication of this is
372 // that it can't use the value of a SEW, VL, or Policy operand as they might
373 // be stale after lowering.
374
375 // Most instructions don't use any of these subfeilds.
376 DemandedFields Res;
377 // Start conservative if registers are used
378 if (MI.isCall() || MI.isInlineAsm() ||
379 MI.readsRegister(RISCV::VL, /*TRI=*/nullptr))
380 Res.demandVL();
381 if (MI.isCall() || MI.isInlineAsm() ||
382 MI.readsRegister(RISCV::VTYPE, /*TRI=*/nullptr))
383 Res.demandVTYPE();
384 // Start conservative on the unlowered form too
385 uint64_t TSFlags = MI.getDesc().TSFlags;
386 if (RISCVII::hasSEWOp(TSFlags)) {
387 Res.demandVTYPE();
388 if (RISCVII::hasVLOp(TSFlags))
389 Res.demandVL();
390
391 // Behavior is independent of mask policy.
392 if (!RISCVII::usesMaskPolicy(TSFlags))
393 Res.MaskPolicy = false;
394 }
395
396 // Loads and stores with implicit EEW do not demand SEW or LMUL directly.
397 // They instead demand the ratio of the two which is used in computing
398 // EMUL, but which allows us the flexibility to change SEW and LMUL
399 // provided we don't change the ratio.
400 // Note: We assume that the instructions initial SEW is the EEW encoded
401 // in the opcode. This is asserted when constructing the VSETVLIInfo.
402 if (getEEWForLoadStore(MI)) {
403 Res.SEW = DemandedFields::SEWNone;
404 Res.LMUL = false;
405 }
406
407 // Store instructions don't use the policy fields.
408 if (RISCVII::hasSEWOp(TSFlags) && MI.getNumExplicitDefs() == 0) {
409 Res.TailPolicy = false;
410 Res.MaskPolicy = false;
411 }
412
413 // If this is a mask reg operation, it only cares about VLMAX.
414 // TODO: Possible extensions to this logic
415 // * Probably ok if available VLMax is larger than demanded
416 // * The policy bits can probably be ignored..
417 if (isMaskRegOp(MI)) {
418 Res.SEW = DemandedFields::SEWNone;
419 Res.LMUL = false;
420 }
421
422 // For vmv.s.x and vfmv.s.f, there are only two behaviors, VL = 0 and VL > 0.
423 if (isScalarInsertInstr(MI)) {
424 Res.LMUL = false;
425 Res.SEWLMULRatio = false;
426 Res.VLAny = false;
427 // For vmv.s.x and vfmv.s.f, if the merge operand is *undefined*, we don't
428 // need to preserve any other bits and are thus compatible with any larger,
429 // etype and can disregard policy bits. Warning: It's tempting to try doing
430 // this for any tail agnostic operation, but we can't as TA requires
431 // tail lanes to either be the original value or -1. We are writing
432 // unknown bits to the lanes here.
433 if (hasUndefinedMergeOp(MI, *MRI)) {
434 if (isFloatScalarMoveOrScalarSplatInstr(MI) && !ST->hasVInstructionsF64())
435 Res.SEW = DemandedFields::SEWGreaterThanOrEqualAndLessThan64;
436 else
437 Res.SEW = DemandedFields::SEWGreaterThanOrEqual;
438 Res.TailPolicy = false;
439 }
440 }
441
442 // vmv.x.s, and vmv.f.s are unconditional and ignore everything except SEW.
443 if (isScalarExtractInstr(MI)) {
444 assert(!RISCVII::hasVLOp(TSFlags));
445 Res.LMUL = false;
446 Res.SEWLMULRatio = false;
447 Res.TailPolicy = false;
448 Res.MaskPolicy = false;
449 }
450
451 return Res;
452}
453
454/// Defines the abstract state with which the forward dataflow models the
455/// values of the VL and VTYPE registers after insertion.
456class VSETVLIInfo {
457 union {
458 Register AVLReg;
459 unsigned AVLImm;
460 };
461
462 enum : uint8_t {
464 AVLIsReg,
465 AVLIsImm,
466 AVLIsVLMAX,
467 AVLIsIgnored,
468 Unknown,
469 } State = Uninitialized;
470
471 // Fields from VTYPE.
473 uint8_t SEW = 0;
474 uint8_t TailAgnostic : 1;
475 uint8_t MaskAgnostic : 1;
476 uint8_t SEWLMULRatioOnly : 1;
477
478public:
479 VSETVLIInfo()
480 : AVLImm(0), TailAgnostic(false), MaskAgnostic(false),
481 SEWLMULRatioOnly(false) {}
482
483 static VSETVLIInfo getUnknown() {
484 VSETVLIInfo Info;
485 Info.setUnknown();
486 return Info;
487 }
488
489 bool isValid() const { return State != Uninitialized; }
490 void setUnknown() { State = Unknown; }
491 bool isUnknown() const { return State == Unknown; }
492
493 void setAVLReg(Register Reg) {
494 assert(Reg.isVirtual());
495 AVLReg = Reg;
496 State = AVLIsReg;
497 }
498
499 void setAVLImm(unsigned Imm) {
500 AVLImm = Imm;
501 State = AVLIsImm;
502 }
503
504 void setAVLVLMAX() { State = AVLIsVLMAX; }
505
506 void setAVLIgnored() { State = AVLIsIgnored; }
507
508 bool hasAVLImm() const { return State == AVLIsImm; }
509 bool hasAVLReg() const { return State == AVLIsReg; }
510 bool hasAVLVLMAX() const { return State == AVLIsVLMAX; }
511 bool hasAVLIgnored() const { return State == AVLIsIgnored; }
512 Register getAVLReg() const {
513 assert(hasAVLReg());
514 return AVLReg;
515 }
516 unsigned getAVLImm() const {
517 assert(hasAVLImm());
518 return AVLImm;
519 }
520
521 void setAVL(VSETVLIInfo Info) {
522 assert(Info.isValid());
523 if (Info.isUnknown())
524 setUnknown();
525 else if (Info.hasAVLReg())
526 setAVLReg(Info.getAVLReg());
527 else if (Info.hasAVLVLMAX())
528 setAVLVLMAX();
529 else if (Info.hasAVLIgnored())
530 setAVLIgnored();
531 else {
532 assert(Info.hasAVLImm());
533 setAVLImm(Info.getAVLImm());
534 }
535 }
536
537 unsigned getSEW() const { return SEW; }
538 RISCVII::VLMUL getVLMUL() const { return VLMul; }
539 bool getTailAgnostic() const { return TailAgnostic; }
540 bool getMaskAgnostic() const { return MaskAgnostic; }
541
542 bool hasNonZeroAVL(const MachineRegisterInfo &MRI) const {
543 if (hasAVLImm())
544 return getAVLImm() > 0;
545 if (hasAVLReg()) {
546 MachineInstr *MI = MRI.getUniqueVRegDef(getAVLReg());
547 assert(MI);
548 return isNonZeroLoadImmediate(*MI);
549 }
550 if (hasAVLVLMAX())
551 return true;
552 if (hasAVLIgnored())
553 return false;
554 return false;
555 }
556
557 bool hasEquallyZeroAVL(const VSETVLIInfo &Other,
558 const MachineRegisterInfo &MRI) const {
559 if (hasSameAVL(Other))
560 return true;
561 return (hasNonZeroAVL(MRI) && Other.hasNonZeroAVL(MRI));
562 }
563
564 bool hasSameAVL(const VSETVLIInfo &Other) const {
565 if (hasAVLReg() && Other.hasAVLReg())
566 return getAVLReg() == Other.getAVLReg();
567
568 if (hasAVLImm() && Other.hasAVLImm())
569 return getAVLImm() == Other.getAVLImm();
570
571 if (hasAVLVLMAX())
572 return Other.hasAVLVLMAX() && hasSameVLMAX(Other);
573
574 if (hasAVLIgnored())
575 return Other.hasAVLIgnored();
576
577 return false;
578 }
579
580 void setVTYPE(unsigned VType) {
581 assert(isValid() && !isUnknown() &&
582 "Can't set VTYPE for uninitialized or unknown");
583 VLMul = RISCVVType::getVLMUL(VType);
584 SEW = RISCVVType::getSEW(VType);
585 TailAgnostic = RISCVVType::isTailAgnostic(VType);
586 MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
587 }
588 void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA) {
589 assert(isValid() && !isUnknown() &&
590 "Can't set VTYPE for uninitialized or unknown");
591 VLMul = L;
592 SEW = S;
593 TailAgnostic = TA;
594 MaskAgnostic = MA;
595 }
596
597 void setVLMul(RISCVII::VLMUL VLMul) { this->VLMul = VLMul; }
598
599 unsigned encodeVTYPE() const {
600 assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
601 "Can't encode VTYPE for uninitialized or unknown");
602 return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
603 }
604
605 bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
606
607 bool hasSameVTYPE(const VSETVLIInfo &Other) const {
608 assert(isValid() && Other.isValid() &&
609 "Can't compare invalid VSETVLIInfos");
610 assert(!isUnknown() && !Other.isUnknown() &&
611 "Can't compare VTYPE in unknown state");
612 assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
613 "Can't compare when only LMUL/SEW ratio is valid.");
614 return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
615 std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
616 Other.MaskAgnostic);
617 }
618
619 unsigned getSEWLMULRatio() const {
620 assert(isValid() && !isUnknown() &&
621 "Can't use VTYPE for uninitialized or unknown");
622 return RISCVVType::getSEWLMULRatio(SEW, VLMul);
623 }
624
625 // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
626 // Note that having the same VLMAX ensures that both share the same
627 // function from AVL to VL; that is, they must produce the same VL value
628 // for any given AVL value.
629 bool hasSameVLMAX(const VSETVLIInfo &Other) const {
630 assert(isValid() && Other.isValid() &&
631 "Can't compare invalid VSETVLIInfos");
632 assert(!isUnknown() && !Other.isUnknown() &&
633 "Can't compare VTYPE in unknown state");
634 return getSEWLMULRatio() == Other.getSEWLMULRatio();
635 }
636
637 bool hasCompatibleVTYPE(const DemandedFields &Used,
638 const VSETVLIInfo &Require) const {
639 return areCompatibleVTYPEs(Require.encodeVTYPE(), encodeVTYPE(), Used);
640 }
641
642 // Determine whether the vector instructions requirements represented by
643 // Require are compatible with the previous vsetvli instruction represented
644 // by this. MI is the instruction whose requirements we're considering.
645 bool isCompatible(const DemandedFields &Used, const VSETVLIInfo &Require,
646 const MachineRegisterInfo &MRI) const {
647 assert(isValid() && Require.isValid() &&
648 "Can't compare invalid VSETVLIInfos");
649 assert(!Require.SEWLMULRatioOnly &&
650 "Expected a valid VTYPE for instruction!");
651 // Nothing is compatible with Unknown.
652 if (isUnknown() || Require.isUnknown())
653 return false;
654
655 // If only our VLMAX ratio is valid, then this isn't compatible.
656 if (SEWLMULRatioOnly)
657 return false;
658
659 if (Used.VLAny && !(hasSameAVL(Require) && hasSameVLMAX(Require)))
660 return false;
661
662 if (Used.VLZeroness && !hasEquallyZeroAVL(Require, MRI))
663 return false;
664
665 return hasCompatibleVTYPE(Used, Require);
666 }
667
668 bool operator==(const VSETVLIInfo &Other) const {
669 // Uninitialized is only equal to another Uninitialized.
670 if (!isValid())
671 return !Other.isValid();
672 if (!Other.isValid())
673 return !isValid();
674
675 // Unknown is only equal to another Unknown.
676 if (isUnknown())
677 return Other.isUnknown();
678 if (Other.isUnknown())
679 return isUnknown();
680
681 if (!hasSameAVL(Other))
682 return false;
683
684 // If the SEWLMULRatioOnly bits are different, then they aren't equal.
685 if (SEWLMULRatioOnly != Other.SEWLMULRatioOnly)
686 return false;
687
688 // If only the VLMAX is valid, check that it is the same.
689 if (SEWLMULRatioOnly)
690 return hasSameVLMAX(Other);
691
692 // If the full VTYPE is valid, check that it is the same.
693 return hasSameVTYPE(Other);
694 }
695
696 bool operator!=(const VSETVLIInfo &Other) const {
697 return !(*this == Other);
698 }
699
700 // Calculate the VSETVLIInfo visible to a block assuming this and Other are
701 // both predecessors.
702 VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
703 // If the new value isn't valid, ignore it.
704 if (!Other.isValid())
705 return *this;
706
707 // If this value isn't valid, this must be the first predecessor, use it.
708 if (!isValid())
709 return Other;
710
711 // If either is unknown, the result is unknown.
712 if (isUnknown() || Other.isUnknown())
713 return VSETVLIInfo::getUnknown();
714
715 // If we have an exact, match return this.
716 if (*this == Other)
717 return *this;
718
719 // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
720 // return an SEW/LMUL ratio only value.
721 if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
722 VSETVLIInfo MergeInfo = *this;
723 MergeInfo.SEWLMULRatioOnly = true;
724 return MergeInfo;
725 }
726
727 // Otherwise the result is unknown.
728 return VSETVLIInfo::getUnknown();
729 }
730
731#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
732 /// Support for debugging, callable in GDB: V->dump()
733 LLVM_DUMP_METHOD void dump() const {
734 print(dbgs());
735 dbgs() << "\n";
736 }
737
738 /// Implement operator<<.
739 /// @{
740 void print(raw_ostream &OS) const {
741 OS << "{";
742 if (!isValid())
743 OS << "Uninitialized";
744 if (isUnknown())
745 OS << "unknown";
746 if (hasAVLReg())
747 OS << "AVLReg=" << (unsigned)AVLReg;
748 if (hasAVLImm())
749 OS << "AVLImm=" << (unsigned)AVLImm;
750 if (hasAVLVLMAX())
751 OS << "AVLVLMAX";
752 if (hasAVLIgnored())
753 OS << "AVLIgnored";
754 OS << ", "
755 << "VLMul=" << (unsigned)VLMul << ", "
756 << "SEW=" << (unsigned)SEW << ", "
757 << "TailAgnostic=" << (bool)TailAgnostic << ", "
758 << "MaskAgnostic=" << (bool)MaskAgnostic << ", "
759 << "SEWLMULRatioOnly=" << (bool)SEWLMULRatioOnly << "}";
760 }
761#endif
762};
763
764#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
766inline raw_ostream &operator<<(raw_ostream &OS, const VSETVLIInfo &V) {
767 V.print(OS);
768 return OS;
769}
770#endif
771
772struct BlockData {
773 // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
774 // block. Calculated in Phase 2.
775 VSETVLIInfo Exit;
776
777 // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
778 // blocks. Calculated in Phase 2, and used by Phase 3.
779 VSETVLIInfo Pred;
780
781 // Keeps track of whether the block is already in the queue.
782 bool InQueue = false;
783
784 BlockData() = default;
785};
786
787class RISCVInsertVSETVLI : public MachineFunctionPass {
788 const RISCVSubtarget *ST;
789 const TargetInstrInfo *TII;
791
792 std::vector<BlockData> BlockInfo;
793 std::queue<const MachineBasicBlock *> WorkList;
794
795public:
796 static char ID;
797
798 RISCVInsertVSETVLI() : MachineFunctionPass(ID) {}
799 bool runOnMachineFunction(MachineFunction &MF) override;
800
801 void getAnalysisUsage(AnalysisUsage &AU) const override {
802 AU.setPreservesCFG();
804 }
805
806 StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
807
808private:
809 bool needVSETVLI(const MachineInstr &MI, const VSETVLIInfo &Require,
810 const VSETVLIInfo &CurInfo) const;
811 bool needVSETVLIPHI(const VSETVLIInfo &Require,
812 const MachineBasicBlock &MBB) const;
813 void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
814 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
815 void insertVSETVLI(MachineBasicBlock &MBB,
817 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
818
819 void transferBefore(VSETVLIInfo &Info, const MachineInstr &MI) const;
820 void transferAfter(VSETVLIInfo &Info, const MachineInstr &MI) const;
821 bool computeVLVTYPEChanges(const MachineBasicBlock &MBB,
822 VSETVLIInfo &Info) const;
823 void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
824 void emitVSETVLIs(MachineBasicBlock &MBB);
825 void doPRE(MachineBasicBlock &MBB);
826 void insertReadVL(MachineBasicBlock &MBB);
827};
828
829class RISCVCoalesceVSETVLI : public MachineFunctionPass {
830public:
831 static char ID;
832 const RISCVSubtarget *ST;
833 const TargetInstrInfo *TII;
835 LiveIntervals *LIS;
836
837 RISCVCoalesceVSETVLI() : MachineFunctionPass(ID) {}
838 bool runOnMachineFunction(MachineFunction &MF) override;
839
840 void getAnalysisUsage(AnalysisUsage &AU) const override {
841 AU.setPreservesCFG();
842
849
851 }
852
853 StringRef getPassName() const override { return RISCV_COALESCE_VSETVLI_NAME; }
854
855private:
856 bool coalesceVSETVLIs(MachineBasicBlock &MBB);
857};
858
859} // end anonymous namespace
860
861char RISCVInsertVSETVLI::ID = 0;
862
864 false, false)
865
866char RISCVCoalesceVSETVLI::ID = 0;
867
868INITIALIZE_PASS(RISCVCoalesceVSETVLI, "riscv-coalesce-vsetvli",
870
871// Return a VSETVLIInfo representing the changes made by this VSETVLI or
872// VSETIVLI instruction.
873static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
874 VSETVLIInfo NewInfo;
875 if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
876 NewInfo.setAVLImm(MI.getOperand(1).getImm());
877 } else {
878 assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
879 MI.getOpcode() == RISCV::PseudoVSETVLIX0);
880 Register AVLReg = MI.getOperand(1).getReg();
881 assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
882 "Can't handle X0, X0 vsetvli yet");
883 if (AVLReg == RISCV::X0)
884 NewInfo.setAVLVLMAX();
885 else
886 NewInfo.setAVLReg(AVLReg);
887 }
888 NewInfo.setVTYPE(MI.getOperand(2).getImm());
889
890 return NewInfo;
891}
892
893static unsigned computeVLMAX(unsigned VLEN, unsigned SEW,
894 RISCVII::VLMUL VLMul) {
895 auto [LMul, Fractional] = RISCVVType::decodeVLMUL(VLMul);
896 if (Fractional)
897 VLEN = VLEN / LMul;
898 else
899 VLEN = VLEN * LMul;
900 return VLEN/SEW;
901}
902
903static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
904 const RISCVSubtarget &ST,
905 const MachineRegisterInfo *MRI) {
906 VSETVLIInfo InstrInfo;
907
908 bool TailAgnostic = true;
909 bool MaskAgnostic = true;
910 if (!hasUndefinedMergeOp(MI, *MRI)) {
911 // Start with undisturbed.
912 TailAgnostic = false;
913 MaskAgnostic = false;
914
915 // If there is a policy operand, use it.
916 if (RISCVII::hasVecPolicyOp(TSFlags)) {
917 const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
918 uint64_t Policy = Op.getImm();
920 "Invalid Policy Value");
921 TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
922 MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
923 }
924
925 // Some pseudo instructions force a tail agnostic policy despite having a
926 // tied def.
928 TailAgnostic = true;
929
930 if (!RISCVII::usesMaskPolicy(TSFlags))
931 MaskAgnostic = true;
932 }
933
934 RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
935
936 unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
937 // A Log2SEW of 0 is an operation on mask registers only.
938 unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
939 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
940
941 if (RISCVII::hasVLOp(TSFlags)) {
942 const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
943 if (VLOp.isImm()) {
944 int64_t Imm = VLOp.getImm();
945 // Conver the VLMax sentintel to X0 register.
946 if (Imm == RISCV::VLMaxSentinel) {
947 // If we know the exact VLEN, see if we can use the constant encoding
948 // for the VLMAX instead. This reduces register pressure slightly.
949 const unsigned VLMAX = computeVLMAX(ST.getRealMaxVLen(), SEW, VLMul);
950 if (ST.getRealMinVLen() == ST.getRealMaxVLen() && VLMAX <= 31)
951 InstrInfo.setAVLImm(VLMAX);
952 else
953 InstrInfo.setAVLVLMAX();
954 }
955 else
956 InstrInfo.setAVLImm(Imm);
957 } else {
958 InstrInfo.setAVLReg(VLOp.getReg());
959 }
960 } else {
961 assert(isScalarExtractInstr(MI));
962 // TODO: If we are more clever about x0,x0 insertion then we should be able
963 // to deduce that the VL is ignored based off of DemandedFields, and remove
964 // the AVLIsIgnored state. Then we can just use an arbitrary immediate AVL.
965 InstrInfo.setAVLIgnored();
966 }
967#ifndef NDEBUG
968 if (std::optional<unsigned> EEW = getEEWForLoadStore(MI)) {
969 assert(SEW == EEW && "Initial SEW doesn't match expected EEW");
970 }
971#endif
972 InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
973
974 // If AVL is defined by a vsetvli with the same VLMAX, we can replace the
975 // AVL operand with the AVL of the defining vsetvli. We avoid general
976 // register AVLs to avoid extending live ranges without being sure we can
977 // kill the original source reg entirely.
978 if (InstrInfo.hasAVLReg()) {
979 MachineInstr *DefMI = MRI->getUniqueVRegDef(InstrInfo.getAVLReg());
980 assert(DefMI);
981 if (isVectorConfigInstr(*DefMI)) {
982 VSETVLIInfo DefInstrInfo = getInfoForVSETVLI(*DefMI);
983 if (DefInstrInfo.hasSameVLMAX(InstrInfo) &&
984 (DefInstrInfo.hasAVLImm() || DefInstrInfo.hasAVLVLMAX()))
985 InstrInfo.setAVL(DefInstrInfo);
986 }
987 }
988
989 return InstrInfo;
990}
991
992void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
993 const VSETVLIInfo &Info,
994 const VSETVLIInfo &PrevInfo) {
995 DebugLoc DL = MI.getDebugLoc();
996 insertVSETVLI(MBB, MachineBasicBlock::iterator(&MI), DL, Info, PrevInfo);
997}
998
999void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB,
1001 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo) {
1002
1003 ++NumInsertedVSETVL;
1004 if (PrevInfo.isValid() && !PrevInfo.isUnknown()) {
1005 // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
1006 // VLMAX.
1007 if (Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
1008 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1010 .addReg(RISCV::X0, RegState::Kill)
1011 .addImm(Info.encodeVTYPE())
1012 .addReg(RISCV::VL, RegState::Implicit);
1013 return;
1014 }
1015
1016 // If our AVL is a virtual register, it might be defined by a VSET(I)VLI. If
1017 // it has the same VLMAX we want and the last VL/VTYPE we observed is the
1018 // same, we can use the X0, X0 form.
1019 if (Info.hasSameVLMAX(PrevInfo) && Info.hasAVLReg()) {
1020 MachineInstr *DefMI = MRI->getUniqueVRegDef(Info.getAVLReg());
1021 assert(DefMI);
1022 if (isVectorConfigInstr(*DefMI)) {
1023 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1024 if (DefInfo.hasSameAVL(PrevInfo) && DefInfo.hasSameVLMAX(PrevInfo)) {
1025 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1027 .addReg(RISCV::X0, RegState::Kill)
1028 .addImm(Info.encodeVTYPE())
1029 .addReg(RISCV::VL, RegState::Implicit);
1030 return;
1031 }
1032 }
1033 }
1034 }
1035
1036 if (Info.hasAVLImm()) {
1037 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
1039 .addImm(Info.getAVLImm())
1040 .addImm(Info.encodeVTYPE());
1041 return;
1042 }
1043
1044 if (Info.hasAVLIgnored()) {
1045 // We can only use x0, x0 if there's no chance of the vtype change causing
1046 // the previous vl to become invalid.
1047 if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
1048 Info.hasSameVLMAX(PrevInfo)) {
1049 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1051 .addReg(RISCV::X0, RegState::Kill)
1052 .addImm(Info.encodeVTYPE())
1053 .addReg(RISCV::VL, RegState::Implicit);
1054 return;
1055 }
1056 // Otherwise use an AVL of 1 to avoid depending on previous vl.
1057 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
1059 .addImm(1)
1060 .addImm(Info.encodeVTYPE());
1061 return;
1062 }
1063
1064 if (Info.hasAVLVLMAX()) {
1065 Register DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
1066 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1068 .addReg(RISCV::X0, RegState::Kill)
1069 .addImm(Info.encodeVTYPE());
1070 return;
1071 }
1072
1073 Register AVLReg = Info.getAVLReg();
1074 MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
1075 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLI))
1077 .addReg(AVLReg)
1078 .addImm(Info.encodeVTYPE());
1079}
1080
1082 auto [LMul, Fractional] = RISCVVType::decodeVLMUL(LMUL);
1083 return Fractional || LMul == 1;
1084}
1085
1086/// Return true if a VSETVLI is required to transition from CurInfo to Require
1087/// before MI.
1088bool RISCVInsertVSETVLI::needVSETVLI(const MachineInstr &MI,
1089 const VSETVLIInfo &Require,
1090 const VSETVLIInfo &CurInfo) const {
1091 assert(Require == computeInfoForInstr(MI, MI.getDesc().TSFlags, *ST, MRI));
1092
1093 if (!CurInfo.isValid() || CurInfo.isUnknown() || CurInfo.hasSEWLMULRatioOnly())
1094 return true;
1095
1096 DemandedFields Used = getDemanded(MI, MRI, ST);
1097
1098 // A slidedown/slideup with an *undefined* merge op can freely clobber
1099 // elements not copied from the source vector (e.g. masked off, tail, or
1100 // slideup's prefix). Notes:
1101 // * We can't modify SEW here since the slide amount is in units of SEW.
1102 // * VL=1 is special only because we have existing support for zero vs
1103 // non-zero VL. We could generalize this if we had a VL > C predicate.
1104 // * The LMUL1 restriction is for machines whose latency may depend on VL.
1105 // * As above, this is only legal for tail "undefined" not "agnostic".
1106 if (isVSlideInstr(MI) && Require.hasAVLImm() && Require.getAVLImm() == 1 &&
1107 isLMUL1OrSmaller(CurInfo.getVLMUL()) && hasUndefinedMergeOp(MI, *MRI)) {
1108 Used.VLAny = false;
1109 Used.VLZeroness = true;
1110 Used.LMUL = false;
1111 Used.TailPolicy = false;
1112 }
1113
1114 // A tail undefined vmv.v.i/x or vfmv.v.f with VL=1 can be treated in the same
1115 // semantically as vmv.s.x. This is particularly useful since we don't have an
1116 // immediate form of vmv.s.x, and thus frequently use vmv.v.i in it's place.
1117 // Since a splat is non-constant time in LMUL, we do need to be careful to not
1118 // increase the number of active vector registers (unlike for vmv.s.x.)
1119 if (isScalarSplatInstr(MI) && Require.hasAVLImm() && Require.getAVLImm() == 1 &&
1120 isLMUL1OrSmaller(CurInfo.getVLMUL()) && hasUndefinedMergeOp(MI, *MRI)) {
1121 Used.LMUL = false;
1122 Used.SEWLMULRatio = false;
1123 Used.VLAny = false;
1124 if (isFloatScalarMoveOrScalarSplatInstr(MI) && !ST->hasVInstructionsF64())
1125 Used.SEW = DemandedFields::SEWGreaterThanOrEqualAndLessThan64;
1126 else
1127 Used.SEW = DemandedFields::SEWGreaterThanOrEqual;
1128 Used.TailPolicy = false;
1129 }
1130
1131 if (CurInfo.isCompatible(Used, Require, *MRI))
1132 return false;
1133
1134 // We didn't find a compatible value. If our AVL is a virtual register,
1135 // it might be defined by a VSET(I)VLI. If it has the same VLMAX we need
1136 // and the last VL/VTYPE we observed is the same, we don't need a
1137 // VSETVLI here.
1138 if (Require.hasAVLReg() && CurInfo.hasCompatibleVTYPE(Used, Require)) {
1139 MachineInstr *DefMI = MRI->getUniqueVRegDef(Require.getAVLReg());
1140 assert(DefMI);
1141 if (isVectorConfigInstr(*DefMI)) {
1142 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1143 if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVLMAX(CurInfo))
1144 return false;
1145 }
1146 }
1147
1148 return true;
1149}
1150
1151// If we don't use LMUL or the SEW/LMUL ratio, then adjust LMUL so that we
1152// maintain the SEW/LMUL ratio. This allows us to eliminate VL toggles in more
1153// places.
1154static VSETVLIInfo adjustIncoming(VSETVLIInfo PrevInfo, VSETVLIInfo NewInfo,
1155 DemandedFields &Demanded) {
1156 VSETVLIInfo Info = NewInfo;
1157
1158 if (!Demanded.LMUL && !Demanded.SEWLMULRatio && PrevInfo.isValid() &&
1159 !PrevInfo.isUnknown()) {
1160 if (auto NewVLMul = RISCVVType::getSameRatioLMUL(
1161 PrevInfo.getSEW(), PrevInfo.getVLMUL(), Info.getSEW()))
1162 Info.setVLMul(*NewVLMul);
1163 Demanded.LMUL = true;
1164 }
1165
1166 return Info;
1167}
1168
1169// Given an incoming state reaching MI, minimally modifies that state so that it
1170// is compatible with MI. The resulting state is guaranteed to be semantically
1171// legal for MI, but may not be the state requested by MI.
1172void RISCVInsertVSETVLI::transferBefore(VSETVLIInfo &Info,
1173 const MachineInstr &MI) const {
1174 uint64_t TSFlags = MI.getDesc().TSFlags;
1175 if (!RISCVII::hasSEWOp(TSFlags))
1176 return;
1177
1178 const VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, *ST, MRI);
1179 assert(NewInfo.isValid() && !NewInfo.isUnknown());
1180 if (Info.isValid() && !needVSETVLI(MI, NewInfo, Info))
1181 return;
1182
1183 const VSETVLIInfo PrevInfo = Info;
1184 if (!Info.isValid() || Info.isUnknown())
1185 Info = NewInfo;
1186
1187 DemandedFields Demanded = getDemanded(MI, MRI, ST);
1188 const VSETVLIInfo IncomingInfo = adjustIncoming(PrevInfo, NewInfo, Demanded);
1189
1190 // If MI only demands that VL has the same zeroness, we only need to set the
1191 // AVL if the zeroness differs. This removes a vsetvli entirely if the types
1192 // match or allows use of cheaper avl preserving variant if VLMAX doesn't
1193 // change. If VLMAX might change, we couldn't use the 'vsetvli x0, x0, vtype"
1194 // variant, so we avoid the transform to prevent extending live range of an
1195 // avl register operand.
1196 // TODO: We can probably relax this for immediates.
1197 bool EquallyZero = IncomingInfo.hasEquallyZeroAVL(PrevInfo, *MRI) &&
1198 IncomingInfo.hasSameVLMAX(PrevInfo);
1199 if (Demanded.VLAny || (Demanded.VLZeroness && !EquallyZero))
1200 Info.setAVL(IncomingInfo);
1201
1202 Info.setVTYPE(
1203 ((Demanded.LMUL || Demanded.SEWLMULRatio) ? IncomingInfo : Info)
1204 .getVLMUL(),
1205 ((Demanded.SEW || Demanded.SEWLMULRatio) ? IncomingInfo : Info).getSEW(),
1206 // Prefer tail/mask agnostic since it can be relaxed to undisturbed later
1207 // if needed.
1208 (Demanded.TailPolicy ? IncomingInfo : Info).getTailAgnostic() ||
1209 IncomingInfo.getTailAgnostic(),
1210 (Demanded.MaskPolicy ? IncomingInfo : Info).getMaskAgnostic() ||
1211 IncomingInfo.getMaskAgnostic());
1212
1213 // If we only knew the sew/lmul ratio previously, replace the VTYPE but keep
1214 // the AVL.
1215 if (Info.hasSEWLMULRatioOnly()) {
1216 VSETVLIInfo RatiolessInfo = IncomingInfo;
1217 RatiolessInfo.setAVL(Info);
1218 Info = RatiolessInfo;
1219 }
1220}
1221
1222// Given a state with which we evaluated MI (see transferBefore above for why
1223// this might be different that the state MI requested), modify the state to
1224// reflect the changes MI might make.
1225void RISCVInsertVSETVLI::transferAfter(VSETVLIInfo &Info,
1226 const MachineInstr &MI) const {
1227 if (isVectorConfigInstr(MI)) {
1228 Info = getInfoForVSETVLI(MI);
1229 return;
1230 }
1231
1233 // Update AVL to vl-output of the fault first load.
1234 Info.setAVLReg(MI.getOperand(1).getReg());
1235 return;
1236 }
1237
1238 // If this is something that updates VL/VTYPE that we don't know about, set
1239 // the state to unknown.
1240 if (MI.isCall() || MI.isInlineAsm() ||
1241 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1242 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1243 Info = VSETVLIInfo::getUnknown();
1244}
1245
1246bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB,
1247 VSETVLIInfo &Info) const {
1248 bool HadVectorOp = false;
1249
1250 Info = BlockInfo[MBB.getNumber()].Pred;
1251 for (const MachineInstr &MI : MBB) {
1252 transferBefore(Info, MI);
1253
1254 if (isVectorConfigInstr(MI) || RISCVII::hasSEWOp(MI.getDesc().TSFlags))
1255 HadVectorOp = true;
1256
1257 transferAfter(Info, MI);
1258 }
1259
1260 return HadVectorOp;
1261}
1262
1263void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
1264
1265 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1266
1267 BBInfo.InQueue = false;
1268
1269 // Start with the previous entry so that we keep the most conservative state
1270 // we have ever found.
1271 VSETVLIInfo InInfo = BBInfo.Pred;
1272 if (MBB.pred_empty()) {
1273 // There are no predecessors, so use the default starting status.
1274 InInfo.setUnknown();
1275 } else {
1277 InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
1278 }
1279
1280 // If we don't have any valid predecessor value, wait until we do.
1281 if (!InInfo.isValid())
1282 return;
1283
1284 // If no change, no need to rerun block
1285 if (InInfo == BBInfo.Pred)
1286 return;
1287
1288 BBInfo.Pred = InInfo;
1289 LLVM_DEBUG(dbgs() << "Entry state of " << printMBBReference(MBB)
1290 << " changed to " << BBInfo.Pred << "\n");
1291
1292 // Note: It's tempting to cache the state changes here, but due to the
1293 // compatibility checks performed a blocks output state can change based on
1294 // the input state. To cache, we'd have to add logic for finding
1295 // never-compatible state changes.
1296 VSETVLIInfo TmpStatus;
1297 computeVLVTYPEChanges(MBB, TmpStatus);
1298
1299 // If the new exit value matches the old exit value, we don't need to revisit
1300 // any blocks.
1301 if (BBInfo.Exit == TmpStatus)
1302 return;
1303
1304 BBInfo.Exit = TmpStatus;
1305 LLVM_DEBUG(dbgs() << "Exit state of " << printMBBReference(MBB)
1306 << " changed to " << BBInfo.Exit << "\n");
1307
1308 // Add the successors to the work list so we can propagate the changed exit
1309 // status.
1310 for (MachineBasicBlock *S : MBB.successors())
1311 if (!BlockInfo[S->getNumber()].InQueue) {
1312 BlockInfo[S->getNumber()].InQueue = true;
1313 WorkList.push(S);
1314 }
1315}
1316
1317// If we weren't able to prove a vsetvli was directly unneeded, it might still
1318// be unneeded if the AVL is a phi node where all incoming values are VL
1319// outputs from the last VSETVLI in their respective basic blocks.
1320bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
1321 const MachineBasicBlock &MBB) const {
1323 return true;
1324
1325 if (!Require.hasAVLReg())
1326 return true;
1327
1328 Register AVLReg = Require.getAVLReg();
1329
1330 // We need the AVL to be produce by a PHI node in this basic block.
1331 MachineInstr *PHI = MRI->getUniqueVRegDef(AVLReg);
1332 assert(PHI);
1333 if (PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
1334 return true;
1335
1336 for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
1337 PHIOp += 2) {
1338 Register InReg = PHI->getOperand(PHIOp).getReg();
1339 MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
1340 const VSETVLIInfo &PBBExit = BlockInfo[PBB->getNumber()].Exit;
1341
1342 // We need the PHI input to the be the output of a VSET(I)VLI.
1343 MachineInstr *DefMI = MRI->getVRegDef(InReg);
1344 if (!DefMI || !isVectorConfigInstr(*DefMI))
1345 return true;
1346
1347 // We found a VSET(I)VLI make sure it matches the output of the
1348 // predecessor block.
1349 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1350 if (DefInfo != PBBExit)
1351 return true;
1352
1353 // Require has the same VL as PBBExit, so if the exit from the
1354 // predecessor has the VTYPE we are looking for we might be able
1355 // to avoid a VSETVLI.
1356 if (PBBExit.isUnknown() || !PBBExit.hasSameVTYPE(Require))
1357 return true;
1358 }
1359
1360 // If all the incoming values to the PHI checked out, we don't need
1361 // to insert a VSETVLI.
1362 return false;
1363}
1364
1365void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1366 VSETVLIInfo CurInfo = BlockInfo[MBB.getNumber()].Pred;
1367 // Track whether the prefix of the block we've scanned is transparent
1368 // (meaning has not yet changed the abstract state).
1369 bool PrefixTransparent = true;
1370 for (MachineInstr &MI : MBB) {
1371 const VSETVLIInfo PrevInfo = CurInfo;
1372 transferBefore(CurInfo, MI);
1373
1374 // If this is an explicit VSETVLI or VSETIVLI, update our state.
1375 if (isVectorConfigInstr(MI)) {
1376 // Conservatively, mark the VL and VTYPE as live.
1377 assert(MI.getOperand(3).getReg() == RISCV::VL &&
1378 MI.getOperand(4).getReg() == RISCV::VTYPE &&
1379 "Unexpected operands where VL and VTYPE should be");
1380 MI.getOperand(3).setIsDead(false);
1381 MI.getOperand(4).setIsDead(false);
1382 PrefixTransparent = false;
1383 }
1384
1385 uint64_t TSFlags = MI.getDesc().TSFlags;
1386 if (RISCVII::hasSEWOp(TSFlags)) {
1387 if (PrevInfo != CurInfo) {
1388 // If this is the first implicit state change, and the state change
1389 // requested can be proven to produce the same register contents, we
1390 // can skip emitting the actual state change and continue as if we
1391 // had since we know the GPR result of the implicit state change
1392 // wouldn't be used and VL/VTYPE registers are correct. Note that
1393 // we *do* need to model the state as if it changed as while the
1394 // register contents are unchanged, the abstract model can change.
1395 if (!PrefixTransparent || needVSETVLIPHI(CurInfo, MBB))
1396 insertVSETVLI(MBB, MI, CurInfo, PrevInfo);
1397 PrefixTransparent = false;
1398 }
1399
1400 if (RISCVII::hasVLOp(TSFlags)) {
1401 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1402 if (VLOp.isReg()) {
1403 Register Reg = VLOp.getReg();
1404 MachineInstr *VLOpDef = MRI->getVRegDef(Reg);
1405
1406 // Erase the AVL operand from the instruction.
1407 VLOp.setReg(RISCV::NoRegister);
1408 VLOp.setIsKill(false);
1409
1410 // If the AVL was an immediate > 31, then it would have been emitted
1411 // as an ADDI. However, the ADDI might not have been used in the
1412 // vsetvli, or a vsetvli might not have been emitted, so it may be
1413 // dead now.
1414 if (VLOpDef && TII->isAddImmediate(*VLOpDef, Reg) &&
1415 MRI->use_nodbg_empty(Reg))
1416 VLOpDef->eraseFromParent();
1417 }
1418 MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1419 /*isImp*/ true));
1420 }
1421 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1422 /*isImp*/ true));
1423 }
1424
1425 if (MI.isCall() || MI.isInlineAsm() ||
1426 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1427 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1428 PrefixTransparent = false;
1429
1430 transferAfter(CurInfo, MI);
1431 }
1432
1433 // If we reach the end of the block and our current info doesn't match the
1434 // expected info, insert a vsetvli to correct.
1435 if (!UseStrictAsserts) {
1436 const VSETVLIInfo &ExitInfo = BlockInfo[MBB.getNumber()].Exit;
1437 if (CurInfo.isValid() && ExitInfo.isValid() && !ExitInfo.isUnknown() &&
1438 CurInfo != ExitInfo) {
1439 // Note there's an implicit assumption here that terminators never use
1440 // or modify VL or VTYPE. Also, fallthrough will return end().
1441 auto InsertPt = MBB.getFirstInstrTerminator();
1442 insertVSETVLI(MBB, InsertPt, MBB.findDebugLoc(InsertPt), ExitInfo,
1443 CurInfo);
1444 CurInfo = ExitInfo;
1445 }
1446 }
1447
1448 if (UseStrictAsserts && CurInfo.isValid()) {
1449 const auto &Info = BlockInfo[MBB.getNumber()];
1450 if (CurInfo != Info.Exit) {
1451 LLVM_DEBUG(dbgs() << "in block " << printMBBReference(MBB) << "\n");
1452 LLVM_DEBUG(dbgs() << " begin state: " << Info.Pred << "\n");
1453 LLVM_DEBUG(dbgs() << " expected end state: " << Info.Exit << "\n");
1454 LLVM_DEBUG(dbgs() << " actual end state: " << CurInfo << "\n");
1455 }
1456 assert(CurInfo == Info.Exit &&
1457 "InsertVSETVLI dataflow invariant violated");
1458 }
1459}
1460
1461/// Perform simple partial redundancy elimination of the VSETVLI instructions
1462/// we're about to insert by looking for cases where we can PRE from the
1463/// beginning of one block to the end of one of its predecessors. Specifically,
1464/// this is geared to catch the common case of a fixed length vsetvl in a single
1465/// block loop when it could execute once in the preheader instead.
1466void RISCVInsertVSETVLI::doPRE(MachineBasicBlock &MBB) {
1467 if (!BlockInfo[MBB.getNumber()].Pred.isUnknown())
1468 return;
1469
1470 MachineBasicBlock *UnavailablePred = nullptr;
1471 VSETVLIInfo AvailableInfo;
1472 for (MachineBasicBlock *P : MBB.predecessors()) {
1473 const VSETVLIInfo &PredInfo = BlockInfo[P->getNumber()].Exit;
1474 if (PredInfo.isUnknown()) {
1475 if (UnavailablePred)
1476 return;
1477 UnavailablePred = P;
1478 } else if (!AvailableInfo.isValid()) {
1479 AvailableInfo = PredInfo;
1480 } else if (AvailableInfo != PredInfo) {
1481 return;
1482 }
1483 }
1484
1485 // Unreachable, single pred, or full redundancy. Note that FRE is handled by
1486 // phase 3.
1487 if (!UnavailablePred || !AvailableInfo.isValid())
1488 return;
1489
1490 // If we don't know the exact VTYPE, we can't copy the vsetvli to the exit of
1491 // the unavailable pred.
1492 if (AvailableInfo.hasSEWLMULRatioOnly())
1493 return;
1494
1495 // Critical edge - TODO: consider splitting?
1496 if (UnavailablePred->succ_size() != 1)
1497 return;
1498
1499 // If the AVL value is a register (other than our VLMAX sentinel),
1500 // we need to prove the value is available at the point we're going
1501 // to insert the vsetvli at.
1502 if (AvailableInfo.hasAVLReg()) {
1503 MachineInstr *AVLDefMI = MRI->getUniqueVRegDef(AvailableInfo.getAVLReg());
1504 assert(AVLDefMI);
1505 // This is an inline dominance check which covers the case of
1506 // UnavailablePred being the preheader of a loop.
1507 if (AVLDefMI->getParent() != UnavailablePred)
1508 return;
1509 for (auto &TermMI : UnavailablePred->terminators())
1510 if (&TermMI == AVLDefMI)
1511 return;
1512 }
1513
1514 // If the AVL isn't used in its predecessors then bail, since we have no AVL
1515 // to insert a vsetvli with.
1516 if (AvailableInfo.hasAVLIgnored())
1517 return;
1518
1519 // Model the effect of changing the input state of the block MBB to
1520 // AvailableInfo. We're looking for two issues here; one legality,
1521 // one profitability.
1522 // 1) If the block doesn't use some of the fields from VL or VTYPE, we
1523 // may hit the end of the block with a different end state. We can
1524 // not make this change without reflowing later blocks as well.
1525 // 2) If we don't actually remove a transition, inserting a vsetvli
1526 // into the predecessor block would be correct, but unprofitable.
1527 VSETVLIInfo OldInfo = BlockInfo[MBB.getNumber()].Pred;
1528 VSETVLIInfo CurInfo = AvailableInfo;
1529 int TransitionsRemoved = 0;
1530 for (const MachineInstr &MI : MBB) {
1531 const VSETVLIInfo LastInfo = CurInfo;
1532 const VSETVLIInfo LastOldInfo = OldInfo;
1533 transferBefore(CurInfo, MI);
1534 transferBefore(OldInfo, MI);
1535 if (CurInfo == LastInfo)
1536 TransitionsRemoved++;
1537 if (LastOldInfo == OldInfo)
1538 TransitionsRemoved--;
1539 transferAfter(CurInfo, MI);
1540 transferAfter(OldInfo, MI);
1541 if (CurInfo == OldInfo)
1542 // Convergence. All transitions after this must match by construction.
1543 break;
1544 }
1545 if (CurInfo != OldInfo || TransitionsRemoved <= 0)
1546 // Issues 1 and 2 above
1547 return;
1548
1549 // Finally, update both data flow state and insert the actual vsetvli.
1550 // Doing both keeps the code in sync with the dataflow results, which
1551 // is critical for correctness of phase 3.
1552 auto OldExit = BlockInfo[UnavailablePred->getNumber()].Exit;
1553 LLVM_DEBUG(dbgs() << "PRE VSETVLI from " << MBB.getName() << " to "
1554 << UnavailablePred->getName() << " with state "
1555 << AvailableInfo << "\n");
1556 BlockInfo[UnavailablePred->getNumber()].Exit = AvailableInfo;
1557 BlockInfo[MBB.getNumber()].Pred = AvailableInfo;
1558
1559 // Note there's an implicit assumption here that terminators never use
1560 // or modify VL or VTYPE. Also, fallthrough will return end().
1561 auto InsertPt = UnavailablePred->getFirstInstrTerminator();
1562 insertVSETVLI(*UnavailablePred, InsertPt,
1563 UnavailablePred->findDebugLoc(InsertPt),
1564 AvailableInfo, OldExit);
1565}
1566
1567// Return true if we can mutate PrevMI to match MI without changing any the
1568// fields which would be observed.
1569static bool canMutatePriorConfig(const MachineInstr &PrevMI,
1570 const MachineInstr &MI,
1571 const DemandedFields &Used,
1572 const MachineRegisterInfo &MRI) {
1573 // If the VL values aren't equal, return false if either a) the former is
1574 // demanded, or b) we can't rewrite the former to be the later for
1575 // implementation reasons.
1576 if (!isVLPreservingConfig(MI)) {
1577 if (Used.VLAny)
1578 return false;
1579
1580 if (Used.VLZeroness) {
1581 if (isVLPreservingConfig(PrevMI))
1582 return false;
1583 if (!getInfoForVSETVLI(PrevMI).hasEquallyZeroAVL(getInfoForVSETVLI(MI),
1584 MRI))
1585 return false;
1586 }
1587
1588 auto &AVL = MI.getOperand(1);
1589 auto &PrevAVL = PrevMI.getOperand(1);
1590
1591 // If the AVL is a register, we need to make sure MI's AVL dominates PrevMI.
1592 // For now just check that PrevMI uses the same virtual register.
1593 if (AVL.isReg() && AVL.getReg() != RISCV::X0 &&
1594 (!MRI.hasOneDef(AVL.getReg()) || !PrevAVL.isReg() ||
1595 PrevAVL.getReg() != AVL.getReg()))
1596 return false;
1597 }
1598
1599 assert(PrevMI.getOperand(2).isImm() && MI.getOperand(2).isImm());
1600 auto PriorVType = PrevMI.getOperand(2).getImm();
1601 auto VType = MI.getOperand(2).getImm();
1602 return areCompatibleVTYPEs(PriorVType, VType, Used);
1603}
1604
1605bool RISCVCoalesceVSETVLI::coalesceVSETVLIs(MachineBasicBlock &MBB) {
1606 MachineInstr *NextMI = nullptr;
1607 // We can have arbitrary code in successors, so VL and VTYPE
1608 // must be considered demanded.
1609 DemandedFields Used;
1610 Used.demandVL();
1611 Used.demandVTYPE();
1613 for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
1614
1615 if (!isVectorConfigInstr(MI)) {
1616 Used.doUnion(getDemanded(MI, MRI, ST));
1617 if (MI.isCall() || MI.isInlineAsm() ||
1618 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1619 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1620 NextMI = nullptr;
1621 continue;
1622 }
1623
1624 Register RegDef = MI.getOperand(0).getReg();
1625 assert(RegDef == RISCV::X0 || RegDef.isVirtual());
1626 if (RegDef != RISCV::X0 && !MRI->use_nodbg_empty(RegDef))
1627 Used.demandVL();
1628
1629 if (NextMI) {
1630 if (!Used.usedVL() && !Used.usedVTYPE()) {
1631 ToDelete.push_back(&MI);
1632 // Leave NextMI unchanged
1633 continue;
1634 }
1635
1636 if (canMutatePriorConfig(MI, *NextMI, Used, *MRI)) {
1637 if (!isVLPreservingConfig(*NextMI)) {
1638 Register DefReg = NextMI->getOperand(0).getReg();
1639
1640 MI.getOperand(0).setReg(DefReg);
1641 MI.getOperand(0).setIsDead(false);
1642
1643 // The def of DefReg moved to MI, so extend the LiveInterval up to
1644 // it.
1645 if (DefReg.isVirtual()) {
1646 LiveInterval &DefLI = LIS->getInterval(DefReg);
1647 SlotIndex MISlot = LIS->getInstructionIndex(MI).getRegSlot();
1648 VNInfo *DefVNI = DefLI.getVNInfoAt(DefLI.beginIndex());
1649 LiveInterval::Segment S(MISlot, DefLI.beginIndex(), DefVNI);
1650 DefLI.addSegment(S);
1651 DefVNI->def = MISlot;
1652 // Mark DefLI as spillable if it was previously unspillable
1653 DefLI.setWeight(0);
1654
1655 // DefReg may have had no uses, in which case we need to shrink
1656 // the LiveInterval up to MI.
1657 LIS->shrinkToUses(&DefLI);
1658 }
1659
1660 Register OldVLReg;
1661 if (MI.getOperand(1).isReg())
1662 OldVLReg = MI.getOperand(1).getReg();
1663 if (NextMI->getOperand(1).isImm())
1664 MI.getOperand(1).ChangeToImmediate(NextMI->getOperand(1).getImm());
1665 else
1666 MI.getOperand(1).ChangeToRegister(NextMI->getOperand(1).getReg(), false);
1667
1668 // Clear NextMI's AVL early so we're not counting it as a use.
1669 if (NextMI->getOperand(1).isReg())
1670 NextMI->getOperand(1).setReg(RISCV::NoRegister);
1671
1672 if (OldVLReg && OldVLReg.isVirtual()) {
1673 // NextMI no longer uses OldVLReg so shrink its LiveInterval.
1674 LIS->shrinkToUses(&LIS->getInterval(OldVLReg));
1675
1676 MachineInstr *VLOpDef = MRI->getUniqueVRegDef(OldVLReg);
1677 if (VLOpDef && TII->isAddImmediate(*VLOpDef, OldVLReg) &&
1678 MRI->use_nodbg_empty(OldVLReg)) {
1679 VLOpDef->eraseFromParent();
1680 LIS->removeInterval(OldVLReg);
1681 }
1682 }
1683 MI.setDesc(NextMI->getDesc());
1684 }
1685 MI.getOperand(2).setImm(NextMI->getOperand(2).getImm());
1686 ToDelete.push_back(NextMI);
1687 // fallthrough
1688 }
1689 }
1690 NextMI = &MI;
1691 Used = getDemanded(MI, MRI, ST);
1692 }
1693
1694 NumCoalescedVSETVL += ToDelete.size();
1695 for (auto *MI : ToDelete) {
1696 LIS->RemoveMachineInstrFromMaps(*MI);
1697 MI->eraseFromParent();
1698 }
1699
1700 return !ToDelete.empty();
1701}
1702
1703void RISCVInsertVSETVLI::insertReadVL(MachineBasicBlock &MBB) {
1704 for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
1705 MachineInstr &MI = *I++;
1707 Register VLOutput = MI.getOperand(1).getReg();
1708 if (!MRI->use_nodbg_empty(VLOutput))
1709 BuildMI(MBB, I, MI.getDebugLoc(), TII->get(RISCV::PseudoReadVL),
1710 VLOutput);
1711 // We don't use the vl output of the VLEFF/VLSEGFF anymore.
1712 MI.getOperand(1).setReg(RISCV::X0);
1713 }
1714 }
1715}
1716
1717bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1718 // Skip if the vector extension is not enabled.
1720 if (!ST->hasVInstructions())
1721 return false;
1722
1723 LLVM_DEBUG(dbgs() << "Entering InsertVSETVLI for " << MF.getName() << "\n");
1724
1725 TII = ST->getInstrInfo();
1726 MRI = &MF.getRegInfo();
1727
1728 assert(BlockInfo.empty() && "Expect empty block infos");
1729 BlockInfo.resize(MF.getNumBlockIDs());
1730
1731 bool HaveVectorOp = false;
1732
1733 // Phase 1 - determine how VL/VTYPE are affected by the each block.
1734 for (const MachineBasicBlock &MBB : MF) {
1735 VSETVLIInfo TmpStatus;
1736 HaveVectorOp |= computeVLVTYPEChanges(MBB, TmpStatus);
1737 // Initial exit state is whatever change we found in the block.
1738 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1739 BBInfo.Exit = TmpStatus;
1740 LLVM_DEBUG(dbgs() << "Initial exit state of " << printMBBReference(MBB)
1741 << " is " << BBInfo.Exit << "\n");
1742
1743 }
1744
1745 // If we didn't find any instructions that need VSETVLI, we're done.
1746 if (!HaveVectorOp) {
1747 BlockInfo.clear();
1748 return false;
1749 }
1750
1751 // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1752 // blocks to the list here, but will also add any that need to be revisited
1753 // during Phase 2 processing.
1754 for (const MachineBasicBlock &MBB : MF) {
1755 WorkList.push(&MBB);
1756 BlockInfo[MBB.getNumber()].InQueue = true;
1757 }
1758 while (!WorkList.empty()) {
1759 const MachineBasicBlock &MBB = *WorkList.front();
1760 WorkList.pop();
1761 computeIncomingVLVTYPE(MBB);
1762 }
1763
1764 // Perform partial redundancy elimination of vsetvli transitions.
1765 for (MachineBasicBlock &MBB : MF)
1766 doPRE(MBB);
1767
1768 // Phase 3 - add any vsetvli instructions needed in the block. Use the
1769 // Phase 2 information to avoid adding vsetvlis before the first vector
1770 // instruction in the block if the VL/VTYPE is satisfied by its
1771 // predecessors.
1772 for (MachineBasicBlock &MBB : MF)
1773 emitVSETVLIs(MBB);
1774
1775 // Insert PseudoReadVL after VLEFF/VLSEGFF and replace it with the vl output
1776 // of VLEFF/VLSEGFF.
1777 for (MachineBasicBlock &MBB : MF)
1778 insertReadVL(MBB);
1779
1780 BlockInfo.clear();
1781 return HaveVectorOp;
1782}
1783
1784/// Returns an instance of the Insert VSETVLI pass.
1786 return new RISCVInsertVSETVLI();
1787}
1788
1789// Now that all vsetvlis are explicit, go through and do block local
1790// DSE and peephole based demanded fields based transforms. Note that
1791// this *must* be done outside the main dataflow so long as we allow
1792// any cross block analysis within the dataflow. We can't have both
1793// demanded fields based mutation and non-local analysis in the
1794// dataflow at the same time without introducing inconsistencies.
1795bool RISCVCoalesceVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1796 // Skip if the vector extension is not enabled.
1797 ST = &MF.getSubtarget<RISCVSubtarget>();
1798 if (!ST->hasVInstructions())
1799 return false;
1800 TII = ST->getInstrInfo();
1801 MRI = &MF.getRegInfo();
1802 LIS = &getAnalysis<LiveIntervals>();
1803
1804 bool Changed = false;
1805 for (MachineBasicBlock &MBB : MF)
1806 Changed |= coalesceVSETVLIs(MBB);
1807
1808 return Changed;
1809}
1810
1812 return new RISCVCoalesceVSETVLI();
1813}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:151
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:529
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static ValueLatticeElement intersect(const ValueLatticeElement &A, const ValueLatticeElement &B)
Combine two sets of facts about the same value into a single set of facts.
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
#define RISCV_COALESCE_VSETVLI_NAME
static unsigned computeVLMAX(unsigned VLEN, unsigned SEW, RISCVII::VLMUL VLMul)
static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags, const RISCVSubtarget &ST, const MachineRegisterInfo *MRI)
#define RISCV_INSERT_VSETVLI_NAME
static VSETVLIInfo adjustIncoming(VSETVLIInfo PrevInfo, VSETVLIInfo NewInfo, DemandedFields &Demanded)
static bool isLMUL1OrSmaller(RISCVII::VLMUL LMUL)
static bool canMutatePriorConfig(const MachineInstr &PrevMI, const MachineInstr &MI, const DemandedFields &Used, const MachineRegisterInfo &MRI)
static cl::opt< bool > UseStrictAsserts("riscv-insert-vsetvl-strict-asserts", cl::init(true), cl::Hidden, cl::desc("Enable strict assertion checking for the dataflow algorithm"))
static cl::opt< bool > DisableInsertVSETVLPHIOpt("riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden, cl::desc("Disable looking through phis when inserting vsetvlis."))
#define DEBUG_TYPE
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
BlockData()=default
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.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:269
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
void setWeight(float Value)
Definition: LiveInterval.h:721
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:385
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:421
reverse_iterator rend()
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
unsigned succ_size() const
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
bool isImplicitDef() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:341
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:561
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:555
bool isRegSequence() const
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:568
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:95
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:68
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
Definition: SlotIndexes.h:240
SlotIndexes pass.
Definition: SlotIndexes.h:300
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetInstrInfo - Interface to description of machine instruction set.
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:61
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
TargetPassConfig.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
static bool usesMaskPolicy(uint64_t TSFlags)
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool doesForceTailAgnostic(uint64_t TSFlags)
static VLMUL getLMul(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasVecPolicyOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool hasSEWOp(uint64_t TSFlags)
static bool isTailAgnostic(unsigned VType)
static RISCVII::VLMUL getVLMUL(unsigned VType)
std::pair< unsigned, bool > decodeVLMUL(RISCVII::VLMUL VLMUL)
unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul)
static bool isMaskAgnostic(unsigned VType)
static bool isValidSEW(unsigned SEW)
unsigned encodeVTYPE(RISCVII::VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic)
static unsigned getSEW(unsigned VType)
std::optional< RISCVII::VLMUL > getSameRatioLMUL(unsigned SEW, RISCVII::VLMUL VLMUL, unsigned EEW)
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
bool isFaultFirstLoad(const MachineInstr &MI)
static constexpr int64_t VLMaxSentinel
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Define
Register definition.
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Uninitialized
Definition: Threading.h:61
bool operator!=(uint64_t V1, const APInt &V2)
Definition: APInt.h:2043
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createRISCVInsertVSETVLIPass()
Returns an instance of the Insert VSETVLI pass.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
FunctionPass * createRISCVCoalesceVSETVLIPass()
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Status intersect(const Status &S) const
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:162