1 //===-- RISCVInstrInfo.cpp - RISCV Instruction Information ------*- C++ -*-===//
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 contains the RISCV implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVInstrInfo.h"
14 #include "MCTargetDesc/RISCVMatInt.h"
15 #include "RISCV.h"
16 #include "RISCVMachineFunctionInfo.h"
17 #include "RISCVSubtarget.h"
18 #include "RISCVTargetMachine.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/MemoryLocation.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/RegisterScavenging.h"
27 #include "llvm/MC/MCInstBuilder.h"
28 #include "llvm/MC/TargetRegistry.h"
29 #include "llvm/Support/ErrorHandling.h"
30 
31 using namespace llvm;
32 
33 #define GEN_CHECK_COMPRESS_INSTR
34 #include "RISCVGenCompressInstEmitter.inc"
35 
36 #define GET_INSTRINFO_CTOR_DTOR
37 #include "RISCVGenInstrInfo.inc"
38 
39 namespace llvm {
40 namespace RISCVVPseudosTable {
41 
42 using namespace RISCV;
43 
44 #define GET_RISCVVPseudosTable_IMPL
45 #include "RISCVGenSearchableTables.inc"
46 
47 } // namespace RISCVVPseudosTable
48 } // namespace llvm
49 
50 RISCVInstrInfo::RISCVInstrInfo(RISCVSubtarget &STI)
51     : RISCVGenInstrInfo(RISCV::ADJCALLSTACKDOWN, RISCV::ADJCALLSTACKUP),
52       STI(STI) {}
53 
54 MCInst RISCVInstrInfo::getNop() const {
55   if (STI.getFeatureBits()[RISCV::FeatureStdExtC])
56     return MCInstBuilder(RISCV::C_NOP);
57   return MCInstBuilder(RISCV::ADDI)
58       .addReg(RISCV::X0)
59       .addReg(RISCV::X0)
60       .addImm(0);
61 }
62 
63 unsigned RISCVInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
64                                              int &FrameIndex) const {
65   switch (MI.getOpcode()) {
66   default:
67     return 0;
68   case RISCV::LB:
69   case RISCV::LBU:
70   case RISCV::LH:
71   case RISCV::LHU:
72   case RISCV::FLH:
73   case RISCV::LW:
74   case RISCV::FLW:
75   case RISCV::LWU:
76   case RISCV::LD:
77   case RISCV::FLD:
78     break;
79   }
80 
81   if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
82       MI.getOperand(2).getImm() == 0) {
83     FrameIndex = MI.getOperand(1).getIndex();
84     return MI.getOperand(0).getReg();
85   }
86 
87   return 0;
88 }
89 
90 unsigned RISCVInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
91                                             int &FrameIndex) const {
92   switch (MI.getOpcode()) {
93   default:
94     return 0;
95   case RISCV::SB:
96   case RISCV::SH:
97   case RISCV::SW:
98   case RISCV::FSH:
99   case RISCV::FSW:
100   case RISCV::SD:
101   case RISCV::FSD:
102     break;
103   }
104 
105   if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
106       MI.getOperand(2).getImm() == 0) {
107     FrameIndex = MI.getOperand(1).getIndex();
108     return MI.getOperand(0).getReg();
109   }
110 
111   return 0;
112 }
113 
114 static bool forwardCopyWillClobberTuple(unsigned DstReg, unsigned SrcReg,
115                                         unsigned NumRegs) {
116   // We really want the positive remainder mod 32 here, that happens to be
117   // easily obtainable with a mask.
118   return ((DstReg - SrcReg) & 0x1f) < NumRegs;
119 }
120 
121 void RISCVInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
122                                  MachineBasicBlock::iterator MBBI,
123                                  const DebugLoc &DL, MCRegister DstReg,
124                                  MCRegister SrcReg, bool KillSrc) const {
125   if (RISCV::GPRRegClass.contains(DstReg, SrcReg)) {
126     BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
127         .addReg(SrcReg, getKillRegState(KillSrc))
128         .addImm(0);
129     return;
130   }
131 
132   // FPR->FPR copies and VR->VR copies.
133   unsigned Opc;
134   bool IsScalableVector = true;
135   unsigned NF = 1;
136   unsigned LMul = 1;
137   unsigned SubRegIdx = RISCV::sub_vrm1_0;
138   if (RISCV::FPR16RegClass.contains(DstReg, SrcReg)) {
139     Opc = RISCV::FSGNJ_H;
140     IsScalableVector = false;
141   } else if (RISCV::FPR32RegClass.contains(DstReg, SrcReg)) {
142     Opc = RISCV::FSGNJ_S;
143     IsScalableVector = false;
144   } else if (RISCV::FPR64RegClass.contains(DstReg, SrcReg)) {
145     Opc = RISCV::FSGNJ_D;
146     IsScalableVector = false;
147   } else if (RISCV::VRRegClass.contains(DstReg, SrcReg)) {
148     Opc = RISCV::PseudoVMV1R_V;
149   } else if (RISCV::VRM2RegClass.contains(DstReg, SrcReg)) {
150     Opc = RISCV::PseudoVMV2R_V;
151   } else if (RISCV::VRM4RegClass.contains(DstReg, SrcReg)) {
152     Opc = RISCV::PseudoVMV4R_V;
153   } else if (RISCV::VRM8RegClass.contains(DstReg, SrcReg)) {
154     Opc = RISCV::PseudoVMV8R_V;
155   } else if (RISCV::VRN2M1RegClass.contains(DstReg, SrcReg)) {
156     Opc = RISCV::PseudoVMV1R_V;
157     SubRegIdx = RISCV::sub_vrm1_0;
158     NF = 2;
159     LMul = 1;
160   } else if (RISCV::VRN2M2RegClass.contains(DstReg, SrcReg)) {
161     Opc = RISCV::PseudoVMV2R_V;
162     SubRegIdx = RISCV::sub_vrm2_0;
163     NF = 2;
164     LMul = 2;
165   } else if (RISCV::VRN2M4RegClass.contains(DstReg, SrcReg)) {
166     Opc = RISCV::PseudoVMV4R_V;
167     SubRegIdx = RISCV::sub_vrm4_0;
168     NF = 2;
169     LMul = 4;
170   } else if (RISCV::VRN3M1RegClass.contains(DstReg, SrcReg)) {
171     Opc = RISCV::PseudoVMV1R_V;
172     SubRegIdx = RISCV::sub_vrm1_0;
173     NF = 3;
174     LMul = 1;
175   } else if (RISCV::VRN3M2RegClass.contains(DstReg, SrcReg)) {
176     Opc = RISCV::PseudoVMV2R_V;
177     SubRegIdx = RISCV::sub_vrm2_0;
178     NF = 3;
179     LMul = 2;
180   } else if (RISCV::VRN4M1RegClass.contains(DstReg, SrcReg)) {
181     Opc = RISCV::PseudoVMV1R_V;
182     SubRegIdx = RISCV::sub_vrm1_0;
183     NF = 4;
184     LMul = 1;
185   } else if (RISCV::VRN4M2RegClass.contains(DstReg, SrcReg)) {
186     Opc = RISCV::PseudoVMV2R_V;
187     SubRegIdx = RISCV::sub_vrm2_0;
188     NF = 4;
189     LMul = 2;
190   } else if (RISCV::VRN5M1RegClass.contains(DstReg, SrcReg)) {
191     Opc = RISCV::PseudoVMV1R_V;
192     SubRegIdx = RISCV::sub_vrm1_0;
193     NF = 5;
194     LMul = 1;
195   } else if (RISCV::VRN6M1RegClass.contains(DstReg, SrcReg)) {
196     Opc = RISCV::PseudoVMV1R_V;
197     SubRegIdx = RISCV::sub_vrm1_0;
198     NF = 6;
199     LMul = 1;
200   } else if (RISCV::VRN7M1RegClass.contains(DstReg, SrcReg)) {
201     Opc = RISCV::PseudoVMV1R_V;
202     SubRegIdx = RISCV::sub_vrm1_0;
203     NF = 7;
204     LMul = 1;
205   } else if (RISCV::VRN8M1RegClass.contains(DstReg, SrcReg)) {
206     Opc = RISCV::PseudoVMV1R_V;
207     SubRegIdx = RISCV::sub_vrm1_0;
208     NF = 8;
209     LMul = 1;
210   } else {
211     llvm_unreachable("Impossible reg-to-reg copy");
212   }
213 
214   if (IsScalableVector) {
215     if (NF == 1) {
216       BuildMI(MBB, MBBI, DL, get(Opc), DstReg)
217           .addReg(SrcReg, getKillRegState(KillSrc));
218     } else {
219       const TargetRegisterInfo *TRI = STI.getRegisterInfo();
220 
221       int I = 0, End = NF, Incr = 1;
222       unsigned SrcEncoding = TRI->getEncodingValue(SrcReg);
223       unsigned DstEncoding = TRI->getEncodingValue(DstReg);
224       if (forwardCopyWillClobberTuple(DstEncoding, SrcEncoding, NF * LMul)) {
225         I = NF - 1;
226         End = -1;
227         Incr = -1;
228       }
229 
230       for (; I != End; I += Incr) {
231         BuildMI(MBB, MBBI, DL, get(Opc), TRI->getSubReg(DstReg, SubRegIdx + I))
232             .addReg(TRI->getSubReg(SrcReg, SubRegIdx + I),
233                     getKillRegState(KillSrc));
234       }
235     }
236   } else {
237     BuildMI(MBB, MBBI, DL, get(Opc), DstReg)
238         .addReg(SrcReg, getKillRegState(KillSrc))
239         .addReg(SrcReg, getKillRegState(KillSrc));
240   }
241 }
242 
243 void RISCVInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
244                                          MachineBasicBlock::iterator I,
245                                          Register SrcReg, bool IsKill, int FI,
246                                          const TargetRegisterClass *RC,
247                                          const TargetRegisterInfo *TRI) const {
248   DebugLoc DL;
249   if (I != MBB.end())
250     DL = I->getDebugLoc();
251 
252   MachineFunction *MF = MBB.getParent();
253   MachineFrameInfo &MFI = MF->getFrameInfo();
254 
255   unsigned Opcode;
256   bool IsScalableVector = true;
257   bool IsZvlsseg = true;
258   if (RISCV::GPRRegClass.hasSubClassEq(RC)) {
259     Opcode = TRI->getRegSizeInBits(RISCV::GPRRegClass) == 32 ?
260              RISCV::SW : RISCV::SD;
261     IsScalableVector = false;
262   } else if (RISCV::FPR16RegClass.hasSubClassEq(RC)) {
263     Opcode = RISCV::FSH;
264     IsScalableVector = false;
265   } else if (RISCV::FPR32RegClass.hasSubClassEq(RC)) {
266     Opcode = RISCV::FSW;
267     IsScalableVector = false;
268   } else if (RISCV::FPR64RegClass.hasSubClassEq(RC)) {
269     Opcode = RISCV::FSD;
270     IsScalableVector = false;
271   } else if (RISCV::VRRegClass.hasSubClassEq(RC)) {
272     Opcode = RISCV::PseudoVSPILL_M1;
273     IsZvlsseg = false;
274   } else if (RISCV::VRM2RegClass.hasSubClassEq(RC)) {
275     Opcode = RISCV::PseudoVSPILL_M2;
276     IsZvlsseg = false;
277   } else if (RISCV::VRM4RegClass.hasSubClassEq(RC)) {
278     Opcode = RISCV::PseudoVSPILL_M4;
279     IsZvlsseg = false;
280   } else if (RISCV::VRM8RegClass.hasSubClassEq(RC)) {
281     Opcode = RISCV::PseudoVSPILL_M8;
282     IsZvlsseg = false;
283   } else if (RISCV::VRN2M1RegClass.hasSubClassEq(RC))
284     Opcode = RISCV::PseudoVSPILL2_M1;
285   else if (RISCV::VRN2M2RegClass.hasSubClassEq(RC))
286     Opcode = RISCV::PseudoVSPILL2_M2;
287   else if (RISCV::VRN2M4RegClass.hasSubClassEq(RC))
288     Opcode = RISCV::PseudoVSPILL2_M4;
289   else if (RISCV::VRN3M1RegClass.hasSubClassEq(RC))
290     Opcode = RISCV::PseudoVSPILL3_M1;
291   else if (RISCV::VRN3M2RegClass.hasSubClassEq(RC))
292     Opcode = RISCV::PseudoVSPILL3_M2;
293   else if (RISCV::VRN4M1RegClass.hasSubClassEq(RC))
294     Opcode = RISCV::PseudoVSPILL4_M1;
295   else if (RISCV::VRN4M2RegClass.hasSubClassEq(RC))
296     Opcode = RISCV::PseudoVSPILL4_M2;
297   else if (RISCV::VRN5M1RegClass.hasSubClassEq(RC))
298     Opcode = RISCV::PseudoVSPILL5_M1;
299   else if (RISCV::VRN6M1RegClass.hasSubClassEq(RC))
300     Opcode = RISCV::PseudoVSPILL6_M1;
301   else if (RISCV::VRN7M1RegClass.hasSubClassEq(RC))
302     Opcode = RISCV::PseudoVSPILL7_M1;
303   else if (RISCV::VRN8M1RegClass.hasSubClassEq(RC))
304     Opcode = RISCV::PseudoVSPILL8_M1;
305   else
306     llvm_unreachable("Can't store this register to stack slot");
307 
308   if (IsScalableVector) {
309     MachineMemOperand *MMO = MF->getMachineMemOperand(
310         MachinePointerInfo::getFixedStack(*MF, FI), MachineMemOperand::MOStore,
311         MemoryLocation::UnknownSize, MFI.getObjectAlign(FI));
312 
313     MFI.setStackID(FI, TargetStackID::ScalableVector);
314     auto MIB = BuildMI(MBB, I, DL, get(Opcode))
315                    .addReg(SrcReg, getKillRegState(IsKill))
316                    .addFrameIndex(FI)
317                    .addMemOperand(MMO);
318     if (IsZvlsseg) {
319       // For spilling/reloading Zvlsseg registers, append the dummy field for
320       // the scaled vector length. The argument will be used when expanding
321       // these pseudo instructions.
322       MIB.addReg(RISCV::X0);
323     }
324   } else {
325     MachineMemOperand *MMO = MF->getMachineMemOperand(
326         MachinePointerInfo::getFixedStack(*MF, FI), MachineMemOperand::MOStore,
327         MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
328 
329     BuildMI(MBB, I, DL, get(Opcode))
330         .addReg(SrcReg, getKillRegState(IsKill))
331         .addFrameIndex(FI)
332         .addImm(0)
333         .addMemOperand(MMO);
334   }
335 }
336 
337 void RISCVInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
338                                           MachineBasicBlock::iterator I,
339                                           Register DstReg, int FI,
340                                           const TargetRegisterClass *RC,
341                                           const TargetRegisterInfo *TRI) const {
342   DebugLoc DL;
343   if (I != MBB.end())
344     DL = I->getDebugLoc();
345 
346   MachineFunction *MF = MBB.getParent();
347   MachineFrameInfo &MFI = MF->getFrameInfo();
348 
349   unsigned Opcode;
350   bool IsScalableVector = true;
351   bool IsZvlsseg = true;
352   if (RISCV::GPRRegClass.hasSubClassEq(RC)) {
353     Opcode = TRI->getRegSizeInBits(RISCV::GPRRegClass) == 32 ?
354              RISCV::LW : RISCV::LD;
355     IsScalableVector = false;
356   } else if (RISCV::FPR16RegClass.hasSubClassEq(RC)) {
357     Opcode = RISCV::FLH;
358     IsScalableVector = false;
359   } else if (RISCV::FPR32RegClass.hasSubClassEq(RC)) {
360     Opcode = RISCV::FLW;
361     IsScalableVector = false;
362   } else if (RISCV::FPR64RegClass.hasSubClassEq(RC)) {
363     Opcode = RISCV::FLD;
364     IsScalableVector = false;
365   } else if (RISCV::VRRegClass.hasSubClassEq(RC)) {
366     Opcode = RISCV::PseudoVRELOAD_M1;
367     IsZvlsseg = false;
368   } else if (RISCV::VRM2RegClass.hasSubClassEq(RC)) {
369     Opcode = RISCV::PseudoVRELOAD_M2;
370     IsZvlsseg = false;
371   } else if (RISCV::VRM4RegClass.hasSubClassEq(RC)) {
372     Opcode = RISCV::PseudoVRELOAD_M4;
373     IsZvlsseg = false;
374   } else if (RISCV::VRM8RegClass.hasSubClassEq(RC)) {
375     Opcode = RISCV::PseudoVRELOAD_M8;
376     IsZvlsseg = false;
377   } else if (RISCV::VRN2M1RegClass.hasSubClassEq(RC))
378     Opcode = RISCV::PseudoVRELOAD2_M1;
379   else if (RISCV::VRN2M2RegClass.hasSubClassEq(RC))
380     Opcode = RISCV::PseudoVRELOAD2_M2;
381   else if (RISCV::VRN2M4RegClass.hasSubClassEq(RC))
382     Opcode = RISCV::PseudoVRELOAD2_M4;
383   else if (RISCV::VRN3M1RegClass.hasSubClassEq(RC))
384     Opcode = RISCV::PseudoVRELOAD3_M1;
385   else if (RISCV::VRN3M2RegClass.hasSubClassEq(RC))
386     Opcode = RISCV::PseudoVRELOAD3_M2;
387   else if (RISCV::VRN4M1RegClass.hasSubClassEq(RC))
388     Opcode = RISCV::PseudoVRELOAD4_M1;
389   else if (RISCV::VRN4M2RegClass.hasSubClassEq(RC))
390     Opcode = RISCV::PseudoVRELOAD4_M2;
391   else if (RISCV::VRN5M1RegClass.hasSubClassEq(RC))
392     Opcode = RISCV::PseudoVRELOAD5_M1;
393   else if (RISCV::VRN6M1RegClass.hasSubClassEq(RC))
394     Opcode = RISCV::PseudoVRELOAD6_M1;
395   else if (RISCV::VRN7M1RegClass.hasSubClassEq(RC))
396     Opcode = RISCV::PseudoVRELOAD7_M1;
397   else if (RISCV::VRN8M1RegClass.hasSubClassEq(RC))
398     Opcode = RISCV::PseudoVRELOAD8_M1;
399   else
400     llvm_unreachable("Can't load this register from stack slot");
401 
402   if (IsScalableVector) {
403     MachineMemOperand *MMO = MF->getMachineMemOperand(
404         MachinePointerInfo::getFixedStack(*MF, FI), MachineMemOperand::MOLoad,
405         MemoryLocation::UnknownSize, MFI.getObjectAlign(FI));
406 
407     MFI.setStackID(FI, TargetStackID::ScalableVector);
408     auto MIB = BuildMI(MBB, I, DL, get(Opcode), DstReg)
409                    .addFrameIndex(FI)
410                    .addMemOperand(MMO);
411     if (IsZvlsseg) {
412       // For spilling/reloading Zvlsseg registers, append the dummy field for
413       // the scaled vector length. The argument will be used when expanding
414       // these pseudo instructions.
415       MIB.addReg(RISCV::X0);
416     }
417   } else {
418     MachineMemOperand *MMO = MF->getMachineMemOperand(
419         MachinePointerInfo::getFixedStack(*MF, FI), MachineMemOperand::MOLoad,
420         MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
421 
422     BuildMI(MBB, I, DL, get(Opcode), DstReg)
423         .addFrameIndex(FI)
424         .addImm(0)
425         .addMemOperand(MMO);
426   }
427 }
428 
429 void RISCVInstrInfo::movImm(MachineBasicBlock &MBB,
430                             MachineBasicBlock::iterator MBBI,
431                             const DebugLoc &DL, Register DstReg, uint64_t Val,
432                             MachineInstr::MIFlag Flag) const {
433   MachineFunction *MF = MBB.getParent();
434   MachineRegisterInfo &MRI = MF->getRegInfo();
435   Register SrcReg = RISCV::X0;
436   Register Result = MRI.createVirtualRegister(&RISCV::GPRRegClass);
437   unsigned Num = 0;
438 
439   if (!STI.is64Bit() && !isInt<32>(Val))
440     report_fatal_error("Should only materialize 32-bit constants for RV32");
441 
442   RISCVMatInt::InstSeq Seq =
443       RISCVMatInt::generateInstSeq(Val, STI.getFeatureBits());
444   assert(!Seq.empty());
445 
446   for (RISCVMatInt::Inst &Inst : Seq) {
447     // Write the final result to DstReg if it's the last instruction in the Seq.
448     // Otherwise, write the result to the temp register.
449     if (++Num == Seq.size())
450       Result = DstReg;
451 
452     if (Inst.Opc == RISCV::LUI) {
453       BuildMI(MBB, MBBI, DL, get(RISCV::LUI), Result)
454           .addImm(Inst.Imm)
455           .setMIFlag(Flag);
456     } else if (Inst.Opc == RISCV::ADDUW) {
457       BuildMI(MBB, MBBI, DL, get(RISCV::ADDUW), Result)
458           .addReg(SrcReg, RegState::Kill)
459           .addReg(RISCV::X0)
460           .setMIFlag(Flag);
461     } else if (Inst.Opc == RISCV::SH1ADD || Inst.Opc == RISCV::SH2ADD ||
462                Inst.Opc == RISCV::SH3ADD) {
463       BuildMI(MBB, MBBI, DL, get(Inst.Opc), Result)
464           .addReg(SrcReg, RegState::Kill)
465           .addReg(SrcReg, RegState::Kill)
466           .setMIFlag(Flag);
467     } else {
468       BuildMI(MBB, MBBI, DL, get(Inst.Opc), Result)
469           .addReg(SrcReg, RegState::Kill)
470           .addImm(Inst.Imm)
471           .setMIFlag(Flag);
472     }
473     // Only the first instruction has X0 as its source.
474     SrcReg = Result;
475   }
476 }
477 
478 static RISCVCC::CondCode getCondFromBranchOpc(unsigned Opc) {
479   switch (Opc) {
480   default:
481     return RISCVCC::COND_INVALID;
482   case RISCV::BEQ:
483     return RISCVCC::COND_EQ;
484   case RISCV::BNE:
485     return RISCVCC::COND_NE;
486   case RISCV::BLT:
487     return RISCVCC::COND_LT;
488   case RISCV::BGE:
489     return RISCVCC::COND_GE;
490   case RISCV::BLTU:
491     return RISCVCC::COND_LTU;
492   case RISCV::BGEU:
493     return RISCVCC::COND_GEU;
494   }
495 }
496 
497 // The contents of values added to Cond are not examined outside of
498 // RISCVInstrInfo, giving us flexibility in what to push to it. For RISCV, we
499 // push BranchOpcode, Reg1, Reg2.
500 static void parseCondBranch(MachineInstr &LastInst, MachineBasicBlock *&Target,
501                             SmallVectorImpl<MachineOperand> &Cond) {
502   // Block ends with fall-through condbranch.
503   assert(LastInst.getDesc().isConditionalBranch() &&
504          "Unknown conditional branch");
505   Target = LastInst.getOperand(2).getMBB();
506   unsigned CC = getCondFromBranchOpc(LastInst.getOpcode());
507   Cond.push_back(MachineOperand::CreateImm(CC));
508   Cond.push_back(LastInst.getOperand(0));
509   Cond.push_back(LastInst.getOperand(1));
510 }
511 
512 const MCInstrDesc &RISCVInstrInfo::getBrCond(RISCVCC::CondCode CC) const {
513   switch (CC) {
514   default:
515     llvm_unreachable("Unknown condition code!");
516   case RISCVCC::COND_EQ:
517     return get(RISCV::BEQ);
518   case RISCVCC::COND_NE:
519     return get(RISCV::BNE);
520   case RISCVCC::COND_LT:
521     return get(RISCV::BLT);
522   case RISCVCC::COND_GE:
523     return get(RISCV::BGE);
524   case RISCVCC::COND_LTU:
525     return get(RISCV::BLTU);
526   case RISCVCC::COND_GEU:
527     return get(RISCV::BGEU);
528   }
529 }
530 
531 RISCVCC::CondCode RISCVCC::getOppositeBranchCondition(RISCVCC::CondCode CC) {
532   switch (CC) {
533   default:
534     llvm_unreachable("Unrecognized conditional branch");
535   case RISCVCC::COND_EQ:
536     return RISCVCC::COND_NE;
537   case RISCVCC::COND_NE:
538     return RISCVCC::COND_EQ;
539   case RISCVCC::COND_LT:
540     return RISCVCC::COND_GE;
541   case RISCVCC::COND_GE:
542     return RISCVCC::COND_LT;
543   case RISCVCC::COND_LTU:
544     return RISCVCC::COND_GEU;
545   case RISCVCC::COND_GEU:
546     return RISCVCC::COND_LTU;
547   }
548 }
549 
550 bool RISCVInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
551                                    MachineBasicBlock *&TBB,
552                                    MachineBasicBlock *&FBB,
553                                    SmallVectorImpl<MachineOperand> &Cond,
554                                    bool AllowModify) const {
555   TBB = FBB = nullptr;
556   Cond.clear();
557 
558   // If the block has no terminators, it just falls into the block after it.
559   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
560   if (I == MBB.end() || !isUnpredicatedTerminator(*I))
561     return false;
562 
563   // Count the number of terminators and find the first unconditional or
564   // indirect branch.
565   MachineBasicBlock::iterator FirstUncondOrIndirectBr = MBB.end();
566   int NumTerminators = 0;
567   for (auto J = I.getReverse(); J != MBB.rend() && isUnpredicatedTerminator(*J);
568        J++) {
569     NumTerminators++;
570     if (J->getDesc().isUnconditionalBranch() ||
571         J->getDesc().isIndirectBranch()) {
572       FirstUncondOrIndirectBr = J.getReverse();
573     }
574   }
575 
576   // If AllowModify is true, we can erase any terminators after
577   // FirstUncondOrIndirectBR.
578   if (AllowModify && FirstUncondOrIndirectBr != MBB.end()) {
579     while (std::next(FirstUncondOrIndirectBr) != MBB.end()) {
580       std::next(FirstUncondOrIndirectBr)->eraseFromParent();
581       NumTerminators--;
582     }
583     I = FirstUncondOrIndirectBr;
584   }
585 
586   // We can't handle blocks that end in an indirect branch.
587   if (I->getDesc().isIndirectBranch())
588     return true;
589 
590   // We can't handle blocks with more than 2 terminators.
591   if (NumTerminators > 2)
592     return true;
593 
594   // Handle a single unconditional branch.
595   if (NumTerminators == 1 && I->getDesc().isUnconditionalBranch()) {
596     TBB = getBranchDestBlock(*I);
597     return false;
598   }
599 
600   // Handle a single conditional branch.
601   if (NumTerminators == 1 && I->getDesc().isConditionalBranch()) {
602     parseCondBranch(*I, TBB, Cond);
603     return false;
604   }
605 
606   // Handle a conditional branch followed by an unconditional branch.
607   if (NumTerminators == 2 && std::prev(I)->getDesc().isConditionalBranch() &&
608       I->getDesc().isUnconditionalBranch()) {
609     parseCondBranch(*std::prev(I), TBB, Cond);
610     FBB = getBranchDestBlock(*I);
611     return false;
612   }
613 
614   // Otherwise, we can't handle this.
615   return true;
616 }
617 
618 unsigned RISCVInstrInfo::removeBranch(MachineBasicBlock &MBB,
619                                       int *BytesRemoved) const {
620   if (BytesRemoved)
621     *BytesRemoved = 0;
622   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
623   if (I == MBB.end())
624     return 0;
625 
626   if (!I->getDesc().isUnconditionalBranch() &&
627       !I->getDesc().isConditionalBranch())
628     return 0;
629 
630   // Remove the branch.
631   if (BytesRemoved)
632     *BytesRemoved += getInstSizeInBytes(*I);
633   I->eraseFromParent();
634 
635   I = MBB.end();
636 
637   if (I == MBB.begin())
638     return 1;
639   --I;
640   if (!I->getDesc().isConditionalBranch())
641     return 1;
642 
643   // Remove the branch.
644   if (BytesRemoved)
645     *BytesRemoved += getInstSizeInBytes(*I);
646   I->eraseFromParent();
647   return 2;
648 }
649 
650 // Inserts a branch into the end of the specific MachineBasicBlock, returning
651 // the number of instructions inserted.
652 unsigned RISCVInstrInfo::insertBranch(
653     MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
654     ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
655   if (BytesAdded)
656     *BytesAdded = 0;
657 
658   // Shouldn't be a fall through.
659   assert(TBB && "insertBranch must not be told to insert a fallthrough");
660   assert((Cond.size() == 3 || Cond.size() == 0) &&
661          "RISCV branch conditions have two components!");
662 
663   // Unconditional branch.
664   if (Cond.empty()) {
665     MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(TBB);
666     if (BytesAdded)
667       *BytesAdded += getInstSizeInBytes(MI);
668     return 1;
669   }
670 
671   // Either a one or two-way conditional branch.
672   auto CC = static_cast<RISCVCC::CondCode>(Cond[0].getImm());
673   MachineInstr &CondMI =
674       *BuildMI(&MBB, DL, getBrCond(CC)).add(Cond[1]).add(Cond[2]).addMBB(TBB);
675   if (BytesAdded)
676     *BytesAdded += getInstSizeInBytes(CondMI);
677 
678   // One-way conditional branch.
679   if (!FBB)
680     return 1;
681 
682   // Two-way conditional branch.
683   MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(FBB);
684   if (BytesAdded)
685     *BytesAdded += getInstSizeInBytes(MI);
686   return 2;
687 }
688 
689 unsigned RISCVInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
690                                               MachineBasicBlock &DestBB,
691                                               const DebugLoc &DL,
692                                               int64_t BrOffset,
693                                               RegScavenger *RS) const {
694   assert(RS && "RegScavenger required for long branching");
695   assert(MBB.empty() &&
696          "new block should be inserted for expanding unconditional branch");
697   assert(MBB.pred_size() == 1);
698 
699   MachineFunction *MF = MBB.getParent();
700   MachineRegisterInfo &MRI = MF->getRegInfo();
701 
702   if (!isInt<32>(BrOffset))
703     report_fatal_error(
704         "Branch offsets outside of the signed 32-bit range not supported");
705 
706   // FIXME: A virtual register must be used initially, as the register
707   // scavenger won't work with empty blocks (SIInstrInfo::insertIndirectBranch
708   // uses the same workaround).
709   Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
710   auto II = MBB.end();
711 
712   MachineInstr &MI = *BuildMI(MBB, II, DL, get(RISCV::PseudoJump))
713                           .addReg(ScratchReg, RegState::Define | RegState::Dead)
714                           .addMBB(&DestBB, RISCVII::MO_CALL);
715 
716   RS->enterBasicBlockEnd(MBB);
717   unsigned Scav = RS->scavengeRegisterBackwards(RISCV::GPRRegClass,
718                                                 MI.getIterator(), false, 0);
719   MRI.replaceRegWith(ScratchReg, Scav);
720   MRI.clearVirtRegs();
721   RS->setRegUsed(Scav);
722   return 8;
723 }
724 
725 bool RISCVInstrInfo::reverseBranchCondition(
726     SmallVectorImpl<MachineOperand> &Cond) const {
727   assert((Cond.size() == 3) && "Invalid branch condition!");
728   auto CC = static_cast<RISCVCC::CondCode>(Cond[0].getImm());
729   Cond[0].setImm(getOppositeBranchCondition(CC));
730   return false;
731 }
732 
733 MachineBasicBlock *
734 RISCVInstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
735   assert(MI.getDesc().isBranch() && "Unexpected opcode!");
736   // The branch target is always the last operand.
737   int NumOp = MI.getNumExplicitOperands();
738   return MI.getOperand(NumOp - 1).getMBB();
739 }
740 
741 bool RISCVInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
742                                            int64_t BrOffset) const {
743   unsigned XLen = STI.getXLen();
744   // Ideally we could determine the supported branch offset from the
745   // RISCVII::FormMask, but this can't be used for Pseudo instructions like
746   // PseudoBR.
747   switch (BranchOp) {
748   default:
749     llvm_unreachable("Unexpected opcode!");
750   case RISCV::BEQ:
751   case RISCV::BNE:
752   case RISCV::BLT:
753   case RISCV::BGE:
754   case RISCV::BLTU:
755   case RISCV::BGEU:
756     return isIntN(13, BrOffset);
757   case RISCV::JAL:
758   case RISCV::PseudoBR:
759     return isIntN(21, BrOffset);
760   case RISCV::PseudoJump:
761     return isIntN(32, SignExtend64(BrOffset + 0x800, XLen));
762   }
763 }
764 
765 unsigned RISCVInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
766   unsigned Opcode = MI.getOpcode();
767 
768   switch (Opcode) {
769   default: {
770     if (MI.getParent() && MI.getParent()->getParent()) {
771       const auto MF = MI.getMF();
772       const auto &TM = static_cast<const RISCVTargetMachine &>(MF->getTarget());
773       const MCRegisterInfo &MRI = *TM.getMCRegisterInfo();
774       const MCSubtargetInfo &STI = *TM.getMCSubtargetInfo();
775       const RISCVSubtarget &ST = MF->getSubtarget<RISCVSubtarget>();
776       if (isCompressibleInst(MI, &ST, MRI, STI))
777         return 2;
778     }
779     return get(Opcode).getSize();
780   }
781   case TargetOpcode::EH_LABEL:
782   case TargetOpcode::IMPLICIT_DEF:
783   case TargetOpcode::KILL:
784   case TargetOpcode::DBG_VALUE:
785     return 0;
786   // These values are determined based on RISCVExpandAtomicPseudoInsts,
787   // RISCVExpandPseudoInsts and RISCVMCCodeEmitter, depending on where the
788   // pseudos are expanded.
789   case RISCV::PseudoCALLReg:
790   case RISCV::PseudoCALL:
791   case RISCV::PseudoJump:
792   case RISCV::PseudoTAIL:
793   case RISCV::PseudoLLA:
794   case RISCV::PseudoLA:
795   case RISCV::PseudoLA_TLS_IE:
796   case RISCV::PseudoLA_TLS_GD:
797     return 8;
798   case RISCV::PseudoAtomicLoadNand32:
799   case RISCV::PseudoAtomicLoadNand64:
800     return 20;
801   case RISCV::PseudoMaskedAtomicSwap32:
802   case RISCV::PseudoMaskedAtomicLoadAdd32:
803   case RISCV::PseudoMaskedAtomicLoadSub32:
804     return 28;
805   case RISCV::PseudoMaskedAtomicLoadNand32:
806     return 32;
807   case RISCV::PseudoMaskedAtomicLoadMax32:
808   case RISCV::PseudoMaskedAtomicLoadMin32:
809     return 44;
810   case RISCV::PseudoMaskedAtomicLoadUMax32:
811   case RISCV::PseudoMaskedAtomicLoadUMin32:
812     return 36;
813   case RISCV::PseudoCmpXchg32:
814   case RISCV::PseudoCmpXchg64:
815     return 16;
816   case RISCV::PseudoMaskedCmpXchg32:
817     return 32;
818   case TargetOpcode::INLINEASM:
819   case TargetOpcode::INLINEASM_BR: {
820     const MachineFunction &MF = *MI.getParent()->getParent();
821     const auto &TM = static_cast<const RISCVTargetMachine &>(MF.getTarget());
822     return getInlineAsmLength(MI.getOperand(0).getSymbolName(),
823                               *TM.getMCAsmInfo());
824   }
825   case RISCV::PseudoVSPILL2_M1:
826   case RISCV::PseudoVSPILL2_M2:
827   case RISCV::PseudoVSPILL2_M4:
828   case RISCV::PseudoVSPILL3_M1:
829   case RISCV::PseudoVSPILL3_M2:
830   case RISCV::PseudoVSPILL4_M1:
831   case RISCV::PseudoVSPILL4_M2:
832   case RISCV::PseudoVSPILL5_M1:
833   case RISCV::PseudoVSPILL6_M1:
834   case RISCV::PseudoVSPILL7_M1:
835   case RISCV::PseudoVSPILL8_M1:
836   case RISCV::PseudoVRELOAD2_M1:
837   case RISCV::PseudoVRELOAD2_M2:
838   case RISCV::PseudoVRELOAD2_M4:
839   case RISCV::PseudoVRELOAD3_M1:
840   case RISCV::PseudoVRELOAD3_M2:
841   case RISCV::PseudoVRELOAD4_M1:
842   case RISCV::PseudoVRELOAD4_M2:
843   case RISCV::PseudoVRELOAD5_M1:
844   case RISCV::PseudoVRELOAD6_M1:
845   case RISCV::PseudoVRELOAD7_M1:
846   case RISCV::PseudoVRELOAD8_M1: {
847     // The values are determined based on expandVSPILL and expandVRELOAD that
848     // expand the pseudos depending on NF.
849     unsigned NF = isRVVSpillForZvlsseg(Opcode)->first;
850     return 4 * (2 * NF - 1);
851   }
852   }
853 }
854 
855 bool RISCVInstrInfo::isAsCheapAsAMove(const MachineInstr &MI) const {
856   const unsigned Opcode = MI.getOpcode();
857   switch (Opcode) {
858   default:
859     break;
860   case RISCV::FSGNJ_D:
861   case RISCV::FSGNJ_S:
862     // The canonical floating-point move is fsgnj rd, rs, rs.
863     return MI.getOperand(1).isReg() && MI.getOperand(2).isReg() &&
864            MI.getOperand(1).getReg() == MI.getOperand(2).getReg();
865   case RISCV::ADDI:
866   case RISCV::ORI:
867   case RISCV::XORI:
868     return (MI.getOperand(1).isReg() &&
869             MI.getOperand(1).getReg() == RISCV::X0) ||
870            (MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0);
871   }
872   return MI.isAsCheapAsAMove();
873 }
874 
875 Optional<DestSourcePair>
876 RISCVInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
877   if (MI.isMoveReg())
878     return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
879   switch (MI.getOpcode()) {
880   default:
881     break;
882   case RISCV::ADDI:
883     // Operand 1 can be a frameindex but callers expect registers
884     if (MI.getOperand(1).isReg() && MI.getOperand(2).isImm() &&
885         MI.getOperand(2).getImm() == 0)
886       return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
887     break;
888   case RISCV::FSGNJ_D:
889   case RISCV::FSGNJ_S:
890     // The canonical floating-point move is fsgnj rd, rs, rs.
891     if (MI.getOperand(1).isReg() && MI.getOperand(2).isReg() &&
892         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
893       return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
894     break;
895   }
896   return None;
897 }
898 
899 bool RISCVInstrInfo::verifyInstruction(const MachineInstr &MI,
900                                        StringRef &ErrInfo) const {
901   const MCInstrInfo *MCII = STI.getInstrInfo();
902   MCInstrDesc const &Desc = MCII->get(MI.getOpcode());
903 
904   for (auto &OI : enumerate(Desc.operands())) {
905     unsigned OpType = OI.value().OperandType;
906     if (OpType >= RISCVOp::OPERAND_FIRST_RISCV_IMM &&
907         OpType <= RISCVOp::OPERAND_LAST_RISCV_IMM) {
908       const MachineOperand &MO = MI.getOperand(OI.index());
909       if (MO.isImm()) {
910         int64_t Imm = MO.getImm();
911         bool Ok;
912         switch (OpType) {
913         default:
914           llvm_unreachable("Unexpected operand type");
915         case RISCVOp::OPERAND_UIMM2:
916           Ok = isUInt<2>(Imm);
917           break;
918         case RISCVOp::OPERAND_UIMM3:
919           Ok = isUInt<3>(Imm);
920           break;
921         case RISCVOp::OPERAND_UIMM4:
922           Ok = isUInt<4>(Imm);
923           break;
924         case RISCVOp::OPERAND_UIMM5:
925           Ok = isUInt<5>(Imm);
926           break;
927         case RISCVOp::OPERAND_UIMM7:
928           Ok = isUInt<7>(Imm);
929           break;
930         case RISCVOp::OPERAND_UIMM12:
931           Ok = isUInt<12>(Imm);
932           break;
933         case RISCVOp::OPERAND_SIMM12:
934           Ok = isInt<12>(Imm);
935           break;
936         case RISCVOp::OPERAND_UIMM20:
937           Ok = isUInt<20>(Imm);
938           break;
939         case RISCVOp::OPERAND_UIMMLOG2XLEN:
940           if (STI.getTargetTriple().isArch64Bit())
941             Ok = isUInt<6>(Imm);
942           else
943             Ok = isUInt<5>(Imm);
944           break;
945         }
946         if (!Ok) {
947           ErrInfo = "Invalid immediate";
948           return false;
949         }
950       }
951     }
952   }
953 
954   return true;
955 }
956 
957 // Return true if get the base operand, byte offset of an instruction and the
958 // memory width. Width is the size of memory that is being loaded/stored.
959 bool RISCVInstrInfo::getMemOperandWithOffsetWidth(
960     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
961     unsigned &Width, const TargetRegisterInfo *TRI) const {
962   if (!LdSt.mayLoadOrStore())
963     return false;
964 
965   // Here we assume the standard RISC-V ISA, which uses a base+offset
966   // addressing mode. You'll need to relax these conditions to support custom
967   // load/stores instructions.
968   if (LdSt.getNumExplicitOperands() != 3)
969     return false;
970   if (!LdSt.getOperand(1).isReg() || !LdSt.getOperand(2).isImm())
971     return false;
972 
973   if (!LdSt.hasOneMemOperand())
974     return false;
975 
976   Width = (*LdSt.memoperands_begin())->getSize();
977   BaseReg = &LdSt.getOperand(1);
978   Offset = LdSt.getOperand(2).getImm();
979   return true;
980 }
981 
982 bool RISCVInstrInfo::areMemAccessesTriviallyDisjoint(
983     const MachineInstr &MIa, const MachineInstr &MIb) const {
984   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
985   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
986 
987   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
988       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
989     return false;
990 
991   // Retrieve the base register, offset from the base register and width. Width
992   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
993   // base registers are identical, and the offset of a lower memory access +
994   // the width doesn't overlap the offset of a higher memory access,
995   // then the memory accesses are different.
996   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
997   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
998   int64_t OffsetA = 0, OffsetB = 0;
999   unsigned int WidthA = 0, WidthB = 0;
1000   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
1001       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
1002     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
1003       int LowOffset = std::min(OffsetA, OffsetB);
1004       int HighOffset = std::max(OffsetA, OffsetB);
1005       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1006       if (LowOffset + LowWidth <= HighOffset)
1007         return true;
1008     }
1009   }
1010   return false;
1011 }
1012 
1013 std::pair<unsigned, unsigned>
1014 RISCVInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
1015   const unsigned Mask = RISCVII::MO_DIRECT_FLAG_MASK;
1016   return std::make_pair(TF & Mask, TF & ~Mask);
1017 }
1018 
1019 ArrayRef<std::pair<unsigned, const char *>>
1020 RISCVInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
1021   using namespace RISCVII;
1022   static const std::pair<unsigned, const char *> TargetFlags[] = {
1023       {MO_CALL, "riscv-call"},
1024       {MO_PLT, "riscv-plt"},
1025       {MO_LO, "riscv-lo"},
1026       {MO_HI, "riscv-hi"},
1027       {MO_PCREL_LO, "riscv-pcrel-lo"},
1028       {MO_PCREL_HI, "riscv-pcrel-hi"},
1029       {MO_GOT_HI, "riscv-got-hi"},
1030       {MO_TPREL_LO, "riscv-tprel-lo"},
1031       {MO_TPREL_HI, "riscv-tprel-hi"},
1032       {MO_TPREL_ADD, "riscv-tprel-add"},
1033       {MO_TLS_GOT_HI, "riscv-tls-got-hi"},
1034       {MO_TLS_GD_HI, "riscv-tls-gd-hi"}};
1035   return makeArrayRef(TargetFlags);
1036 }
1037 bool RISCVInstrInfo::isFunctionSafeToOutlineFrom(
1038     MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
1039   const Function &F = MF.getFunction();
1040 
1041   // Can F be deduplicated by the linker? If it can, don't outline from it.
1042   if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
1043     return false;
1044 
1045   // Don't outline from functions with section markings; the program could
1046   // expect that all the code is in the named section.
1047   if (F.hasSection())
1048     return false;
1049 
1050   // It's safe to outline from MF.
1051   return true;
1052 }
1053 
1054 bool RISCVInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
1055                                             unsigned &Flags) const {
1056   // More accurate safety checking is done in getOutliningCandidateInfo.
1057   return true;
1058 }
1059 
1060 // Enum values indicating how an outlined call should be constructed.
1061 enum MachineOutlinerConstructionID {
1062   MachineOutlinerDefault
1063 };
1064 
1065 outliner::OutlinedFunction RISCVInstrInfo::getOutliningCandidateInfo(
1066     std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
1067 
1068   // First we need to filter out candidates where the X5 register (IE t0) can't
1069   // be used to setup the function call.
1070   auto CannotInsertCall = [](outliner::Candidate &C) {
1071     const TargetRegisterInfo *TRI = C.getMF()->getSubtarget().getRegisterInfo();
1072 
1073     C.initLRU(*TRI);
1074     LiveRegUnits LRU = C.LRU;
1075     return !LRU.available(RISCV::X5);
1076   };
1077 
1078   llvm::erase_if(RepeatedSequenceLocs, CannotInsertCall);
1079 
1080   // If the sequence doesn't have enough candidates left, then we're done.
1081   if (RepeatedSequenceLocs.size() < 2)
1082     return outliner::OutlinedFunction();
1083 
1084   unsigned SequenceSize = 0;
1085 
1086   auto I = RepeatedSequenceLocs[0].front();
1087   auto E = std::next(RepeatedSequenceLocs[0].back());
1088   for (; I != E; ++I)
1089     SequenceSize += getInstSizeInBytes(*I);
1090 
1091   // call t0, function = 8 bytes.
1092   unsigned CallOverhead = 8;
1093   for (auto &C : RepeatedSequenceLocs)
1094     C.setCallInfo(MachineOutlinerDefault, CallOverhead);
1095 
1096   // jr t0 = 4 bytes, 2 bytes if compressed instructions are enabled.
1097   unsigned FrameOverhead = 4;
1098   if (RepeatedSequenceLocs[0].getMF()->getSubtarget()
1099           .getFeatureBits()[RISCV::FeatureStdExtC])
1100     FrameOverhead = 2;
1101 
1102   return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
1103                                     FrameOverhead, MachineOutlinerDefault);
1104 }
1105 
1106 outliner::InstrType
1107 RISCVInstrInfo::getOutliningType(MachineBasicBlock::iterator &MBBI,
1108                                  unsigned Flags) const {
1109   MachineInstr &MI = *MBBI;
1110   MachineBasicBlock *MBB = MI.getParent();
1111   const TargetRegisterInfo *TRI =
1112       MBB->getParent()->getSubtarget().getRegisterInfo();
1113 
1114   // Positions generally can't safely be outlined.
1115   if (MI.isPosition()) {
1116     // We can manually strip out CFI instructions later.
1117     if (MI.isCFIInstruction())
1118       return outliner::InstrType::Invisible;
1119 
1120     return outliner::InstrType::Illegal;
1121   }
1122 
1123   // Don't trust the user to write safe inline assembly.
1124   if (MI.isInlineAsm())
1125     return outliner::InstrType::Illegal;
1126 
1127   // We can't outline branches to other basic blocks.
1128   if (MI.isTerminator() && !MBB->succ_empty())
1129     return outliner::InstrType::Illegal;
1130 
1131   // We need support for tail calls to outlined functions before return
1132   // statements can be allowed.
1133   if (MI.isReturn())
1134     return outliner::InstrType::Illegal;
1135 
1136   // Don't allow modifying the X5 register which we use for return addresses for
1137   // these outlined functions.
1138   if (MI.modifiesRegister(RISCV::X5, TRI) ||
1139       MI.getDesc().hasImplicitDefOfPhysReg(RISCV::X5))
1140     return outliner::InstrType::Illegal;
1141 
1142   // Make sure the operands don't reference something unsafe.
1143   for (const auto &MO : MI.operands())
1144     if (MO.isMBB() || MO.isBlockAddress() || MO.isCPI() || MO.isJTI())
1145       return outliner::InstrType::Illegal;
1146 
1147   // Don't allow instructions which won't be materialized to impact outlining
1148   // analysis.
1149   if (MI.isMetaInstruction())
1150     return outliner::InstrType::Invisible;
1151 
1152   return outliner::InstrType::Legal;
1153 }
1154 
1155 void RISCVInstrInfo::buildOutlinedFrame(
1156     MachineBasicBlock &MBB, MachineFunction &MF,
1157     const outliner::OutlinedFunction &OF) const {
1158 
1159   // Strip out any CFI instructions
1160   bool Changed = true;
1161   while (Changed) {
1162     Changed = false;
1163     auto I = MBB.begin();
1164     auto E = MBB.end();
1165     for (; I != E; ++I) {
1166       if (I->isCFIInstruction()) {
1167         I->removeFromParent();
1168         Changed = true;
1169         break;
1170       }
1171     }
1172   }
1173 
1174   MBB.addLiveIn(RISCV::X5);
1175 
1176   // Add in a return instruction to the end of the outlined frame.
1177   MBB.insert(MBB.end(), BuildMI(MF, DebugLoc(), get(RISCV::JALR))
1178       .addReg(RISCV::X0, RegState::Define)
1179       .addReg(RISCV::X5)
1180       .addImm(0));
1181 }
1182 
1183 MachineBasicBlock::iterator RISCVInstrInfo::insertOutlinedCall(
1184     Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
1185     MachineFunction &MF, const outliner::Candidate &C) const {
1186 
1187   // Add in a call instruction to the outlined function at the given location.
1188   It = MBB.insert(It,
1189                   BuildMI(MF, DebugLoc(), get(RISCV::PseudoCALLReg), RISCV::X5)
1190                       .addGlobalAddress(M.getNamedValue(MF.getName()), 0,
1191                                         RISCVII::MO_CALL));
1192   return It;
1193 }
1194 
1195 // clang-format off
1196 #define CASE_VFMA_OPCODE_COMMON(OP, TYPE, LMUL)                                \
1197   RISCV::PseudoV##OP##_##TYPE##_##LMUL
1198 
1199 #define CASE_VFMA_OPCODE_LMULS(OP, TYPE)                                       \
1200   CASE_VFMA_OPCODE_COMMON(OP, TYPE, MF8):                                      \
1201   case CASE_VFMA_OPCODE_COMMON(OP, TYPE, MF4):                                 \
1202   case CASE_VFMA_OPCODE_COMMON(OP, TYPE, MF2):                                 \
1203   case CASE_VFMA_OPCODE_COMMON(OP, TYPE, M1):                                  \
1204   case CASE_VFMA_OPCODE_COMMON(OP, TYPE, M2):                                  \
1205   case CASE_VFMA_OPCODE_COMMON(OP, TYPE, M4):                                  \
1206   case CASE_VFMA_OPCODE_COMMON(OP, TYPE, M8)
1207 
1208 #define CASE_VFMA_SPLATS(OP)                                                   \
1209   CASE_VFMA_OPCODE_LMULS(OP, VF16):                                            \
1210   case CASE_VFMA_OPCODE_LMULS(OP, VF32):                                       \
1211   case CASE_VFMA_OPCODE_LMULS(OP, VF64)
1212 // clang-format on
1213 
1214 bool RISCVInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
1215                                            unsigned &SrcOpIdx1,
1216                                            unsigned &SrcOpIdx2) const {
1217   const MCInstrDesc &Desc = MI.getDesc();
1218   if (!Desc.isCommutable())
1219     return false;
1220 
1221   switch (MI.getOpcode()) {
1222   case CASE_VFMA_SPLATS(FMADD):
1223   case CASE_VFMA_SPLATS(FMSUB):
1224   case CASE_VFMA_SPLATS(FMACC):
1225   case CASE_VFMA_SPLATS(FMSAC):
1226   case CASE_VFMA_SPLATS(FNMADD):
1227   case CASE_VFMA_SPLATS(FNMSUB):
1228   case CASE_VFMA_SPLATS(FNMACC):
1229   case CASE_VFMA_SPLATS(FNMSAC):
1230   case CASE_VFMA_OPCODE_LMULS(FMACC, VV):
1231   case CASE_VFMA_OPCODE_LMULS(FMSAC, VV):
1232   case CASE_VFMA_OPCODE_LMULS(FNMACC, VV):
1233   case CASE_VFMA_OPCODE_LMULS(FNMSAC, VV):
1234   case CASE_VFMA_OPCODE_LMULS(MADD, VX):
1235   case CASE_VFMA_OPCODE_LMULS(NMSUB, VX):
1236   case CASE_VFMA_OPCODE_LMULS(MACC, VX):
1237   case CASE_VFMA_OPCODE_LMULS(NMSAC, VX):
1238   case CASE_VFMA_OPCODE_LMULS(MACC, VV):
1239   case CASE_VFMA_OPCODE_LMULS(NMSAC, VV): {
1240     // If the tail policy is undisturbed we can't commute.
1241     assert(RISCVII::hasVecPolicyOp(MI.getDesc().TSFlags));
1242     if ((MI.getOperand(MI.getNumExplicitOperands() - 1).getImm() & 1) == 0)
1243       return false;
1244 
1245     // For these instructions we can only swap operand 1 and operand 3 by
1246     // changing the opcode.
1247     unsigned CommutableOpIdx1 = 1;
1248     unsigned CommutableOpIdx2 = 3;
1249     if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, CommutableOpIdx1,
1250                               CommutableOpIdx2))
1251       return false;
1252     return true;
1253   }
1254   case CASE_VFMA_OPCODE_LMULS(FMADD, VV):
1255   case CASE_VFMA_OPCODE_LMULS(FMSUB, VV):
1256   case CASE_VFMA_OPCODE_LMULS(FNMADD, VV):
1257   case CASE_VFMA_OPCODE_LMULS(FNMSUB, VV):
1258   case CASE_VFMA_OPCODE_LMULS(MADD, VV):
1259   case CASE_VFMA_OPCODE_LMULS(NMSUB, VV): {
1260     // If the tail policy is undisturbed we can't commute.
1261     assert(RISCVII::hasVecPolicyOp(MI.getDesc().TSFlags));
1262     if ((MI.getOperand(MI.getNumExplicitOperands() - 1).getImm() & 1) == 0)
1263       return false;
1264 
1265     // For these instructions we have more freedom. We can commute with the
1266     // other multiplicand or with the addend/subtrahend/minuend.
1267 
1268     // Any fixed operand must be from source 1, 2 or 3.
1269     if (SrcOpIdx1 != CommuteAnyOperandIndex && SrcOpIdx1 > 3)
1270       return false;
1271     if (SrcOpIdx2 != CommuteAnyOperandIndex && SrcOpIdx2 > 3)
1272       return false;
1273 
1274     // It both ops are fixed one must be the tied source.
1275     if (SrcOpIdx1 != CommuteAnyOperandIndex &&
1276         SrcOpIdx2 != CommuteAnyOperandIndex && SrcOpIdx1 != 1 && SrcOpIdx2 != 1)
1277       return false;
1278 
1279     // Look for two different register operands assumed to be commutable
1280     // regardless of the FMA opcode. The FMA opcode is adjusted later if
1281     // needed.
1282     if (SrcOpIdx1 == CommuteAnyOperandIndex ||
1283         SrcOpIdx2 == CommuteAnyOperandIndex) {
1284       // At least one of operands to be commuted is not specified and
1285       // this method is free to choose appropriate commutable operands.
1286       unsigned CommutableOpIdx1 = SrcOpIdx1;
1287       if (SrcOpIdx1 == SrcOpIdx2) {
1288         // Both of operands are not fixed. Set one of commutable
1289         // operands to the tied source.
1290         CommutableOpIdx1 = 1;
1291       } else if (SrcOpIdx1 == CommuteAnyOperandIndex) {
1292         // Only one of the operands is not fixed.
1293         CommutableOpIdx1 = SrcOpIdx2;
1294       }
1295 
1296       // CommutableOpIdx1 is well defined now. Let's choose another commutable
1297       // operand and assign its index to CommutableOpIdx2.
1298       unsigned CommutableOpIdx2;
1299       if (CommutableOpIdx1 != 1) {
1300         // If we haven't already used the tied source, we must use it now.
1301         CommutableOpIdx2 = 1;
1302       } else {
1303         Register Op1Reg = MI.getOperand(CommutableOpIdx1).getReg();
1304 
1305         // The commuted operands should have different registers.
1306         // Otherwise, the commute transformation does not change anything and
1307         // is useless. We use this as a hint to make our decision.
1308         if (Op1Reg != MI.getOperand(2).getReg())
1309           CommutableOpIdx2 = 2;
1310         else
1311           CommutableOpIdx2 = 3;
1312       }
1313 
1314       // Assign the found pair of commutable indices to SrcOpIdx1 and
1315       // SrcOpIdx2 to return those values.
1316       if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, CommutableOpIdx1,
1317                                 CommutableOpIdx2))
1318         return false;
1319     }
1320 
1321     return true;
1322   }
1323   }
1324 
1325   return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
1326 }
1327 
1328 #define CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, LMUL)               \
1329   case RISCV::PseudoV##OLDOP##_##TYPE##_##LMUL:                                \
1330     Opc = RISCV::PseudoV##NEWOP##_##TYPE##_##LMUL;                             \
1331     break;
1332 
1333 #define CASE_VFMA_CHANGE_OPCODE_LMULS(OLDOP, NEWOP, TYPE)                      \
1334   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, MF8)                      \
1335   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, MF4)                      \
1336   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, MF2)                      \
1337   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, M1)                       \
1338   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, M2)                       \
1339   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, M4)                       \
1340   CASE_VFMA_CHANGE_OPCODE_COMMON(OLDOP, NEWOP, TYPE, M8)
1341 
1342 #define CASE_VFMA_CHANGE_OPCODE_SPLATS(OLDOP, NEWOP)                           \
1343   CASE_VFMA_CHANGE_OPCODE_LMULS(OLDOP, NEWOP, VF16)                            \
1344   CASE_VFMA_CHANGE_OPCODE_LMULS(OLDOP, NEWOP, VF32)                            \
1345   CASE_VFMA_CHANGE_OPCODE_LMULS(OLDOP, NEWOP, VF64)
1346 
1347 MachineInstr *RISCVInstrInfo::commuteInstructionImpl(MachineInstr &MI,
1348                                                      bool NewMI,
1349                                                      unsigned OpIdx1,
1350                                                      unsigned OpIdx2) const {
1351   auto cloneIfNew = [NewMI](MachineInstr &MI) -> MachineInstr & {
1352     if (NewMI)
1353       return *MI.getParent()->getParent()->CloneMachineInstr(&MI);
1354     return MI;
1355   };
1356 
1357   switch (MI.getOpcode()) {
1358   case CASE_VFMA_SPLATS(FMACC):
1359   case CASE_VFMA_SPLATS(FMADD):
1360   case CASE_VFMA_SPLATS(FMSAC):
1361   case CASE_VFMA_SPLATS(FMSUB):
1362   case CASE_VFMA_SPLATS(FNMACC):
1363   case CASE_VFMA_SPLATS(FNMADD):
1364   case CASE_VFMA_SPLATS(FNMSAC):
1365   case CASE_VFMA_SPLATS(FNMSUB):
1366   case CASE_VFMA_OPCODE_LMULS(FMACC, VV):
1367   case CASE_VFMA_OPCODE_LMULS(FMSAC, VV):
1368   case CASE_VFMA_OPCODE_LMULS(FNMACC, VV):
1369   case CASE_VFMA_OPCODE_LMULS(FNMSAC, VV):
1370   case CASE_VFMA_OPCODE_LMULS(MADD, VX):
1371   case CASE_VFMA_OPCODE_LMULS(NMSUB, VX):
1372   case CASE_VFMA_OPCODE_LMULS(MACC, VX):
1373   case CASE_VFMA_OPCODE_LMULS(NMSAC, VX):
1374   case CASE_VFMA_OPCODE_LMULS(MACC, VV):
1375   case CASE_VFMA_OPCODE_LMULS(NMSAC, VV): {
1376     // It only make sense to toggle these between clobbering the
1377     // addend/subtrahend/minuend one of the multiplicands.
1378     assert((OpIdx1 == 1 || OpIdx2 == 1) && "Unexpected opcode index");
1379     assert((OpIdx1 == 3 || OpIdx2 == 3) && "Unexpected opcode index");
1380     unsigned Opc;
1381     switch (MI.getOpcode()) {
1382       default:
1383         llvm_unreachable("Unexpected opcode");
1384       CASE_VFMA_CHANGE_OPCODE_SPLATS(FMACC, FMADD)
1385       CASE_VFMA_CHANGE_OPCODE_SPLATS(FMADD, FMACC)
1386       CASE_VFMA_CHANGE_OPCODE_SPLATS(FMSAC, FMSUB)
1387       CASE_VFMA_CHANGE_OPCODE_SPLATS(FMSUB, FMSAC)
1388       CASE_VFMA_CHANGE_OPCODE_SPLATS(FNMACC, FNMADD)
1389       CASE_VFMA_CHANGE_OPCODE_SPLATS(FNMADD, FNMACC)
1390       CASE_VFMA_CHANGE_OPCODE_SPLATS(FNMSAC, FNMSUB)
1391       CASE_VFMA_CHANGE_OPCODE_SPLATS(FNMSUB, FNMSAC)
1392       CASE_VFMA_CHANGE_OPCODE_LMULS(FMACC, FMADD, VV)
1393       CASE_VFMA_CHANGE_OPCODE_LMULS(FMSAC, FMSUB, VV)
1394       CASE_VFMA_CHANGE_OPCODE_LMULS(FNMACC, FNMADD, VV)
1395       CASE_VFMA_CHANGE_OPCODE_LMULS(FNMSAC, FNMSUB, VV)
1396       CASE_VFMA_CHANGE_OPCODE_LMULS(MACC, MADD, VX)
1397       CASE_VFMA_CHANGE_OPCODE_LMULS(MADD, MACC, VX)
1398       CASE_VFMA_CHANGE_OPCODE_LMULS(NMSAC, NMSUB, VX)
1399       CASE_VFMA_CHANGE_OPCODE_LMULS(NMSUB, NMSAC, VX)
1400       CASE_VFMA_CHANGE_OPCODE_LMULS(MACC, MADD, VV)
1401       CASE_VFMA_CHANGE_OPCODE_LMULS(NMSAC, NMSUB, VV)
1402     }
1403 
1404     auto &WorkingMI = cloneIfNew(MI);
1405     WorkingMI.setDesc(get(Opc));
1406     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1407                                                    OpIdx1, OpIdx2);
1408   }
1409   case CASE_VFMA_OPCODE_LMULS(FMADD, VV):
1410   case CASE_VFMA_OPCODE_LMULS(FMSUB, VV):
1411   case CASE_VFMA_OPCODE_LMULS(FNMADD, VV):
1412   case CASE_VFMA_OPCODE_LMULS(FNMSUB, VV):
1413   case CASE_VFMA_OPCODE_LMULS(MADD, VV):
1414   case CASE_VFMA_OPCODE_LMULS(NMSUB, VV): {
1415     assert((OpIdx1 == 1 || OpIdx2 == 1) && "Unexpected opcode index");
1416     // If one of the operands, is the addend we need to change opcode.
1417     // Otherwise we're just swapping 2 of the multiplicands.
1418     if (OpIdx1 == 3 || OpIdx2 == 3) {
1419       unsigned Opc;
1420       switch (MI.getOpcode()) {
1421         default:
1422           llvm_unreachable("Unexpected opcode");
1423         CASE_VFMA_CHANGE_OPCODE_LMULS(FMADD, FMACC, VV)
1424         CASE_VFMA_CHANGE_OPCODE_LMULS(FMSUB, FMSAC, VV)
1425         CASE_VFMA_CHANGE_OPCODE_LMULS(FNMADD, FNMACC, VV)
1426         CASE_VFMA_CHANGE_OPCODE_LMULS(FNMSUB, FNMSAC, VV)
1427         CASE_VFMA_CHANGE_OPCODE_LMULS(MADD, MACC, VV)
1428         CASE_VFMA_CHANGE_OPCODE_LMULS(NMSUB, NMSAC, VV)
1429       }
1430 
1431       auto &WorkingMI = cloneIfNew(MI);
1432       WorkingMI.setDesc(get(Opc));
1433       return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1434                                                      OpIdx1, OpIdx2);
1435     }
1436     // Let the default code handle it.
1437     break;
1438   }
1439   }
1440 
1441   return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
1442 }
1443 
1444 #undef CASE_VFMA_CHANGE_OPCODE_SPLATS
1445 #undef CASE_VFMA_CHANGE_OPCODE_LMULS
1446 #undef CASE_VFMA_CHANGE_OPCODE_COMMON
1447 #undef CASE_VFMA_SPLATS
1448 #undef CASE_VFMA_OPCODE_LMULS
1449 #undef CASE_VFMA_OPCODE_COMMON
1450 
1451 // clang-format off
1452 #define CASE_WIDEOP_OPCODE_COMMON(OP, LMUL)                                    \
1453   RISCV::PseudoV##OP##_##LMUL##_TIED
1454 
1455 #define CASE_WIDEOP_OPCODE_LMULS(OP)                                           \
1456   CASE_WIDEOP_OPCODE_COMMON(OP, MF8):                                          \
1457   case CASE_WIDEOP_OPCODE_COMMON(OP, MF4):                                     \
1458   case CASE_WIDEOP_OPCODE_COMMON(OP, MF2):                                     \
1459   case CASE_WIDEOP_OPCODE_COMMON(OP, M1):                                      \
1460   case CASE_WIDEOP_OPCODE_COMMON(OP, M2):                                      \
1461   case CASE_WIDEOP_OPCODE_COMMON(OP, M4)
1462 // clang-format on
1463 
1464 #define CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, LMUL)                             \
1465   case RISCV::PseudoV##OP##_##LMUL##_TIED:                                     \
1466     NewOpc = RISCV::PseudoV##OP##_##LMUL;                                      \
1467     break;
1468 
1469 #define CASE_WIDEOP_CHANGE_OPCODE_LMULS(OP)                                    \
1470   CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, MF8)                                    \
1471   CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, MF4)                                    \
1472   CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, MF2)                                    \
1473   CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, M1)                                     \
1474   CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, M2)                                     \
1475   CASE_WIDEOP_CHANGE_OPCODE_COMMON(OP, M4)
1476 
1477 MachineInstr *RISCVInstrInfo::convertToThreeAddress(MachineInstr &MI,
1478                                                     LiveVariables *LV) const {
1479   switch (MI.getOpcode()) {
1480   default:
1481     break;
1482   case CASE_WIDEOP_OPCODE_LMULS(FWADD_WV):
1483   case CASE_WIDEOP_OPCODE_LMULS(FWSUB_WV):
1484   case CASE_WIDEOP_OPCODE_LMULS(WADD_WV):
1485   case CASE_WIDEOP_OPCODE_LMULS(WADDU_WV):
1486   case CASE_WIDEOP_OPCODE_LMULS(WSUB_WV):
1487   case CASE_WIDEOP_OPCODE_LMULS(WSUBU_WV): {
1488     // clang-format off
1489     unsigned NewOpc;
1490     switch (MI.getOpcode()) {
1491     default:
1492       llvm_unreachable("Unexpected opcode");
1493     CASE_WIDEOP_CHANGE_OPCODE_LMULS(FWADD_WV)
1494     CASE_WIDEOP_CHANGE_OPCODE_LMULS(FWSUB_WV)
1495     CASE_WIDEOP_CHANGE_OPCODE_LMULS(WADD_WV)
1496     CASE_WIDEOP_CHANGE_OPCODE_LMULS(WADDU_WV)
1497     CASE_WIDEOP_CHANGE_OPCODE_LMULS(WSUB_WV)
1498     CASE_WIDEOP_CHANGE_OPCODE_LMULS(WSUBU_WV)
1499     }
1500     //clang-format on
1501 
1502     MachineBasicBlock &MBB = *MI.getParent();
1503     MachineInstrBuilder MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
1504                                   .add(MI.getOperand(0))
1505                                   .add(MI.getOperand(1))
1506                                   .add(MI.getOperand(2))
1507                                   .add(MI.getOperand(3))
1508                                   .add(MI.getOperand(4));
1509     MIB.copyImplicitOps(MI);
1510 
1511     if (LV) {
1512       unsigned NumOps = MI.getNumOperands();
1513       for (unsigned I = 1; I < NumOps; ++I) {
1514         MachineOperand &Op = MI.getOperand(I);
1515         if (Op.isReg() && Op.isKill())
1516           LV->replaceKillInstruction(Op.getReg(), MI, *MIB);
1517       }
1518     }
1519 
1520     return MIB;
1521   }
1522   }
1523 
1524   return nullptr;
1525 }
1526 
1527 #undef CASE_WIDEOP_CHANGE_OPCODE_LMULS
1528 #undef CASE_WIDEOP_CHANGE_OPCODE_COMMON
1529 #undef CASE_WIDEOP_OPCODE_LMULS
1530 #undef CASE_WIDEOP_OPCODE_COMMON
1531 
1532 Register RISCVInstrInfo::getVLENFactoredAmount(MachineFunction &MF,
1533                                                MachineBasicBlock &MBB,
1534                                                MachineBasicBlock::iterator II,
1535                                                const DebugLoc &DL,
1536                                                int64_t Amount,
1537                                                MachineInstr::MIFlag Flag) const {
1538   assert(Amount > 0 && "There is no need to get VLEN scaled value.");
1539   assert(Amount % 8 == 0 &&
1540          "Reserve the stack by the multiple of one vector size.");
1541 
1542   MachineRegisterInfo &MRI = MF.getRegInfo();
1543   const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
1544   int64_t NumOfVReg = Amount / 8;
1545 
1546   Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
1547   BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENB), VL)
1548     .setMIFlag(Flag);
1549   assert(isInt<32>(NumOfVReg) &&
1550          "Expect the number of vector registers within 32-bits.");
1551   if (isPowerOf2_32(NumOfVReg)) {
1552     uint32_t ShiftAmount = Log2_32(NumOfVReg);
1553     if (ShiftAmount == 0)
1554       return VL;
1555     BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), VL)
1556         .addReg(VL, RegState::Kill)
1557         .addImm(ShiftAmount)
1558         .setMIFlag(Flag);
1559   } else if (isPowerOf2_32(NumOfVReg - 1)) {
1560     Register ScaledRegister = MRI.createVirtualRegister(&RISCV::GPRRegClass);
1561     uint32_t ShiftAmount = Log2_32(NumOfVReg - 1);
1562     BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), ScaledRegister)
1563         .addReg(VL)
1564         .addImm(ShiftAmount)
1565         .setMIFlag(Flag);
1566     BuildMI(MBB, II, DL, TII->get(RISCV::ADD), VL)
1567         .addReg(ScaledRegister, RegState::Kill)
1568         .addReg(VL, RegState::Kill)
1569         .setMIFlag(Flag);
1570   } else if (isPowerOf2_32(NumOfVReg + 1)) {
1571     Register ScaledRegister = MRI.createVirtualRegister(&RISCV::GPRRegClass);
1572     uint32_t ShiftAmount = Log2_32(NumOfVReg + 1);
1573     BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), ScaledRegister)
1574         .addReg(VL)
1575         .addImm(ShiftAmount)
1576         .setMIFlag(Flag);
1577     BuildMI(MBB, II, DL, TII->get(RISCV::SUB), VL)
1578         .addReg(ScaledRegister, RegState::Kill)
1579         .addReg(VL, RegState::Kill)
1580         .setMIFlag(Flag);
1581   } else {
1582     Register N = MRI.createVirtualRegister(&RISCV::GPRRegClass);
1583     if (!isInt<12>(NumOfVReg))
1584       movImm(MBB, II, DL, N, NumOfVReg);
1585     else {
1586       BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), N)
1587           .addReg(RISCV::X0)
1588           .addImm(NumOfVReg)
1589           .setMIFlag(Flag);
1590     }
1591     if (!MF.getSubtarget<RISCVSubtarget>().hasStdExtM())
1592       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
1593           MF.getFunction(),
1594           "M-extension must be enabled to calculate the vscaled size/offset."});
1595     BuildMI(MBB, II, DL, TII->get(RISCV::MUL), VL)
1596         .addReg(VL, RegState::Kill)
1597         .addReg(N, RegState::Kill)
1598         .setMIFlag(Flag);
1599   }
1600 
1601   return VL;
1602 }
1603 
1604 static bool isRVVWholeLoadStore(unsigned Opcode) {
1605   switch (Opcode) {
1606   default:
1607     return false;
1608   case RISCV::VS1R_V:
1609   case RISCV::VS2R_V:
1610   case RISCV::VS4R_V:
1611   case RISCV::VS8R_V:
1612   case RISCV::VL1RE8_V:
1613   case RISCV::VL2RE8_V:
1614   case RISCV::VL4RE8_V:
1615   case RISCV::VL8RE8_V:
1616   case RISCV::VL1RE16_V:
1617   case RISCV::VL2RE16_V:
1618   case RISCV::VL4RE16_V:
1619   case RISCV::VL8RE16_V:
1620   case RISCV::VL1RE32_V:
1621   case RISCV::VL2RE32_V:
1622   case RISCV::VL4RE32_V:
1623   case RISCV::VL8RE32_V:
1624   case RISCV::VL1RE64_V:
1625   case RISCV::VL2RE64_V:
1626   case RISCV::VL4RE64_V:
1627   case RISCV::VL8RE64_V:
1628     return true;
1629   }
1630 }
1631 
1632 bool RISCVInstrInfo::isRVVSpill(const MachineInstr &MI, bool CheckFIs) const {
1633   // RVV lacks any support for immediate addressing for stack addresses, so be
1634   // conservative.
1635   unsigned Opcode = MI.getOpcode();
1636   if (!RISCVVPseudosTable::getPseudoInfo(Opcode) &&
1637       !isRVVWholeLoadStore(Opcode) && !isRVVSpillForZvlsseg(Opcode))
1638     return false;
1639   return !CheckFIs || any_of(MI.operands(), [](const MachineOperand &MO) {
1640     return MO.isFI();
1641   });
1642 }
1643 
1644 Optional<std::pair<unsigned, unsigned>>
1645 RISCVInstrInfo::isRVVSpillForZvlsseg(unsigned Opcode) const {
1646   switch (Opcode) {
1647   default:
1648     return None;
1649   case RISCV::PseudoVSPILL2_M1:
1650   case RISCV::PseudoVRELOAD2_M1:
1651     return std::make_pair(2u, 1u);
1652   case RISCV::PseudoVSPILL2_M2:
1653   case RISCV::PseudoVRELOAD2_M2:
1654     return std::make_pair(2u, 2u);
1655   case RISCV::PseudoVSPILL2_M4:
1656   case RISCV::PseudoVRELOAD2_M4:
1657     return std::make_pair(2u, 4u);
1658   case RISCV::PseudoVSPILL3_M1:
1659   case RISCV::PseudoVRELOAD3_M1:
1660     return std::make_pair(3u, 1u);
1661   case RISCV::PseudoVSPILL3_M2:
1662   case RISCV::PseudoVRELOAD3_M2:
1663     return std::make_pair(3u, 2u);
1664   case RISCV::PseudoVSPILL4_M1:
1665   case RISCV::PseudoVRELOAD4_M1:
1666     return std::make_pair(4u, 1u);
1667   case RISCV::PseudoVSPILL4_M2:
1668   case RISCV::PseudoVRELOAD4_M2:
1669     return std::make_pair(4u, 2u);
1670   case RISCV::PseudoVSPILL5_M1:
1671   case RISCV::PseudoVRELOAD5_M1:
1672     return std::make_pair(5u, 1u);
1673   case RISCV::PseudoVSPILL6_M1:
1674   case RISCV::PseudoVRELOAD6_M1:
1675     return std::make_pair(6u, 1u);
1676   case RISCV::PseudoVSPILL7_M1:
1677   case RISCV::PseudoVRELOAD7_M1:
1678     return std::make_pair(7u, 1u);
1679   case RISCV::PseudoVSPILL8_M1:
1680   case RISCV::PseudoVRELOAD8_M1:
1681     return std::make_pair(8u, 1u);
1682   }
1683 }
1684