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