1 //===-- RISCVAsmBackend.cpp - RISCV Assembler Backend ---------------------===//
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 #include "RISCVAsmBackend.h"
10 #include "RISCVMCExpr.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCDirectives.h"
15 #include "llvm/MC/MCELFObjectWriter.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace llvm;
24 
25 // If linker relaxation is enabled, or the relax option had previously been
26 // enabled, always emit relocations even if the fixup can be resolved. This is
27 // necessary for correctness as offsets may change during relaxation.
28 bool RISCVAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
29                                             const MCFixup &Fixup,
30                                             const MCValue &Target) {
31   bool ShouldForce = false;
32 
33   switch ((unsigned)Fixup.getKind()) {
34   default:
35     break;
36   case RISCV::fixup_riscv_got_hi20:
37     return true;
38   case RISCV::fixup_riscv_pcrel_lo12_i:
39   case RISCV::fixup_riscv_pcrel_lo12_s:
40     // For pcrel_lo12, force a relocation if the target of the corresponding
41     // pcrel_hi20 is not in the same fragment.
42     const MCFixup *T = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup();
43     if (!T) {
44       Asm.getContext().reportError(Fixup.getLoc(),
45                                    "could not find corresponding %pcrel_hi");
46       return false;
47     }
48 
49     switch ((unsigned)T->getKind()) {
50     default:
51       llvm_unreachable("Unexpected fixup kind for pcrel_lo12");
52       break;
53     case RISCV::fixup_riscv_got_hi20:
54       ShouldForce = true;
55       break;
56     case RISCV::fixup_riscv_pcrel_hi20:
57       ShouldForce = T->getValue()->findAssociatedFragment() !=
58                     Fixup.getValue()->findAssociatedFragment();
59       break;
60     }
61     break;
62   }
63 
64   return ShouldForce || STI.getFeatureBits()[RISCV::FeatureRelax] ||
65          ForceRelocs;
66 }
67 
68 bool RISCVAsmBackend::fixupNeedsRelaxationAdvanced(const MCFixup &Fixup,
69                                                    bool Resolved,
70                                                    uint64_t Value,
71                                                    const MCRelaxableFragment *DF,
72                                                    const MCAsmLayout &Layout,
73                                                    const bool WasForced) const {
74   // Return true if the symbol is actually unresolved.
75   // Resolved could be always false when shouldForceRelocation return true.
76   // We use !WasForced to indicate that the symbol is unresolved and not forced
77   // by shouldForceRelocation.
78   if (!Resolved && !WasForced)
79     return true;
80 
81   int64_t Offset = int64_t(Value);
82   switch ((unsigned)Fixup.getKind()) {
83   default:
84     return false;
85   case RISCV::fixup_riscv_rvc_branch:
86     // For compressed branch instructions the immediate must be
87     // in the range [-256, 254].
88     return Offset > 254 || Offset < -256;
89   case RISCV::fixup_riscv_rvc_jump:
90     // For compressed jump instructions the immediate must be
91     // in the range [-2048, 2046].
92     return Offset > 2046 || Offset < -2048;
93   }
94 }
95 
96 void RISCVAsmBackend::relaxInstruction(const MCInst &Inst,
97                                        const MCSubtargetInfo &STI,
98                                        MCInst &Res) const {
99   // TODO: replace this with call to auto generated uncompressinstr() function.
100   switch (Inst.getOpcode()) {
101   default:
102     llvm_unreachable("Opcode not expected!");
103   case RISCV::C_BEQZ:
104     // c.beqz $rs1, $imm -> beq $rs1, X0, $imm.
105     Res.setOpcode(RISCV::BEQ);
106     Res.addOperand(Inst.getOperand(0));
107     Res.addOperand(MCOperand::createReg(RISCV::X0));
108     Res.addOperand(Inst.getOperand(1));
109     break;
110   case RISCV::C_BNEZ:
111     // c.bnez $rs1, $imm -> bne $rs1, X0, $imm.
112     Res.setOpcode(RISCV::BNE);
113     Res.addOperand(Inst.getOperand(0));
114     Res.addOperand(MCOperand::createReg(RISCV::X0));
115     Res.addOperand(Inst.getOperand(1));
116     break;
117   case RISCV::C_J:
118     // c.j $imm -> jal X0, $imm.
119     Res.setOpcode(RISCV::JAL);
120     Res.addOperand(MCOperand::createReg(RISCV::X0));
121     Res.addOperand(Inst.getOperand(0));
122     break;
123   case RISCV::C_JAL:
124     // c.jal $imm -> jal X1, $imm.
125     Res.setOpcode(RISCV::JAL);
126     Res.addOperand(MCOperand::createReg(RISCV::X1));
127     Res.addOperand(Inst.getOperand(0));
128     break;
129   }
130 }
131 
132 // Given a compressed control flow instruction this function returns
133 // the expanded instruction.
134 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
135   switch (Op) {
136   default:
137     return Op;
138   case RISCV::C_BEQZ:
139     return RISCV::BEQ;
140   case RISCV::C_BNEZ:
141     return RISCV::BNE;
142   case RISCV::C_J:
143   case RISCV::C_JAL: // fall through.
144     return RISCV::JAL;
145   }
146 }
147 
148 bool RISCVAsmBackend::mayNeedRelaxation(const MCInst &Inst,
149                                         const MCSubtargetInfo &STI) const {
150   return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
151 }
152 
153 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
154   bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
155   unsigned MinNopLen = HasStdExtC ? 2 : 4;
156 
157   if ((Count % MinNopLen) != 0)
158     return false;
159 
160   // The canonical nop on RISC-V is addi x0, x0, 0.
161   uint64_t Nop32Count = Count / 4;
162   for (uint64_t i = Nop32Count; i != 0; --i)
163     OS.write("\x13\0\0\0", 4);
164 
165   // The canonical nop on RVC is c.nop.
166   if (HasStdExtC) {
167     uint64_t Nop16Count = (Count - Nop32Count * 4) / 2;
168     for (uint64_t i = Nop16Count; i != 0; --i)
169       OS.write("\x01\0", 2);
170   }
171 
172   return true;
173 }
174 
175 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
176                                  MCContext &Ctx) {
177   unsigned Kind = Fixup.getKind();
178   switch (Kind) {
179   default:
180     llvm_unreachable("Unknown fixup kind!");
181   case RISCV::fixup_riscv_got_hi20:
182     llvm_unreachable("Relocation should be unconditionally forced\n");
183   case FK_Data_1:
184   case FK_Data_2:
185   case FK_Data_4:
186   case FK_Data_8:
187     return Value;
188   case RISCV::fixup_riscv_lo12_i:
189   case RISCV::fixup_riscv_pcrel_lo12_i:
190     return Value & 0xfff;
191   case RISCV::fixup_riscv_lo12_s:
192   case RISCV::fixup_riscv_pcrel_lo12_s:
193     return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
194   case RISCV::fixup_riscv_hi20:
195   case RISCV::fixup_riscv_pcrel_hi20:
196     // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
197     return ((Value + 0x800) >> 12) & 0xfffff;
198   case RISCV::fixup_riscv_jal: {
199     if (!isInt<21>(Value))
200       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
201     if (Value & 0x1)
202       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
203     // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
204     unsigned Sbit = (Value >> 20) & 0x1;
205     unsigned Hi8 = (Value >> 12) & 0xff;
206     unsigned Mid1 = (Value >> 11) & 0x1;
207     unsigned Lo10 = (Value >> 1) & 0x3ff;
208     // Inst{31} = Sbit;
209     // Inst{30-21} = Lo10;
210     // Inst{20} = Mid1;
211     // Inst{19-12} = Hi8;
212     Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
213     return Value;
214   }
215   case RISCV::fixup_riscv_branch: {
216     if (!isInt<13>(Value))
217       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
218     if (Value & 0x1)
219       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
220     // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
221     // Value.
222     unsigned Sbit = (Value >> 12) & 0x1;
223     unsigned Hi1 = (Value >> 11) & 0x1;
224     unsigned Mid6 = (Value >> 5) & 0x3f;
225     unsigned Lo4 = (Value >> 1) & 0xf;
226     // Inst{31} = Sbit;
227     // Inst{30-25} = Mid6;
228     // Inst{11-8} = Lo4;
229     // Inst{7} = Hi1;
230     Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
231     return Value;
232   }
233   case RISCV::fixup_riscv_call:
234   case RISCV::fixup_riscv_call_plt: {
235     // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
236     // we need to add 0x800ULL before extract upper bits to reflect the
237     // effect of the sign extension.
238     uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
239     uint64_t LowerImm = Value & 0xfffULL;
240     return UpperImm | ((LowerImm << 20) << 32);
241   }
242   case RISCV::fixup_riscv_rvc_jump: {
243     // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
244     unsigned Bit11  = (Value >> 11) & 0x1;
245     unsigned Bit4   = (Value >> 4) & 0x1;
246     unsigned Bit9_8 = (Value >> 8) & 0x3;
247     unsigned Bit10  = (Value >> 10) & 0x1;
248     unsigned Bit6   = (Value >> 6) & 0x1;
249     unsigned Bit7   = (Value >> 7) & 0x1;
250     unsigned Bit3_1 = (Value >> 1) & 0x7;
251     unsigned Bit5   = (Value >> 5) & 0x1;
252     Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
253             (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
254     return Value;
255   }
256   case RISCV::fixup_riscv_rvc_branch: {
257     // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
258     unsigned Bit8   = (Value >> 8) & 0x1;
259     unsigned Bit7_6 = (Value >> 6) & 0x3;
260     unsigned Bit5   = (Value >> 5) & 0x1;
261     unsigned Bit4_3 = (Value >> 3) & 0x3;
262     unsigned Bit2_1 = (Value >> 1) & 0x3;
263     Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
264             (Bit5 << 2);
265     return Value;
266   }
267 
268   }
269 }
270 
271 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
272                                  const MCValue &Target,
273                                  MutableArrayRef<char> Data, uint64_t Value,
274                                  bool IsResolved,
275                                  const MCSubtargetInfo *STI) const {
276   MCContext &Ctx = Asm.getContext();
277   MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
278   if (!Value)
279     return; // Doesn't change encoding.
280   // Apply any target-specific value adjustments.
281   Value = adjustFixupValue(Fixup, Value, Ctx);
282 
283   // Shift the value into position.
284   Value <<= Info.TargetOffset;
285 
286   unsigned Offset = Fixup.getOffset();
287   unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
288 
289   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
290 
291   // For each byte of the fragment that the fixup touches, mask in the
292   // bits from the fixup value.
293   for (unsigned i = 0; i != NumBytes; ++i) {
294     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
295   }
296 }
297 
298 // Linker relaxation may change code size. We have to insert Nops
299 // for .align directive when linker relaxation enabled. So then Linker
300 // could satisfy alignment by removing Nops.
301 // The function return the total Nops Size we need to insert.
302 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
303     const MCAlignFragment &AF, unsigned &Size) {
304   // Calculate Nops Size only when linker relaxation enabled.
305   if (!STI.getFeatureBits()[RISCV::FeatureRelax])
306     return false;
307 
308   bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
309   unsigned MinNopLen = HasStdExtC ? 2 : 4;
310 
311   Size = AF.getAlignment() - MinNopLen;
312   return true;
313 }
314 
315 // We need to insert R_RISCV_ALIGN relocation type to indicate the
316 // position of Nops and the total bytes of the Nops have been inserted
317 // when linker relaxation enabled.
318 // The function insert fixup_riscv_align fixup which eventually will
319 // transfer to R_RISCV_ALIGN relocation type.
320 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
321                                                     const MCAsmLayout &Layout,
322                                                     MCAlignFragment &AF) {
323   // Insert the fixup only when linker relaxation enabled.
324   if (!STI.getFeatureBits()[RISCV::FeatureRelax])
325     return false;
326 
327   // Calculate total Nops we need to insert.
328   unsigned Count;
329   shouldInsertExtraNopBytesForCodeAlign(AF, Count);
330   // No Nop need to insert, simply return.
331   if (Count == 0)
332     return false;
333 
334   MCContext &Ctx = Asm.getContext();
335   const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
336   // Create fixup_riscv_align fixup.
337   MCFixup Fixup =
338       MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
339 
340   uint64_t FixedValue = 0;
341   MCValue NopBytes = MCValue::get(Count);
342 
343   Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
344                                    FixedValue);
345 
346   return true;
347 }
348 
349 std::unique_ptr<MCObjectTargetWriter>
350 RISCVAsmBackend::createObjectTargetWriter() const {
351   return createRISCVELFObjectWriter(OSABI, Is64Bit);
352 }
353 
354 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
355                                           const MCSubtargetInfo &STI,
356                                           const MCRegisterInfo &MRI,
357                                           const MCTargetOptions &Options) {
358   const Triple &TT = STI.getTargetTriple();
359   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
360   return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
361 }
362