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