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