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/MCAsmLayout.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm;
25 
26 Optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
27   if (STI.getTargetTriple().isOSBinFormatELF()) {
28     unsigned Type;
29     Type = llvm::StringSwitch<unsigned>(Name)
30 #define ELF_RELOC(X, Y) .Case(#X, Y)
31 #include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
32 #undef ELF_RELOC
33                .Default(-1u);
34     if (Type != -1u)
35       return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
36   }
37   return None;
38 }
39 
40 const MCFixupKindInfo &
41 RISCVAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
42   const static MCFixupKindInfo Infos[] = {
43       // This table *must* be in the order that the fixup_* kinds are defined in
44       // RISCVFixupKinds.h.
45       //
46       // name                      offset bits  flags
47       {"fixup_riscv_hi20", 12, 20, 0},
48       {"fixup_riscv_lo12_i", 20, 12, 0},
49       {"fixup_riscv_lo12_s", 0, 32, 0},
50       {"fixup_riscv_pcrel_hi20", 12, 20,
51        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
52       {"fixup_riscv_pcrel_lo12_i", 20, 12,
53        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
54       {"fixup_riscv_pcrel_lo12_s", 0, 32,
55        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
56       {"fixup_riscv_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
57       {"fixup_riscv_tprel_hi20", 12, 20, 0},
58       {"fixup_riscv_tprel_lo12_i", 20, 12, 0},
59       {"fixup_riscv_tprel_lo12_s", 0, 32, 0},
60       {"fixup_riscv_tprel_add", 0, 0, 0},
61       {"fixup_riscv_tls_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
62       {"fixup_riscv_tls_gd_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
63       {"fixup_riscv_jal", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
64       {"fixup_riscv_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
65       {"fixup_riscv_rvc_jump", 2, 11, MCFixupKindInfo::FKF_IsPCRel},
66       {"fixup_riscv_rvc_branch", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
67       {"fixup_riscv_call", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
68       {"fixup_riscv_call_plt", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
69       {"fixup_riscv_relax", 0, 0, 0},
70       {"fixup_riscv_align", 0, 0, 0}};
71   static_assert((array_lengthof(Infos)) == RISCV::NumTargetFixupKinds,
72                 "Not all fixup kinds added to Infos array");
73 
74   // Fixup kinds from .reloc directive are like R_RISCV_NONE. They
75   // do not require any extra processing.
76   if (Kind >= FirstLiteralRelocationKind)
77     return MCAsmBackend::getFixupKindInfo(FK_NONE);
78 
79   if (Kind < FirstTargetFixupKind)
80     return MCAsmBackend::getFixupKindInfo(Kind);
81 
82   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
83          "Invalid kind!");
84   return Infos[Kind - FirstTargetFixupKind];
85 }
86 
87 // If linker relaxation is enabled, or the relax option had previously been
88 // enabled, always emit relocations even if the fixup can be resolved. This is
89 // necessary for correctness as offsets may change during relaxation.
90 bool RISCVAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
91                                             const MCFixup &Fixup,
92                                             const MCValue &Target) {
93   if (Fixup.getKind() >= FirstLiteralRelocationKind)
94     return true;
95   switch (Fixup.getTargetKind()) {
96   default:
97     break;
98   case FK_Data_1:
99   case FK_Data_2:
100   case FK_Data_4:
101   case FK_Data_8:
102     if (Target.isAbsolute())
103       return false;
104     break;
105   case RISCV::fixup_riscv_got_hi20:
106   case RISCV::fixup_riscv_tls_got_hi20:
107   case RISCV::fixup_riscv_tls_gd_hi20:
108     return true;
109   }
110 
111   return STI.getFeatureBits()[RISCV::FeatureRelax] || ForceRelocs;
112 }
113 
114 bool RISCVAsmBackend::fixupNeedsRelaxationAdvanced(const MCFixup &Fixup,
115                                                    bool Resolved,
116                                                    uint64_t Value,
117                                                    const MCRelaxableFragment *DF,
118                                                    const MCAsmLayout &Layout,
119                                                    const bool WasForced) const {
120   // Return true if the symbol is actually unresolved.
121   // Resolved could be always false when shouldForceRelocation return true.
122   // We use !WasForced to indicate that the symbol is unresolved and not forced
123   // by shouldForceRelocation.
124   if (!Resolved && !WasForced)
125     return true;
126 
127   int64_t Offset = int64_t(Value);
128   switch (Fixup.getTargetKind()) {
129   default:
130     return false;
131   case RISCV::fixup_riscv_rvc_branch:
132     // For compressed branch instructions the immediate must be
133     // in the range [-256, 254].
134     return Offset > 254 || Offset < -256;
135   case RISCV::fixup_riscv_rvc_jump:
136     // For compressed jump instructions the immediate must be
137     // in the range [-2048, 2046].
138     return Offset > 2046 || Offset < -2048;
139   }
140 }
141 
142 void RISCVAsmBackend::relaxInstruction(const MCInst &Inst,
143                                        const MCSubtargetInfo &STI,
144                                        MCInst &Res) const {
145   // TODO: replace this with call to auto generated uncompressinstr() function.
146   switch (Inst.getOpcode()) {
147   default:
148     llvm_unreachable("Opcode not expected!");
149   case RISCV::C_BEQZ:
150     // c.beqz $rs1, $imm -> beq $rs1, X0, $imm.
151     Res.setOpcode(RISCV::BEQ);
152     Res.addOperand(Inst.getOperand(0));
153     Res.addOperand(MCOperand::createReg(RISCV::X0));
154     Res.addOperand(Inst.getOperand(1));
155     break;
156   case RISCV::C_BNEZ:
157     // c.bnez $rs1, $imm -> bne $rs1, X0, $imm.
158     Res.setOpcode(RISCV::BNE);
159     Res.addOperand(Inst.getOperand(0));
160     Res.addOperand(MCOperand::createReg(RISCV::X0));
161     Res.addOperand(Inst.getOperand(1));
162     break;
163   case RISCV::C_J:
164     // c.j $imm -> jal X0, $imm.
165     Res.setOpcode(RISCV::JAL);
166     Res.addOperand(MCOperand::createReg(RISCV::X0));
167     Res.addOperand(Inst.getOperand(0));
168     break;
169   case RISCV::C_JAL:
170     // c.jal $imm -> jal X1, $imm.
171     Res.setOpcode(RISCV::JAL);
172     Res.addOperand(MCOperand::createReg(RISCV::X1));
173     Res.addOperand(Inst.getOperand(0));
174     break;
175   }
176 }
177 
178 // Given a compressed control flow instruction this function returns
179 // the expanded instruction.
180 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
181   switch (Op) {
182   default:
183     return Op;
184   case RISCV::C_BEQZ:
185     return RISCV::BEQ;
186   case RISCV::C_BNEZ:
187     return RISCV::BNE;
188   case RISCV::C_J:
189   case RISCV::C_JAL: // fall through.
190     return RISCV::JAL;
191   }
192 }
193 
194 bool RISCVAsmBackend::mayNeedRelaxation(const MCInst &Inst,
195                                         const MCSubtargetInfo &STI) const {
196   return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
197 }
198 
199 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
200   bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
201   unsigned MinNopLen = HasStdExtC ? 2 : 4;
202 
203   if ((Count % MinNopLen) != 0)
204     return false;
205 
206   // The canonical nop on RISC-V is addi x0, x0, 0.
207   for (; Count >= 4; Count -= 4)
208     OS.write("\x13\0\0\0", 4);
209 
210   // The canonical nop on RVC is c.nop.
211   if (Count && HasStdExtC)
212     OS.write("\x01\0", 2);
213 
214   return true;
215 }
216 
217 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
218                                  MCContext &Ctx) {
219   switch (Fixup.getTargetKind()) {
220   default:
221     llvm_unreachable("Unknown fixup kind!");
222   case RISCV::fixup_riscv_got_hi20:
223   case RISCV::fixup_riscv_tls_got_hi20:
224   case RISCV::fixup_riscv_tls_gd_hi20:
225     llvm_unreachable("Relocation should be unconditionally forced\n");
226   case FK_Data_1:
227   case FK_Data_2:
228   case FK_Data_4:
229   case FK_Data_8:
230   case FK_Data_6b:
231     return Value;
232   case RISCV::fixup_riscv_lo12_i:
233   case RISCV::fixup_riscv_pcrel_lo12_i:
234   case RISCV::fixup_riscv_tprel_lo12_i:
235     return Value & 0xfff;
236   case RISCV::fixup_riscv_lo12_s:
237   case RISCV::fixup_riscv_pcrel_lo12_s:
238   case RISCV::fixup_riscv_tprel_lo12_s:
239     return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
240   case RISCV::fixup_riscv_hi20:
241   case RISCV::fixup_riscv_pcrel_hi20:
242   case RISCV::fixup_riscv_tprel_hi20:
243     // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
244     return ((Value + 0x800) >> 12) & 0xfffff;
245   case RISCV::fixup_riscv_jal: {
246     if (!isInt<21>(Value))
247       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
248     if (Value & 0x1)
249       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
250     // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
251     unsigned Sbit = (Value >> 20) & 0x1;
252     unsigned Hi8 = (Value >> 12) & 0xff;
253     unsigned Mid1 = (Value >> 11) & 0x1;
254     unsigned Lo10 = (Value >> 1) & 0x3ff;
255     // Inst{31} = Sbit;
256     // Inst{30-21} = Lo10;
257     // Inst{20} = Mid1;
258     // Inst{19-12} = Hi8;
259     Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
260     return Value;
261   }
262   case RISCV::fixup_riscv_branch: {
263     if (!isInt<13>(Value))
264       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
265     if (Value & 0x1)
266       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
267     // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
268     // Value.
269     unsigned Sbit = (Value >> 12) & 0x1;
270     unsigned Hi1 = (Value >> 11) & 0x1;
271     unsigned Mid6 = (Value >> 5) & 0x3f;
272     unsigned Lo4 = (Value >> 1) & 0xf;
273     // Inst{31} = Sbit;
274     // Inst{30-25} = Mid6;
275     // Inst{11-8} = Lo4;
276     // Inst{7} = Hi1;
277     Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
278     return Value;
279   }
280   case RISCV::fixup_riscv_call:
281   case RISCV::fixup_riscv_call_plt: {
282     // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
283     // we need to add 0x800ULL before extract upper bits to reflect the
284     // effect of the sign extension.
285     uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
286     uint64_t LowerImm = Value & 0xfffULL;
287     return UpperImm | ((LowerImm << 20) << 32);
288   }
289   case RISCV::fixup_riscv_rvc_jump: {
290     // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
291     unsigned Bit11  = (Value >> 11) & 0x1;
292     unsigned Bit4   = (Value >> 4) & 0x1;
293     unsigned Bit9_8 = (Value >> 8) & 0x3;
294     unsigned Bit10  = (Value >> 10) & 0x1;
295     unsigned Bit6   = (Value >> 6) & 0x1;
296     unsigned Bit7   = (Value >> 7) & 0x1;
297     unsigned Bit3_1 = (Value >> 1) & 0x7;
298     unsigned Bit5   = (Value >> 5) & 0x1;
299     Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
300             (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
301     return Value;
302   }
303   case RISCV::fixup_riscv_rvc_branch: {
304     // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
305     unsigned Bit8   = (Value >> 8) & 0x1;
306     unsigned Bit7_6 = (Value >> 6) & 0x3;
307     unsigned Bit5   = (Value >> 5) & 0x1;
308     unsigned Bit4_3 = (Value >> 3) & 0x3;
309     unsigned Bit2_1 = (Value >> 1) & 0x3;
310     Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
311             (Bit5 << 2);
312     return Value;
313   }
314 
315   }
316 }
317 
318 bool RISCVAsmBackend::evaluateTargetFixup(
319     const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
320     const MCFragment *DF, const MCValue &Target, uint64_t &Value,
321     bool &WasForced) {
322   const MCFixup *AUIPCFixup;
323   const MCFragment *AUIPCDF;
324   MCValue AUIPCTarget;
325   switch (Fixup.getTargetKind()) {
326   default:
327     llvm_unreachable("Unexpected fixup kind!");
328   case RISCV::fixup_riscv_pcrel_hi20:
329     AUIPCFixup = &Fixup;
330     AUIPCDF = DF;
331     AUIPCTarget = Target;
332     break;
333   case RISCV::fixup_riscv_pcrel_lo12_i:
334   case RISCV::fixup_riscv_pcrel_lo12_s: {
335     AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
336     if (!AUIPCFixup) {
337       Asm.getContext().reportError(Fixup.getLoc(),
338                                    "could not find corresponding %pcrel_hi");
339       return true;
340     }
341 
342     // MCAssembler::evaluateFixup will emit an error for this case when it sees
343     // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
344     const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
345     if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Layout, AUIPCFixup))
346       return true;
347     break;
348   }
349   }
350 
351   if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
352     return false;
353 
354   const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
355   const MCSymbol &SA = A->getSymbol();
356   if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
357     return false;
358 
359   auto *Writer = Asm.getWriterPtr();
360   if (!Writer)
361     return false;
362 
363   bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
364       Asm, SA, *AUIPCDF, false, true);
365   if (!IsResolved)
366     return false;
367 
368   Value = Layout.getSymbolOffset(SA) + AUIPCTarget.getConstant();
369   Value -= Layout.getFragmentOffset(AUIPCDF) + AUIPCFixup->getOffset();
370 
371   if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget)) {
372     WasForced = true;
373     return false;
374   }
375 
376   return true;
377 }
378 
379 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
380                                  const MCValue &Target,
381                                  MutableArrayRef<char> Data, uint64_t Value,
382                                  bool IsResolved,
383                                  const MCSubtargetInfo *STI) const {
384   MCFixupKind Kind = Fixup.getKind();
385   if (Kind >= FirstLiteralRelocationKind)
386     return;
387   MCContext &Ctx = Asm.getContext();
388   MCFixupKindInfo Info = getFixupKindInfo(Kind);
389   if (!Value)
390     return; // Doesn't change encoding.
391   // Apply any target-specific value adjustments.
392   Value = adjustFixupValue(Fixup, Value, Ctx);
393 
394   // Shift the value into position.
395   Value <<= Info.TargetOffset;
396 
397   unsigned Offset = Fixup.getOffset();
398   unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
399 
400   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
401 
402   // For each byte of the fragment that the fixup touches, mask in the
403   // bits from the fixup value.
404   for (unsigned i = 0; i != NumBytes; ++i) {
405     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
406   }
407 }
408 
409 // Linker relaxation may change code size. We have to insert Nops
410 // for .align directive when linker relaxation enabled. So then Linker
411 // could satisfy alignment by removing Nops.
412 // The function return the total Nops Size we need to insert.
413 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
414     const MCAlignFragment &AF, unsigned &Size) {
415   // Calculate Nops Size only when linker relaxation enabled.
416   if (!STI.getFeatureBits()[RISCV::FeatureRelax])
417     return false;
418 
419   bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
420   unsigned MinNopLen = HasStdExtC ? 2 : 4;
421 
422   if (AF.getAlignment() <= MinNopLen) {
423     return false;
424   } else {
425     Size = AF.getAlignment() - MinNopLen;
426     return true;
427   }
428 }
429 
430 // We need to insert R_RISCV_ALIGN relocation type to indicate the
431 // position of Nops and the total bytes of the Nops have been inserted
432 // when linker relaxation enabled.
433 // The function insert fixup_riscv_align fixup which eventually will
434 // transfer to R_RISCV_ALIGN relocation type.
435 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
436                                                     const MCAsmLayout &Layout,
437                                                     MCAlignFragment &AF) {
438   // Insert the fixup only when linker relaxation enabled.
439   if (!STI.getFeatureBits()[RISCV::FeatureRelax])
440     return false;
441 
442   // Calculate total Nops we need to insert. If there are none to insert
443   // then simply return.
444   unsigned Count;
445   if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
446     return false;
447 
448   MCContext &Ctx = Asm.getContext();
449   const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
450   // Create fixup_riscv_align fixup.
451   MCFixup Fixup =
452       MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
453 
454   uint64_t FixedValue = 0;
455   MCValue NopBytes = MCValue::get(Count);
456 
457   Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
458                                    FixedValue);
459 
460   return true;
461 }
462 
463 std::unique_ptr<MCObjectTargetWriter>
464 RISCVAsmBackend::createObjectTargetWriter() const {
465   return createRISCVELFObjectWriter(OSABI, Is64Bit);
466 }
467 
468 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
469                                           const MCSubtargetInfo &STI,
470                                           const MCRegisterInfo &MRI,
471                                           const MCTargetOptions &Options) {
472   const Triple &TT = STI.getTargetTriple();
473   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
474   return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
475 }
476