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