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