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