1 //===-- RISCVInstrInfo.cpp - RISCV Instruction Information ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the RISCV implementation of the TargetInstrInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "RISCVInstrInfo.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"
27 #define GET_INSTRINFO_CTOR_DTOR
28 #include "RISCVGenInstrInfo.inc"
32 RISCVInstrInfo::RISCVInstrInfo()
33 : RISCVGenInstrInfo(RISCV::ADJCALLSTACKDOWN, RISCV::ADJCALLSTACKUP) {}
35 unsigned RISCVInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
36 int &FrameIndex) const {
37 switch (MI.getOpcode()) {
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();
61 unsigned RISCVInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
62 int &FrameIndex) const {
63 switch (MI.getOpcode()) {
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();
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))
97 if (RISCV::FPR32RegClass.contains(DstReg, SrcReg))
99 else if (RISCV::FPR64RegClass.contains(DstReg, SrcReg))
100 Opc = RISCV::FSGNJ_D;
102 llvm_unreachable("Impossible reg-to-reg copy");
104 BuildMI(MBB, MBBI, DL, get(Opc), DstReg)
105 .addReg(SrcReg, getKillRegState(KillSrc))
106 .addReg(SrcReg, getKillRegState(KillSrc));
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 {
116 DL = I->getDebugLoc();
120 if (RISCV::GPRRegClass.hasSubClassEq(RC))
121 Opcode = TRI->getRegSizeInBits(RISCV::GPRRegClass) == 32 ?
122 RISCV::SW : RISCV::SD;
123 else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
125 else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
128 llvm_unreachable("Can't store this register to stack slot");
130 BuildMI(MBB, I, DL, get(Opcode))
131 .addReg(SrcReg, getKillRegState(IsKill))
136 void RISCVInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
137 MachineBasicBlock::iterator I,
138 unsigned DstReg, int FI,
139 const TargetRegisterClass *RC,
140 const TargetRegisterInfo *TRI) const {
143 DL = I->getDebugLoc();
147 if (RISCV::GPRRegClass.hasSubClassEq(RC))
148 Opcode = TRI->getRegSizeInBits(RISCV::GPRRegClass) == 32 ?
149 RISCV::LW : RISCV::LD;
150 else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
152 else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
155 llvm_unreachable("Can't load this register from stack slot");
157 BuildMI(MBB, I, DL, get(Opcode), DstReg).addFrameIndex(FI).addImm(0);
160 void RISCVInstrInfo::movImm32(MachineBasicBlock &MBB,
161 MachineBasicBlock::iterator MBBI,
162 const DebugLoc &DL, unsigned DstReg, uint64_t Val,
163 MachineInstr::MIFlag Flag) const {
164 assert(isInt<32>(Val) && "Can only materialize 32-bit constants");
166 // TODO: If the value can be materialized using only one instruction, only
167 // insert a single instruction.
169 uint64_t Hi20 = ((Val + 0x800) >> 12) & 0xfffff;
170 uint64_t Lo12 = SignExtend64<12>(Val);
171 BuildMI(MBB, MBBI, DL, get(RISCV::LUI), DstReg)
174 BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
175 .addReg(DstReg, RegState::Kill)
180 // The contents of values added to Cond are not examined outside of
181 // RISCVInstrInfo, giving us flexibility in what to push to it. For RISCV, we
182 // push BranchOpcode, Reg1, Reg2.
183 static void parseCondBranch(MachineInstr &LastInst, MachineBasicBlock *&Target,
184 SmallVectorImpl<MachineOperand> &Cond) {
185 // Block ends with fall-through condbranch.
186 assert(LastInst.getDesc().isConditionalBranch() &&
187 "Unknown conditional branch");
188 Target = LastInst.getOperand(2).getMBB();
189 Cond.push_back(MachineOperand::CreateImm(LastInst.getOpcode()));
190 Cond.push_back(LastInst.getOperand(0));
191 Cond.push_back(LastInst.getOperand(1));
194 static unsigned getOppositeBranchOpcode(int Opc) {
197 llvm_unreachable("Unrecognized conditional branch");
213 bool RISCVInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
214 MachineBasicBlock *&TBB,
215 MachineBasicBlock *&FBB,
216 SmallVectorImpl<MachineOperand> &Cond,
217 bool AllowModify) const {
221 // If the block has no terminators, it just falls into the block after it.
222 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
223 if (I == MBB.end() || !isUnpredicatedTerminator(*I))
226 // Count the number of terminators and find the first unconditional or
228 MachineBasicBlock::iterator FirstUncondOrIndirectBr = MBB.end();
229 int NumTerminators = 0;
230 for (auto J = I.getReverse(); J != MBB.rend() && isUnpredicatedTerminator(*J);
233 if (J->getDesc().isUnconditionalBranch() ||
234 J->getDesc().isIndirectBranch()) {
235 FirstUncondOrIndirectBr = J.getReverse();
239 // If AllowModify is true, we can erase any terminators after
240 // FirstUncondOrIndirectBR.
241 if (AllowModify && FirstUncondOrIndirectBr != MBB.end()) {
242 while (std::next(FirstUncondOrIndirectBr) != MBB.end()) {
243 std::next(FirstUncondOrIndirectBr)->eraseFromParent();
246 I = FirstUncondOrIndirectBr;
249 // We can't handle blocks that end in an indirect branch.
250 if (I->getDesc().isIndirectBranch())
253 // We can't handle blocks with more than 2 terminators.
254 if (NumTerminators > 2)
257 // Handle a single unconditional branch.
258 if (NumTerminators == 1 && I->getDesc().isUnconditionalBranch()) {
259 TBB = I->getOperand(0).getMBB();
263 // Handle a single conditional branch.
264 if (NumTerminators == 1 && I->getDesc().isConditionalBranch()) {
265 parseCondBranch(*I, TBB, Cond);
269 // Handle a conditional branch followed by an unconditional branch.
270 if (NumTerminators == 2 && std::prev(I)->getDesc().isConditionalBranch() &&
271 I->getDesc().isUnconditionalBranch()) {
272 parseCondBranch(*std::prev(I), TBB, Cond);
273 FBB = I->getOperand(0).getMBB();
277 // Otherwise, we can't handle this.
281 unsigned RISCVInstrInfo::removeBranch(MachineBasicBlock &MBB,
282 int *BytesRemoved) const {
285 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
289 if (!I->getDesc().isUnconditionalBranch() &&
290 !I->getDesc().isConditionalBranch())
293 // Remove the branch.
294 I->eraseFromParent();
296 *BytesRemoved += getInstSizeInBytes(*I);
300 if (I == MBB.begin())
303 if (!I->getDesc().isConditionalBranch())
306 // Remove the branch.
307 I->eraseFromParent();
309 *BytesRemoved += getInstSizeInBytes(*I);
313 // Inserts a branch into the end of the specific MachineBasicBlock, returning
314 // the number of instructions inserted.
315 unsigned RISCVInstrInfo::insertBranch(
316 MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
317 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
321 // Shouldn't be a fall through.
322 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
323 assert((Cond.size() == 3 || Cond.size() == 0) &&
324 "RISCV branch conditions have two components!");
326 // Unconditional branch.
328 MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(TBB);
330 *BytesAdded += getInstSizeInBytes(MI);
334 // Either a one or two-way conditional branch.
335 unsigned Opc = Cond[0].getImm();
336 MachineInstr &CondMI =
337 *BuildMI(&MBB, DL, get(Opc)).add(Cond[1]).add(Cond[2]).addMBB(TBB);
339 *BytesAdded += getInstSizeInBytes(CondMI);
341 // One-way conditional branch.
345 // Two-way conditional branch.
346 MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(FBB);
348 *BytesAdded += getInstSizeInBytes(MI);
352 unsigned RISCVInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
353 MachineBasicBlock &DestBB,
356 RegScavenger *RS) const {
357 assert(RS && "RegScavenger required for long branching");
358 assert(MBB.empty() &&
359 "new block should be inserted for expanding unconditional branch");
360 assert(MBB.pred_size() == 1);
362 MachineFunction *MF = MBB.getParent();
363 MachineRegisterInfo &MRI = MF->getRegInfo();
364 const auto &TM = static_cast<const RISCVTargetMachine &>(MF->getTarget());
366 if (TM.isPositionIndependent())
367 report_fatal_error("Unable to insert indirect branch");
369 if (!isInt<32>(BrOffset))
371 "Branch offsets outside of the signed 32-bit range not supported");
373 // FIXME: A virtual register must be used initially, as the register
374 // scavenger won't work with empty blocks (SIInstrInfo::insertIndirectBranch
375 // uses the same workaround).
376 unsigned ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
379 MachineInstr &LuiMI = *BuildMI(MBB, II, DL, get(RISCV::LUI), ScratchReg)
380 .addMBB(&DestBB, RISCVII::MO_HI);
381 BuildMI(MBB, II, DL, get(RISCV::PseudoBRIND))
382 .addReg(ScratchReg, RegState::Kill)
383 .addMBB(&DestBB, RISCVII::MO_LO);
385 RS->enterBasicBlockEnd(MBB);
386 unsigned Scav = RS->scavengeRegisterBackwards(
387 RISCV::GPRRegClass, MachineBasicBlock::iterator(LuiMI), false, 0);
388 MRI.replaceRegWith(ScratchReg, Scav);
390 RS->setRegUsed(Scav);
394 bool RISCVInstrInfo::reverseBranchCondition(
395 SmallVectorImpl<MachineOperand> &Cond) const {
396 assert((Cond.size() == 3) && "Invalid branch condition!");
397 Cond[0].setImm(getOppositeBranchOpcode(Cond[0].getImm()));
402 RISCVInstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
403 assert(MI.getDesc().isBranch() && "Unexpected opcode!");
404 // The branch target is always the last operand.
405 int NumOp = MI.getNumExplicitOperands();
406 return MI.getOperand(NumOp - 1).getMBB();
409 bool RISCVInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
410 int64_t BrOffset) const {
411 // Ideally we could determine the supported branch offset from the
412 // RISCVII::FormMask, but this can't be used for Pseudo instructions like
416 llvm_unreachable("Unexpected opcode!");
423 return isIntN(13, BrOffset);
425 case RISCV::PseudoBR:
426 return isIntN(21, BrOffset);
430 unsigned RISCVInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
431 unsigned Opcode = MI.getOpcode();
434 default: { return get(Opcode).getSize(); }
435 case TargetOpcode::EH_LABEL:
436 case TargetOpcode::IMPLICIT_DEF:
437 case TargetOpcode::KILL:
438 case TargetOpcode::DBG_VALUE:
440 case RISCV::PseudoCALL:
441 case RISCV::PseudoTAIL:
443 case TargetOpcode::INLINEASM: {
444 const MachineFunction &MF = *MI.getParent()->getParent();
445 const auto &TM = static_cast<const RISCVTargetMachine &>(MF.getTarget());
446 return getInlineAsmLength(MI.getOperand(0).getSymbolName(),