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