xref: /llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVAsmBackend.cpp (revision 814b34f31e163e76b816194004689985f5b9fd7b)
1 //===-- RISCVAsmBackend.cpp - RISC-V 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/MCAsmInfo.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCContext.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/CommandLine.h"
21 #include "llvm/Support/EndianStream.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LEB128.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 using namespace llvm;
27 
28 static cl::opt<bool> RelaxBranches("riscv-asm-relax-branches", cl::init(true),
29                                    cl::Hidden);
30 // Temporary workaround for old linkers that do not support ULEB128 relocations,
31 // which are abused by DWARF v5 DW_LLE_offset_pair/DW_RLE_offset_pair
32 // implemented in Clang/LLVM.
33 static cl::opt<bool> ULEB128Reloc(
34     "riscv-uleb128-reloc", cl::init(true), cl::Hidden,
35     cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"));
36 
37 std::optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
38   if (STI.getTargetTriple().isOSBinFormatELF()) {
39     unsigned Type;
40     Type = llvm::StringSwitch<unsigned>(Name)
41 #define ELF_RELOC(NAME, ID) .Case(#NAME, ID)
42 #include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
43 #undef ELF_RELOC
44 #define ELF_RISCV_NONSTANDARD_RELOC(_VENDOR, NAME, ID) .Case(#NAME, ID)
45 #include "llvm/BinaryFormat/ELFRelocs/RISCV_nonstandard.def"
46 #undef ELF_RISCV_NONSTANDARD_RELOC
47                .Case("BFD_RELOC_NONE", ELF::R_RISCV_NONE)
48                .Case("BFD_RELOC_32", ELF::R_RISCV_32)
49                .Case("BFD_RELOC_64", ELF::R_RISCV_64)
50                .Default(-1u);
51     if (Type != -1u)
52       return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
53   }
54   return std::nullopt;
55 }
56 
57 const MCFixupKindInfo &
58 RISCVAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
59   const static MCFixupKindInfo Infos[] = {
60       // This table *must* be in the order that the fixup_* kinds are defined in
61       // RISCVFixupKinds.h.
62       //
63       // name                      offset bits  flags
64       {"fixup_riscv_hi20", 12, 20, 0},
65       {"fixup_riscv_lo12_i", 20, 12, 0},
66       {"fixup_riscv_12_i", 20, 12, 0},
67       {"fixup_riscv_lo12_s", 0, 32, 0},
68       {"fixup_riscv_pcrel_hi20", 12, 20,
69        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
70       {"fixup_riscv_pcrel_lo12_i", 20, 12,
71        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
72       {"fixup_riscv_pcrel_lo12_s", 0, 32,
73        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
74       {"fixup_riscv_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
75       {"fixup_riscv_tprel_hi20", 12, 20, 0},
76       {"fixup_riscv_tprel_lo12_i", 20, 12, 0},
77       {"fixup_riscv_tprel_lo12_s", 0, 32, 0},
78       {"fixup_riscv_tprel_add", 0, 0, 0},
79       {"fixup_riscv_tls_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
80       {"fixup_riscv_tls_gd_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
81       {"fixup_riscv_jal", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
82       {"fixup_riscv_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
83       {"fixup_riscv_rvc_jump", 2, 11, MCFixupKindInfo::FKF_IsPCRel},
84       {"fixup_riscv_rvc_branch", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
85       {"fixup_riscv_call", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
86       {"fixup_riscv_call_plt", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
87       {"fixup_riscv_relax", 0, 0, 0},
88       {"fixup_riscv_align", 0, 0, 0},
89 
90       {"fixup_riscv_tlsdesc_hi20", 12, 20,
91        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
92       {"fixup_riscv_tlsdesc_load_lo12", 20, 12, 0},
93       {"fixup_riscv_tlsdesc_add_lo12", 20, 12, 0},
94       {"fixup_riscv_tlsdesc_call", 0, 0, 0},
95   };
96   static_assert((std::size(Infos)) == RISCV::NumTargetFixupKinds,
97                 "Not all fixup kinds added to Infos array");
98 
99   // Fixup kinds from .reloc directive are like R_RISCV_NONE. They
100   // do not require any extra processing.
101   if (Kind >= FirstLiteralRelocationKind)
102     return MCAsmBackend::getFixupKindInfo(FK_NONE);
103 
104   if (Kind < FirstTargetFixupKind)
105     return MCAsmBackend::getFixupKindInfo(Kind);
106 
107   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
108          "Invalid kind!");
109   return Infos[Kind - FirstTargetFixupKind];
110 }
111 
112 // If linker relaxation is enabled, or the relax option had previously been
113 // enabled, always emit relocations even if the fixup can be resolved. This is
114 // necessary for correctness as offsets may change during relaxation.
115 bool RISCVAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
116                                             const MCFixup &Fixup,
117                                             const MCValue &Target,
118                                             const uint64_t,
119                                             const MCSubtargetInfo *STI) {
120   if (Fixup.getKind() >= FirstLiteralRelocationKind)
121     return true;
122   switch (Fixup.getTargetKind()) {
123   default:
124     break;
125   case FK_Data_1:
126   case FK_Data_2:
127   case FK_Data_4:
128   case FK_Data_8:
129   case FK_Data_leb128:
130     if (Target.isAbsolute())
131       return false;
132     break;
133   case RISCV::fixup_riscv_got_hi20:
134   case RISCV::fixup_riscv_tls_got_hi20:
135   case RISCV::fixup_riscv_tls_gd_hi20:
136   case RISCV::fixup_riscv_tlsdesc_hi20:
137     return true;
138   }
139 
140   return STI->hasFeature(RISCV::FeatureRelax) || ForceRelocs;
141 }
142 
143 bool RISCVAsmBackend::fixupNeedsRelaxationAdvanced(
144     const MCAssembler &Asm, const MCFixup &Fixup, bool Resolved, uint64_t Value,
145     const MCRelaxableFragment *DF, const bool WasForced) const {
146   if (!RelaxBranches)
147     return false;
148 
149   int64_t Offset = int64_t(Value);
150   unsigned Kind = Fixup.getTargetKind();
151 
152   // Return true if the symbol is actually unresolved.
153   // Resolved could be always false when shouldForceRelocation return true.
154   // We use !WasForced to indicate that the symbol is unresolved and not forced
155   // by shouldForceRelocation.
156   if (!Resolved && !WasForced)
157     return true;
158 
159   switch (Kind) {
160   default:
161     return false;
162   case RISCV::fixup_riscv_rvc_branch:
163     // For compressed branch instructions the immediate must be
164     // in the range [-256, 254].
165     return Offset > 254 || Offset < -256;
166   case RISCV::fixup_riscv_rvc_jump:
167     // For compressed jump instructions the immediate must be
168     // in the range [-2048, 2046].
169     return Offset > 2046 || Offset < -2048;
170   case RISCV::fixup_riscv_branch:
171     // For conditional branch instructions the immediate must be
172     // in the range [-4096, 4095].
173     return !isInt<13>(Offset);
174   }
175 }
176 
177 void RISCVAsmBackend::relaxInstruction(MCInst &Inst,
178                                        const MCSubtargetInfo &STI) const {
179   MCInst Res;
180   switch (Inst.getOpcode()) {
181   default:
182     llvm_unreachable("Opcode not expected!");
183   case RISCV::C_BEQZ:
184   case RISCV::C_BNEZ:
185   case RISCV::C_J:
186   case RISCV::C_JAL: {
187     [[maybe_unused]] bool Success = RISCVRVC::uncompress(Res, Inst, STI);
188     assert(Success && "Can't uncompress instruction");
189     break;
190   }
191   case RISCV::BEQ:
192   case RISCV::BNE:
193   case RISCV::BLT:
194   case RISCV::BGE:
195   case RISCV::BLTU:
196   case RISCV::BGEU:
197     Res.setOpcode(getRelaxedOpcode(Inst.getOpcode()));
198     Res.addOperand(Inst.getOperand(0));
199     Res.addOperand(Inst.getOperand(1));
200     Res.addOperand(Inst.getOperand(2));
201     break;
202   }
203   Inst = std::move(Res);
204 }
205 
206 bool RISCVAsmBackend::relaxDwarfLineAddr(const MCAssembler &Asm,
207                                          MCDwarfLineAddrFragment &DF,
208                                          bool &WasRelaxed) const {
209   MCContext &C = Asm.getContext();
210 
211   int64_t LineDelta = DF.getLineDelta();
212   const MCExpr &AddrDelta = DF.getAddrDelta();
213   SmallVectorImpl<char> &Data = DF.getContents();
214   SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
215   size_t OldSize = Data.size();
216 
217   int64_t Value;
218   [[maybe_unused]] bool IsAbsolute =
219       AddrDelta.evaluateKnownAbsolute(Value, Asm);
220   assert(IsAbsolute && "CFA with invalid expression");
221 
222   Data.clear();
223   Fixups.clear();
224   raw_svector_ostream OS(Data);
225 
226   // INT64_MAX is a signal that this is actually a DW_LNE_end_sequence.
227   if (LineDelta != INT64_MAX) {
228     OS << uint8_t(dwarf::DW_LNS_advance_line);
229     encodeSLEB128(LineDelta, OS);
230   }
231 
232   unsigned Offset;
233   std::pair<MCFixupKind, MCFixupKind> Fixup;
234 
235   // According to the DWARF specification, the `DW_LNS_fixed_advance_pc` opcode
236   // takes a single unsigned half (unencoded) operand. The maximum encodable
237   // value is therefore 65535.  Set a conservative upper bound for relaxation.
238   if (Value > 60000) {
239     unsigned PtrSize = C.getAsmInfo()->getCodePointerSize();
240 
241     OS << uint8_t(dwarf::DW_LNS_extended_op);
242     encodeULEB128(PtrSize + 1, OS);
243 
244     OS << uint8_t(dwarf::DW_LNE_set_address);
245     Offset = OS.tell();
246     assert((PtrSize == 4 || PtrSize == 8) && "Unexpected pointer size");
247     Fixup = RISCV::getRelocPairForSize(PtrSize);
248     OS.write_zeros(PtrSize);
249   } else {
250     OS << uint8_t(dwarf::DW_LNS_fixed_advance_pc);
251     Offset = OS.tell();
252     Fixup = RISCV::getRelocPairForSize(2);
253     support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
254   }
255 
256   const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
257   Fixups.push_back(MCFixup::create(Offset, MBE.getLHS(), std::get<0>(Fixup)));
258   Fixups.push_back(MCFixup::create(Offset, MBE.getRHS(), std::get<1>(Fixup)));
259 
260   if (LineDelta == INT64_MAX) {
261     OS << uint8_t(dwarf::DW_LNS_extended_op);
262     OS << uint8_t(1);
263     OS << uint8_t(dwarf::DW_LNE_end_sequence);
264   } else {
265     OS << uint8_t(dwarf::DW_LNS_copy);
266   }
267 
268   WasRelaxed = OldSize != Data.size();
269   return true;
270 }
271 
272 bool RISCVAsmBackend::relaxDwarfCFA(const MCAssembler &Asm,
273                                     MCDwarfCallFrameFragment &DF,
274                                     bool &WasRelaxed) const {
275   const MCExpr &AddrDelta = DF.getAddrDelta();
276   SmallVectorImpl<char> &Data = DF.getContents();
277   SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
278   size_t OldSize = Data.size();
279 
280   int64_t Value;
281   if (AddrDelta.evaluateAsAbsolute(Value, Asm))
282     return false;
283   [[maybe_unused]] bool IsAbsolute =
284       AddrDelta.evaluateKnownAbsolute(Value, Asm);
285   assert(IsAbsolute && "CFA with invalid expression");
286 
287   Data.clear();
288   Fixups.clear();
289   raw_svector_ostream OS(Data);
290 
291   assert(Asm.getContext().getAsmInfo()->getMinInstAlignment() == 1 &&
292          "expected 1-byte alignment");
293   if (Value == 0) {
294     WasRelaxed = OldSize != Data.size();
295     return true;
296   }
297 
298   auto AddFixups = [&Fixups, &AddrDelta](unsigned Offset,
299                                          std::pair<unsigned, unsigned> Fixup) {
300     const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
301     Fixups.push_back(
302         MCFixup::create(Offset, MBE.getLHS(),
303                         static_cast<MCFixupKind>(FirstLiteralRelocationKind +
304                                                  std::get<0>(Fixup))));
305     Fixups.push_back(
306         MCFixup::create(Offset, MBE.getRHS(),
307                         static_cast<MCFixupKind>(FirstLiteralRelocationKind +
308                                                  std::get<1>(Fixup))));
309   };
310 
311   if (isUIntN(6, Value)) {
312     OS << uint8_t(dwarf::DW_CFA_advance_loc);
313     AddFixups(0, {ELF::R_RISCV_SET6, ELF::R_RISCV_SUB6});
314   } else if (isUInt<8>(Value)) {
315     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
316     support::endian::write<uint8_t>(OS, 0, llvm::endianness::little);
317     AddFixups(1, {ELF::R_RISCV_SET8, ELF::R_RISCV_SUB8});
318   } else if (isUInt<16>(Value)) {
319     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
320     support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
321     AddFixups(1, {ELF::R_RISCV_SET16, ELF::R_RISCV_SUB16});
322   } else if (isUInt<32>(Value)) {
323     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
324     support::endian::write<uint32_t>(OS, 0, llvm::endianness::little);
325     AddFixups(1, {ELF::R_RISCV_SET32, ELF::R_RISCV_SUB32});
326   } else {
327     llvm_unreachable("unsupported CFA encoding");
328   }
329 
330   WasRelaxed = OldSize != Data.size();
331   return true;
332 }
333 
334 std::pair<bool, bool> RISCVAsmBackend::relaxLEB128(const MCAssembler &Asm,
335                                                    MCLEBFragment &LF,
336                                                    int64_t &Value) const {
337   if (LF.isSigned())
338     return std::make_pair(false, false);
339   const MCExpr &Expr = LF.getValue();
340   if (ULEB128Reloc) {
341     LF.getFixups().push_back(
342         MCFixup::create(0, &Expr, FK_Data_leb128, Expr.getLoc()));
343   }
344   return std::make_pair(Expr.evaluateKnownAbsolute(Value, Asm), false);
345 }
346 
347 // Given a compressed control flow instruction this function returns
348 // the expanded instruction.
349 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
350   switch (Op) {
351   default:
352     return Op;
353   case RISCV::C_BEQZ:
354     return RISCV::BEQ;
355   case RISCV::C_BNEZ:
356     return RISCV::BNE;
357   case RISCV::C_J:
358   case RISCV::C_JAL: // fall through.
359     return RISCV::JAL;
360   case RISCV::BEQ:
361     return RISCV::PseudoLongBEQ;
362   case RISCV::BNE:
363     return RISCV::PseudoLongBNE;
364   case RISCV::BLT:
365     return RISCV::PseudoLongBLT;
366   case RISCV::BGE:
367     return RISCV::PseudoLongBGE;
368   case RISCV::BLTU:
369     return RISCV::PseudoLongBLTU;
370   case RISCV::BGEU:
371     return RISCV::PseudoLongBGEU;
372   }
373 }
374 
375 bool RISCVAsmBackend::mayNeedRelaxation(const MCInst &Inst,
376                                         const MCSubtargetInfo &STI) const {
377   return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
378 }
379 
380 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count,
381                                    const MCSubtargetInfo *STI) const {
382   // We mostly follow binutils' convention here: align to even boundary with a
383   // 0-fill padding.  We emit up to 1 2-byte nop, though we use c.nop if RVC is
384   // enabled or 0-fill otherwise.  The remainder is now padded with 4-byte nops.
385 
386   // Instructions always are at even addresses.  We must be in a data area or
387   // be unaligned due to some other reason.
388   if (Count % 2) {
389     OS.write("\0", 1);
390     Count -= 1;
391   }
392 
393   bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
394                           STI->hasFeature(RISCV::FeatureStdExtZca);
395   // The canonical nop on RVC is c.nop.
396   if (Count % 4 == 2) {
397     OS.write(UseCompressedNop ? "\x01\0" : "\0\0", 2);
398     Count -= 2;
399   }
400 
401   // The canonical nop on RISC-V is addi x0, x0, 0.
402   for (; Count >= 4; Count -= 4)
403     OS.write("\x13\0\0\0", 4);
404 
405   return true;
406 }
407 
408 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
409                                  MCContext &Ctx) {
410   switch (Fixup.getTargetKind()) {
411   default:
412     llvm_unreachable("Unknown fixup kind!");
413   case RISCV::fixup_riscv_got_hi20:
414   case RISCV::fixup_riscv_tls_got_hi20:
415   case RISCV::fixup_riscv_tls_gd_hi20:
416   case RISCV::fixup_riscv_tlsdesc_hi20:
417     llvm_unreachable("Relocation should be unconditionally forced\n");
418   case FK_Data_1:
419   case FK_Data_2:
420   case FK_Data_4:
421   case FK_Data_8:
422   case FK_Data_leb128:
423     return Value;
424   case RISCV::fixup_riscv_lo12_i:
425   case RISCV::fixup_riscv_pcrel_lo12_i:
426   case RISCV::fixup_riscv_tprel_lo12_i:
427   case RISCV::fixup_riscv_tlsdesc_load_lo12:
428     return Value & 0xfff;
429   case RISCV::fixup_riscv_12_i:
430     if (!isInt<12>(Value)) {
431       Ctx.reportError(Fixup.getLoc(),
432                       "operand must be a constant 12-bit integer");
433     }
434     return Value & 0xfff;
435   case RISCV::fixup_riscv_lo12_s:
436   case RISCV::fixup_riscv_pcrel_lo12_s:
437   case RISCV::fixup_riscv_tprel_lo12_s:
438     return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
439   case RISCV::fixup_riscv_hi20:
440   case RISCV::fixup_riscv_pcrel_hi20:
441   case RISCV::fixup_riscv_tprel_hi20:
442     // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
443     return ((Value + 0x800) >> 12) & 0xfffff;
444   case RISCV::fixup_riscv_jal: {
445     if (!isInt<21>(Value))
446       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
447     if (Value & 0x1)
448       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
449     // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
450     unsigned Sbit = (Value >> 20) & 0x1;
451     unsigned Hi8 = (Value >> 12) & 0xff;
452     unsigned Mid1 = (Value >> 11) & 0x1;
453     unsigned Lo10 = (Value >> 1) & 0x3ff;
454     // Inst{31} = Sbit;
455     // Inst{30-21} = Lo10;
456     // Inst{20} = Mid1;
457     // Inst{19-12} = Hi8;
458     Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
459     return Value;
460   }
461   case RISCV::fixup_riscv_branch: {
462     if (!isInt<13>(Value))
463       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
464     if (Value & 0x1)
465       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
466     // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
467     // Value.
468     unsigned Sbit = (Value >> 12) & 0x1;
469     unsigned Hi1 = (Value >> 11) & 0x1;
470     unsigned Mid6 = (Value >> 5) & 0x3f;
471     unsigned Lo4 = (Value >> 1) & 0xf;
472     // Inst{31} = Sbit;
473     // Inst{30-25} = Mid6;
474     // Inst{11-8} = Lo4;
475     // Inst{7} = Hi1;
476     Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
477     return Value;
478   }
479   case RISCV::fixup_riscv_call:
480   case RISCV::fixup_riscv_call_plt: {
481     // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
482     // we need to add 0x800ULL before extract upper bits to reflect the
483     // effect of the sign extension.
484     uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
485     uint64_t LowerImm = Value & 0xfffULL;
486     return UpperImm | ((LowerImm << 20) << 32);
487   }
488   case RISCV::fixup_riscv_rvc_jump: {
489     if (!isInt<12>(Value))
490       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
491     // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
492     unsigned Bit11  = (Value >> 11) & 0x1;
493     unsigned Bit4   = (Value >> 4) & 0x1;
494     unsigned Bit9_8 = (Value >> 8) & 0x3;
495     unsigned Bit10  = (Value >> 10) & 0x1;
496     unsigned Bit6   = (Value >> 6) & 0x1;
497     unsigned Bit7   = (Value >> 7) & 0x1;
498     unsigned Bit3_1 = (Value >> 1) & 0x7;
499     unsigned Bit5   = (Value >> 5) & 0x1;
500     Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
501             (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
502     return Value;
503   }
504   case RISCV::fixup_riscv_rvc_branch: {
505     if (!isInt<9>(Value))
506       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
507     // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
508     unsigned Bit8   = (Value >> 8) & 0x1;
509     unsigned Bit7_6 = (Value >> 6) & 0x3;
510     unsigned Bit5   = (Value >> 5) & 0x1;
511     unsigned Bit4_3 = (Value >> 3) & 0x3;
512     unsigned Bit2_1 = (Value >> 1) & 0x3;
513     Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
514             (Bit5 << 2);
515     return Value;
516   }
517 
518   }
519 }
520 
521 bool RISCVAsmBackend::evaluateTargetFixup(const MCAssembler &Asm,
522                                           const MCFixup &Fixup,
523                                           const MCFragment *DF,
524                                           const MCValue &Target,
525                                           const MCSubtargetInfo *STI,
526                                           uint64_t &Value, bool &WasForced) {
527   const MCFixup *AUIPCFixup;
528   const MCFragment *AUIPCDF;
529   MCValue AUIPCTarget;
530   switch (Fixup.getTargetKind()) {
531   default:
532     llvm_unreachable("Unexpected fixup kind!");
533   case RISCV::fixup_riscv_tlsdesc_hi20:
534   case RISCV::fixup_riscv_pcrel_hi20:
535     AUIPCFixup = &Fixup;
536     AUIPCDF = DF;
537     AUIPCTarget = Target;
538     break;
539   case RISCV::fixup_riscv_pcrel_lo12_i:
540   case RISCV::fixup_riscv_pcrel_lo12_s: {
541     AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
542     if (!AUIPCFixup) {
543       Asm.getContext().reportError(Fixup.getLoc(),
544                                    "could not find corresponding %pcrel_hi");
545       return true;
546     }
547 
548     // MCAssembler::evaluateFixup will emit an error for this case when it sees
549     // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
550     const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
551     if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Asm, AUIPCFixup))
552       return true;
553     break;
554   }
555   }
556 
557   if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
558     return false;
559 
560   const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
561   const MCSymbolELF &SA = cast<MCSymbolELF>(A->getSymbol());
562   if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
563     return false;
564 
565   bool IsResolved = &SA.getSection() == AUIPCDF->getParent() &&
566                     SA.getBinding() == ELF::STB_LOCAL &&
567                     SA.getType() != ELF::STT_GNU_IFUNC;
568   if (!IsResolved)
569     return false;
570 
571   Value = Asm.getSymbolOffset(SA) + AUIPCTarget.getConstant();
572   Value -= Asm.getFragmentOffset(*AUIPCDF) + AUIPCFixup->getOffset();
573 
574   if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget, Value, STI)) {
575     WasForced = true;
576     return false;
577   }
578 
579   return true;
580 }
581 
582 bool RISCVAsmBackend::handleAddSubRelocations(const MCAssembler &Asm,
583                                               const MCFragment &F,
584                                               const MCFixup &Fixup,
585                                               const MCValue &Target,
586                                               uint64_t &FixedValue) const {
587   uint64_t FixedValueA, FixedValueB;
588   unsigned TA = 0, TB = 0;
589   switch (Fixup.getKind()) {
590   case llvm::FK_Data_1:
591     TA = ELF::R_RISCV_ADD8;
592     TB = ELF::R_RISCV_SUB8;
593     break;
594   case llvm::FK_Data_2:
595     TA = ELF::R_RISCV_ADD16;
596     TB = ELF::R_RISCV_SUB16;
597     break;
598   case llvm::FK_Data_4:
599     TA = ELF::R_RISCV_ADD32;
600     TB = ELF::R_RISCV_SUB32;
601     break;
602   case llvm::FK_Data_8:
603     TA = ELF::R_RISCV_ADD64;
604     TB = ELF::R_RISCV_SUB64;
605     break;
606   case llvm::FK_Data_leb128:
607     TA = ELF::R_RISCV_SET_ULEB128;
608     TB = ELF::R_RISCV_SUB_ULEB128;
609     break;
610   default:
611     llvm_unreachable("unsupported fixup size");
612   }
613   MCValue A = MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
614   MCValue B = MCValue::get(Target.getSymB());
615   auto FA = MCFixup::create(
616       Fixup.getOffset(), nullptr,
617       static_cast<MCFixupKind>(FirstLiteralRelocationKind + TA));
618   auto FB = MCFixup::create(
619       Fixup.getOffset(), nullptr,
620       static_cast<MCFixupKind>(FirstLiteralRelocationKind + TB));
621   auto &Assembler = const_cast<MCAssembler &>(Asm);
622   Asm.getWriter().recordRelocation(Assembler, &F, FA, A, FixedValueA);
623   Asm.getWriter().recordRelocation(Assembler, &F, FB, B, FixedValueB);
624   FixedValue = FixedValueA - FixedValueB;
625   return true;
626 }
627 
628 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
629                                  const MCValue &Target,
630                                  MutableArrayRef<char> Data, uint64_t Value,
631                                  bool IsResolved,
632                                  const MCSubtargetInfo *STI) const {
633   MCFixupKind Kind = Fixup.getKind();
634   if (Kind >= FirstLiteralRelocationKind)
635     return;
636   MCContext &Ctx = Asm.getContext();
637   MCFixupKindInfo Info = getFixupKindInfo(Kind);
638   if (!Value)
639     return; // Doesn't change encoding.
640   // Apply any target-specific value adjustments.
641   Value = adjustFixupValue(Fixup, Value, Ctx);
642 
643   // Shift the value into position.
644   Value <<= Info.TargetOffset;
645 
646   unsigned Offset = Fixup.getOffset();
647   unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
648 
649   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
650 
651   // For each byte of the fragment that the fixup touches, mask in the
652   // bits from the fixup value.
653   for (unsigned i = 0; i != NumBytes; ++i) {
654     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
655   }
656 }
657 
658 // Linker relaxation may change code size. We have to insert Nops
659 // for .align directive when linker relaxation enabled. So then Linker
660 // could satisfy alignment by removing Nops.
661 // The function return the total Nops Size we need to insert.
662 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
663     const MCAlignFragment &AF, unsigned &Size) {
664   // Calculate Nops Size only when linker relaxation enabled.
665   const MCSubtargetInfo *STI = AF.getSubtargetInfo();
666   if (!STI->hasFeature(RISCV::FeatureRelax))
667     return false;
668 
669   bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
670                           STI->hasFeature(RISCV::FeatureStdExtZca);
671   unsigned MinNopLen = UseCompressedNop ? 2 : 4;
672 
673   if (AF.getAlignment() <= MinNopLen) {
674     return false;
675   } else {
676     Size = AF.getAlignment().value() - MinNopLen;
677     return true;
678   }
679 }
680 
681 // We need to insert R_RISCV_ALIGN relocation type to indicate the
682 // position of Nops and the total bytes of the Nops have been inserted
683 // when linker relaxation enabled.
684 // The function insert fixup_riscv_align fixup which eventually will
685 // transfer to R_RISCV_ALIGN relocation type.
686 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
687                                                     MCAlignFragment &AF) {
688   // Insert the fixup only when linker relaxation enabled.
689   const MCSubtargetInfo *STI = AF.getSubtargetInfo();
690   if (!STI->hasFeature(RISCV::FeatureRelax))
691     return false;
692 
693   // Calculate total Nops we need to insert. If there are none to insert
694   // then simply return.
695   unsigned Count;
696   if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
697     return false;
698 
699   MCContext &Ctx = Asm.getContext();
700   const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
701   // Create fixup_riscv_align fixup.
702   MCFixup Fixup =
703       MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
704 
705   uint64_t FixedValue = 0;
706   MCValue NopBytes = MCValue::get(Count);
707 
708   Asm.getWriter().recordRelocation(Asm, &AF, Fixup, NopBytes, FixedValue);
709 
710   return true;
711 }
712 
713 std::unique_ptr<MCObjectTargetWriter>
714 RISCVAsmBackend::createObjectTargetWriter() const {
715   return createRISCVELFObjectWriter(OSABI, Is64Bit);
716 }
717 
718 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
719                                           const MCSubtargetInfo &STI,
720                                           const MCRegisterInfo &MRI,
721                                           const MCTargetOptions &Options) {
722   const Triple &TT = STI.getTargetTriple();
723   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
724   return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
725 }
726