LLVM 24.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"
31#include "llvm/ADT/Statistic.h"
36#include <queue>
37using namespace llvm;
38using namespace RISCV;
39
40#define DEBUG_TYPE "riscv-insert-vsetvli"
41#define RISCV_INSERT_VSETVLI_NAME "RISC-V Insert VSETVLI pass"
42
43STATISTIC(NumInsertedVSETVL, "Number of VSETVL inst inserted");
44STATISTIC(NumCoalescedVSETVL, "Number of VSETVL inst coalesced");
45
47 DEBUG_TYPE "-whole-vector-register-move-valid-vtype", cl::Hidden,
48 cl::desc("Insert vsetvlis before vmvNr.vs to ensure vtype is valid and "
49 "vill is cleared"),
50 cl::init(true));
51
52namespace {
53
54/// Given a virtual register \p Reg, return the corresponding VNInfo for it.
55/// This will return nullptr if the virtual register is an implicit_def or
56/// if LiveIntervals is not available.
58 const LiveIntervals *LIS) {
59 assert(Reg.isVirtual());
60 if (!LIS)
61 return nullptr;
62 auto &LI = LIS->getInterval(Reg);
64 return LI.getVNInfoBefore(SI);
65}
66
68 return MI.getOperand(RISCVII::getVLOpNum(MI.getDesc()));
69}
70
71struct BlockData {
72 // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
73 // block. Calculated in Phase 2.
74 VSETVLIInfo Exit;
75
76 // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
77 // blocks. Calculated in Phase 2, and used by Phase 3.
78 VSETVLIInfo Pred;
79
80 // Keeps track of whether the block is already in the queue.
81 bool InQueue = false;
82
83 BlockData() = default;
84};
85
86enum TKTMMode {
87 VSETTK = 0,
88 VSETTM = 1,
89};
90
91class RISCVInsertVSETVLI : public MachineFunctionPass {
92 const RISCVSubtarget *ST;
93 const TargetInstrInfo *TII;
94 MachineRegisterInfo *MRI;
95 // Possibly null!
96 LiveIntervals *LIS;
97 RISCVVSETVLIInfoAnalysis VIA;
98
99 std::vector<BlockData> BlockInfo;
100 std::queue<const MachineBasicBlock *> WorkList;
101
102public:
103 static char ID;
104
105 RISCVInsertVSETVLI() : MachineFunctionPass(ID) {}
106 bool runOnMachineFunction(MachineFunction &MF) override;
107
108 void getAnalysisUsage(AnalysisUsage &AU) const override {
109 AU.setPreservesCFG();
110
111 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
112 AU.addPreserved<LiveIntervalsWrapperPass>();
113 AU.addPreserved<SlotIndexesWrapperPass>();
114 AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
115 AU.addPreserved<LiveStacksWrapperLegacy>();
116
118 }
119
120 StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
121
122private:
123 bool needVSETVLI(const DemandedFields &Used, const VSETVLIInfo &Require,
124 const VSETVLIInfo &CurInfo) const;
125 bool needVSETVLIPHI(const VSETVLIInfo &Require,
126 const MachineBasicBlock &MBB) const;
127 void insertVSETVLI(MachineBasicBlock &MBB,
129 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
130
131 void transferBefore(VSETVLIInfo &Info, const MachineInstr &MI) const;
132 void transferAfter(VSETVLIInfo &Info, const MachineInstr &MI) const;
133 bool computeVLVTYPEChanges(const MachineBasicBlock &MBB,
134 VSETVLIInfo &Info) const;
135 void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
136 void emitVSETVLIs(MachineBasicBlock &MBB);
137 void doPRE(MachineBasicBlock &MBB);
138 void insertReadVL(MachineBasicBlock &MBB);
139
140 bool canMutatePriorConfig(const MachineInstr &PrevMI, const MachineInstr &MI,
141 const DemandedFields &Used,
142 MachineInstr *&AVLDefToMove) const;
143 void coalesceVSETVLIs(MachineBasicBlock &MBB) const;
144 bool canMutatePriorConfigWithTWiden(const MachineInstr &PrevMI,
145 const MachineInstr &MI) const;
146 void coalesceVSETVLIsForTWiden(MachineBasicBlock &MBB) const;
147 bool insertVSETMTK(MachineBasicBlock &MBB, TKTMMode Mode) const;
148};
149
150} // end anonymous namespace
151
152char RISCVInsertVSETVLI::ID = 0;
153char &llvm::RISCVInsertVSETVLIID = RISCVInsertVSETVLI::ID;
154
156 false, false)
157
158void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB,
159 MachineBasicBlock::iterator InsertPt,
161 const VSETVLIInfo &PrevInfo) {
162 ++NumInsertedVSETVL;
163
164 if (PrevInfo.isKnown()) {
165 // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
166 // VLMAX.
167 if (Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
168 auto MI = BuildMI(MBB, InsertPt, DL,
169 TII->get(Info.getTWiden() ? RISCV::PseudoSF_VSETTNTX0X0
170 : RISCV::PseudoVSETVLIX0X0))
171 .addReg(RISCV::X0, RegState::Define | RegState::Dead)
172 .addReg(RISCV::X0, RegState::Kill)
173 .addImm(Info.encodeVTYPE())
174 .addReg(RISCV::VL, RegState::Implicit);
175 if (LIS)
176 LIS->InsertMachineInstrInMaps(*MI);
177 return;
178 }
179
180 // If our AVL is a virtual register, it might be defined by a VSET(I)VLI. If
181 // it has the same VLMAX we want and the last VL/VTYPE we observed is the
182 // same, we can use the X0, X0 form.
183 if (Info.hasSameVLMAX(PrevInfo) && Info.hasAVLReg()) {
184 if (const MachineInstr *DefMI = Info.getAVLDefMI(LIS);
185 DefMI && RISCVInstrInfo::isVectorConfigInstr(*DefMI)) {
186 VSETVLIInfo DefInfo = VIA.getInfoForVSETVLI(*DefMI);
187 if (DefInfo.hasSameAVL(PrevInfo) && DefInfo.hasSameVLMAX(PrevInfo)) {
188 auto MI =
189 BuildMI(MBB, InsertPt, DL,
190 TII->get(Info.getTWiden() ? RISCV::PseudoSF_VSETTNTX0X0
191 : RISCV::PseudoVSETVLIX0X0))
192 .addReg(RISCV::X0, RegState::Define | RegState::Dead)
193 .addReg(RISCV::X0, RegState::Kill)
194 .addImm(Info.encodeVTYPE())
195 .addReg(RISCV::VL, RegState::Implicit);
196 if (LIS)
197 LIS->InsertMachineInstrInMaps(*MI);
198 return;
199 }
200 }
201 }
202 }
203
204 if (Info.hasAVLImm()) {
205 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
206 .addReg(RISCV::X0, RegState::Define | RegState::Dead)
207 .addImm(Info.getAVLImm())
208 .addImm(Info.encodeVTYPE());
209 if (LIS)
210 LIS->InsertMachineInstrInMaps(*MI);
211 return;
212 }
213
214 if (Info.hasAVLVLMAX()) {
215 Register DestReg = MRI->createVirtualRegister(&RISCV::GPRNoX0RegClass);
216 auto MI = BuildMI(MBB, InsertPt, DL,
217 TII->get(Info.getTWiden() ? RISCV::PseudoSF_VSETTNTX0
218 : RISCV::PseudoVSETVLIX0))
219 .addReg(DestReg, RegState::Define | RegState::Dead)
220 .addReg(RISCV::X0, RegState::Kill)
221 .addImm(Info.encodeVTYPE());
222 if (LIS) {
223 LIS->InsertMachineInstrInMaps(*MI);
224 LIS->createAndComputeVirtRegInterval(DestReg);
225 }
226 return;
227 }
228
229 Register AVLReg = Info.getAVLReg();
230 MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
231 auto MI = BuildMI(MBB, InsertPt, DL,
232 TII->get(Info.getTWiden() ? RISCV::PseudoSF_VSETTNT
233 : RISCV::PseudoVSETVLI))
235 .addReg(AVLReg)
236 .addImm(Info.encodeVTYPE());
237 if (LIS) {
239 LiveInterval &LI = LIS->getInterval(AVLReg);
241 const VNInfo *CurVNI = Info.getAVLVNInfo();
242 // If the AVL value isn't live at MI, do a quick check to see if it's easily
243 // extendable. Otherwise, we need to copy it.
244 if (LI.getVNInfoBefore(SI) != CurVNI) {
245 if (!LI.liveAt(SI) && LI.containsOneValue())
246 LIS->extendToIndices(LI, SI);
247 else {
248 Register AVLCopyReg =
249 MRI->createVirtualRegister(&RISCV::GPRNoX0RegClass);
250 MachineBasicBlock *MBB = LIS->getMBBFromIndex(CurVNI->def);
252 if (CurVNI->isPHIDef())
253 II = MBB->getFirstNonPHI();
254 else {
255 II = LIS->getInstructionFromIndex(CurVNI->def);
256 II = std::next(II);
257 }
258 assert(II.isValid());
259 auto AVLCopy = BuildMI(*MBB, II, DL, TII->get(RISCV::COPY), AVLCopyReg)
260 .addReg(AVLReg);
261 LIS->InsertMachineInstrInMaps(*AVLCopy);
262 MI->getOperand(1).setReg(AVLCopyReg);
263 LIS->createAndComputeVirtRegInterval(AVLCopyReg);
264 }
265 }
266 }
267}
268
269/// Return true if a VSETVLI is required to transition from CurInfo to Require
270/// given a set of DemandedFields \p Used.
271bool RISCVInsertVSETVLI::needVSETVLI(const DemandedFields &Used,
272 const VSETVLIInfo &Require,
273 const VSETVLIInfo &CurInfo) const {
274 if (!CurInfo.isKnown() || CurInfo.hasSEWLMULRatioOnly())
275 return true;
276
277 if (CurInfo.isCompatible(Used, Require, LIS))
278 return false;
279
280 return true;
281}
282
283// If we don't use LMUL or the SEW/LMUL ratio, then adjust LMUL so that we
284// maintain the SEW/LMUL ratio. This allows us to eliminate VL toggles in more
285// places.
287 const VSETVLIInfo &NewInfo,
288 DemandedFields &Demanded) {
289 VSETVLIInfo Info = NewInfo;
290
291 if (!Demanded.LMUL && !Demanded.SEWLMULRatio && PrevInfo.isKnown()) {
292 if (auto NewVLMul = RISCVVType::getSameRatioLMUL(PrevInfo.getSEWLMULRatio(),
293 Info.getSEW()))
294 Info.setVLMul(*NewVLMul);
296 }
297
298 return Info;
299}
300
301// Given an incoming state reaching MI, minimally modifies that state so that it
302// is compatible with MI. The resulting state is guaranteed to be semantically
303// legal for MI, but may not be the state requested by MI.
304void RISCVInsertVSETVLI::transferBefore(VSETVLIInfo &Info,
305 const MachineInstr &MI) const {
308 (!Info.isKnown() || Info.hasSEWLMULRatioOnly())) {
309 // Use an arbitrary but valid AVL and VTYPE so vill will be cleared. It may
310 // be coalesced into another vsetvli since we won't demand any fields.
311 VSETVLIInfo NewInfo; // Need a new VSETVLIInfo to clear SEWLMULRatioOnly
312 NewInfo.setAVLImm(1);
313 NewInfo.setVTYPE(RISCVVType::LMUL_1, /*sew*/ 8, /*ta*/ true, /*ma*/ true,
314 /*AltFmt*/ false, /*W*/ 0);
315 Info = NewInfo;
316 return;
317 }
318
319 if (!RISCVII::hasSEWOp(MI.getDesc().TSFlags))
320 return;
321
322 DemandedFields Demanded = getDemanded(MI, ST);
323
324 const VSETVLIInfo NewInfo = VIA.computeInfoForInstr(MI);
325 assert(NewInfo.isKnown());
326 if (Info.isValid() && !needVSETVLI(Demanded, NewInfo, Info))
327 return;
328
329 const VSETVLIInfo PrevInfo = Info;
330 if (!Info.isKnown())
331 Info = NewInfo;
332
333 const VSETVLIInfo IncomingInfo = adjustIncoming(PrevInfo, NewInfo, Demanded);
334
335 // If MI only demands that VL has the same zeroness, we only need to set the
336 // AVL if the zeroness differs. This removes a vsetvli entirely if the types
337 // match or allows use of cheaper avl preserving variant if VLMAX doesn't
338 // change. If VLMAX might change, we couldn't use the 'vsetvli x0, x0, vtype"
339 // variant, so we avoid the transform to prevent extending live range of an
340 // avl register operand.
341 // TODO: We can probably relax this for immediates.
342 bool EquallyZero = IncomingInfo.hasEquallyZeroAVL(PrevInfo, LIS) &&
343 IncomingInfo.hasSameVLMAX(PrevInfo);
344 if (Demanded.VLAny || (Demanded.VLZeroness && !EquallyZero))
345 Info.setAVL(IncomingInfo);
346
347 // If we only knew the sew/lmul ratio previously, replace the VTYPE.
348 if (Info.hasSEWLMULRatioOnly()) {
349 VSETVLIInfo RatiolessInfo = IncomingInfo;
350 RatiolessInfo.setAVL(Info);
351 Info = RatiolessInfo;
352 } else {
353 unsigned SEW =
354 ((Demanded.SEW || Demanded.SEWLMULRatio) ? IncomingInfo : Info)
355 .getSEW();
356 Info.setVTYPE(
357 ((Demanded.LMUL || Demanded.SEWLMULRatio) ? IncomingInfo : Info)
358 .getVLMUL(),
359 SEW,
360 // Prefer tail/mask agnostic since it can be relaxed to undisturbed
361 // later if needed.
362 (Demanded.TailPolicy ? IncomingInfo : Info).getTailAgnostic() ||
363 IncomingInfo.getTailAgnostic(),
364 (Demanded.MaskPolicy ? IncomingInfo : Info).getMaskAgnostic() ||
365 IncomingInfo.getMaskAgnostic(),
366 // AltFmt requires SEW < 32.
367 (Demanded.AltFmt ? IncomingInfo : Info).getAltFmt() && SEW < 32,
368 Demanded.TWiden ? IncomingInfo.getTWiden() : 0);
369 }
370}
371
372// Given a state with which we evaluated MI (see transferBefore above for why
373// this might be different that the state MI requested), modify the state to
374// reflect the changes MI might make.
375void RISCVInsertVSETVLI::transferAfter(VSETVLIInfo &Info,
376 const MachineInstr &MI) const {
377 if (RISCVInstrInfo::isVectorConfigInstr(MI)) {
379 return;
380 }
381
382 // SETTM/TK will modify VTYPE, but it only affects the TM/TK bits.
383 // It is safe for other RVV operations.
384 // The TM/TK value will be maintained in insertVSETMTK.
385 if (RISCVInstrInfo::isXSfmmVectorConfigTMTKInstr(MI))
386 return;
387
388 if (RISCVInstrInfo::isFaultOnlyFirstLoad(MI)) {
389 // Update AVL to vl-output of the fault first load.
390 assert(MI.getOperand(1).getReg().isVirtual());
391 if (LIS) {
392 auto &LI = LIS->getInterval(MI.getOperand(1).getReg());
393 SlotIndex SI =
395 VNInfo *VNI = LI.getVNInfoAt(SI);
396 Info.setAVLRegDef(VNI, MI.getOperand(1).getReg());
397 } else
398 Info.setAVLRegDef(nullptr, MI.getOperand(1).getReg());
399 return;
400 }
401
402 // If this is something that updates VL/VTYPE that we don't know about, set
403 // the state to unknown.
404 if (MI.isCall() || MI.isInlineAsm() ||
405 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
406 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
408}
409
410bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB,
411 VSETVLIInfo &Info) const {
412 bool HadVectorOp = false;
413
414 Info = BlockInfo[MBB.getNumber()].Pred;
415 for (const MachineInstr &MI : MBB) {
416 transferBefore(Info, MI);
417
418 if (RISCVInstrInfo::isVectorConfigInstr(MI) ||
419 RISCVII::hasSEWOp(MI.getDesc().TSFlags) ||
421 RISCVInstrInfo::isXSfmmVectorConfigInstr(MI))
422 HadVectorOp = true;
423
424 transferAfter(Info, MI);
425 }
426
427 return HadVectorOp;
428}
429
430void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
431
432 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
433
434 BBInfo.InQueue = false;
435
436 // Start with the previous entry so that we keep the most conservative state
437 // we have ever found.
438 VSETVLIInfo InInfo = BBInfo.Pred;
439 if (MBB.pred_empty()) {
440 // There are no predecessors, so use the default starting status.
441 InInfo.setUnknown();
442 } else {
443 for (MachineBasicBlock *P : MBB.predecessors())
444 InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
445 }
446
447 // If we don't have any valid predecessor value, wait until we do.
448 if (!InInfo.isValid())
449 return;
450
451 // If no change, no need to rerun block
452 if (InInfo == BBInfo.Pred)
453 return;
454
455 BBInfo.Pred = InInfo;
456 LLVM_DEBUG(dbgs() << "Entry state of " << printMBBReference(MBB)
457 << " changed to " << BBInfo.Pred << "\n");
458
459 // Note: It's tempting to cache the state changes here, but due to the
460 // compatibility checks performed a blocks output state can change based on
461 // the input state. To cache, we'd have to add logic for finding
462 // never-compatible state changes.
463 VSETVLIInfo TmpStatus;
464 computeVLVTYPEChanges(MBB, TmpStatus);
465
466 // If the new exit value matches the old exit value, we don't need to revisit
467 // any blocks.
468 if (BBInfo.Exit == TmpStatus)
469 return;
470
471 BBInfo.Exit = TmpStatus;
472 LLVM_DEBUG(dbgs() << "Exit state of " << printMBBReference(MBB)
473 << " changed to " << BBInfo.Exit << "\n");
474
475 // Add the successors to the work list so we can propagate the changed exit
476 // status.
477 for (MachineBasicBlock *S : MBB.successors())
478 if (!BlockInfo[S->getNumber()].InQueue) {
479 BlockInfo[S->getNumber()].InQueue = true;
480 WorkList.push(S);
481 }
482}
483
484// If we weren't able to prove a vsetvli was directly unneeded, it might still
485// be unneeded if the AVL was a phi node where all incoming values are VL
486// outputs from the last VSETVLI in their respective basic blocks.
487bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
488 const MachineBasicBlock &MBB) const {
489 if (!Require.hasAVLReg())
490 return true;
491
492 if (!LIS)
493 return true;
494
495 // We need the AVL to have been produced by a PHI node in this basic block.
496 const VNInfo *Valno = Require.getAVLVNInfo();
497 if (!Valno->isPHIDef() || LIS->getMBBFromIndex(Valno->def) != &MBB)
498 return true;
499
500 const LiveRange &LR = LIS->getInterval(Require.getAVLReg());
501
502 for (auto *PBB : MBB.predecessors()) {
503 const VSETVLIInfo &PBBExit = BlockInfo[PBB->getNumber()].Exit;
504
505 // We need the PHI input to the be the output of a VSET(I)VLI.
506 const VNInfo *Value = LR.getVNInfoBefore(LIS->getMBBEndIdx(PBB));
507 if (!Value)
508 return true;
509 MachineInstr *DefMI = LIS->getInstructionFromIndex(Value->def);
510 if (!DefMI || !RISCVInstrInfo::isVectorConfigInstr(*DefMI))
511 return true;
512
513 // We found a VSET(I)VLI make sure it matches the output of the
514 // predecessor block.
515 VSETVLIInfo DefInfo = VIA.getInfoForVSETVLI(*DefMI);
516 if (DefInfo != PBBExit)
517 return true;
518
519 // Require has the same VL as PBBExit, so if the exit from the
520 // predecessor has the VTYPE we are looking for we might be able
521 // to avoid a VSETVLI.
522 if (PBBExit.isUnknown() || !PBBExit.hasSameVTYPE(Require))
523 return true;
524 }
525
526 // If all the incoming values to the PHI checked out, we don't need
527 // to insert a VSETVLI.
528 return false;
529}
530
531void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
532 VSETVLIInfo CurInfo = BlockInfo[MBB.getNumber()].Pred;
533 // Track whether the prefix of the block we've scanned is transparent
534 // (meaning has not yet changed the abstract state).
535 bool PrefixTransparent = true;
536 for (MachineInstr &MI : MBB) {
537 const VSETVLIInfo PrevInfo = CurInfo;
538 transferBefore(CurInfo, MI);
539
540 // If this is an explicit VSETVLI or VSETIVLI, update our state.
541 if (RISCVInstrInfo::isVectorConfigInstr(MI)) {
542 // Conservatively, mark the VL and VTYPE as live.
543 assert(MI.getOperand(3).getReg() == RISCV::VL &&
544 MI.getOperand(4).getReg() == RISCV::VTYPE &&
545 "Unexpected operands where VL and VTYPE should be");
546 MI.getOperand(3).setIsDead(false);
547 MI.getOperand(4).setIsDead(false);
548 PrefixTransparent = false;
549 }
550
553 if (!PrevInfo.isCompatible(DemandedFields::all(), CurInfo, LIS)) {
554 insertVSETVLI(MBB, MI, MI.getDebugLoc(), CurInfo, PrevInfo);
555 PrefixTransparent = false;
556 }
557 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
558 /*isImp*/ true));
559 }
560
561 uint64_t TSFlags = MI.getDesc().TSFlags;
562 if (RISCVII::hasSEWOp(TSFlags)) {
563 if (!PrevInfo.isCompatible(DemandedFields::all(), CurInfo, LIS)) {
564 // If this is the first implicit state change, and the state change
565 // requested can be proven to produce the same register contents, we
566 // can skip emitting the actual state change and continue as if we
567 // had since we know the GPR result of the implicit state change
568 // wouldn't be used and VL/VTYPE registers are correct. Note that
569 // we *do* need to model the state as if it changed as while the
570 // register contents are unchanged, the abstract model can change.
571 if (!PrefixTransparent || needVSETVLIPHI(CurInfo, MBB))
572 insertVSETVLI(MBB, MI, MI.getDebugLoc(), CurInfo, PrevInfo);
573 PrefixTransparent = false;
574 }
575
576 if (RISCVII::hasVLOp(TSFlags)) {
577 MachineOperand &VLOp = getVLOp(MI);
578 if (VLOp.isReg()) {
579 Register Reg = VLOp.getReg();
580
581 // Erase the AVL operand from the instruction.
582 VLOp.setReg(Register());
583 VLOp.setIsKill(false);
584 if (LIS) {
585 LiveInterval &LI = LIS->getInterval(Reg);
587 LIS->shrinkToUses(&LI, &DeadMIs);
588 // We might have separate components that need split due to
589 // needVSETVLIPHI causing us to skip inserting a new VL def.
591 LIS->splitSeparateComponents(LI, SplitLIs);
592
593 // If the AVL was an immediate > 31, then it would have been emitted
594 // as an ADDI. However, the ADDI might not have been used in the
595 // vsetvli, or a vsetvli might not have been emitted, so it may be
596 // dead now.
597 for (MachineInstr *DeadMI : DeadMIs) {
598 if (!TII->isAddImmediate(*DeadMI, Reg))
599 continue;
600 LIS->RemoveMachineInstrFromMaps(*DeadMI);
601 Register AddReg = DeadMI->getOperand(1).getReg();
602 DeadMI->eraseFromParent();
603 if (AddReg.isVirtual())
604 LIS->shrinkToUses(&LIS->getInterval(AddReg));
605 }
606 }
607 }
608 MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
609 /*isImp*/ true));
610 }
611 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
612 /*isImp*/ true));
613 }
614
615 if (MI.isInlineAsm()) {
616 MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ true,
617 /*isImp*/ true));
618 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ true,
619 /*isImp*/ true));
620 }
621
622 if (MI.isCall() || MI.isInlineAsm() ||
623 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
624 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
625 PrefixTransparent = false;
626
627 transferAfter(CurInfo, MI);
628 }
629
630 const auto &Info = BlockInfo[MBB.getNumber()];
631 if (CurInfo != Info.Exit) {
632 LLVM_DEBUG(dbgs() << "in block " << printMBBReference(MBB) << "\n");
633 LLVM_DEBUG(dbgs() << " begin state: " << Info.Pred << "\n");
634 LLVM_DEBUG(dbgs() << " expected end state: " << Info.Exit << "\n");
635 LLVM_DEBUG(dbgs() << " actual end state: " << CurInfo << "\n");
636 }
637 assert(CurInfo == Info.Exit && "InsertVSETVLI dataflow invariant violated");
638}
639
640/// Perform simple partial redundancy elimination of the VSETVLI instructions
641/// we're about to insert by looking for cases where we can PRE from the
642/// beginning of one block to the end of one of its predecessors. Specifically,
643/// this is geared to catch the common case of a fixed length vsetvl in a single
644/// block loop when it could execute once in the preheader instead.
645void RISCVInsertVSETVLI::doPRE(MachineBasicBlock &MBB) {
646 if (!BlockInfo[MBB.getNumber()].Pred.isUnknown())
647 return;
648
649 MachineBasicBlock *UnavailablePred = nullptr;
650 VSETVLIInfo AvailableInfo;
651 for (MachineBasicBlock *P : MBB.predecessors()) {
652 const VSETVLIInfo &PredInfo = BlockInfo[P->getNumber()].Exit;
653 if (PredInfo.isUnknown()) {
654 if (UnavailablePred)
655 return;
656 UnavailablePred = P;
657 } else if (!AvailableInfo.isValid()) {
658 AvailableInfo = PredInfo;
659 } else if (AvailableInfo != PredInfo) {
660 return;
661 }
662 }
663
664 // Unreachable, single pred, or full redundancy. Note that FRE is handled by
665 // phase 3.
666 if (!UnavailablePred || !AvailableInfo.isValid())
667 return;
668
669 if (!LIS)
670 return;
671
672 // If we don't know the exact VTYPE, we can't copy the vsetvli to the exit of
673 // the unavailable pred.
674 if (AvailableInfo.hasSEWLMULRatioOnly())
675 return;
676
677 // Critical edge - TODO: consider splitting?
678 if (UnavailablePred->succ_size() != 1)
679 return;
680
681 // If the AVL value is a register (other than our VLMAX sentinel),
682 // we need to prove the value is available at the point we're going
683 // to insert the vsetvli at.
684 if (AvailableInfo.hasAVLReg()) {
685 SlotIndex SI = AvailableInfo.getAVLVNInfo()->def;
686 // This is an inline dominance check which covers the case of
687 // UnavailablePred being the preheader of a loop.
688 if (LIS->getMBBFromIndex(SI) != UnavailablePred)
689 return;
690 if (!UnavailablePred->terminators().empty() &&
691 SI >= LIS->getInstructionIndex(*UnavailablePred->getFirstTerminator()))
692 return;
693 }
694
695 // Model the effect of changing the input state of the block MBB to
696 // AvailableInfo. We're looking for two issues here; one legality,
697 // one profitability.
698 // 1) If the block doesn't use some of the fields from VL or VTYPE, we
699 // may hit the end of the block with a different end state. We can
700 // not make this change without reflowing later blocks as well.
701 // 2) If we don't actually remove a transition, inserting a vsetvli
702 // into the predecessor block would be correct, but unprofitable.
703 VSETVLIInfo OldInfo = BlockInfo[MBB.getNumber()].Pred;
704 VSETVLIInfo CurInfo = AvailableInfo;
705 int TransitionsRemoved = 0;
706 for (const MachineInstr &MI : MBB) {
707 const VSETVLIInfo LastInfo = CurInfo;
708 const VSETVLIInfo LastOldInfo = OldInfo;
709 transferBefore(CurInfo, MI);
710 transferBefore(OldInfo, MI);
711 if (CurInfo == LastInfo)
712 TransitionsRemoved++;
713 if (LastOldInfo == OldInfo)
714 TransitionsRemoved--;
715 transferAfter(CurInfo, MI);
716 transferAfter(OldInfo, MI);
717 if (CurInfo == OldInfo)
718 // Convergence. All transitions after this must match by construction.
719 break;
720 }
721 if (CurInfo != OldInfo || TransitionsRemoved <= 0)
722 // Issues 1 and 2 above
723 return;
724
725 // Finally, update both data flow state and insert the actual vsetvli.
726 // Doing both keeps the code in sync with the dataflow results, which
727 // is critical for correctness of phase 3.
728 auto OldExit = BlockInfo[UnavailablePred->getNumber()].Exit;
729 LLVM_DEBUG(dbgs() << "PRE VSETVLI from " << MBB.getName() << " to "
730 << UnavailablePred->getName() << " with state "
731 << AvailableInfo << "\n");
732 BlockInfo[UnavailablePred->getNumber()].Exit = AvailableInfo;
733 BlockInfo[MBB.getNumber()].Pred = AvailableInfo;
734
735 // Note there's an implicit assumption here that terminators never use
736 // or modify VL or VTYPE. Also, fallthrough will return end().
737 auto InsertPt = UnavailablePred->getFirstInstrTerminator();
738 insertVSETVLI(*UnavailablePred, InsertPt,
739 UnavailablePred->findDebugLoc(InsertPt),
740 AvailableInfo, OldExit);
741}
742
743// Return true if we can mutate PrevMI to match MI without changing any the
744// fields which would be observed.
745// If AVLDefToMove is non-null after the call, it points to an ADDI
746// instruction that needs to be moved before PrevMI.
747bool RISCVInsertVSETVLI::canMutatePriorConfig(
748 const MachineInstr &PrevMI, const MachineInstr &MI,
749 const DemandedFields &Used, MachineInstr *&AVLDefToMove) const {
750 AVLDefToMove = nullptr;
751 // If the VL values aren't equal, return false if either a) the former is
752 // demanded, or b) we can't rewrite the former to be the later for
753 // implementation reasons.
754 if (!RISCVInstrInfo::isVLPreservingConfig(MI)) {
755 if (Used.VLAny)
756 return false;
757
758 if (Used.VLZeroness) {
759 if (RISCVInstrInfo::isVLPreservingConfig(PrevMI))
760 return false;
761 if (!VIA.getInfoForVSETVLI(PrevMI).hasEquallyZeroAVL(
762 VIA.getInfoForVSETVLI(MI), LIS))
763 return false;
764 }
765
766 auto &AVL = MI.getOperand(1);
767
768 // If the AVL is a register, we need to make sure its definition is the same
769 // at PrevMI as it was at MI.
770 if (AVL.isReg() && AVL.getReg() != RISCV::X0) {
771 VNInfo *VNI = getVNInfoFromReg(AVL.getReg(), MI, LIS);
772 VNInfo *PrevVNI = getVNInfoFromReg(AVL.getReg(), PrevMI, LIS);
773 if (!VNI || !PrevVNI || VNI != PrevVNI) {
774 // If LIS is null, we were not able to get the VNInfo so we don't know
775 // if the AVL def needs to be moved.
776 if (!LIS)
777 return false;
778 // If the AVL is defined by a load immediate instruction (ADDI x0, imm),
779 // it can be moved earlier since it has no register dependencies.
780 if (!AVL.getReg().isVirtual())
781 return false;
782
783 MachineInstr *DefMI = MRI->getUniqueVRegDef(AVL.getReg());
784 if (!DefMI || !RISCVInstrInfo::isLoadImmediate(*DefMI) ||
785 DefMI->getParent() != PrevMI.getParent()) {
786 return false;
787 }
788 // Mark that this ADDI needs to be moved.
789 AVLDefToMove = DefMI;
790 }
791 }
792
793 // If we define VL and need to move the definition up, check we can extend
794 // the live interval upwards from MI to PrevMI.
795 Register VL = MI.getOperand(0).getReg();
796 if (VL.isVirtual() && LIS &&
797 LIS->getInterval(VL).overlaps(LIS->getInstructionIndex(PrevMI),
798 LIS->getInstructionIndex(MI)))
799 return false;
800 }
801
802 assert(PrevMI.getOperand(2).isImm() && MI.getOperand(2).isImm());
803 auto PriorVType = PrevMI.getOperand(2).getImm();
804 auto VType = MI.getOperand(2).getImm();
805 return areCompatibleVTYPEs(PriorVType, VType, Used);
806}
807
808void RISCVInsertVSETVLI::coalesceVSETVLIs(MachineBasicBlock &MBB) const {
809 MachineInstr *NextMI = nullptr;
810 // We can have arbitrary code in successors, so VL and VTYPE
811 // must be considered demanded.
812 DemandedFields Used;
813 Used.demandVL();
814 Used.demandVTYPE();
816
817 auto dropAVLUse = [&](MachineOperand &MO) {
818 if (!MO.isReg() || !MO.getReg().isVirtual())
819 return;
820 Register OldVLReg = MO.getReg();
821 MO.setReg(Register());
822
823 if (LIS)
824 LIS->shrinkToUses(&LIS->getInterval(OldVLReg));
825
826 MachineInstr *VLOpDef = MRI->getUniqueVRegDef(OldVLReg);
827 if (VLOpDef && TII->isAddImmediate(*VLOpDef, OldVLReg) &&
828 MRI->use_nodbg_empty(OldVLReg))
829 ToDelete.push_back(VLOpDef);
830 };
831
832 for (MachineInstr &MI : make_early_inc_range(reverse(MBB))) {
833 // TODO: Support XSfmm.
834 if (RISCVII::hasTWidenOp(MI.getDesc().TSFlags) ||
835 RISCVInstrInfo::isXSfmmVectorConfigInstr(MI)) {
836 NextMI = nullptr;
837 continue;
838 }
839
840 if (!RISCVInstrInfo::isVectorConfigInstr(MI)) {
841 Used.doUnion(getDemanded(MI, ST));
842 if (MI.isCall() || MI.isInlineAsm() ||
843 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
844 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
845 NextMI = nullptr;
846 continue;
847 }
848
849 if (!MI.getOperand(0).isDead())
850 Used.demandVL();
851
852 if (NextMI) {
853 if (!Used.usedVL() && !Used.usedVTYPE()) {
854 dropAVLUse(MI.getOperand(1));
855 if (LIS)
857 MI.eraseFromParent();
858 NumCoalescedVSETVL++;
859 // Leave NextMI unchanged
860 continue;
861 }
862
863 MachineInstr *AVLDefToMove = nullptr;
864 if (canMutatePriorConfig(MI, *NextMI, Used, AVLDefToMove)) {
865 if (!RISCVInstrInfo::isVLPreservingConfig(*NextMI)) {
866 Register DefReg = NextMI->getOperand(0).getReg();
867
868 MI.getOperand(0).setReg(DefReg);
869 MI.getOperand(0).setIsDead(false);
870
871 // Move the AVL from NextMI to MI
872 dropAVLUse(MI.getOperand(1));
873 if (NextMI->getOperand(1).isImm())
874 MI.getOperand(1).ChangeToImmediate(NextMI->getOperand(1).getImm());
875 else {
876 MI.getOperand(1).ChangeToRegister(NextMI->getOperand(1).getReg(),
877 false);
878
879 // If canMutatePriorConfig indicated that an ADDI needs to be moved,
880 // move it now.
881 if (AVLDefToMove) {
882 AVLDefToMove->moveBefore(&MI);
883 if (LIS)
884 LIS->handleMove(*AVLDefToMove);
885 }
886 }
887 dropAVLUse(NextMI->getOperand(1));
888
889 // The def of DefReg moved to MI, so extend the LiveInterval up to
890 // it.
891 if (DefReg.isVirtual() && LIS) {
892 LiveInterval &DefLI = LIS->getInterval(DefReg);
893 SlotIndex MISlot = LIS->getInstructionIndex(MI).getRegSlot();
894 SlotIndex NextMISlot =
895 LIS->getInstructionIndex(*NextMI).getRegSlot();
896 VNInfo *DefVNI = DefLI.getVNInfoAt(NextMISlot);
897 LiveInterval::Segment S(MISlot, NextMISlot, DefVNI);
898 DefLI.addSegment(S);
899 DefVNI->def = MISlot;
900 // Mark DefLI as spillable if it was previously unspillable
901 DefLI.setWeight(0);
902
903 // DefReg may have had no uses, in which case we need to shrink
904 // the LiveInterval up to MI.
905 LIS->shrinkToUses(&DefLI);
906 }
907
908 MI.setDesc(NextMI->getDesc());
909 }
910 MI.getOperand(2).setImm(NextMI->getOperand(2).getImm());
911
912 dropAVLUse(NextMI->getOperand(1));
913 if (LIS)
914 LIS->RemoveMachineInstrFromMaps(*NextMI);
915 NextMI->eraseFromParent();
916 NumCoalescedVSETVL++;
917 // fallthrough
918 }
919 }
920 NextMI = &MI;
921 Used = getDemanded(MI, ST);
922 }
923
924 // Loop over the dead AVL values, and delete them now. This has
925 // to be outside the above loop to avoid invalidating iterators.
926 for (auto *MI : ToDelete) {
927 assert(MI->getOpcode() == RISCV::ADDI);
928 Register AddReg = MI->getOperand(1).getReg();
929 if (LIS) {
930 LIS->removeInterval(MI->getOperand(0).getReg());
932 }
933 MI->eraseFromParent();
934 if (LIS && AddReg.isVirtual())
935 LIS->shrinkToUses(&LIS->getInterval(AddReg));
936 }
937}
938
939// When twiden != 0, LMUL, tail policy, and mask policy from the user are
940// ignored. The tail policy and mask policy are always treated as agnostic. The
941// normal RVV instruction will ignore the twiden parameter. This observation
942// could allow the RVV instruction and xsfmm instruction to share the same
943// configuration instruction.
944//
945// We need to make sure the AVL, SEW, and AltFmt is same between VSETVL and
946// VSETVLTN.
947//
948// For example:
949//
950// %avl = SETTM or SETTK
951// ...
952// VSETVL %avl, type1
953// VSETVLTNT %avl, type2
954//
955// ->
956//
957// %avl = SETTM or SETTK
958// ...
959// VSETVLTNT %avl, type2
960//
961bool RISCVInsertVSETVLI::canMutatePriorConfigWithTWiden(
962 const MachineInstr &PrevMI, const MachineInstr &MI) const {
963
964 if (PrevMI.getOpcode() != RISCV::PseudoVSETVLI)
965 return false;
966
967 if (MI.getOpcode() != RISCV::PseudoSF_VSETTNT)
968 return false;
969
970 auto PrevInfo = VIA.getInfoForVSETVLI(PrevMI);
971 auto CurrInfo = VIA.getInfoForVSETVLI(MI);
972
973 assert(CurrInfo.hasAVLReg() && "Invalid PseudoSF_VSETTNT without an AVLReg.");
974
975 auto AVLReg = CurrInfo.getAVLReg();
976
977 auto *AVLRegDefMI = MRI->getUniqueVRegDef(AVLReg);
978
979 if (!AVLRegDefMI)
980 return false;
981
982 if (!RISCVInstrInfo::isXSfmmVectorConfigTMTKInstr(*AVLRegDefMI))
983 return false;
984
985 auto AVLRegDefMIInfo = VIA.computeInfoForInstr(*AVLRegDefMI);
986 if (AVLRegDefMIInfo.getTWiden() != CurrInfo.getTWiden())
987 return false;
988
989 if (AVLRegDefMIInfo.getSEW() != PrevInfo.getSEW())
990 return false;
991
992 // CurrInfo twiden != 0, so TailAgnostic and MaskAgnostic bit default to 1
993 if (!PrevInfo.getTailAgnostic() || !PrevInfo.getMaskAgnostic())
994 return false;
995
996 if (!PrevInfo.hasSameAVL(CurrInfo))
997 return false;
998
999 if (PrevInfo.getSEW() != CurrInfo.getSEW())
1000 return false;
1001
1002 if (PrevInfo.getAltFmt() != CurrInfo.getAltFmt())
1003 return false;
1004
1005 // The PrevMI's LMUL should be at least 8/KMAX; otherwise, converting it to a
1006 // tile-widening version could result in a VLMAX smaller than what AVLRegDefMI
1007 // expects, causing the LMUL information from PrevMI to be lost.
1008 auto [LMul, Fractional] = decodeVLMUL(PrevInfo.getVLMUL());
1009 unsigned KMAX = (CurrInfo.getSEW() >= 32) ? 1 : (32 / CurrInfo.getSEW());
1010
1011 if (Fractional || LMul < (8 / KMAX))
1012 return false;
1013
1014 return true;
1015}
1016
1017void RISCVInsertVSETVLI::coalesceVSETVLIsForTWiden(
1018 MachineBasicBlock &MBB) const {
1019 MachineInstr *NextMI = nullptr;
1020
1021 for (MachineInstr &MI : make_early_inc_range(reverse(MBB))) {
1022
1023 if (!RISCVInstrInfo::isVectorConfigInstr(MI))
1024 continue;
1025
1026 if (NextMI) {
1027 // If only TWiden different. Update the MI and drop the NextMI.
1028 if (canMutatePriorConfigWithTWiden(MI, *NextMI)) {
1029
1030 auto NextInfo = VIA.getInfoForVSETVLI(*NextMI);
1031 MI.getOperand(2).setImm(NextInfo.encodeVTYPE());
1032
1033 if (LIS)
1034 LIS->RemoveMachineInstrFromMaps(*NextMI);
1035 NextMI->eraseFromParent();
1036 }
1037 }
1038 NextMI = &MI;
1039 }
1040}
1041
1042void RISCVInsertVSETVLI::insertReadVL(MachineBasicBlock &MBB) {
1043 for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
1044 MachineInstr &MI = *I++;
1045 if (RISCVInstrInfo::isFaultOnlyFirstLoad(MI)) {
1046 Register VLOutput = MI.getOperand(1).getReg();
1047 assert(VLOutput.isVirtual());
1048 if (!MI.getOperand(1).isDead()) {
1049 auto ReadVLMI = BuildMI(MBB, I, MI.getDebugLoc(),
1050 TII->get(RISCV::PseudoReadVL), VLOutput);
1051 // Move the LiveInterval's definition down to PseudoReadVL.
1052 if (LIS) {
1053 SlotIndex NewDefSI =
1054 LIS->InsertMachineInstrInMaps(*ReadVLMI).getRegSlot();
1055 LiveInterval &DefLI = LIS->getInterval(VLOutput);
1056 LiveRange::Segment *DefSeg = DefLI.getSegmentContaining(NewDefSI);
1057 VNInfo *DefVNI = DefLI.getVNInfoAt(DefSeg->start);
1058 DefLI.removeSegment(DefSeg->start, NewDefSI);
1059 DefVNI->def = NewDefSI;
1060 }
1061 }
1062 // We don't use the vl output of the VLEFF/VLSEGFF anymore.
1063 MI.getOperand(1).setReg(RISCV::X0);
1064 MI.addRegisterDefined(RISCV::VL, MRI->getTargetRegisterInfo());
1065 }
1066 }
1067}
1068
1069bool RISCVInsertVSETVLI::insertVSETMTK(MachineBasicBlock &MBB,
1070 TKTMMode Mode) const {
1071
1072 bool Changed = false;
1073 for (auto &MI : MBB) {
1074 uint64_t TSFlags = MI.getDesc().TSFlags;
1075 if (RISCVInstrInfo::isXSfmmVectorConfigTMTKInstr(MI) ||
1076 !RISCVII::hasSEWOp(TSFlags) || !RISCVII::hasTWidenOp(TSFlags))
1077 continue;
1078
1079 VSETVLIInfo CurrInfo = VIA.computeInfoForInstr(MI);
1080
1081 unsigned Opcode = 0, OpNum = 0;
1082 switch (Mode) {
1083 case VSETTK:
1084 if (!RISCVII::hasTKOp(TSFlags))
1085 continue;
1086 OpNum = RISCVII::getTKOpNum(MI.getDesc());
1087 Opcode = RISCV::PseudoSF_VSETTK;
1088 break;
1089 case VSETTM:
1090 if (!RISCVII::hasTMOp(TSFlags))
1091 continue;
1092 OpNum = RISCVII::getTMOpNum(MI.getDesc());
1093 Opcode = RISCV::PseudoSF_VSETTM;
1094 break;
1095 }
1096
1097 assert(OpNum && Opcode && "Invalid OpNum or Opcode");
1098
1099 MachineOperand &Op = MI.getOperand(OpNum);
1100
1101 auto TmpMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(Opcode))
1102 .addReg(RISCV::X0, RegState::Define | RegState::Dead)
1103 .addReg(Op.getReg())
1104 .addImm(Log2_32(CurrInfo.getSEW()))
1105 .addImm(CurrInfo.getTWiden());
1106
1107 Changed = true;
1108 Register Reg = Op.getReg();
1109 Op.setReg(Register());
1110 Op.setIsKill(false);
1111 if (LIS) {
1112 LIS->InsertMachineInstrInMaps(*TmpMI);
1113 LiveInterval &LI = LIS->getInterval(Reg);
1114
1115 // Erase the AVL operand from the instruction.
1116 LIS->shrinkToUses(&LI);
1117 // TODO: Enable this once needVSETVLIPHI is supported.
1118 // SmallVector<LiveInterval *> SplitLIs;
1119 // LIS->splitSeparateComponents(LI, SplitLIs);
1120 }
1121 }
1122 return Changed;
1123}
1124
1125bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1126 // Skip if the vector extension is not enabled.
1127 ST = &MF.getSubtarget<RISCVSubtarget>();
1128 if (!ST->hasVInstructions())
1129 return false;
1130
1131 LLVM_DEBUG(dbgs() << "Entering InsertVSETVLI for " << MF.getName() << "\n");
1132
1133 TII = ST->getInstrInfo();
1134 MRI = &MF.getRegInfo();
1135 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
1136 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
1137 VIA = RISCVVSETVLIInfoAnalysis(ST, LIS);
1138
1139 assert(BlockInfo.empty() && "Expect empty block infos");
1140 BlockInfo.resize(MF.getNumBlockIDs());
1141
1142 bool HaveVectorOp = false;
1143
1144 // Phase 1 - determine how VL/VTYPE are affected by the each block.
1145 for (const MachineBasicBlock &MBB : MF) {
1146 VSETVLIInfo TmpStatus;
1147 HaveVectorOp |= computeVLVTYPEChanges(MBB, TmpStatus);
1148 // Initial exit state is whatever change we found in the block.
1149 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1150 BBInfo.Exit = TmpStatus;
1151 LLVM_DEBUG(dbgs() << "Initial exit state of " << printMBBReference(MBB)
1152 << " is " << BBInfo.Exit << "\n");
1153
1154 }
1155
1156 // If we didn't find any instructions that need VSETVLI, we're done.
1157 if (!HaveVectorOp) {
1158 BlockInfo.clear();
1159 return false;
1160 }
1161
1162 // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1163 // blocks to the list here, but will also add any that need to be revisited
1164 // during Phase 2 processing.
1165 for (const MachineBasicBlock &MBB : MF) {
1166 WorkList.push(&MBB);
1167 BlockInfo[MBB.getNumber()].InQueue = true;
1168 }
1169 while (!WorkList.empty()) {
1170 const MachineBasicBlock &MBB = *WorkList.front();
1171 WorkList.pop();
1172 computeIncomingVLVTYPE(MBB);
1173 }
1174
1175 // Perform partial redundancy elimination of vsetvli transitions.
1176 for (MachineBasicBlock &MBB : MF)
1177 doPRE(MBB);
1178
1179 // Phase 3 - add any vsetvli instructions needed in the block. Use the
1180 // Phase 2 information to avoid adding vsetvlis before the first vector
1181 // instruction in the block if the VL/VTYPE is satisfied by its
1182 // predecessors.
1183 for (MachineBasicBlock &MBB : MF)
1184 emitVSETVLIs(MBB);
1185
1186 // Now that all vsetvlis are explicit, go through and do block local
1187 // DSE and peephole based demanded fields based transforms. Note that
1188 // this *must* be done outside the main dataflow so long as we allow
1189 // any cross block analysis within the dataflow. We can't have both
1190 // demanded fields based mutation and non-local analysis in the
1191 // dataflow at the same time without introducing inconsistencies.
1192 // We're visiting blocks from the bottom up because a VSETVLI in the
1193 // earlier block might become dead when its uses in later blocks are
1194 // optimized away.
1195 for (MachineBasicBlock *MBB : post_order(&MF))
1196 coalesceVSETVLIs(*MBB);
1197
1198 if (ST->hasVendorXSfmmbase()) {
1199 for (MachineBasicBlock &MBB : MF)
1200 coalesceVSETVLIsForTWiden(MBB);
1201 }
1202
1203 // Insert PseudoReadVL after VLEFF/VLSEGFF and replace it with the vl output
1204 // of VLEFF/VLSEGFF.
1205 for (MachineBasicBlock &MBB : MF)
1206 insertReadVL(MBB);
1207
1208 if (ST->hasVendorXSfmmbase()) {
1209 for (MachineBasicBlock &MBB : MF) {
1210 insertVSETMTK(MBB, VSETTM);
1211 insertVSETMTK(MBB, VSETTK);
1212 }
1213 }
1214
1215 BlockInfo.clear();
1216 return HaveVectorOp;
1217}
1218
1219/// Returns an instance of the Insert VSETVLI pass.
1221 return new RISCVInsertVSETVLI();
1222}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static cl::opt< bool > EnsureWholeVectorRegisterMoveValidVTYPE(DEBUG_TYPE "-whole-vector-register-move-valid-vtype", cl::Hidden, cl::desc("Insert vsetvlis before vmvNr.vs to ensure vtype is valid and " "vill is cleared"), cl::init(true))
static VSETVLIInfo adjustIncoming(const VSETVLIInfo &PrevInfo, const VSETVLIInfo &NewInfo, DemandedFields &Demanded)
#define RISCV_INSERT_VSETVLI_NAME
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Optimize VGPR LiveRange
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
BlockData()=default
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
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
A debug info location.
Definition DebugLoc.h:126
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LiveInterval - This class represents the liveness of a register, or stack slot.
void setWeight(float Value)
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
LLVM_ABI void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
bool liveAt(SlotIndex index) const
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
bool containsOneValue() const
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI 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()
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI 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.
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 & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
LLVM_ABI void moveBefore(MachineInstr *MovePos)
Move the instruction before MovePos.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
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)
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
bool hasVInstructions() const
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) const
VSETVLIInfo computeInfoForInstr(const MachineInstr &MI) const
Defines the abstract state with which the forward dataflow models the values of the VL and VTYPE regi...
bool hasSameVTYPE(const VSETVLIInfo &Other) const
VSETVLIInfo intersect(const VSETVLIInfo &Other) const
bool hasSameVLMAX(const VSETVLIInfo &Other) const
bool isCompatible(const DemandedFields &Used, const VSETVLIInfo &Require, const LiveIntervals *LIS) const
bool hasSameAVL(const VSETVLIInfo &Other) const
const VNInfo * getAVLVNInfo() const
RISCVVType::VLMUL getVLMUL() const
bool hasEquallyZeroAVL(const VSETVLIInfo &Other, const LiveIntervals *LIS) const
void setAVL(const VSETVLIInfo &Info)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
void push_back(const T &Elt)
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Changed
static unsigned getTMOpNum(const MCInstrDesc &Desc)
static bool hasTWidenOp(uint64_t TSFlags)
static unsigned getTKOpNum(const MCInstrDesc &Desc)
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool hasTKOp(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasTMOp(uint64_t TSFlags)
static bool hasSEWOp(uint64_t TSFlags)
LLVM_ABI std::optional< VLMUL > getSameRatioLMUL(unsigned Ratio, unsigned EEW)
LLVM_ABI std::pair< unsigned, bool > decodeVLMUL(VLMUL VLMul)
static const MachineOperand & getVLOp(const MachineInstr &MI)
DemandedFields getDemanded(const MachineInstr &MI, const RISCVSubtarget *ST)
Return the fields and properties demanded by the provided instruction.
bool areCompatibleVTYPEs(uint64_t CurVType, uint64_t NewVType, const DemandedFields &Used)
Return true if moving from CurVType to NewVType is indistinguishable from the perspective of an instr...
static VNInfo * getVNInfoFromReg(Register Reg, const MachineInstr &MI, const LiveIntervals *LIS)
Given a virtual register Reg, return the corresponding VNInfo for it.
bool isVectorCopy(const TargetRegisterInfo *TRI, const MachineInstr &MI)
Return true if MI is a copy that will be lowered to one or more vmvNr.vs.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Dead
Unused definition.
@ Define
Register definition.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:326
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
FunctionPass * createRISCVInsertVSETVLIPass()
Returns an instance of the Insert VSETVLI pass.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
DWARFExpression::Operation Op
char & RISCVInsertVSETVLIID
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Which subfields of VL or VTYPE have values we need to preserve?
enum llvm::RISCV::DemandedFields::@326061152055210015167034143142117063364004052074 SEW
enum llvm::RISCV::DemandedFields::@201276154261047021277240313173154105356124146047 LMUL