1 //===-- RISCVInstrInfo.cpp - RISCV Instruction Information ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the RISCV implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVInstrInfo.h"
15 #include "RISCV.h"
16 #include "RISCVSubtarget.h"
17 #include "RISCVTargetMachine.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/RegisterScavenging.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/TargetRegistry.h"
26 
27 #define GET_INSTRINFO_CTOR_DTOR
28 #include "RISCVGenInstrInfo.inc"
29 
30 using namespace llvm;
31 
32 RISCVInstrInfo::RISCVInstrInfo()
33     : RISCVGenInstrInfo(RISCV::ADJCALLSTACKDOWN, RISCV::ADJCALLSTACKUP) {}
34 
35 unsigned RISCVInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
36                                              int &FrameIndex) const {
37   switch (MI.getOpcode()) {
38   default:
39     return 0;
40   case RISCV::LB:
41   case RISCV::LBU:
42   case RISCV::LH:
43   case RISCV::LHU:
44   case RISCV::LW:
45   case RISCV::FLW:
46   case RISCV::LWU:
47   case RISCV::LD:
48   case RISCV::FLD:
49     break;
50   }
51 
52   if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
53       MI.getOperand(2).getImm() == 0) {
54     FrameIndex = MI.getOperand(1).getIndex();
55     return MI.getOperand(0).getReg();
56   }
57 
58   return 0;
59 }
60 
61 unsigned RISCVInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
62                                             int &FrameIndex) const {
63   switch (MI.getOpcode()) {
64   default:
65     return 0;
66   case RISCV::SB:
67   case RISCV::SH:
68   case RISCV::SW:
69   case RISCV::FSW:
70   case RISCV::SD:
71   case RISCV::FSD:
72     break;
73   }
74 
75   if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
76       MI.getOperand(1).getImm() == 0) {
77     FrameIndex = MI.getOperand(0).getIndex();
78     return MI.getOperand(2).getReg();
79   }
80 
81   return 0;
82 }
83 
84 void RISCVInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
85                                  MachineBasicBlock::iterator MBBI,
86                                  const DebugLoc &DL, unsigned DstReg,
87                                  unsigned SrcReg, bool KillSrc) const {
88   if (RISCV::GPRRegClass.contains(DstReg, SrcReg)) {
89     BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
90         .addReg(SrcReg, getKillRegState(KillSrc))
91         .addImm(0);
92     return;
93   }
94 
95   // FPR->FPR copies
96   unsigned Opc;
97   if (RISCV::FPR32RegClass.contains(DstReg, SrcReg))
98     Opc = RISCV::FSGNJ_S;
99   else if (RISCV::FPR64RegClass.contains(DstReg, SrcReg))
100     Opc = RISCV::FSGNJ_D;
101   else
102     llvm_unreachable("Impossible reg-to-reg copy");
103 
104   BuildMI(MBB, MBBI, DL, get(Opc), DstReg)
105       .addReg(SrcReg, getKillRegState(KillSrc))
106       .addReg(SrcReg, getKillRegState(KillSrc));
107 }
108 
109 void RISCVInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
110                                          MachineBasicBlock::iterator I,
111                                          unsigned SrcReg, bool IsKill, int FI,
112                                          const TargetRegisterClass *RC,
113                                          const TargetRegisterInfo *TRI) const {
114   DebugLoc DL;
115   if (I != MBB.end())
116     DL = I->getDebugLoc();
117 
118   unsigned Opcode;
119 
120   if (RISCV::GPRRegClass.hasSubClassEq(RC))
121     Opcode = RISCV::SW;
122   else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
123     Opcode = RISCV::FSW;
124   else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
125     Opcode = RISCV::FSD;
126   else
127     llvm_unreachable("Can't store this register to stack slot");
128 
129   BuildMI(MBB, I, DL, get(Opcode))
130       .addReg(SrcReg, getKillRegState(IsKill))
131       .addFrameIndex(FI)
132       .addImm(0);
133 }
134 
135 void RISCVInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
136                                           MachineBasicBlock::iterator I,
137                                           unsigned DstReg, int FI,
138                                           const TargetRegisterClass *RC,
139                                           const TargetRegisterInfo *TRI) const {
140   DebugLoc DL;
141   if (I != MBB.end())
142     DL = I->getDebugLoc();
143 
144   unsigned Opcode;
145 
146   if (RISCV::GPRRegClass.hasSubClassEq(RC))
147     Opcode = RISCV::LW;
148   else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
149     Opcode = RISCV::FLW;
150   else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
151     Opcode = RISCV::FLD;
152   else
153     llvm_unreachable("Can't load this register from stack slot");
154 
155   BuildMI(MBB, I, DL, get(Opcode), DstReg).addFrameIndex(FI).addImm(0);
156 }
157 
158 void RISCVInstrInfo::movImm32(MachineBasicBlock &MBB,
159                               MachineBasicBlock::iterator MBBI,
160                               const DebugLoc &DL, unsigned DstReg, uint64_t Val,
161                               MachineInstr::MIFlag Flag) const {
162   assert(isInt<32>(Val) && "Can only materialize 32-bit constants");
163 
164   // TODO: If the value can be materialized using only one instruction, only
165   // insert a single instruction.
166 
167   uint64_t Hi20 = ((Val + 0x800) >> 12) & 0xfffff;
168   uint64_t Lo12 = SignExtend64<12>(Val);
169   BuildMI(MBB, MBBI, DL, get(RISCV::LUI), DstReg)
170       .addImm(Hi20)
171       .setMIFlag(Flag);
172   BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
173       .addReg(DstReg, RegState::Kill)
174       .addImm(Lo12)
175       .setMIFlag(Flag);
176 }
177 
178 // The contents of values added to Cond are not examined outside of
179 // RISCVInstrInfo, giving us flexibility in what to push to it. For RISCV, we
180 // push BranchOpcode, Reg1, Reg2.
181 static void parseCondBranch(MachineInstr &LastInst, MachineBasicBlock *&Target,
182                             SmallVectorImpl<MachineOperand> &Cond) {
183   // Block ends with fall-through condbranch.
184   assert(LastInst.getDesc().isConditionalBranch() &&
185          "Unknown conditional branch");
186   Target = LastInst.getOperand(2).getMBB();
187   Cond.push_back(MachineOperand::CreateImm(LastInst.getOpcode()));
188   Cond.push_back(LastInst.getOperand(0));
189   Cond.push_back(LastInst.getOperand(1));
190 }
191 
192 static unsigned getOppositeBranchOpcode(int Opc) {
193   switch (Opc) {
194   default:
195     llvm_unreachable("Unrecognized conditional branch");
196   case RISCV::BEQ:
197     return RISCV::BNE;
198   case RISCV::BNE:
199     return RISCV::BEQ;
200   case RISCV::BLT:
201     return RISCV::BGE;
202   case RISCV::BGE:
203     return RISCV::BLT;
204   case RISCV::BLTU:
205     return RISCV::BGEU;
206   case RISCV::BGEU:
207     return RISCV::BLTU;
208   }
209 }
210 
211 bool RISCVInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
212                                    MachineBasicBlock *&TBB,
213                                    MachineBasicBlock *&FBB,
214                                    SmallVectorImpl<MachineOperand> &Cond,
215                                    bool AllowModify) const {
216   TBB = FBB = nullptr;
217   Cond.clear();
218 
219   // If the block has no terminators, it just falls into the block after it.
220   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
221   if (I == MBB.end() || !isUnpredicatedTerminator(*I))
222     return false;
223 
224   // Count the number of terminators and find the first unconditional or
225   // indirect branch.
226   MachineBasicBlock::iterator FirstUncondOrIndirectBr = MBB.end();
227   int NumTerminators = 0;
228   for (auto J = I.getReverse(); J != MBB.rend() && isUnpredicatedTerminator(*J);
229        J++) {
230     NumTerminators++;
231     if (J->getDesc().isUnconditionalBranch() ||
232         J->getDesc().isIndirectBranch()) {
233       FirstUncondOrIndirectBr = J.getReverse();
234     }
235   }
236 
237   // If AllowModify is true, we can erase any terminators after
238   // FirstUncondOrIndirectBR.
239   if (AllowModify && FirstUncondOrIndirectBr != MBB.end()) {
240     while (std::next(FirstUncondOrIndirectBr) != MBB.end()) {
241       std::next(FirstUncondOrIndirectBr)->eraseFromParent();
242       NumTerminators--;
243     }
244     I = FirstUncondOrIndirectBr;
245   }
246 
247   // We can't handle blocks that end in an indirect branch.
248   if (I->getDesc().isIndirectBranch())
249     return true;
250 
251   // We can't handle blocks with more than 2 terminators.
252   if (NumTerminators > 2)
253     return true;
254 
255   // Handle a single unconditional branch.
256   if (NumTerminators == 1 && I->getDesc().isUnconditionalBranch()) {
257     TBB = I->getOperand(0).getMBB();
258     return false;
259   }
260 
261   // Handle a single conditional branch.
262   if (NumTerminators == 1 && I->getDesc().isConditionalBranch()) {
263     parseCondBranch(*I, TBB, Cond);
264     return false;
265   }
266 
267   // Handle a conditional branch followed by an unconditional branch.
268   if (NumTerminators == 2 && std::prev(I)->getDesc().isConditionalBranch() &&
269       I->getDesc().isUnconditionalBranch()) {
270     parseCondBranch(*std::prev(I), TBB, Cond);
271     FBB = I->getOperand(0).getMBB();
272     return false;
273   }
274 
275   // Otherwise, we can't handle this.
276   return true;
277 }
278 
279 unsigned RISCVInstrInfo::removeBranch(MachineBasicBlock &MBB,
280                                       int *BytesRemoved) const {
281   if (BytesRemoved)
282     *BytesRemoved = 0;
283   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
284   if (I == MBB.end())
285     return 0;
286 
287   if (!I->getDesc().isUnconditionalBranch() &&
288       !I->getDesc().isConditionalBranch())
289     return 0;
290 
291   // Remove the branch.
292   I->eraseFromParent();
293   if (BytesRemoved)
294     *BytesRemoved += getInstSizeInBytes(*I);
295 
296   I = MBB.end();
297 
298   if (I == MBB.begin())
299     return 1;
300   --I;
301   if (!I->getDesc().isConditionalBranch())
302     return 1;
303 
304   // Remove the branch.
305   I->eraseFromParent();
306   if (BytesRemoved)
307     *BytesRemoved += getInstSizeInBytes(*I);
308   return 2;
309 }
310 
311 // Inserts a branch into the end of the specific MachineBasicBlock, returning
312 // the number of instructions inserted.
313 unsigned RISCVInstrInfo::insertBranch(
314     MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
315     ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
316   if (BytesAdded)
317     *BytesAdded = 0;
318 
319   // Shouldn't be a fall through.
320   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
321   assert((Cond.size() == 3 || Cond.size() == 0) &&
322          "RISCV branch conditions have two components!");
323 
324   // Unconditional branch.
325   if (Cond.empty()) {
326     MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(TBB);
327     if (BytesAdded)
328       *BytesAdded += getInstSizeInBytes(MI);
329     return 1;
330   }
331 
332   // Either a one or two-way conditional branch.
333   unsigned Opc = Cond[0].getImm();
334   MachineInstr &CondMI =
335       *BuildMI(&MBB, DL, get(Opc)).add(Cond[1]).add(Cond[2]).addMBB(TBB);
336   if (BytesAdded)
337     *BytesAdded += getInstSizeInBytes(CondMI);
338 
339   // One-way conditional branch.
340   if (!FBB)
341     return 1;
342 
343   // Two-way conditional branch.
344   MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(FBB);
345   if (BytesAdded)
346     *BytesAdded += getInstSizeInBytes(MI);
347   return 2;
348 }
349 
350 unsigned RISCVInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
351                                               MachineBasicBlock &DestBB,
352                                               const DebugLoc &DL,
353                                               int64_t BrOffset,
354                                               RegScavenger *RS) const {
355   assert(RS && "RegScavenger required for long branching");
356   assert(MBB.empty() &&
357          "new block should be inserted for expanding unconditional branch");
358   assert(MBB.pred_size() == 1);
359 
360   MachineFunction *MF = MBB.getParent();
361   MachineRegisterInfo &MRI = MF->getRegInfo();
362   const auto &TM = static_cast<const RISCVTargetMachine &>(MF->getTarget());
363   const auto &STI = MF->getSubtarget<RISCVSubtarget>();
364 
365   if (TM.isPositionIndependent() || STI.is64Bit())
366     report_fatal_error("Unable to insert indirect branch");
367 
368   if (!isInt<32>(BrOffset))
369     report_fatal_error(
370         "Branch offsets outside of the signed 32-bit range not supported");
371 
372   // FIXME: A virtual register must be used initially, as the register
373   // scavenger won't work with empty blocks (SIInstrInfo::insertIndirectBranch
374   // uses the same workaround).
375   unsigned ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
376   auto II = MBB.end();
377 
378   MachineInstr &LuiMI = *BuildMI(MBB, II, DL, get(RISCV::LUI), ScratchReg)
379                              .addMBB(&DestBB, RISCVII::MO_HI);
380   BuildMI(MBB, II, DL, get(RISCV::PseudoBRIND))
381       .addReg(ScratchReg, RegState::Kill)
382       .addMBB(&DestBB, RISCVII::MO_LO);
383 
384   RS->enterBasicBlockEnd(MBB);
385   unsigned Scav = RS->scavengeRegisterBackwards(
386       RISCV::GPRRegClass, MachineBasicBlock::iterator(LuiMI), false, 0);
387   MRI.replaceRegWith(ScratchReg, Scav);
388   MRI.clearVirtRegs();
389   RS->setRegUsed(Scav);
390   return 8;
391 }
392 
393 bool RISCVInstrInfo::reverseBranchCondition(
394     SmallVectorImpl<MachineOperand> &Cond) const {
395   assert((Cond.size() == 3) && "Invalid branch condition!");
396   Cond[0].setImm(getOppositeBranchOpcode(Cond[0].getImm()));
397   return false;
398 }
399 
400 MachineBasicBlock *
401 RISCVInstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
402   assert(MI.getDesc().isBranch() && "Unexpected opcode!");
403   // The branch target is always the last operand.
404   int NumOp = MI.getNumExplicitOperands();
405   return MI.getOperand(NumOp - 1).getMBB();
406 }
407 
408 bool RISCVInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
409                                            int64_t BrOffset) const {
410   // Ideally we could determine the supported branch offset from the
411   // RISCVII::FormMask, but this can't be used for Pseudo instructions like
412   // PseudoBR.
413   switch (BranchOp) {
414   default:
415     llvm_unreachable("Unexpected opcode!");
416   case RISCV::BEQ:
417   case RISCV::BNE:
418   case RISCV::BLT:
419   case RISCV::BGE:
420   case RISCV::BLTU:
421   case RISCV::BGEU:
422     return isIntN(13, BrOffset);
423   case RISCV::JAL:
424   case RISCV::PseudoBR:
425     return isIntN(21, BrOffset);
426   }
427 }
428 
429 unsigned RISCVInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
430   unsigned Opcode = MI.getOpcode();
431 
432   switch (Opcode) {
433   default: { return get(Opcode).getSize(); }
434   case TargetOpcode::EH_LABEL:
435   case TargetOpcode::IMPLICIT_DEF:
436   case TargetOpcode::KILL:
437   case TargetOpcode::DBG_VALUE:
438     return 0;
439   case RISCV::PseudoCALL:
440     return 8;
441   case TargetOpcode::INLINEASM: {
442     const MachineFunction &MF = *MI.getParent()->getParent();
443     const auto &TM = static_cast<const RISCVTargetMachine &>(MF.getTarget());
444     return getInlineAsmLength(MI.getOperand(0).getSymbolName(),
445                               *TM.getMCAsmInfo());
446   }
447   }
448 }
449