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.
11 //
12 // This pass consists of 3 phases:
13 //
14 // Phase 1 collects how each basic block affects VL/VTYPE.
15 //
16 // Phase 2 uses the information from phase 1 to do a data flow analysis to
17 // propagate the VL/VTYPE changes through the function. This gives us the
18 // VL/VTYPE at the start of each basic block.
19 //
20 // Phase 3 inserts VSETVLI instructions in each basic block. Information from
21 // phase 2 is used to prevent inserting a VSETVLI before the first vector
22 // instruction in the block if possible.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "RISCV.h"
27 #include "RISCVSubtarget.h"
28 #include "llvm/CodeGen/LiveIntervals.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include <queue>
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "riscv-insert-vsetvli"
34 #define RISCV_INSERT_VSETVLI_NAME "RISCV Insert VSETVLI pass"
35 
36 static cl::opt<bool> DisableInsertVSETVLPHIOpt(
37     "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
38     cl::desc("Disable looking through phis when inserting vsetvlis."));
39 
40 namespace {
41 
42 class VSETVLIInfo {
43   union {
44     Register AVLReg;
45     unsigned AVLImm;
46   };
47 
48   enum : uint8_t {
49     Uninitialized,
50     AVLIsReg,
51     AVLIsImm,
52     Unknown,
53   } State = Uninitialized;
54 
55   // Fields from VTYPE.
56   RISCVII::VLMUL VLMul = RISCVII::LMUL_1;
57   uint8_t SEW = 0;
58   uint8_t TailAgnostic : 1;
59   uint8_t MaskAgnostic : 1;
60   uint8_t MaskRegOp : 1;
61   uint8_t SEWLMULRatioOnly : 1;
62 
63 public:
64   VSETVLIInfo()
65       : AVLImm(0), TailAgnostic(false), MaskAgnostic(false), MaskRegOp(false),
66         SEWLMULRatioOnly(false) {}
67 
68   static VSETVLIInfo getUnknown() {
69     VSETVLIInfo Info;
70     Info.setUnknown();
71     return Info;
72   }
73 
74   bool isValid() const { return State != Uninitialized; }
75   void setUnknown() { State = Unknown; }
76   bool isUnknown() const { return State == Unknown; }
77 
78   void setAVLReg(Register Reg) {
79     AVLReg = Reg;
80     State = AVLIsReg;
81   }
82 
83   void setAVLImm(unsigned Imm) {
84     AVLImm = Imm;
85     State = AVLIsImm;
86   }
87 
88   bool hasAVLImm() const { return State == AVLIsImm; }
89   bool hasAVLReg() const { return State == AVLIsReg; }
90   Register getAVLReg() const {
91     assert(hasAVLReg());
92     return AVLReg;
93   }
94   unsigned getAVLImm() const {
95     assert(hasAVLImm());
96     return AVLImm;
97   }
98 
99   bool hasSameAVL(const VSETVLIInfo &Other) const {
100     assert(isValid() && Other.isValid() &&
101            "Can't compare invalid VSETVLIInfos");
102     assert(!isUnknown() && !Other.isUnknown() &&
103            "Can't compare AVL in unknown state");
104     if (hasAVLReg() && Other.hasAVLReg())
105       return getAVLReg() == Other.getAVLReg();
106 
107     if (hasAVLImm() && Other.hasAVLImm())
108       return getAVLImm() == Other.getAVLImm();
109 
110     return false;
111   }
112 
113   void setVTYPE(unsigned VType) {
114     assert(isValid() && !isUnknown() &&
115            "Can't set VTYPE for uninitialized or unknown");
116     VLMul = RISCVVType::getVLMUL(VType);
117     SEW = RISCVVType::getSEW(VType);
118     TailAgnostic = RISCVVType::isTailAgnostic(VType);
119     MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
120   }
121   void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA, bool MRO) {
122     assert(isValid() && !isUnknown() &&
123            "Can't set VTYPE for uninitialized or unknown");
124     VLMul = L;
125     SEW = S;
126     TailAgnostic = TA;
127     MaskAgnostic = MA;
128     MaskRegOp = MRO;
129   }
130 
131   unsigned encodeVTYPE() const {
132     assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
133            "Can't encode VTYPE for uninitialized or unknown");
134     return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
135   }
136 
137   bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
138 
139   bool hasSameVTYPE(const VSETVLIInfo &Other) const {
140     assert(isValid() && Other.isValid() &&
141            "Can't compare invalid VSETVLIInfos");
142     assert(!isUnknown() && !Other.isUnknown() &&
143            "Can't compare VTYPE in unknown state");
144     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
145            "Can't compare when only LMUL/SEW ratio is valid.");
146     return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
147            std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
148                     Other.MaskAgnostic);
149   }
150 
151   static unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul) {
152     unsigned LMul;
153     bool Fractional;
154     std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(VLMul);
155 
156     // Convert LMul to a fixed point value with 3 fractional bits.
157     LMul = Fractional ? (8 / LMul) : (LMul * 8);
158 
159     assert(SEW >= 8 && "Unexpected SEW value");
160     return (SEW * 8) / LMul;
161   }
162 
163   unsigned getSEWLMULRatio() const {
164     assert(isValid() && !isUnknown() &&
165            "Can't use VTYPE for uninitialized or unknown");
166     return getSEWLMULRatio(SEW, VLMul);
167   }
168 
169   // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
170   bool hasSameVLMAX(const VSETVLIInfo &Other) const {
171     assert(isValid() && Other.isValid() &&
172            "Can't compare invalid VSETVLIInfos");
173     assert(!isUnknown() && !Other.isUnknown() &&
174            "Can't compare VTYPE in unknown state");
175     return getSEWLMULRatio() == Other.getSEWLMULRatio();
176   }
177 
178   // Determine whether the vector instructions requirements represented by
179   // InstrInfo are compatible with the previous vsetvli instruction represented
180   // by this.
181   bool isCompatible(const VSETVLIInfo &InstrInfo) const {
182     assert(isValid() && InstrInfo.isValid() &&
183            "Can't compare invalid VSETVLIInfos");
184     assert(!InstrInfo.SEWLMULRatioOnly &&
185            "Expected a valid VTYPE for instruction!");
186     // Nothing is compatible with Unknown.
187     if (isUnknown() || InstrInfo.isUnknown())
188       return false;
189 
190     // If only our VLMAX ratio is valid, then this isn't compatible.
191     if (SEWLMULRatioOnly)
192       return false;
193 
194     // If the instruction doesn't need an AVLReg and the SEW matches, consider
195     // it compatible.
196     if (InstrInfo.hasAVLReg() && InstrInfo.AVLReg == RISCV::NoRegister) {
197       if (SEW == InstrInfo.SEW)
198         return true;
199     }
200 
201     // VTypes must match unless the instruction is a mask reg operation, then it
202     // only care about VLMAX.
203     // FIXME: Mask reg operations are probably ok if "this" VLMAX is larger
204     // than "InstrInfo".
205     if (!hasSameVTYPE(InstrInfo) &&
206         !(InstrInfo.MaskRegOp && hasSameVLMAX(InstrInfo) &&
207           TailAgnostic == InstrInfo.TailAgnostic &&
208           MaskAgnostic == InstrInfo.MaskAgnostic))
209       return false;
210 
211     return hasSameAVL(InstrInfo);
212   }
213 
214   bool isCompatibleWithLoadStoreEEW(unsigned EEW,
215                                     const VSETVLIInfo &InstrInfo) const {
216     assert(isValid() && InstrInfo.isValid() &&
217            "Can't compare invalid VSETVLIInfos");
218     assert(!InstrInfo.SEWLMULRatioOnly &&
219            "Expected a valid VTYPE for instruction!");
220     assert(EEW == InstrInfo.SEW && "Mismatched EEW/SEW for store");
221 
222     if (isUnknown() || hasSEWLMULRatioOnly())
223       return false;
224 
225     if (!hasSameAVL(InstrInfo))
226       return false;
227 
228     // TODO: This check isn't required for stores. But we should ignore for all
229     // stores not just unit-stride and strided so leaving it for now.
230     if (TailAgnostic != InstrInfo.TailAgnostic ||
231         MaskAgnostic != InstrInfo.MaskAgnostic)
232       return false;
233 
234     return getSEWLMULRatio() == getSEWLMULRatio(EEW, InstrInfo.VLMul);
235   }
236 
237   bool operator==(const VSETVLIInfo &Other) const {
238     // Uninitialized is only equal to another Uninitialized.
239     if (!isValid())
240       return !Other.isValid();
241     if (!Other.isValid())
242       return !isValid();
243 
244     // Unknown is only equal to another Unknown.
245     if (isUnknown())
246       return Other.isUnknown();
247     if (Other.isUnknown())
248       return isUnknown();
249 
250     if (!hasSameAVL(Other))
251       return false;
252 
253     // If only the VLMAX is valid, check that it is the same.
254     if (SEWLMULRatioOnly && Other.SEWLMULRatioOnly)
255       return hasSameVLMAX(Other);
256 
257     // If the full VTYPE is valid, check that it is the same.
258     if (!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly)
259       return hasSameVTYPE(Other);
260 
261     // If the SEWLMULRatioOnly bits are different, then they aren't equal.
262     return false;
263   }
264 
265   // Calculate the VSETVLIInfo visible to a block assuming this and Other are
266   // both predecessors.
267   VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
268     // If the new value isn't valid, ignore it.
269     if (!Other.isValid())
270       return *this;
271 
272     // If this value isn't valid, this must be the first predecessor, use it.
273     if (!isValid())
274       return Other;
275 
276     // If either is unknown, the result is unknown.
277     if (isUnknown() || Other.isUnknown())
278       return VSETVLIInfo::getUnknown();
279 
280     // If we have an exact, match return this.
281     if (*this == Other)
282       return *this;
283 
284     // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
285     // return an SEW/LMUL ratio only value.
286     if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
287       VSETVLIInfo MergeInfo = *this;
288       MergeInfo.SEWLMULRatioOnly = true;
289       return MergeInfo;
290     }
291 
292     // Otherwise the result is unknown.
293     return VSETVLIInfo::getUnknown();
294   }
295 
296   // Calculate the VSETVLIInfo visible at the end of the block assuming this
297   // is the predecessor value, and Other is change for this block.
298   VSETVLIInfo merge(const VSETVLIInfo &Other) const {
299     assert(isValid() && "Can only merge with a valid VSETVLInfo");
300 
301     // Nothing changed from the predecessor, keep it.
302     if (!Other.isValid())
303       return *this;
304 
305     // If the change is compatible with the input, we won't create a VSETVLI
306     // and should keep the predecessor.
307     if (isCompatible(Other))
308       return *this;
309 
310     // Otherwise just use whatever is in this block.
311     return Other;
312   }
313 };
314 
315 struct BlockData {
316   // The VSETVLIInfo that represents the net changes to the VL/VTYPE registers
317   // made by this block. Calculated in Phase 1.
318   VSETVLIInfo Change;
319 
320   // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
321   // block. Calculated in Phase 2.
322   VSETVLIInfo Exit;
323 
324   // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
325   // blocks. Calculated in Phase 2, and used by Phase 3.
326   VSETVLIInfo Pred;
327 
328   // Keeps track of whether the block is already in the queue.
329   bool InQueue = false;
330 
331   BlockData() {}
332 };
333 
334 class RISCVInsertVSETVLI : public MachineFunctionPass {
335   const TargetInstrInfo *TII;
336   MachineRegisterInfo *MRI;
337 
338   std::vector<BlockData> BlockInfo;
339   std::queue<const MachineBasicBlock *> WorkList;
340 
341 public:
342   static char ID;
343 
344   RISCVInsertVSETVLI() : MachineFunctionPass(ID) {
345     initializeRISCVInsertVSETVLIPass(*PassRegistry::getPassRegistry());
346   }
347   bool runOnMachineFunction(MachineFunction &MF) override;
348 
349   void getAnalysisUsage(AnalysisUsage &AU) const override {
350     AU.setPreservesCFG();
351     MachineFunctionPass::getAnalysisUsage(AU);
352   }
353 
354   StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
355 
356 private:
357   bool needVSETVLI(const VSETVLIInfo &Require, const VSETVLIInfo &CurInfo);
358   bool needVSETVLIPHI(const VSETVLIInfo &Require, const MachineBasicBlock &MBB);
359   void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
360                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
361 
362   bool computeVLVTYPEChanges(const MachineBasicBlock &MBB);
363   void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
364   void emitVSETVLIs(MachineBasicBlock &MBB);
365 };
366 
367 } // end anonymous namespace
368 
369 char RISCVInsertVSETVLI::ID = 0;
370 
371 INITIALIZE_PASS(RISCVInsertVSETVLI, DEBUG_TYPE, RISCV_INSERT_VSETVLI_NAME,
372                 false, false)
373 
374 static MachineInstr *elideCopies(MachineInstr *MI,
375                                  const MachineRegisterInfo *MRI) {
376   while (true) {
377     if (!MI->isFullCopy())
378       return MI;
379     if (!Register::isVirtualRegister(MI->getOperand(1).getReg()))
380       return nullptr;
381     MI = MRI->getVRegDef(MI->getOperand(1).getReg());
382     if (!MI)
383       return nullptr;
384   }
385 }
386 
387 static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
388                                        const MachineRegisterInfo *MRI) {
389   VSETVLIInfo InstrInfo;
390   unsigned NumOperands = MI.getNumExplicitOperands();
391   bool HasPolicy = RISCVII::hasVecPolicyOp(TSFlags);
392 
393   // Default to tail agnostic unless the destination is tied to a source.
394   // Unless the source is undef. In that case the user would have some control
395   // over the tail values. Some pseudo instructions force a tail agnostic policy
396   // despite having a tied def.
397   bool ForceTailAgnostic = RISCVII::doesForceTailAgnostic(TSFlags);
398   bool TailAgnostic = true;
399   // If the instruction has policy argument, use the argument.
400   if (HasPolicy) {
401     const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
402     TailAgnostic = Op.getImm() & 0x1;
403   }
404 
405   unsigned UseOpIdx;
406   if (!(ForceTailAgnostic || (HasPolicy && TailAgnostic)) &&
407       MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
408     TailAgnostic = false;
409     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
410     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
411     MachineInstr *UseMI = MRI->getVRegDef(UseMO.getReg());
412     if (UseMI) {
413       UseMI = elideCopies(UseMI, MRI);
414       if (UseMI && UseMI->isImplicitDef())
415         TailAgnostic = true;
416     }
417   }
418 
419   // Remove the tail policy so we can find the SEW and VL.
420   if (HasPolicy)
421     --NumOperands;
422 
423   RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
424 
425   unsigned Log2SEW = MI.getOperand(NumOperands - 1).getImm();
426   // A Log2SEW of 0 is an operation on mask registers only.
427   bool MaskRegOp = Log2SEW == 0;
428   unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
429   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
430 
431   if (RISCVII::hasVLOp(TSFlags)) {
432     const MachineOperand &VLOp = MI.getOperand(NumOperands - 2);
433     if (VLOp.isImm())
434       InstrInfo.setAVLImm(VLOp.getImm());
435     else
436       InstrInfo.setAVLReg(VLOp.getReg());
437   } else
438     InstrInfo.setAVLReg(RISCV::NoRegister);
439   InstrInfo.setVTYPE(VLMul, SEW, /*TailAgnostic*/ TailAgnostic,
440                      /*MaskAgnostic*/ false, MaskRegOp);
441 
442   return InstrInfo;
443 }
444 
445 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
446                                        const VSETVLIInfo &Info,
447                                        const VSETVLIInfo &PrevInfo) {
448   DebugLoc DL = MI.getDebugLoc();
449 
450   // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
451   // VLMAX.
452   if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
453       Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
454     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLIX0))
455         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
456         .addReg(RISCV::X0, RegState::Kill)
457         .addImm(Info.encodeVTYPE())
458         .addReg(RISCV::VL, RegState::Implicit);
459     return;
460   }
461 
462   if (Info.hasAVLImm()) {
463     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
464         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
465         .addImm(Info.getAVLImm())
466         .addImm(Info.encodeVTYPE());
467     return;
468   }
469 
470   Register AVLReg = Info.getAVLReg();
471   if (AVLReg == RISCV::NoRegister) {
472     // We can only use x0, x0 if there's no chance of the vtype change causing
473     // the previous vl to become invalid.
474     if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
475         Info.hasSameVLMAX(PrevInfo)) {
476       BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLIX0))
477           .addReg(RISCV::X0, RegState::Define | RegState::Dead)
478           .addReg(RISCV::X0, RegState::Kill)
479           .addImm(Info.encodeVTYPE())
480           .addReg(RISCV::VL, RegState::Implicit);
481       return;
482     }
483     // Otherwise use an AVL of 0 to avoid depending on previous vl.
484     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
485         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
486         .addImm(0)
487         .addImm(Info.encodeVTYPE());
488     return;
489   }
490 
491   if (AVLReg.isVirtual())
492     MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
493 
494   // Use X0 as the DestReg unless AVLReg is X0. We also need to change the
495   // opcode if the AVLReg is X0 as they have different register classes for
496   // the AVL operand.
497   Register DestReg = RISCV::X0;
498   unsigned Opcode = RISCV::PseudoVSETVLI;
499   if (AVLReg == RISCV::X0) {
500     DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
501     Opcode = RISCV::PseudoVSETVLIX0;
502   }
503   BuildMI(MBB, MI, DL, TII->get(Opcode))
504       .addReg(DestReg, RegState::Define | RegState::Dead)
505       .addReg(AVLReg)
506       .addImm(Info.encodeVTYPE());
507 }
508 
509 // Return a VSETVLIInfo representing the changes made by this VSETVLI or
510 // VSETIVLI instruction.
511 static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
512   VSETVLIInfo NewInfo;
513   if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
514     NewInfo.setAVLImm(MI.getOperand(1).getImm());
515   } else {
516     assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
517            MI.getOpcode() == RISCV::PseudoVSETVLIX0);
518     Register AVLReg = MI.getOperand(1).getReg();
519     assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
520            "Can't handle X0, X0 vsetvli yet");
521     NewInfo.setAVLReg(AVLReg);
522   }
523   NewInfo.setVTYPE(MI.getOperand(2).getImm());
524 
525   return NewInfo;
526 }
527 
528 bool RISCVInsertVSETVLI::needVSETVLI(const VSETVLIInfo &Require,
529                                      const VSETVLIInfo &CurInfo) {
530   if (CurInfo.isCompatible(Require))
531     return false;
532 
533   // We didn't find a compatible value. If our AVL is a virtual register,
534   // it might be defined by a VSET(I)VLI. If it has the same VTYPE we need
535   // and the last VL/VTYPE we observed is the same, we don't need a
536   // VSETVLI here.
537   if (!CurInfo.isUnknown() && Require.hasAVLReg() &&
538       Require.getAVLReg().isVirtual() && !CurInfo.hasSEWLMULRatioOnly() &&
539       Require.hasSameVTYPE(CurInfo)) {
540     if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
541       if (DefMI->getOpcode() == RISCV::PseudoVSETVLI ||
542           DefMI->getOpcode() == RISCV::PseudoVSETVLIX0 ||
543           DefMI->getOpcode() == RISCV::PseudoVSETIVLI) {
544         VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
545         if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVTYPE(CurInfo))
546           return false;
547       }
548     }
549   }
550 
551   return true;
552 }
553 
554 bool canSkipVSETVLIForLoadStore(const MachineInstr &MI,
555                                 const VSETVLIInfo &Require,
556                                 const VSETVLIInfo &CurInfo) {
557   unsigned EEW;
558   switch (MI.getOpcode()) {
559   default:
560     return false;
561   case RISCV::PseudoVLE8_V_M1:
562   case RISCV::PseudoVLE8_V_M1_MASK:
563   case RISCV::PseudoVLE8_V_M2:
564   case RISCV::PseudoVLE8_V_M2_MASK:
565   case RISCV::PseudoVLE8_V_M4:
566   case RISCV::PseudoVLE8_V_M4_MASK:
567   case RISCV::PseudoVLE8_V_M8:
568   case RISCV::PseudoVLE8_V_M8_MASK:
569   case RISCV::PseudoVLE8_V_MF2:
570   case RISCV::PseudoVLE8_V_MF2_MASK:
571   case RISCV::PseudoVLE8_V_MF4:
572   case RISCV::PseudoVLE8_V_MF4_MASK:
573   case RISCV::PseudoVLE8_V_MF8:
574   case RISCV::PseudoVLE8_V_MF8_MASK:
575   case RISCV::PseudoVLSE8_V_M1:
576   case RISCV::PseudoVLSE8_V_M1_MASK:
577   case RISCV::PseudoVLSE8_V_M2:
578   case RISCV::PseudoVLSE8_V_M2_MASK:
579   case RISCV::PseudoVLSE8_V_M4:
580   case RISCV::PseudoVLSE8_V_M4_MASK:
581   case RISCV::PseudoVLSE8_V_M8:
582   case RISCV::PseudoVLSE8_V_M8_MASK:
583   case RISCV::PseudoVLSE8_V_MF2:
584   case RISCV::PseudoVLSE8_V_MF2_MASK:
585   case RISCV::PseudoVLSE8_V_MF4:
586   case RISCV::PseudoVLSE8_V_MF4_MASK:
587   case RISCV::PseudoVLSE8_V_MF8:
588   case RISCV::PseudoVLSE8_V_MF8_MASK:
589   case RISCV::PseudoVSE8_V_M1:
590   case RISCV::PseudoVSE8_V_M1_MASK:
591   case RISCV::PseudoVSE8_V_M2:
592   case RISCV::PseudoVSE8_V_M2_MASK:
593   case RISCV::PseudoVSE8_V_M4:
594   case RISCV::PseudoVSE8_V_M4_MASK:
595   case RISCV::PseudoVSE8_V_M8:
596   case RISCV::PseudoVSE8_V_M8_MASK:
597   case RISCV::PseudoVSE8_V_MF2:
598   case RISCV::PseudoVSE8_V_MF2_MASK:
599   case RISCV::PseudoVSE8_V_MF4:
600   case RISCV::PseudoVSE8_V_MF4_MASK:
601   case RISCV::PseudoVSE8_V_MF8:
602   case RISCV::PseudoVSE8_V_MF8_MASK:
603   case RISCV::PseudoVSSE8_V_M1:
604   case RISCV::PseudoVSSE8_V_M1_MASK:
605   case RISCV::PseudoVSSE8_V_M2:
606   case RISCV::PseudoVSSE8_V_M2_MASK:
607   case RISCV::PseudoVSSE8_V_M4:
608   case RISCV::PseudoVSSE8_V_M4_MASK:
609   case RISCV::PseudoVSSE8_V_M8:
610   case RISCV::PseudoVSSE8_V_M8_MASK:
611   case RISCV::PseudoVSSE8_V_MF2:
612   case RISCV::PseudoVSSE8_V_MF2_MASK:
613   case RISCV::PseudoVSSE8_V_MF4:
614   case RISCV::PseudoVSSE8_V_MF4_MASK:
615   case RISCV::PseudoVSSE8_V_MF8:
616   case RISCV::PseudoVSSE8_V_MF8_MASK:
617     EEW = 8;
618     break;
619   case RISCV::PseudoVLE16_V_M1:
620   case RISCV::PseudoVLE16_V_M1_MASK:
621   case RISCV::PseudoVLE16_V_M2:
622   case RISCV::PseudoVLE16_V_M2_MASK:
623   case RISCV::PseudoVLE16_V_M4:
624   case RISCV::PseudoVLE16_V_M4_MASK:
625   case RISCV::PseudoVLE16_V_M8:
626   case RISCV::PseudoVLE16_V_M8_MASK:
627   case RISCV::PseudoVLE16_V_MF2:
628   case RISCV::PseudoVLE16_V_MF2_MASK:
629   case RISCV::PseudoVLE16_V_MF4:
630   case RISCV::PseudoVLE16_V_MF4_MASK:
631   case RISCV::PseudoVLSE16_V_M1:
632   case RISCV::PseudoVLSE16_V_M1_MASK:
633   case RISCV::PseudoVLSE16_V_M2:
634   case RISCV::PseudoVLSE16_V_M2_MASK:
635   case RISCV::PseudoVLSE16_V_M4:
636   case RISCV::PseudoVLSE16_V_M4_MASK:
637   case RISCV::PseudoVLSE16_V_M8:
638   case RISCV::PseudoVLSE16_V_M8_MASK:
639   case RISCV::PseudoVLSE16_V_MF2:
640   case RISCV::PseudoVLSE16_V_MF2_MASK:
641   case RISCV::PseudoVLSE16_V_MF4:
642   case RISCV::PseudoVLSE16_V_MF4_MASK:
643   case RISCV::PseudoVSE16_V_M1:
644   case RISCV::PseudoVSE16_V_M1_MASK:
645   case RISCV::PseudoVSE16_V_M2:
646   case RISCV::PseudoVSE16_V_M2_MASK:
647   case RISCV::PseudoVSE16_V_M4:
648   case RISCV::PseudoVSE16_V_M4_MASK:
649   case RISCV::PseudoVSE16_V_M8:
650   case RISCV::PseudoVSE16_V_M8_MASK:
651   case RISCV::PseudoVSE16_V_MF2:
652   case RISCV::PseudoVSE16_V_MF2_MASK:
653   case RISCV::PseudoVSE16_V_MF4:
654   case RISCV::PseudoVSE16_V_MF4_MASK:
655   case RISCV::PseudoVSSE16_V_M1:
656   case RISCV::PseudoVSSE16_V_M1_MASK:
657   case RISCV::PseudoVSSE16_V_M2:
658   case RISCV::PseudoVSSE16_V_M2_MASK:
659   case RISCV::PseudoVSSE16_V_M4:
660   case RISCV::PseudoVSSE16_V_M4_MASK:
661   case RISCV::PseudoVSSE16_V_M8:
662   case RISCV::PseudoVSSE16_V_M8_MASK:
663   case RISCV::PseudoVSSE16_V_MF2:
664   case RISCV::PseudoVSSE16_V_MF2_MASK:
665   case RISCV::PseudoVSSE16_V_MF4:
666   case RISCV::PseudoVSSE16_V_MF4_MASK:
667     EEW = 16;
668     break;
669   case RISCV::PseudoVLE32_V_M1:
670   case RISCV::PseudoVLE32_V_M1_MASK:
671   case RISCV::PseudoVLE32_V_M2:
672   case RISCV::PseudoVLE32_V_M2_MASK:
673   case RISCV::PseudoVLE32_V_M4:
674   case RISCV::PseudoVLE32_V_M4_MASK:
675   case RISCV::PseudoVLE32_V_M8:
676   case RISCV::PseudoVLE32_V_M8_MASK:
677   case RISCV::PseudoVLE32_V_MF2:
678   case RISCV::PseudoVLE32_V_MF2_MASK:
679   case RISCV::PseudoVLSE32_V_M1:
680   case RISCV::PseudoVLSE32_V_M1_MASK:
681   case RISCV::PseudoVLSE32_V_M2:
682   case RISCV::PseudoVLSE32_V_M2_MASK:
683   case RISCV::PseudoVLSE32_V_M4:
684   case RISCV::PseudoVLSE32_V_M4_MASK:
685   case RISCV::PseudoVLSE32_V_M8:
686   case RISCV::PseudoVLSE32_V_M8_MASK:
687   case RISCV::PseudoVLSE32_V_MF2:
688   case RISCV::PseudoVLSE32_V_MF2_MASK:
689   case RISCV::PseudoVSE32_V_M1:
690   case RISCV::PseudoVSE32_V_M1_MASK:
691   case RISCV::PseudoVSE32_V_M2:
692   case RISCV::PseudoVSE32_V_M2_MASK:
693   case RISCV::PseudoVSE32_V_M4:
694   case RISCV::PseudoVSE32_V_M4_MASK:
695   case RISCV::PseudoVSE32_V_M8:
696   case RISCV::PseudoVSE32_V_M8_MASK:
697   case RISCV::PseudoVSE32_V_MF2:
698   case RISCV::PseudoVSE32_V_MF2_MASK:
699   case RISCV::PseudoVSSE32_V_M1:
700   case RISCV::PseudoVSSE32_V_M1_MASK:
701   case RISCV::PseudoVSSE32_V_M2:
702   case RISCV::PseudoVSSE32_V_M2_MASK:
703   case RISCV::PseudoVSSE32_V_M4:
704   case RISCV::PseudoVSSE32_V_M4_MASK:
705   case RISCV::PseudoVSSE32_V_M8:
706   case RISCV::PseudoVSSE32_V_M8_MASK:
707   case RISCV::PseudoVSSE32_V_MF2:
708   case RISCV::PseudoVSSE32_V_MF2_MASK:
709     EEW = 32;
710     break;
711   case RISCV::PseudoVLE64_V_M1:
712   case RISCV::PseudoVLE64_V_M1_MASK:
713   case RISCV::PseudoVLE64_V_M2:
714   case RISCV::PseudoVLE64_V_M2_MASK:
715   case RISCV::PseudoVLE64_V_M4:
716   case RISCV::PseudoVLE64_V_M4_MASK:
717   case RISCV::PseudoVLE64_V_M8:
718   case RISCV::PseudoVLE64_V_M8_MASK:
719   case RISCV::PseudoVLSE64_V_M1:
720   case RISCV::PseudoVLSE64_V_M1_MASK:
721   case RISCV::PseudoVLSE64_V_M2:
722   case RISCV::PseudoVLSE64_V_M2_MASK:
723   case RISCV::PseudoVLSE64_V_M4:
724   case RISCV::PseudoVLSE64_V_M4_MASK:
725   case RISCV::PseudoVLSE64_V_M8:
726   case RISCV::PseudoVLSE64_V_M8_MASK:
727   case RISCV::PseudoVSE64_V_M1:
728   case RISCV::PseudoVSE64_V_M1_MASK:
729   case RISCV::PseudoVSE64_V_M2:
730   case RISCV::PseudoVSE64_V_M2_MASK:
731   case RISCV::PseudoVSE64_V_M4:
732   case RISCV::PseudoVSE64_V_M4_MASK:
733   case RISCV::PseudoVSE64_V_M8:
734   case RISCV::PseudoVSE64_V_M8_MASK:
735   case RISCV::PseudoVSSE64_V_M1:
736   case RISCV::PseudoVSSE64_V_M1_MASK:
737   case RISCV::PseudoVSSE64_V_M2:
738   case RISCV::PseudoVSSE64_V_M2_MASK:
739   case RISCV::PseudoVSSE64_V_M4:
740   case RISCV::PseudoVSSE64_V_M4_MASK:
741   case RISCV::PseudoVSSE64_V_M8:
742   case RISCV::PseudoVSSE64_V_M8_MASK:
743     EEW = 64;
744     break;
745   }
746 
747   return CurInfo.isCompatibleWithLoadStoreEEW(EEW, Require);
748 }
749 
750 bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB) {
751   bool HadVectorOp = false;
752 
753   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
754   for (const MachineInstr &MI : MBB) {
755     // If this is an explicit VSETVLI or VSETIVLI, update our state.
756     if (MI.getOpcode() == RISCV::PseudoVSETVLI ||
757         MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
758         MI.getOpcode() == RISCV::PseudoVSETIVLI) {
759       HadVectorOp = true;
760       BBInfo.Change = getInfoForVSETVLI(MI);
761       continue;
762     }
763 
764     uint64_t TSFlags = MI.getDesc().TSFlags;
765     if (RISCVII::hasSEWOp(TSFlags)) {
766       HadVectorOp = true;
767 
768       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
769 
770       if (!BBInfo.Change.isValid()) {
771         BBInfo.Change = NewInfo;
772       } else {
773         // If this instruction isn't compatible with the previous VL/VTYPE
774         // we need to insert a VSETVLI.
775         // If this is a unit-stride or strided load/store, we may be able to use
776         // the EMUL=(EEW/SEW)*LMUL relationship to avoid changing vtype.
777         // NOTE: We only do this if the vtype we're comparing against was
778         // created in this block. We need the first and third phase to treat
779         // the store the same way.
780         if (!canSkipVSETVLIForLoadStore(MI, NewInfo, BBInfo.Change) &&
781             needVSETVLI(NewInfo, BBInfo.Change))
782           BBInfo.Change = NewInfo;
783       }
784     }
785 
786     // If this is something that updates VL/VTYPE that we don't know about, set
787     // the state to unknown.
788     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
789         MI.modifiesRegister(RISCV::VTYPE)) {
790       BBInfo.Change = VSETVLIInfo::getUnknown();
791     }
792   }
793 
794   // Initial exit state is whatever change we found in the block.
795   BBInfo.Exit = BBInfo.Change;
796 
797   return HadVectorOp;
798 }
799 
800 void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
801   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
802 
803   BBInfo.InQueue = false;
804 
805   VSETVLIInfo InInfo;
806   if (MBB.pred_empty()) {
807     // There are no predecessors, so use the default starting status.
808     InInfo.setUnknown();
809   } else {
810     for (MachineBasicBlock *P : MBB.predecessors())
811       InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
812   }
813 
814   // If we don't have any valid predecessor value, wait until we do.
815   if (!InInfo.isValid())
816     return;
817 
818   BBInfo.Pred = InInfo;
819 
820   VSETVLIInfo TmpStatus = BBInfo.Pred.merge(BBInfo.Change);
821 
822   // If the new exit value matches the old exit value, we don't need to revisit
823   // any blocks.
824   if (BBInfo.Exit == TmpStatus)
825     return;
826 
827   BBInfo.Exit = TmpStatus;
828 
829   // Add the successors to the work list so we can propagate the changed exit
830   // status.
831   for (MachineBasicBlock *S : MBB.successors())
832     if (!BlockInfo[S->getNumber()].InQueue)
833       WorkList.push(S);
834 }
835 
836 // If we weren't able to prove a vsetvli was directly unneeded, it might still
837 // be/ unneeded if the AVL is a phi node where all incoming values are VL
838 // outputs from the last VSETVLI in their respective basic blocks.
839 bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
840                                         const MachineBasicBlock &MBB) {
841   if (DisableInsertVSETVLPHIOpt)
842     return true;
843 
844   if (!Require.hasAVLReg())
845     return true;
846 
847   Register AVLReg = Require.getAVLReg();
848   if (!AVLReg.isVirtual())
849     return true;
850 
851   // We need the AVL to be produce by a PHI node in this basic block.
852   MachineInstr *PHI = MRI->getVRegDef(AVLReg);
853   if (!PHI || PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
854     return true;
855 
856   for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
857        PHIOp += 2) {
858     Register InReg = PHI->getOperand(PHIOp).getReg();
859     MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
860     const BlockData &PBBInfo = BlockInfo[PBB->getNumber()];
861     // If the exit from the predecessor has the VTYPE we are looking for
862     // we might be able to avoid a VSETVLI.
863     if (PBBInfo.Exit.isUnknown() || !PBBInfo.Exit.hasSameVTYPE(Require))
864       return true;
865 
866     // We need the PHI input to the be the output of a VSET(I)VLI.
867     MachineInstr *DefMI = MRI->getVRegDef(InReg);
868     if (!DefMI || (DefMI->getOpcode() != RISCV::PseudoVSETVLI &&
869                    DefMI->getOpcode() != RISCV::PseudoVSETVLIX0 &&
870                    DefMI->getOpcode() != RISCV::PseudoVSETIVLI))
871       return true;
872 
873     // We found a VSET(I)VLI make sure it matches the output of the
874     // predecessor block.
875     VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
876     if (!DefInfo.hasSameAVL(PBBInfo.Exit) ||
877         !DefInfo.hasSameVTYPE(PBBInfo.Exit))
878       return true;
879   }
880 
881   // If all the incoming values to the PHI checked out, we don't need
882   // to insert a VSETVLI.
883   return false;
884 }
885 
886 void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
887   VSETVLIInfo CurInfo;
888   // Only be set if current VSETVLIInfo is from an explicit VSET(I)VLI.
889   MachineInstr *PrevVSETVLIMI = nullptr;
890 
891   for (MachineInstr &MI : MBB) {
892     // If this is an explicit VSETVLI or VSETIVLI, update our state.
893     if (MI.getOpcode() == RISCV::PseudoVSETVLI ||
894         MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
895         MI.getOpcode() == RISCV::PseudoVSETIVLI) {
896       // Conservatively, mark the VL and VTYPE as live.
897       assert(MI.getOperand(3).getReg() == RISCV::VL &&
898              MI.getOperand(4).getReg() == RISCV::VTYPE &&
899              "Unexpected operands where VL and VTYPE should be");
900       MI.getOperand(3).setIsDead(false);
901       MI.getOperand(4).setIsDead(false);
902       CurInfo = getInfoForVSETVLI(MI);
903       PrevVSETVLIMI = &MI;
904       continue;
905     }
906 
907     uint64_t TSFlags = MI.getDesc().TSFlags;
908     if (RISCVII::hasSEWOp(TSFlags)) {
909       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
910       if (RISCVII::hasVLOp(TSFlags)) {
911         MachineOperand &VLOp = MI.getOperand(MI.getNumExplicitOperands() - 2);
912         if (VLOp.isReg()) {
913           // Erase the AVL operand from the instruction.
914           VLOp.setReg(RISCV::NoRegister);
915           VLOp.setIsKill(false);
916         }
917         MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
918                                                 /*isImp*/ true));
919       }
920       MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
921                                               /*isImp*/ true));
922 
923       if (!CurInfo.isValid()) {
924         // We haven't found any vector instructions or VL/VTYPE changes yet,
925         // use the predecessor information.
926         assert(BlockInfo[MBB.getNumber()].Pred.isValid() &&
927                "Expected a valid predecessor state.");
928         if (needVSETVLI(NewInfo, BlockInfo[MBB.getNumber()].Pred) &&
929             needVSETVLIPHI(NewInfo, MBB)) {
930           insertVSETVLI(MBB, MI, NewInfo, BlockInfo[MBB.getNumber()].Pred);
931           CurInfo = NewInfo;
932         }
933       } else {
934         // If this instruction isn't compatible with the previous VL/VTYPE
935         // we need to insert a VSETVLI.
936         // If this is a unit-stride or strided load/store, we may be able to use
937         // the EMUL=(EEW/SEW)*LMUL relationship to avoid changing vtype.
938         // NOTE: We can't use predecessor information for the store. We must
939         // treat it the same as the first phase so that we produce the correct
940         // vl/vtype for succesor blocks.
941         if (!canSkipVSETVLIForLoadStore(MI, NewInfo, CurInfo) &&
942             needVSETVLI(NewInfo, CurInfo)) {
943           // If the previous VL/VTYPE is set by VSETVLI and do not use, Merge it
944           // with current VL/VTYPE.
945           bool NeedInsertVSETVLI = true;
946           if (PrevVSETVLIMI) {
947             bool HasSameAVL =
948                 CurInfo.hasSameAVL(NewInfo) ||
949                 (NewInfo.hasAVLReg() && NewInfo.getAVLReg().isVirtual() &&
950                  NewInfo.getAVLReg() == PrevVSETVLIMI->getOperand(0).getReg());
951             // If these two VSETVLI have the same AVL and the same VLMAX,
952             // we could merge these two VSETVLI.
953             if (HasSameAVL &&
954                 CurInfo.getSEWLMULRatio() == NewInfo.getSEWLMULRatio()) {
955               PrevVSETVLIMI->getOperand(2).setImm(NewInfo.encodeVTYPE());
956               NeedInsertVSETVLI = false;
957             }
958           }
959           if (NeedInsertVSETVLI)
960             insertVSETVLI(MBB, MI, NewInfo, CurInfo);
961           CurInfo = NewInfo;
962         }
963       }
964       PrevVSETVLIMI = nullptr;
965     }
966 
967     // If this is something updates VL/VTYPE that we don't know about, set
968     // the state to unknown.
969     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
970         MI.modifiesRegister(RISCV::VTYPE)) {
971       CurInfo = VSETVLIInfo::getUnknown();
972       PrevVSETVLIMI = nullptr;
973     }
974   }
975 }
976 
977 bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
978   // Skip if the vector extension is not enabled.
979   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
980   if (!ST.hasStdExtV())
981     return false;
982 
983   TII = ST.getInstrInfo();
984   MRI = &MF.getRegInfo();
985 
986   assert(BlockInfo.empty() && "Expect empty block infos");
987   BlockInfo.resize(MF.getNumBlockIDs());
988 
989   bool HaveVectorOp = false;
990 
991   // Phase 1 - determine how VL/VTYPE are affected by the each block.
992   for (const MachineBasicBlock &MBB : MF)
993     HaveVectorOp |= computeVLVTYPEChanges(MBB);
994 
995   // If we didn't find any instructions that need VSETVLI, we're done.
996   if (HaveVectorOp) {
997     // Phase 2 - determine the exit VL/VTYPE from each block. We add all
998     // blocks to the list here, but will also add any that need to be revisited
999     // during Phase 2 processing.
1000     for (const MachineBasicBlock &MBB : MF) {
1001       WorkList.push(&MBB);
1002       BlockInfo[MBB.getNumber()].InQueue = true;
1003     }
1004     while (!WorkList.empty()) {
1005       const MachineBasicBlock &MBB = *WorkList.front();
1006       WorkList.pop();
1007       computeIncomingVLVTYPE(MBB);
1008     }
1009 
1010     // Phase 3 - add any vsetvli instructions needed in the block. Use the
1011     // Phase 2 information to avoid adding vsetvlis before the first vector
1012     // instruction in the block if the VL/VTYPE is satisfied by its
1013     // predecessors.
1014     for (MachineBasicBlock &MBB : MF)
1015       emitVSETVLIs(MBB);
1016   }
1017 
1018   BlockInfo.clear();
1019 
1020   return HaveVectorOp;
1021 }
1022 
1023 /// Returns an instance of the Insert VSETVLI pass.
1024 FunctionPass *llvm::createRISCVInsertVSETVLIPass() {
1025   return new RISCVInsertVSETVLI();
1026 }
1027