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