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