1 //===- RISCVInsertVSETVLI.cpp - Insert VSETVLI instructions ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a function pass that inserts VSETVLI instructions where
10 // needed and expands the vl outputs of VLEFF/VLSEGFF to PseudoReadVL
11 // instructions.
12 //
13 // This pass consists of 3 phases:
14 //
15 // Phase 1 collects how each basic block affects VL/VTYPE.
16 //
17 // Phase 2 uses the information from phase 1 to do a data flow analysis to
18 // propagate the VL/VTYPE changes through the function. This gives us the
19 // VL/VTYPE at the start of each basic block.
20 //
21 // Phase 3 inserts VSETVLI instructions in each basic block. Information from
22 // phase 2 is used to prevent inserting a VSETVLI before the first vector
23 // instruction in the block if possible.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "RISCV.h"
28 #include "RISCVSubtarget.h"
29 #include "llvm/CodeGen/LiveIntervals.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include <queue>
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "riscv-insert-vsetvli"
35 #define RISCV_INSERT_VSETVLI_NAME "RISCV Insert VSETVLI pass"
36 
37 static cl::opt<bool> DisableInsertVSETVLPHIOpt(
38     "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
39     cl::desc("Disable looking through phis when inserting vsetvlis."));
40 
41 static cl::opt<bool> UseStrictAsserts(
42     "riscv-insert-vsetvl-strict-asserts", cl::init(true), cl::Hidden,
43     cl::desc("Enable strict assertion checking for the dataflow algorithm"));
44 
45 namespace {
46 
47 static unsigned getVLOpNum(const MachineInstr &MI) {
48   return RISCVII::getVLOpNum(MI.getDesc());
49 }
50 
51 static unsigned getSEWOpNum(const MachineInstr &MI) {
52   return RISCVII::getSEWOpNum(MI.getDesc());
53 }
54 
55 static bool isScalarMoveInstr(const MachineInstr &MI) {
56   switch (MI.getOpcode()) {
57   default:
58     return false;
59   case RISCV::PseudoVMV_S_X_M1:
60   case RISCV::PseudoVMV_S_X_M2:
61   case RISCV::PseudoVMV_S_X_M4:
62   case RISCV::PseudoVMV_S_X_M8:
63   case RISCV::PseudoVMV_S_X_MF2:
64   case RISCV::PseudoVMV_S_X_MF4:
65   case RISCV::PseudoVMV_S_X_MF8:
66   case RISCV::PseudoVFMV_S_F16_M1:
67   case RISCV::PseudoVFMV_S_F16_M2:
68   case RISCV::PseudoVFMV_S_F16_M4:
69   case RISCV::PseudoVFMV_S_F16_M8:
70   case RISCV::PseudoVFMV_S_F16_MF2:
71   case RISCV::PseudoVFMV_S_F16_MF4:
72   case RISCV::PseudoVFMV_S_F32_M1:
73   case RISCV::PseudoVFMV_S_F32_M2:
74   case RISCV::PseudoVFMV_S_F32_M4:
75   case RISCV::PseudoVFMV_S_F32_M8:
76   case RISCV::PseudoVFMV_S_F32_MF2:
77   case RISCV::PseudoVFMV_S_F64_M1:
78   case RISCV::PseudoVFMV_S_F64_M2:
79   case RISCV::PseudoVFMV_S_F64_M4:
80   case RISCV::PseudoVFMV_S_F64_M8:
81     return true;
82   }
83 }
84 
85 /// Get the EEW for a load or store instruction.  Return None if MI is not
86 /// a load or store which ignores SEW.
87 static Optional<unsigned> getEEWForLoadStore(const MachineInstr &MI) {
88   switch (MI.getOpcode()) {
89   default:
90     return None;
91   case RISCV::PseudoVLE8_V_M1:
92   case RISCV::PseudoVLE8_V_M1_MASK:
93   case RISCV::PseudoVLE8_V_M2:
94   case RISCV::PseudoVLE8_V_M2_MASK:
95   case RISCV::PseudoVLE8_V_M4:
96   case RISCV::PseudoVLE8_V_M4_MASK:
97   case RISCV::PseudoVLE8_V_M8:
98   case RISCV::PseudoVLE8_V_M8_MASK:
99   case RISCV::PseudoVLE8_V_MF2:
100   case RISCV::PseudoVLE8_V_MF2_MASK:
101   case RISCV::PseudoVLE8_V_MF4:
102   case RISCV::PseudoVLE8_V_MF4_MASK:
103   case RISCV::PseudoVLE8_V_MF8:
104   case RISCV::PseudoVLE8_V_MF8_MASK:
105   case RISCV::PseudoVLSE8_V_M1:
106   case RISCV::PseudoVLSE8_V_M1_MASK:
107   case RISCV::PseudoVLSE8_V_M2:
108   case RISCV::PseudoVLSE8_V_M2_MASK:
109   case RISCV::PseudoVLSE8_V_M4:
110   case RISCV::PseudoVLSE8_V_M4_MASK:
111   case RISCV::PseudoVLSE8_V_M8:
112   case RISCV::PseudoVLSE8_V_M8_MASK:
113   case RISCV::PseudoVLSE8_V_MF2:
114   case RISCV::PseudoVLSE8_V_MF2_MASK:
115   case RISCV::PseudoVLSE8_V_MF4:
116   case RISCV::PseudoVLSE8_V_MF4_MASK:
117   case RISCV::PseudoVLSE8_V_MF8:
118   case RISCV::PseudoVLSE8_V_MF8_MASK:
119   case RISCV::PseudoVSE8_V_M1:
120   case RISCV::PseudoVSE8_V_M1_MASK:
121   case RISCV::PseudoVSE8_V_M2:
122   case RISCV::PseudoVSE8_V_M2_MASK:
123   case RISCV::PseudoVSE8_V_M4:
124   case RISCV::PseudoVSE8_V_M4_MASK:
125   case RISCV::PseudoVSE8_V_M8:
126   case RISCV::PseudoVSE8_V_M8_MASK:
127   case RISCV::PseudoVSE8_V_MF2:
128   case RISCV::PseudoVSE8_V_MF2_MASK:
129   case RISCV::PseudoVSE8_V_MF4:
130   case RISCV::PseudoVSE8_V_MF4_MASK:
131   case RISCV::PseudoVSE8_V_MF8:
132   case RISCV::PseudoVSE8_V_MF8_MASK:
133   case RISCV::PseudoVSSE8_V_M1:
134   case RISCV::PseudoVSSE8_V_M1_MASK:
135   case RISCV::PseudoVSSE8_V_M2:
136   case RISCV::PseudoVSSE8_V_M2_MASK:
137   case RISCV::PseudoVSSE8_V_M4:
138   case RISCV::PseudoVSSE8_V_M4_MASK:
139   case RISCV::PseudoVSSE8_V_M8:
140   case RISCV::PseudoVSSE8_V_M8_MASK:
141   case RISCV::PseudoVSSE8_V_MF2:
142   case RISCV::PseudoVSSE8_V_MF2_MASK:
143   case RISCV::PseudoVSSE8_V_MF4:
144   case RISCV::PseudoVSSE8_V_MF4_MASK:
145   case RISCV::PseudoVSSE8_V_MF8:
146   case RISCV::PseudoVSSE8_V_MF8_MASK:
147     return 8;
148   case RISCV::PseudoVLE16_V_M1:
149   case RISCV::PseudoVLE16_V_M1_MASK:
150   case RISCV::PseudoVLE16_V_M2:
151   case RISCV::PseudoVLE16_V_M2_MASK:
152   case RISCV::PseudoVLE16_V_M4:
153   case RISCV::PseudoVLE16_V_M4_MASK:
154   case RISCV::PseudoVLE16_V_M8:
155   case RISCV::PseudoVLE16_V_M8_MASK:
156   case RISCV::PseudoVLE16_V_MF2:
157   case RISCV::PseudoVLE16_V_MF2_MASK:
158   case RISCV::PseudoVLE16_V_MF4:
159   case RISCV::PseudoVLE16_V_MF4_MASK:
160   case RISCV::PseudoVLSE16_V_M1:
161   case RISCV::PseudoVLSE16_V_M1_MASK:
162   case RISCV::PseudoVLSE16_V_M2:
163   case RISCV::PseudoVLSE16_V_M2_MASK:
164   case RISCV::PseudoVLSE16_V_M4:
165   case RISCV::PseudoVLSE16_V_M4_MASK:
166   case RISCV::PseudoVLSE16_V_M8:
167   case RISCV::PseudoVLSE16_V_M8_MASK:
168   case RISCV::PseudoVLSE16_V_MF2:
169   case RISCV::PseudoVLSE16_V_MF2_MASK:
170   case RISCV::PseudoVLSE16_V_MF4:
171   case RISCV::PseudoVLSE16_V_MF4_MASK:
172   case RISCV::PseudoVSE16_V_M1:
173   case RISCV::PseudoVSE16_V_M1_MASK:
174   case RISCV::PseudoVSE16_V_M2:
175   case RISCV::PseudoVSE16_V_M2_MASK:
176   case RISCV::PseudoVSE16_V_M4:
177   case RISCV::PseudoVSE16_V_M4_MASK:
178   case RISCV::PseudoVSE16_V_M8:
179   case RISCV::PseudoVSE16_V_M8_MASK:
180   case RISCV::PseudoVSE16_V_MF2:
181   case RISCV::PseudoVSE16_V_MF2_MASK:
182   case RISCV::PseudoVSE16_V_MF4:
183   case RISCV::PseudoVSE16_V_MF4_MASK:
184   case RISCV::PseudoVSSE16_V_M1:
185   case RISCV::PseudoVSSE16_V_M1_MASK:
186   case RISCV::PseudoVSSE16_V_M2:
187   case RISCV::PseudoVSSE16_V_M2_MASK:
188   case RISCV::PseudoVSSE16_V_M4:
189   case RISCV::PseudoVSSE16_V_M4_MASK:
190   case RISCV::PseudoVSSE16_V_M8:
191   case RISCV::PseudoVSSE16_V_M8_MASK:
192   case RISCV::PseudoVSSE16_V_MF2:
193   case RISCV::PseudoVSSE16_V_MF2_MASK:
194   case RISCV::PseudoVSSE16_V_MF4:
195   case RISCV::PseudoVSSE16_V_MF4_MASK:
196     return 16;
197   case RISCV::PseudoVLE32_V_M1:
198   case RISCV::PseudoVLE32_V_M1_MASK:
199   case RISCV::PseudoVLE32_V_M2:
200   case RISCV::PseudoVLE32_V_M2_MASK:
201   case RISCV::PseudoVLE32_V_M4:
202   case RISCV::PseudoVLE32_V_M4_MASK:
203   case RISCV::PseudoVLE32_V_M8:
204   case RISCV::PseudoVLE32_V_M8_MASK:
205   case RISCV::PseudoVLE32_V_MF2:
206   case RISCV::PseudoVLE32_V_MF2_MASK:
207   case RISCV::PseudoVLSE32_V_M1:
208   case RISCV::PseudoVLSE32_V_M1_MASK:
209   case RISCV::PseudoVLSE32_V_M2:
210   case RISCV::PseudoVLSE32_V_M2_MASK:
211   case RISCV::PseudoVLSE32_V_M4:
212   case RISCV::PseudoVLSE32_V_M4_MASK:
213   case RISCV::PseudoVLSE32_V_M8:
214   case RISCV::PseudoVLSE32_V_M8_MASK:
215   case RISCV::PseudoVLSE32_V_MF2:
216   case RISCV::PseudoVLSE32_V_MF2_MASK:
217   case RISCV::PseudoVSE32_V_M1:
218   case RISCV::PseudoVSE32_V_M1_MASK:
219   case RISCV::PseudoVSE32_V_M2:
220   case RISCV::PseudoVSE32_V_M2_MASK:
221   case RISCV::PseudoVSE32_V_M4:
222   case RISCV::PseudoVSE32_V_M4_MASK:
223   case RISCV::PseudoVSE32_V_M8:
224   case RISCV::PseudoVSE32_V_M8_MASK:
225   case RISCV::PseudoVSE32_V_MF2:
226   case RISCV::PseudoVSE32_V_MF2_MASK:
227   case RISCV::PseudoVSSE32_V_M1:
228   case RISCV::PseudoVSSE32_V_M1_MASK:
229   case RISCV::PseudoVSSE32_V_M2:
230   case RISCV::PseudoVSSE32_V_M2_MASK:
231   case RISCV::PseudoVSSE32_V_M4:
232   case RISCV::PseudoVSSE32_V_M4_MASK:
233   case RISCV::PseudoVSSE32_V_M8:
234   case RISCV::PseudoVSSE32_V_M8_MASK:
235   case RISCV::PseudoVSSE32_V_MF2:
236   case RISCV::PseudoVSSE32_V_MF2_MASK:
237     return 32;
238   case RISCV::PseudoVLE64_V_M1:
239   case RISCV::PseudoVLE64_V_M1_MASK:
240   case RISCV::PseudoVLE64_V_M2:
241   case RISCV::PseudoVLE64_V_M2_MASK:
242   case RISCV::PseudoVLE64_V_M4:
243   case RISCV::PseudoVLE64_V_M4_MASK:
244   case RISCV::PseudoVLE64_V_M8:
245   case RISCV::PseudoVLE64_V_M8_MASK:
246   case RISCV::PseudoVLSE64_V_M1:
247   case RISCV::PseudoVLSE64_V_M1_MASK:
248   case RISCV::PseudoVLSE64_V_M2:
249   case RISCV::PseudoVLSE64_V_M2_MASK:
250   case RISCV::PseudoVLSE64_V_M4:
251   case RISCV::PseudoVLSE64_V_M4_MASK:
252   case RISCV::PseudoVLSE64_V_M8:
253   case RISCV::PseudoVLSE64_V_M8_MASK:
254   case RISCV::PseudoVSE64_V_M1:
255   case RISCV::PseudoVSE64_V_M1_MASK:
256   case RISCV::PseudoVSE64_V_M2:
257   case RISCV::PseudoVSE64_V_M2_MASK:
258   case RISCV::PseudoVSE64_V_M4:
259   case RISCV::PseudoVSE64_V_M4_MASK:
260   case RISCV::PseudoVSE64_V_M8:
261   case RISCV::PseudoVSE64_V_M8_MASK:
262   case RISCV::PseudoVSSE64_V_M1:
263   case RISCV::PseudoVSSE64_V_M1_MASK:
264   case RISCV::PseudoVSSE64_V_M2:
265   case RISCV::PseudoVSSE64_V_M2_MASK:
266   case RISCV::PseudoVSSE64_V_M4:
267   case RISCV::PseudoVSSE64_V_M4_MASK:
268   case RISCV::PseudoVSSE64_V_M8:
269   case RISCV::PseudoVSSE64_V_M8_MASK:
270     return 64;
271   }
272 }
273 
274 static unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul) {
275   unsigned LMul;
276   bool Fractional;
277   std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(VLMul);
278 
279   // Convert LMul to a fixed point value with 3 fractional bits.
280   LMul = Fractional ? (8 / LMul) : (LMul * 8);
281 
282   assert(SEW >= 8 && "Unexpected SEW value");
283   return (SEW * 8) / LMul;
284 }
285 
286 /// Which subfields of VL or VTYPE have values we need to preserve?
287 struct DemandedFields {
288   bool VL = false;
289   bool SEW = false;
290   bool LMUL = false;
291   bool SEWLMULRatio = false;
292   bool TailPolicy = false;
293   bool MaskPolicy = false;
294 
295   // Return true if any part of VTYPE was used
296   bool usedVTYPE() {
297     return SEW || LMUL || SEWLMULRatio || TailPolicy || MaskPolicy;
298   }
299 
300   // Mark all VTYPE subfields and properties as demanded
301   void demandVTYPE() {
302     SEW = true;
303     LMUL = true;
304     SEWLMULRatio = true;
305     TailPolicy = true;
306     MaskPolicy = true;
307   }
308 };
309 
310 /// Return true if the two values of the VTYPE register provided are
311 /// indistinguishable from the perspective of an instruction (or set of
312 /// instructions) which use only the Used subfields and properties.
313 static bool areCompatibleVTYPEs(uint64_t VType1,
314                                 uint64_t VType2,
315                                 const DemandedFields &Used) {
316   if (Used.SEW &&
317       RISCVVType::getSEW(VType1) != RISCVVType::getSEW(VType2))
318     return false;
319 
320   if (Used.LMUL &&
321       RISCVVType::getVLMUL(VType1) != RISCVVType::getVLMUL(VType2))
322     return false;
323 
324   if (Used.SEWLMULRatio) {
325     auto Ratio1 = getSEWLMULRatio(RISCVVType::getSEW(VType1),
326                                   RISCVVType::getVLMUL(VType1));
327     auto Ratio2 = getSEWLMULRatio(RISCVVType::getSEW(VType2),
328                                   RISCVVType::getVLMUL(VType2));
329     if (Ratio1 != Ratio2)
330       return false;
331   }
332 
333   if (Used.TailPolicy &&
334       RISCVVType::isTailAgnostic(VType1) != RISCVVType::isTailAgnostic(VType2))
335     return false;
336   if (Used.MaskPolicy &&
337       RISCVVType::isMaskAgnostic(VType1) != RISCVVType::isMaskAgnostic(VType2))
338     return false;
339   return true;
340 }
341 
342 /// Return the fields and properties demanded by the provided instruction.
343 static DemandedFields getDemanded(const MachineInstr &MI) {
344   // Warning: This function has to work on both the lowered (i.e. post
345   // emitVSETVLIs) and pre-lowering forms.  The main implication of this is
346   // that it can't use the value of a SEW, VL, or Policy operand as they might
347   // be stale after lowering.
348 
349   // Most instructions don't use any of these subfeilds.
350   DemandedFields Res;
351   // Start conservative if registers are used
352   if (MI.isCall() || MI.isInlineAsm() || MI.readsRegister(RISCV::VL))
353     Res.VL = true;
354   if (MI.isCall() || MI.isInlineAsm() || MI.readsRegister(RISCV::VTYPE))
355     Res.demandVTYPE();
356   // Start conservative on the unlowered form too
357   uint64_t TSFlags = MI.getDesc().TSFlags;
358   if (RISCVII::hasSEWOp(TSFlags)) {
359     Res.demandVTYPE();
360     if (RISCVII::hasVLOp(TSFlags))
361       Res.VL = true;
362   }
363 
364   // Loads and stores with implicit EEW do not demand SEW or LMUL directly.
365   // They instead demand the ratio of the two which is used in computing
366   // EMUL, but which allows us the flexibility to change SEW and LMUL
367   // provided we don't change the ratio.
368   if (getEEWForLoadStore(MI)) {
369     Res.SEW = false;
370     Res.LMUL = false;
371   }
372 
373   return Res;
374 }
375 
376 /// Defines the abstract state with which the forward dataflow models the
377 /// values of the VL and VTYPE registers after insertion.
378 class VSETVLIInfo {
379   union {
380     Register AVLReg;
381     unsigned AVLImm;
382   };
383 
384   enum : uint8_t {
385     Uninitialized,
386     AVLIsReg,
387     AVLIsImm,
388     Unknown,
389   } State = Uninitialized;
390 
391   // Fields from VTYPE.
392   RISCVII::VLMUL VLMul = RISCVII::LMUL_1;
393   uint8_t SEW = 0;
394   uint8_t TailAgnostic : 1;
395   uint8_t MaskAgnostic : 1;
396   uint8_t SEWLMULRatioOnly : 1;
397 
398 public:
399   VSETVLIInfo()
400       : AVLImm(0), TailAgnostic(false), MaskAgnostic(false),
401         SEWLMULRatioOnly(false) {}
402 
403   static VSETVLIInfo getUnknown() {
404     VSETVLIInfo Info;
405     Info.setUnknown();
406     return Info;
407   }
408 
409   bool isValid() const { return State != Uninitialized; }
410   void setUnknown() { State = Unknown; }
411   bool isUnknown() const { return State == Unknown; }
412 
413   void setAVLReg(Register Reg) {
414     AVLReg = Reg;
415     State = AVLIsReg;
416   }
417 
418   void setAVLImm(unsigned Imm) {
419     AVLImm = Imm;
420     State = AVLIsImm;
421   }
422 
423   bool hasAVLImm() const { return State == AVLIsImm; }
424   bool hasAVLReg() const { return State == AVLIsReg; }
425   Register getAVLReg() const {
426     assert(hasAVLReg());
427     return AVLReg;
428   }
429   unsigned getAVLImm() const {
430     assert(hasAVLImm());
431     return AVLImm;
432   }
433 
434   unsigned getSEW() const { return SEW; }
435   RISCVII::VLMUL getVLMUL() const { return VLMul; }
436 
437   bool hasZeroAVL() const {
438     if (hasAVLImm())
439       return getAVLImm() == 0;
440     return false;
441   }
442   bool hasNonZeroAVL() const {
443     if (hasAVLImm())
444       return getAVLImm() > 0;
445     if (hasAVLReg())
446       return getAVLReg() == RISCV::X0;
447     return false;
448   }
449 
450   bool hasSameAVL(const VSETVLIInfo &Other) const {
451     assert(isValid() && Other.isValid() &&
452            "Can't compare invalid VSETVLIInfos");
453     assert(!isUnknown() && !Other.isUnknown() &&
454            "Can't compare AVL in unknown state");
455     if (hasAVLReg() && Other.hasAVLReg())
456       return getAVLReg() == Other.getAVLReg();
457 
458     if (hasAVLImm() && Other.hasAVLImm())
459       return getAVLImm() == Other.getAVLImm();
460 
461     return false;
462   }
463 
464   void setVTYPE(unsigned VType) {
465     assert(isValid() && !isUnknown() &&
466            "Can't set VTYPE for uninitialized or unknown");
467     VLMul = RISCVVType::getVLMUL(VType);
468     SEW = RISCVVType::getSEW(VType);
469     TailAgnostic = RISCVVType::isTailAgnostic(VType);
470     MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
471   }
472   void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA) {
473     assert(isValid() && !isUnknown() &&
474            "Can't set VTYPE for uninitialized or unknown");
475     VLMul = L;
476     SEW = S;
477     TailAgnostic = TA;
478     MaskAgnostic = MA;
479   }
480 
481   unsigned encodeVTYPE() const {
482     assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
483            "Can't encode VTYPE for uninitialized or unknown");
484     return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
485   }
486 
487   bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
488 
489   bool hasSameSEW(const VSETVLIInfo &Other) const {
490     assert(isValid() && Other.isValid() &&
491            "Can't compare invalid VSETVLIInfos");
492     assert(!isUnknown() && !Other.isUnknown() &&
493            "Can't compare VTYPE in unknown state");
494     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
495            "Can't compare when only LMUL/SEW ratio is valid.");
496     return SEW == Other.SEW;
497   }
498 
499   bool hasSameVTYPE(const VSETVLIInfo &Other) const {
500     assert(isValid() && Other.isValid() &&
501            "Can't compare invalid VSETVLIInfos");
502     assert(!isUnknown() && !Other.isUnknown() &&
503            "Can't compare VTYPE in unknown state");
504     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
505            "Can't compare when only LMUL/SEW ratio is valid.");
506     return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
507            std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
508                     Other.MaskAgnostic);
509   }
510 
511   unsigned getSEWLMULRatio() const {
512     assert(isValid() && !isUnknown() &&
513            "Can't use VTYPE for uninitialized or unknown");
514     return ::getSEWLMULRatio(SEW, VLMul);
515   }
516 
517   // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
518   // Note that having the same VLMAX ensures that both share the same
519   // function from AVL to VL; that is, they must produce the same VL value
520   // for any given AVL value.
521   bool hasSameVLMAX(const VSETVLIInfo &Other) const {
522     assert(isValid() && Other.isValid() &&
523            "Can't compare invalid VSETVLIInfos");
524     assert(!isUnknown() && !Other.isUnknown() &&
525            "Can't compare VTYPE in unknown state");
526     return getSEWLMULRatio() == Other.getSEWLMULRatio();
527   }
528 
529   bool hasSamePolicy(const VSETVLIInfo &Other) const {
530     assert(isValid() && Other.isValid() &&
531            "Can't compare invalid VSETVLIInfos");
532     assert(!isUnknown() && !Other.isUnknown() &&
533            "Can't compare VTYPE in unknown state");
534     return TailAgnostic == Other.TailAgnostic &&
535            MaskAgnostic == Other.MaskAgnostic;
536   }
537 
538   bool hasCompatibleVTYPE(const MachineInstr &MI,
539                           const VSETVLIInfo &Require) const {
540     // Simple case, see if full VTYPE matches.
541     if (hasSameVTYPE(Require))
542       return true;
543 
544     // If this is a mask reg operation, it only cares about VLMAX.
545     // FIXME: Mask reg operations are probably ok if "this" VLMAX is larger
546     // than "Require".
547     // FIXME: The policy bits can probably be ignored for mask reg operations.
548     const unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
549     // A Log2SEW of 0 is an operation on mask registers only.
550     const bool MaskRegOp = Log2SEW == 0;
551     if (MaskRegOp && hasSameVLMAX(Require) &&
552         TailAgnostic == Require.TailAgnostic &&
553         MaskAgnostic == Require.MaskAgnostic)
554       return true;
555 
556     DemandedFields Used = getDemanded(MI);
557     // Store instructions don't use the policy fields.
558     // TODO: Move this into getDemanded; it is here only to avoid changing
559     // behavior of the post pass in an otherwise NFC code restructure.
560     uint64_t TSFlags = MI.getDesc().TSFlags;
561     if (RISCVII::hasSEWOp(TSFlags) && MI.getNumExplicitDefs() == 0) {
562       Used.TailPolicy = false;
563       Used.MaskPolicy = false;
564     }
565     return areCompatibleVTYPEs(encodeVTYPE(), Require.encodeVTYPE(), Used);
566   }
567 
568   // Determine whether the vector instructions requirements represented by
569   // Require are compatible with the previous vsetvli instruction represented
570   // by this.  MI is the instruction whose requirements we're considering.
571   bool isCompatible(const MachineInstr &MI, const VSETVLIInfo &Require) const {
572     assert(isValid() && Require.isValid() &&
573            "Can't compare invalid VSETVLIInfos");
574     assert(!Require.SEWLMULRatioOnly &&
575            "Expected a valid VTYPE for instruction!");
576     // Nothing is compatible with Unknown.
577     if (isUnknown() || Require.isUnknown())
578       return false;
579 
580     // If only our VLMAX ratio is valid, then this isn't compatible.
581     if (SEWLMULRatioOnly)
582       return false;
583 
584     // If the instruction doesn't need an AVLReg and the SEW matches, consider
585     // it compatible.
586     if (Require.hasAVLReg() && Require.AVLReg == RISCV::NoRegister)
587       if (SEW == Require.SEW)
588         return true;
589 
590     return hasSameAVL(Require) && hasCompatibleVTYPE(MI, Require);
591   }
592 
593   bool operator==(const VSETVLIInfo &Other) const {
594     // Uninitialized is only equal to another Uninitialized.
595     if (!isValid())
596       return !Other.isValid();
597     if (!Other.isValid())
598       return !isValid();
599 
600     // Unknown is only equal to another Unknown.
601     if (isUnknown())
602       return Other.isUnknown();
603     if (Other.isUnknown())
604       return isUnknown();
605 
606     if (!hasSameAVL(Other))
607       return false;
608 
609     // If the SEWLMULRatioOnly bits are different, then they aren't equal.
610     if (SEWLMULRatioOnly != Other.SEWLMULRatioOnly)
611       return false;
612 
613     // If only the VLMAX is valid, check that it is the same.
614     if (SEWLMULRatioOnly)
615       return hasSameVLMAX(Other);
616 
617     // If the full VTYPE is valid, check that it is the same.
618     return hasSameVTYPE(Other);
619   }
620 
621   bool operator!=(const VSETVLIInfo &Other) const {
622     return !(*this == Other);
623   }
624 
625   // Calculate the VSETVLIInfo visible to a block assuming this and Other are
626   // both predecessors.
627   VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
628     // If the new value isn't valid, ignore it.
629     if (!Other.isValid())
630       return *this;
631 
632     // If this value isn't valid, this must be the first predecessor, use it.
633     if (!isValid())
634       return Other;
635 
636     // If either is unknown, the result is unknown.
637     if (isUnknown() || Other.isUnknown())
638       return VSETVLIInfo::getUnknown();
639 
640     // If we have an exact, match return this.
641     if (*this == Other)
642       return *this;
643 
644     // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
645     // return an SEW/LMUL ratio only value.
646     if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
647       VSETVLIInfo MergeInfo = *this;
648       MergeInfo.SEWLMULRatioOnly = true;
649       return MergeInfo;
650     }
651 
652     // Otherwise the result is unknown.
653     return VSETVLIInfo::getUnknown();
654   }
655 
656 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
657   /// Support for debugging, callable in GDB: V->dump()
658   LLVM_DUMP_METHOD void dump() const {
659     print(dbgs());
660     dbgs() << "\n";
661   }
662 
663   /// Implement operator<<.
664   /// @{
665   void print(raw_ostream &OS) const {
666     OS << "{";
667     if (!isValid())
668       OS << "Uninitialized";
669     if (isUnknown())
670       OS << "unknown";;
671     if (hasAVLReg())
672       OS << "AVLReg=" << (unsigned)AVLReg;
673     if (hasAVLImm())
674       OS << "AVLImm=" << (unsigned)AVLImm;
675     OS << ", "
676        << "VLMul=" << (unsigned)VLMul << ", "
677        << "SEW=" << (unsigned)SEW << ", "
678        << "TailAgnostic=" << (bool)TailAgnostic << ", "
679        << "MaskAgnostic=" << (bool)MaskAgnostic << ", "
680        << "SEWLMULRatioOnly=" << (bool)SEWLMULRatioOnly << "}";
681   }
682 #endif
683 };
684 
685 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
686 LLVM_ATTRIBUTE_USED
687 inline raw_ostream &operator<<(raw_ostream &OS, const VSETVLIInfo &V) {
688   V.print(OS);
689   return OS;
690 }
691 #endif
692 
693 struct BlockData {
694   // The VSETVLIInfo that represents the net changes to the VL/VTYPE registers
695   // made by this block. Calculated in Phase 1.
696   VSETVLIInfo Change;
697 
698   // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
699   // block. Calculated in Phase 2.
700   VSETVLIInfo Exit;
701 
702   // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
703   // blocks. Calculated in Phase 2, and used by Phase 3.
704   VSETVLIInfo Pred;
705 
706   // Keeps track of whether the block is already in the queue.
707   bool InQueue = false;
708 
709   BlockData() = default;
710 };
711 
712 class RISCVInsertVSETVLI : public MachineFunctionPass {
713   const TargetInstrInfo *TII;
714   MachineRegisterInfo *MRI;
715 
716   std::vector<BlockData> BlockInfo;
717   std::queue<const MachineBasicBlock *> WorkList;
718 
719 public:
720   static char ID;
721 
722   RISCVInsertVSETVLI() : MachineFunctionPass(ID) {
723     initializeRISCVInsertVSETVLIPass(*PassRegistry::getPassRegistry());
724   }
725   bool runOnMachineFunction(MachineFunction &MF) override;
726 
727   void getAnalysisUsage(AnalysisUsage &AU) const override {
728     AU.setPreservesCFG();
729     MachineFunctionPass::getAnalysisUsage(AU);
730   }
731 
732   StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
733 
734 private:
735   bool needVSETVLI(const MachineInstr &MI, const VSETVLIInfo &Require,
736                    const VSETVLIInfo &CurInfo) const;
737   bool needVSETVLIPHI(const VSETVLIInfo &Require,
738                       const MachineBasicBlock &MBB) const;
739   void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
740                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
741   void insertVSETVLI(MachineBasicBlock &MBB,
742                      MachineBasicBlock::iterator InsertPt, DebugLoc DL,
743                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
744 
745   void transferBefore(VSETVLIInfo &Info, const MachineInstr &MI);
746   void transferAfter(VSETVLIInfo &Info, const MachineInstr &MI);
747   bool computeVLVTYPEChanges(const MachineBasicBlock &MBB);
748   void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
749   void emitVSETVLIs(MachineBasicBlock &MBB);
750   void doLocalPrepass(MachineBasicBlock &MBB);
751   void doLocalPostpass(MachineBasicBlock &MBB);
752   void doPRE(MachineBasicBlock &MBB);
753   void insertReadVL(MachineBasicBlock &MBB);
754 };
755 
756 } // end anonymous namespace
757 
758 char RISCVInsertVSETVLI::ID = 0;
759 
760 INITIALIZE_PASS(RISCVInsertVSETVLI, DEBUG_TYPE, RISCV_INSERT_VSETVLI_NAME,
761                 false, false)
762 
763 static bool isVectorConfigInstr(const MachineInstr &MI) {
764   return MI.getOpcode() == RISCV::PseudoVSETVLI ||
765          MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
766          MI.getOpcode() == RISCV::PseudoVSETIVLI;
767 }
768 
769 /// Return true if this is 'vsetvli x0, x0, vtype' which preserves
770 /// VL and only sets VTYPE.
771 static bool isVLPreservingConfig(const MachineInstr &MI) {
772   if (MI.getOpcode() != RISCV::PseudoVSETVLIX0)
773     return false;
774   assert(RISCV::X0 == MI.getOperand(1).getReg());
775   return RISCV::X0 == MI.getOperand(0).getReg();
776 }
777 
778 static MachineInstr *elideCopies(MachineInstr *MI,
779                                  const MachineRegisterInfo *MRI) {
780   while (true) {
781     if (!MI->isFullCopy())
782       return MI;
783     if (!Register::isVirtualRegister(MI->getOperand(1).getReg()))
784       return nullptr;
785     MI = MRI->getVRegDef(MI->getOperand(1).getReg());
786     if (!MI)
787       return nullptr;
788   }
789 }
790 
791 static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
792                                        const MachineRegisterInfo *MRI) {
793   VSETVLIInfo InstrInfo;
794 
795   // If the instruction has policy argument, use the argument.
796   // If there is no policy argument, default to tail agnostic unless the
797   // destination is tied to a source. Unless the source is undef. In that case
798   // the user would have some control over the policy values.
799   bool TailAgnostic = true;
800   bool UsesMaskPolicy = RISCVII::usesMaskPolicy(TSFlags);
801   // FIXME: Could we look at the above or below instructions to choose the
802   // matched mask policy to reduce vsetvli instructions? Default mask policy is
803   // agnostic if instructions use mask policy, otherwise is undisturbed. Because
804   // most mask operations are mask undisturbed, so we could possibly reduce the
805   // vsetvli between mask and nomasked instruction sequence.
806   bool MaskAgnostic = UsesMaskPolicy;
807   unsigned UseOpIdx;
808   if (RISCVII::hasVecPolicyOp(TSFlags)) {
809     const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
810     uint64_t Policy = Op.getImm();
811     assert(Policy <= (RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC) &&
812            "Invalid Policy Value");
813     // Although in some cases, mismatched passthru/maskedoff with policy value
814     // does not make sense (ex. tied operand is IMPLICIT_DEF with non-TAMA
815     // policy, or tied operand is not IMPLICIT_DEF with TAMA policy), but users
816     // have set the policy value explicitly, so compiler would not fix it.
817     TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
818     MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
819   } else if (MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
820     TailAgnostic = false;
821     if (UsesMaskPolicy)
822       MaskAgnostic = false;
823     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
824     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
825     MachineInstr *UseMI = MRI->getVRegDef(UseMO.getReg());
826     if (UseMI) {
827       UseMI = elideCopies(UseMI, MRI);
828       if (UseMI && UseMI->isImplicitDef()) {
829         TailAgnostic = true;
830         if (UsesMaskPolicy)
831           MaskAgnostic = true;
832       }
833     }
834     // Some pseudo instructions force a tail agnostic policy despite having a
835     // tied def.
836     if (RISCVII::doesForceTailAgnostic(TSFlags))
837       TailAgnostic = true;
838   }
839 
840   RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
841 
842   unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
843   // A Log2SEW of 0 is an operation on mask registers only.
844   unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
845   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
846 
847   if (RISCVII::hasVLOp(TSFlags)) {
848     const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
849     if (VLOp.isImm()) {
850       int64_t Imm = VLOp.getImm();
851       // Conver the VLMax sentintel to X0 register.
852       if (Imm == RISCV::VLMaxSentinel)
853         InstrInfo.setAVLReg(RISCV::X0);
854       else
855         InstrInfo.setAVLImm(Imm);
856     } else {
857       InstrInfo.setAVLReg(VLOp.getReg());
858     }
859   } else {
860     InstrInfo.setAVLReg(RISCV::NoRegister);
861   }
862   InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
863 
864   return InstrInfo;
865 }
866 
867 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
868                                        const VSETVLIInfo &Info,
869                                        const VSETVLIInfo &PrevInfo) {
870   DebugLoc DL = MI.getDebugLoc();
871   insertVSETVLI(MBB, MachineBasicBlock::iterator(&MI), DL, Info, PrevInfo);
872 }
873 
874 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB,
875                      MachineBasicBlock::iterator InsertPt, DebugLoc DL,
876                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo) {
877 
878   // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
879   // VLMAX.
880   if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
881       Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
882     BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
883         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
884         .addReg(RISCV::X0, RegState::Kill)
885         .addImm(Info.encodeVTYPE())
886         .addReg(RISCV::VL, RegState::Implicit);
887     return;
888   }
889 
890   if (Info.hasAVLImm()) {
891     BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
892         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
893         .addImm(Info.getAVLImm())
894         .addImm(Info.encodeVTYPE());
895     return;
896   }
897 
898   Register AVLReg = Info.getAVLReg();
899   if (AVLReg == RISCV::NoRegister) {
900     // We can only use x0, x0 if there's no chance of the vtype change causing
901     // the previous vl to become invalid.
902     if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
903         Info.hasSameVLMAX(PrevInfo)) {
904       BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
905           .addReg(RISCV::X0, RegState::Define | RegState::Dead)
906           .addReg(RISCV::X0, RegState::Kill)
907           .addImm(Info.encodeVTYPE())
908           .addReg(RISCV::VL, RegState::Implicit);
909       return;
910     }
911     // Otherwise use an AVL of 0 to avoid depending on previous vl.
912     BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
913         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
914         .addImm(0)
915         .addImm(Info.encodeVTYPE());
916     return;
917   }
918 
919   if (AVLReg.isVirtual())
920     MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
921 
922   // Use X0 as the DestReg unless AVLReg is X0. We also need to change the
923   // opcode if the AVLReg is X0 as they have different register classes for
924   // the AVL operand.
925   Register DestReg = RISCV::X0;
926   unsigned Opcode = RISCV::PseudoVSETVLI;
927   if (AVLReg == RISCV::X0) {
928     DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
929     Opcode = RISCV::PseudoVSETVLIX0;
930   }
931   BuildMI(MBB, InsertPt, DL, TII->get(Opcode))
932       .addReg(DestReg, RegState::Define | RegState::Dead)
933       .addReg(AVLReg)
934       .addImm(Info.encodeVTYPE());
935 }
936 
937 // Return a VSETVLIInfo representing the changes made by this VSETVLI or
938 // VSETIVLI instruction.
939 static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
940   VSETVLIInfo NewInfo;
941   if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
942     NewInfo.setAVLImm(MI.getOperand(1).getImm());
943   } else {
944     assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
945            MI.getOpcode() == RISCV::PseudoVSETVLIX0);
946     Register AVLReg = MI.getOperand(1).getReg();
947     assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
948            "Can't handle X0, X0 vsetvli yet");
949     NewInfo.setAVLReg(AVLReg);
950   }
951   NewInfo.setVTYPE(MI.getOperand(2).getImm());
952 
953   return NewInfo;
954 }
955 
956 /// Return true if a VSETVLI is required to transition from CurInfo to Require
957 /// before MI.
958 bool RISCVInsertVSETVLI::needVSETVLI(const MachineInstr &MI,
959                                      const VSETVLIInfo &Require,
960                                      const VSETVLIInfo &CurInfo) const {
961   assert(Require == computeInfoForInstr(MI, MI.getDesc().TSFlags, MRI));
962 
963   if (CurInfo.isCompatible(MI, Require))
964     return false;
965 
966   // For vmv.s.x and vfmv.s.f, there is only two behaviors, VL = 0 and VL > 0.
967   // So it's compatible when we could make sure that both VL be the same
968   // situation.  Additionally, if writing to an implicit_def operand, we
969   // don't need to preserve any other bits and are thus compatible with any
970   // larger etype, and can disregard policy bits.
971   if (isScalarMoveInstr(MI) &&
972       ((CurInfo.hasNonZeroAVL() && Require.hasNonZeroAVL()) ||
973        (CurInfo.hasZeroAVL() && Require.hasZeroAVL()))) {
974     auto *VRegDef = MRI->getVRegDef(MI.getOperand(1).getReg());
975     if (VRegDef && VRegDef->isImplicitDef() &&
976         CurInfo.getSEW() >= Require.getSEW())
977       return false;
978     if (CurInfo.hasSameSEW(Require) && CurInfo.hasSamePolicy(Require))
979       return false;
980   }
981 
982   // We didn't find a compatible value. If our AVL is a virtual register,
983   // it might be defined by a VSET(I)VLI. If it has the same VLMAX we need
984   // and the last VL/VTYPE we observed is the same, we don't need a
985   // VSETVLI here.
986   if (!CurInfo.isUnknown() && Require.hasAVLReg() &&
987       Require.getAVLReg().isVirtual() && !CurInfo.hasSEWLMULRatioOnly() &&
988       CurInfo.hasCompatibleVTYPE(MI, Require)) {
989     if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
990       if (isVectorConfigInstr(*DefMI)) {
991         VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
992         if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVLMAX(CurInfo))
993           return false;
994       }
995     }
996   }
997 
998   return true;
999 }
1000 
1001 // Given an incoming state reaching MI, modifies that state so that it is minimally
1002 // compatible with MI.  The resulting state is guaranteed to be semantically legal
1003 // for MI, but may not be the state requested by MI.
1004 void RISCVInsertVSETVLI::transferBefore(VSETVLIInfo &Info, const MachineInstr &MI) {
1005   uint64_t TSFlags = MI.getDesc().TSFlags;
1006   if (!RISCVII::hasSEWOp(TSFlags))
1007     return;
1008   VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
1009 
1010   if (!Info.isValid()) {
1011     Info = NewInfo;
1012   } else {
1013     // If this instruction isn't compatible with the previous VL/VTYPE
1014     // we need to insert a VSETVLI.
1015     // NOTE: We only do this if the vtype we're comparing against was
1016     // created in this block. We need the first and third phase to treat
1017     // the store the same way.
1018     if (needVSETVLI(MI, NewInfo, Info))
1019       Info = NewInfo;
1020   }
1021 }
1022 
1023 // Given a state with which we evaluated MI (see transferBefore above for why
1024 // this might be different that the state MI requested), modify the state to
1025 // reflect the changes MI might make.
1026 void RISCVInsertVSETVLI::transferAfter(VSETVLIInfo &Info, const MachineInstr &MI) {
1027   if (isVectorConfigInstr(MI)) {
1028     Info = getInfoForVSETVLI(MI);
1029     return;
1030   }
1031 
1032   if (RISCV::isFaultFirstLoad(MI)) {
1033     // Update AVL to vl-output of the fault first load.
1034     Info.setAVLReg(MI.getOperand(1).getReg());
1035     return;
1036   }
1037 
1038   // If this is something that updates VL/VTYPE that we don't know about, set
1039   // the state to unknown.
1040   if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
1041       MI.modifiesRegister(RISCV::VTYPE))
1042     Info = VSETVLIInfo::getUnknown();
1043 }
1044 
1045 bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB) {
1046   bool HadVectorOp = false;
1047 
1048   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1049   BBInfo.Change = BBInfo.Pred;
1050   for (const MachineInstr &MI : MBB) {
1051     transferBefore(BBInfo.Change, MI);
1052 
1053     if (isVectorConfigInstr(MI) || RISCVII::hasSEWOp(MI.getDesc().TSFlags))
1054       HadVectorOp = true;
1055 
1056     transferAfter(BBInfo.Change, MI);
1057   }
1058 
1059   return HadVectorOp;
1060 }
1061 
1062 void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
1063 
1064   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1065 
1066   BBInfo.InQueue = false;
1067 
1068   VSETVLIInfo InInfo;
1069   if (MBB.pred_empty()) {
1070     // There are no predecessors, so use the default starting status.
1071     InInfo.setUnknown();
1072   } else {
1073     for (MachineBasicBlock *P : MBB.predecessors())
1074       InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
1075   }
1076 
1077   // If we don't have any valid predecessor value, wait until we do.
1078   if (!InInfo.isValid())
1079     return;
1080 
1081   // If no change, no need to rerun block
1082   if (InInfo == BBInfo.Pred)
1083     return;
1084 
1085   BBInfo.Pred = InInfo;
1086   LLVM_DEBUG(dbgs() << "Entry state of " << printMBBReference(MBB)
1087                     << " changed to " << BBInfo.Pred << "\n");
1088 
1089   // Note: It's tempting to cache the state changes here, but due to the
1090   // compatibility checks performed a blocks output state can change based on
1091   // the input state.  To cache, we'd have to add logic for finding
1092   // never-compatible state changes.
1093   computeVLVTYPEChanges(MBB);
1094   VSETVLIInfo TmpStatus = BBInfo.Change;
1095 
1096   // If the new exit value matches the old exit value, we don't need to revisit
1097   // any blocks.
1098   if (BBInfo.Exit == TmpStatus)
1099     return;
1100 
1101   BBInfo.Exit = TmpStatus;
1102   LLVM_DEBUG(dbgs() << "Exit state of " << printMBBReference(MBB)
1103                     << " changed to " << BBInfo.Exit << "\n");
1104 
1105   // Add the successors to the work list so we can propagate the changed exit
1106   // status.
1107   for (MachineBasicBlock *S : MBB.successors())
1108     if (!BlockInfo[S->getNumber()].InQueue)
1109       WorkList.push(S);
1110 }
1111 
1112 // If we weren't able to prove a vsetvli was directly unneeded, it might still
1113 // be unneeded if the AVL is a phi node where all incoming values are VL
1114 // outputs from the last VSETVLI in their respective basic blocks.
1115 bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
1116                                         const MachineBasicBlock &MBB) const {
1117   if (DisableInsertVSETVLPHIOpt)
1118     return true;
1119 
1120   if (!Require.hasAVLReg())
1121     return true;
1122 
1123   Register AVLReg = Require.getAVLReg();
1124   if (!AVLReg.isVirtual())
1125     return true;
1126 
1127   // We need the AVL to be produce by a PHI node in this basic block.
1128   MachineInstr *PHI = MRI->getVRegDef(AVLReg);
1129   if (!PHI || PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
1130     return true;
1131 
1132   for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
1133        PHIOp += 2) {
1134     Register InReg = PHI->getOperand(PHIOp).getReg();
1135     MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
1136     const BlockData &PBBInfo = BlockInfo[PBB->getNumber()];
1137     // If the exit from the predecessor has the VTYPE we are looking for
1138     // we might be able to avoid a VSETVLI.
1139     if (PBBInfo.Exit.isUnknown() || !PBBInfo.Exit.hasSameVTYPE(Require))
1140       return true;
1141 
1142     // We need the PHI input to the be the output of a VSET(I)VLI.
1143     MachineInstr *DefMI = MRI->getVRegDef(InReg);
1144     if (!DefMI || !isVectorConfigInstr(*DefMI))
1145       return true;
1146 
1147     // We found a VSET(I)VLI make sure it matches the output of the
1148     // predecessor block.
1149     VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1150     if (!DefInfo.hasSameAVL(PBBInfo.Exit) ||
1151         !DefInfo.hasSameVTYPE(PBBInfo.Exit))
1152       return true;
1153   }
1154 
1155   // If all the incoming values to the PHI checked out, we don't need
1156   // to insert a VSETVLI.
1157   return false;
1158 }
1159 
1160 void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1161   VSETVLIInfo CurInfo = BlockInfo[MBB.getNumber()].Pred;
1162   // Track whether the prefix of the block we've scanned is transparent
1163   // (meaning has not yet changed the abstract state).
1164   bool PrefixTransparent = true;
1165   for (MachineInstr &MI : MBB) {
1166     const VSETVLIInfo PrevInfo = CurInfo;
1167     transferBefore(CurInfo, MI);
1168 
1169     // If this is an explicit VSETVLI or VSETIVLI, update our state.
1170     if (isVectorConfigInstr(MI)) {
1171       // Conservatively, mark the VL and VTYPE as live.
1172       assert(MI.getOperand(3).getReg() == RISCV::VL &&
1173              MI.getOperand(4).getReg() == RISCV::VTYPE &&
1174              "Unexpected operands where VL and VTYPE should be");
1175       MI.getOperand(3).setIsDead(false);
1176       MI.getOperand(4).setIsDead(false);
1177       PrefixTransparent = false;
1178     }
1179 
1180     uint64_t TSFlags = MI.getDesc().TSFlags;
1181     if (RISCVII::hasSEWOp(TSFlags)) {
1182       if (PrevInfo != CurInfo) {
1183         // If this is the first implicit state change, and the state change
1184         // requested can be proven to produce the same register contents, we
1185         // can skip emitting the actual state change and continue as if we
1186         // had since we know the GPR result of the implicit state change
1187         // wouldn't be used and VL/VTYPE registers are correct.  Note that
1188         // we *do* need to model the state as if it changed as while the
1189         // register contents are unchanged, the abstract model can change.
1190         if (!PrefixTransparent || needVSETVLIPHI(CurInfo, MBB))
1191           insertVSETVLI(MBB, MI, CurInfo, PrevInfo);
1192         PrefixTransparent = false;
1193       }
1194 
1195       if (RISCVII::hasVLOp(TSFlags)) {
1196         MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1197         if (VLOp.isReg()) {
1198           // Erase the AVL operand from the instruction.
1199           VLOp.setReg(RISCV::NoRegister);
1200           VLOp.setIsKill(false);
1201         }
1202         MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1203                                                 /*isImp*/ true));
1204       }
1205       MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1206                                               /*isImp*/ true));
1207     }
1208 
1209     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
1210         MI.modifiesRegister(RISCV::VTYPE))
1211       PrefixTransparent = false;
1212 
1213     transferAfter(CurInfo, MI);
1214   }
1215 
1216   // If we reach the end of the block and our current info doesn't match the
1217   // expected info, insert a vsetvli to correct.
1218   if (!UseStrictAsserts) {
1219     const VSETVLIInfo &ExitInfo = BlockInfo[MBB.getNumber()].Exit;
1220     if (CurInfo.isValid() && ExitInfo.isValid() && !ExitInfo.isUnknown() &&
1221         CurInfo != ExitInfo) {
1222       // Note there's an implicit assumption here that terminators never use
1223       // or modify VL or VTYPE.  Also, fallthrough will return end().
1224       auto InsertPt = MBB.getFirstInstrTerminator();
1225       insertVSETVLI(MBB, InsertPt, MBB.findDebugLoc(InsertPt), ExitInfo,
1226                     CurInfo);
1227       CurInfo = ExitInfo;
1228     }
1229   }
1230 
1231   if (UseStrictAsserts && CurInfo.isValid()) {
1232     const auto &Info = BlockInfo[MBB.getNumber()];
1233     if (CurInfo != Info.Exit) {
1234       LLVM_DEBUG(dbgs() << "in block " << printMBBReference(MBB) << "\n");
1235       LLVM_DEBUG(dbgs() << "  begin        state: " << Info.Pred << "\n");
1236       LLVM_DEBUG(dbgs() << "  expected end state: " << Info.Exit << "\n");
1237       LLVM_DEBUG(dbgs() << "  actual   end state: " << CurInfo << "\n");
1238     }
1239     assert(CurInfo == Info.Exit &&
1240            "InsertVSETVLI dataflow invariant violated");
1241   }
1242 }
1243 
1244 void RISCVInsertVSETVLI::doLocalPrepass(MachineBasicBlock &MBB) {
1245   VSETVLIInfo CurInfo = VSETVLIInfo::getUnknown();
1246   for (MachineInstr &MI : MBB) {
1247     // If this is an explicit VSETVLI or VSETIVLI, update our state.
1248     if (isVectorConfigInstr(MI)) {
1249       CurInfo = getInfoForVSETVLI(MI);
1250       continue;
1251     }
1252 
1253     const uint64_t TSFlags = MI.getDesc().TSFlags;
1254     if (isScalarMoveInstr(MI)) {
1255       assert(RISCVII::hasSEWOp(TSFlags) && RISCVII::hasVLOp(TSFlags));
1256       const VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
1257 
1258       // For vmv.s.x and vfmv.s.f, there are only two behaviors, VL = 0 and
1259       // VL > 0. We can discard the user requested AVL and just use the last
1260       // one if we can prove it equally zero.  This removes a vsetvli entirely
1261       // if the types match or allows use of cheaper avl preserving variant
1262       // if VLMAX doesn't change.  If VLMAX might change, we couldn't use
1263       // the 'vsetvli x0, x0, vtype" variant, so we avoid the transform to
1264       // prevent extending live range of an avl register operand.
1265       // TODO: We can probably relax this for immediates.
1266       if (((CurInfo.hasNonZeroAVL() && NewInfo.hasNonZeroAVL()) ||
1267            (CurInfo.hasZeroAVL() && NewInfo.hasZeroAVL())) &&
1268           NewInfo.hasSameVLMAX(CurInfo)) {
1269         MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1270         if (CurInfo.hasAVLImm())
1271           VLOp.ChangeToImmediate(CurInfo.getAVLImm());
1272         else
1273           VLOp.ChangeToRegister(CurInfo.getAVLReg(), /*IsDef*/ false);
1274         CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1275         continue;
1276       }
1277     }
1278 
1279     if (RISCVII::hasSEWOp(TSFlags)) {
1280       if (RISCVII::hasVLOp(TSFlags)) {
1281         const auto Require = computeInfoForInstr(MI, TSFlags, MRI);
1282         // Two cases involving an AVL resulting from a previous vsetvli.
1283         // 1) If the AVL is the result of a previous vsetvli which has the
1284         //    same AVL and VLMAX as our current state, we can reuse the AVL
1285         //    from the current state for the new one.  This allows us to
1286         //    generate 'vsetvli x0, x0, vtype" or possible skip the transition
1287         //    entirely.
1288         // 2) If AVL is defined by a vsetvli with the same VLMAX, we can
1289         //    replace the AVL operand with the AVL of the defining vsetvli.
1290         //    We avoid general register AVLs to avoid extending live ranges
1291         //    without being sure we can kill the original source reg entirely.
1292         if (Require.hasAVLReg() && Require.getAVLReg().isVirtual()) {
1293           if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
1294             if (isVectorConfigInstr(*DefMI)) {
1295               VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1296               // case 1
1297               if (!CurInfo.isUnknown() && DefInfo.hasSameAVL(CurInfo) &&
1298                   DefInfo.hasSameVLMAX(CurInfo)) {
1299                 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1300                 if (CurInfo.hasAVLImm())
1301                   VLOp.ChangeToImmediate(CurInfo.getAVLImm());
1302                 else {
1303                   MRI->clearKillFlags(CurInfo.getAVLReg());
1304                   VLOp.ChangeToRegister(CurInfo.getAVLReg(), /*IsDef*/ false);
1305                 }
1306                 CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1307                 continue;
1308               }
1309               // case 2
1310               if (DefInfo.hasSameVLMAX(Require) &&
1311                   (DefInfo.hasAVLImm() || DefInfo.getAVLReg() == RISCV::X0)) {
1312                 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1313                 if (DefInfo.hasAVLImm())
1314                   VLOp.ChangeToImmediate(DefInfo.getAVLImm());
1315                 else
1316                   VLOp.ChangeToRegister(DefInfo.getAVLReg(), /*IsDef*/ false);
1317                 CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1318                 continue;
1319               }
1320             }
1321           }
1322         }
1323       }
1324       CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1325       continue;
1326     }
1327 
1328     transferAfter(CurInfo, MI);
1329   }
1330 }
1331 
1332 /// Return true if the VL value configured must be equal to the requested one.
1333 static bool hasFixedResult(const VSETVLIInfo &Info, const RISCVSubtarget &ST) {
1334   if (!Info.hasAVLImm())
1335     // VLMAX is always the same value.
1336     // TODO: Could extend to other registers by looking at the associated vreg
1337     // def placement.
1338     return RISCV::X0 == Info.getAVLReg();
1339 
1340   unsigned AVL = Info.getAVLImm();
1341   unsigned SEW = Info.getSEW();
1342   unsigned AVLInBits = AVL * SEW;
1343 
1344   unsigned LMul;
1345   bool Fractional;
1346   std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(Info.getVLMUL());
1347 
1348   if (Fractional)
1349     return ST.getRealMinVLen() / LMul >= AVLInBits;
1350   return ST.getRealMinVLen() * LMul >= AVLInBits;
1351 }
1352 
1353 /// Perform simple partial redundancy elimination of the VSETVLI instructions
1354 /// we're about to insert by looking for cases where we can PRE from the
1355 /// beginning of one block to the end of one of its predecessors.  Specifically,
1356 /// this is geared to catch the common case of a fixed length vsetvl in a single
1357 /// block loop when it could execute once in the preheader instead.
1358 void RISCVInsertVSETVLI::doPRE(MachineBasicBlock &MBB) {
1359   const MachineFunction &MF = *MBB.getParent();
1360   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1361 
1362   if (!BlockInfo[MBB.getNumber()].Pred.isUnknown())
1363     return;
1364 
1365   MachineBasicBlock *UnavailablePred = nullptr;
1366   VSETVLIInfo AvailableInfo;
1367   for (MachineBasicBlock *P : MBB.predecessors()) {
1368     const VSETVLIInfo &PredInfo = BlockInfo[P->getNumber()].Exit;
1369     if (PredInfo.isUnknown()) {
1370       if (UnavailablePred)
1371         return;
1372       UnavailablePred = P;
1373     } else if (!AvailableInfo.isValid()) {
1374       AvailableInfo = PredInfo;
1375     } else if (AvailableInfo != PredInfo) {
1376       return;
1377     }
1378   }
1379 
1380   // Unreachable, single pred, or full redundancy. Note that FRE is handled by
1381   // phase 3.
1382   if (!UnavailablePred || !AvailableInfo.isValid())
1383     return;
1384 
1385   // Critical edge - TODO: consider splitting?
1386   if (UnavailablePred->succ_size() != 1)
1387     return;
1388 
1389   // If VL can be less than AVL, then we can't reduce the frequency of exec.
1390   if (!hasFixedResult(AvailableInfo, ST))
1391     return;
1392 
1393   // Does it actually let us remove an implicit transition in MBB?
1394   bool Found = false;
1395   for (auto &MI : MBB) {
1396     if (isVectorConfigInstr(MI))
1397       return;
1398 
1399     const uint64_t TSFlags = MI.getDesc().TSFlags;
1400     if (RISCVII::hasSEWOp(TSFlags)) {
1401       if (AvailableInfo != computeInfoForInstr(MI, TSFlags, MRI))
1402         return;
1403       Found = true;
1404       break;
1405     }
1406   }
1407   if (!Found)
1408     return;
1409 
1410   // Finally, update both data flow state and insert the actual vsetvli.
1411   // Doing both keeps the code in sync with the dataflow results, which
1412   // is critical for correctness of phase 3.
1413   auto OldInfo = BlockInfo[UnavailablePred->getNumber()].Exit;
1414   LLVM_DEBUG(dbgs() << "PRE VSETVLI from " << MBB.getName() << " to "
1415                     << UnavailablePred->getName() << " with state "
1416                     << AvailableInfo << "\n");
1417   BlockInfo[UnavailablePred->getNumber()].Exit = AvailableInfo;
1418   BlockInfo[MBB.getNumber()].Pred = AvailableInfo;
1419 
1420   // Note there's an implicit assumption here that terminators never use
1421   // or modify VL or VTYPE.  Also, fallthrough will return end().
1422   auto InsertPt = UnavailablePred->getFirstInstrTerminator();
1423   insertVSETVLI(*UnavailablePred, InsertPt,
1424                 UnavailablePred->findDebugLoc(InsertPt),
1425                 AvailableInfo, OldInfo);
1426 }
1427 
1428 static void doUnion(DemandedFields &A, DemandedFields B) {
1429   A.VL |= B.VL;
1430   A.SEW |= B.SEW;
1431   A.LMUL |= B.LMUL;
1432   A.SEWLMULRatio |= B.SEWLMULRatio;
1433   A.TailPolicy |= B.TailPolicy;
1434   A.MaskPolicy |= B.MaskPolicy;
1435 }
1436 
1437 // Return true if we can mutate PrevMI's VTYPE to match MI's
1438 // without changing any the fields which have been used.
1439 // TODO: Restructure code to allow code reuse between this and isCompatible
1440 // above.
1441 static bool canMutatePriorConfig(const MachineInstr &PrevMI,
1442                                  const MachineInstr &MI,
1443                                  const DemandedFields &Used) {
1444   // TODO: Extend this to handle cases where VL does change, but VL
1445   // has not been used.  (e.g. over a vmv.x.s)
1446   if (!isVLPreservingConfig(MI))
1447     // Note: `vsetvli x0, x0, vtype' is the canonical instruction
1448     // for this case.  If you find yourself wanting to add other forms
1449     // to this "unused VTYPE" case, we're probably missing a
1450     // canonicalization earlier.
1451     return false;
1452 
1453   if (!PrevMI.getOperand(2).isImm() || !MI.getOperand(2).isImm())
1454     return false;
1455 
1456   auto PriorVType = PrevMI.getOperand(2).getImm();
1457   auto VType = MI.getOperand(2).getImm();
1458   return areCompatibleVTYPEs(PriorVType, VType, Used);
1459 }
1460 
1461 void RISCVInsertVSETVLI::doLocalPostpass(MachineBasicBlock &MBB) {
1462   MachineInstr *PrevMI = nullptr;
1463   DemandedFields Used;
1464   SmallVector<MachineInstr*> ToDelete;
1465   for (MachineInstr &MI : MBB) {
1466     // Note: Must be *before* vsetvli handling to account for config cases
1467     // which only change some subfields.
1468     doUnion(Used, getDemanded(MI));
1469 
1470     if (!isVectorConfigInstr(MI))
1471       continue;
1472 
1473     if (PrevMI) {
1474       if (!Used.VL && !Used.usedVTYPE()) {
1475         ToDelete.push_back(PrevMI);
1476         // fallthrough
1477       } else if (canMutatePriorConfig(*PrevMI, MI, Used)) {
1478         PrevMI->getOperand(2).setImm(MI.getOperand(2).getImm());
1479         ToDelete.push_back(&MI);
1480         // Leave PrevMI unchanged
1481         continue;
1482       }
1483     }
1484     PrevMI = &MI;
1485     Used = getDemanded(MI);
1486     Register VRegDef = MI.getOperand(0).getReg();
1487     if (VRegDef != RISCV::X0 &&
1488         !(VRegDef.isVirtual() && MRI->use_nodbg_empty(VRegDef)))
1489       Used.VL = true;
1490   }
1491 
1492   for (auto *MI : ToDelete)
1493     MI->eraseFromParent();
1494 }
1495 
1496 void RISCVInsertVSETVLI::insertReadVL(MachineBasicBlock &MBB) {
1497   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
1498     MachineInstr &MI = *I++;
1499     if (RISCV::isFaultFirstLoad(MI)) {
1500       Register VLOutput = MI.getOperand(1).getReg();
1501       if (!MRI->use_nodbg_empty(VLOutput))
1502         BuildMI(MBB, I, MI.getDebugLoc(), TII->get(RISCV::PseudoReadVL),
1503                 VLOutput);
1504       // We don't use the vl output of the VLEFF/VLSEGFF anymore.
1505       MI.getOperand(1).setReg(RISCV::X0);
1506     }
1507   }
1508 }
1509 
1510 bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1511   // Skip if the vector extension is not enabled.
1512   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1513   if (!ST.hasVInstructions())
1514     return false;
1515 
1516   LLVM_DEBUG(dbgs() << "Entering InsertVSETVLI for " << MF.getName() << "\n");
1517 
1518   TII = ST.getInstrInfo();
1519   MRI = &MF.getRegInfo();
1520 
1521   assert(BlockInfo.empty() && "Expect empty block infos");
1522   BlockInfo.resize(MF.getNumBlockIDs());
1523 
1524   // Scan the block locally for cases where we can mutate the operands
1525   // of the instructions to reduce state transitions.  Critically, this
1526   // must be done before we start propagating data flow states as these
1527   // transforms are allowed to change the contents of VTYPE and VL so
1528   // long as the semantics of the program stays the same.
1529   for (MachineBasicBlock &MBB : MF)
1530     doLocalPrepass(MBB);
1531 
1532   bool HaveVectorOp = false;
1533 
1534   // Phase 1 - determine how VL/VTYPE are affected by the each block.
1535   for (const MachineBasicBlock &MBB : MF) {
1536     HaveVectorOp |= computeVLVTYPEChanges(MBB);
1537     // Initial exit state is whatever change we found in the block.
1538     BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1539     BBInfo.Exit = BBInfo.Change;
1540     LLVM_DEBUG(dbgs() << "Initial exit state of " << printMBBReference(MBB)
1541                       << " is " << BBInfo.Exit << "\n");
1542 
1543   }
1544 
1545   // If we didn't find any instructions that need VSETVLI, we're done.
1546   if (!HaveVectorOp) {
1547     BlockInfo.clear();
1548     return false;
1549   }
1550 
1551   // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1552   // blocks to the list here, but will also add any that need to be revisited
1553   // during Phase 2 processing.
1554   for (const MachineBasicBlock &MBB : MF) {
1555     WorkList.push(&MBB);
1556     BlockInfo[MBB.getNumber()].InQueue = true;
1557   }
1558   while (!WorkList.empty()) {
1559     const MachineBasicBlock &MBB = *WorkList.front();
1560     WorkList.pop();
1561     computeIncomingVLVTYPE(MBB);
1562   }
1563 
1564   // Perform partial redundancy elimination of vsetvli transitions.
1565   for (MachineBasicBlock &MBB : MF)
1566     doPRE(MBB);
1567 
1568   // Phase 3 - add any vsetvli instructions needed in the block. Use the
1569   // Phase 2 information to avoid adding vsetvlis before the first vector
1570   // instruction in the block if the VL/VTYPE is satisfied by its
1571   // predecessors.
1572   for (MachineBasicBlock &MBB : MF)
1573     emitVSETVLIs(MBB);
1574 
1575   // Now that all vsetvlis are explicit, go through and do block local
1576   // DSE and peephole based demanded fields based transforms.  Note that
1577   // this *must* be done outside the main dataflow so long as we allow
1578   // any cross block analysis within the dataflow.  We can't have both
1579   // demanded fields based mutation and non-local analysis in the
1580   // dataflow at the same time without introducing inconsistencies.
1581   for (MachineBasicBlock &MBB : MF)
1582     doLocalPostpass(MBB);
1583 
1584   // Once we're fully done rewriting all the instructions, do a final pass
1585   // through to check for VSETVLIs which write to an unused destination.
1586   // For the non X0, X0 variant, we can replace the destination register
1587   // with X0 to reduce register pressure.  This is really a generic
1588   // optimization which can be applied to any dead def (TODO: generalize).
1589   for (MachineBasicBlock &MBB : MF) {
1590     for (MachineInstr &MI : MBB) {
1591       if (MI.getOpcode() == RISCV::PseudoVSETVLI ||
1592           MI.getOpcode() == RISCV::PseudoVSETIVLI) {
1593         Register VRegDef = MI.getOperand(0).getReg();
1594         if (VRegDef != RISCV::X0 && MRI->use_nodbg_empty(VRegDef))
1595           MI.getOperand(0).setReg(RISCV::X0);
1596       }
1597     }
1598   }
1599 
1600   // Insert PseudoReadVL after VLEFF/VLSEGFF and replace it with the vl output
1601   // of VLEFF/VLSEGFF.
1602   for (MachineBasicBlock &MBB : MF)
1603     insertReadVL(MBB);
1604 
1605   BlockInfo.clear();
1606   return HaveVectorOp;
1607 }
1608 
1609 /// Returns an instance of the Insert VSETVLI pass.
1610 FunctionPass *llvm::createRISCVInsertVSETVLIPass() {
1611   return new RISCVInsertVSETVLI();
1612 }
1613