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