LLVM 20.0.0git
RISCVAsmBackend.cpp
Go to the documentation of this file.
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"
16#include "llvm/MC/MCExpr.h"
18#include "llvm/MC/MCSymbol.h"
19#include "llvm/MC/MCValue.h"
23#include "llvm/Support/LEB128.h"
25
26using namespace llvm;
27
28static cl::opt<bool> RelaxBranches("riscv-asm-relax-branches", cl::init(true),
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.
34 "riscv-uleb128-reloc", cl::init(true), cl::Hidden,
35 cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"));
36
37std::optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
39 unsigned Type;
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
57const MCFixupKindInfo &
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,
70 {"fixup_riscv_pcrel_lo12_i", 20, 12,
72 {"fixup_riscv_pcrel_lo12_s", 0, 32,
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,
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)
103
104 if (Kind < FirstTargetFixupKind)
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.
116 const MCFixup &Fixup,
117 const MCValue &Target,
118 const MCSubtargetInfo *STI) {
119 if (Fixup.getKind() >= FirstLiteralRelocationKind)
120 return true;
121 switch (Fixup.getTargetKind()) {
122 default:
123 break;
124 case FK_Data_1:
125 case FK_Data_2:
126 case FK_Data_4:
127 case FK_Data_8:
128 case FK_Data_leb128:
129 if (Target.isAbsolute())
130 return false;
131 break;
136 return true;
137 }
138
139 return STI->hasFeature(RISCV::FeatureRelax) || ForceRelocs;
140}
141
143 const MCAssembler &Asm, const MCFixup &Fixup, bool Resolved, uint64_t Value,
144 const MCRelaxableFragment *DF, const bool WasForced) const {
145 if (!RelaxBranches)
146 return false;
147
148 int64_t Offset = int64_t(Value);
149 unsigned Kind = Fixup.getTargetKind();
150
151 // Return true if the symbol is actually unresolved.
152 // Resolved could be always false when shouldForceRelocation return true.
153 // We use !WasForced to indicate that the symbol is unresolved and not forced
154 // by shouldForceRelocation.
155 if (!Resolved && !WasForced)
156 return true;
157
158 switch (Kind) {
159 default:
160 return false;
162 // For compressed branch instructions the immediate must be
163 // in the range [-256, 254].
164 return Offset > 254 || Offset < -256;
166 // For compressed jump instructions the immediate must be
167 // in the range [-2048, 2046].
168 return Offset > 2046 || Offset < -2048;
170 // For conditional branch instructions the immediate must be
171 // in the range [-4096, 4095].
172 return !isInt<13>(Offset);
173 }
174}
175
177 const MCSubtargetInfo &STI) const {
178 MCInst Res;
179 switch (Inst.getOpcode()) {
180 default:
181 llvm_unreachable("Opcode not expected!");
182 case RISCV::C_BEQZ:
183 case RISCV::C_BNEZ:
184 case RISCV::C_J:
185 case RISCV::C_JAL: {
186 [[maybe_unused]] bool Success = RISCVRVC::uncompress(Res, Inst, STI);
187 assert(Success && "Can't uncompress instruction");
188 break;
189 }
190 case RISCV::BEQ:
191 case RISCV::BNE:
192 case RISCV::BLT:
193 case RISCV::BGE:
194 case RISCV::BLTU:
195 case RISCV::BGEU:
197 Res.addOperand(Inst.getOperand(0));
198 Res.addOperand(Inst.getOperand(1));
199 Res.addOperand(Inst.getOperand(2));
200 break;
201 }
202 Inst = std::move(Res);
203}
204
207 bool &WasRelaxed) const {
208 MCContext &C = Asm.getContext();
209
210 int64_t LineDelta = DF.getLineDelta();
211 const MCExpr &AddrDelta = DF.getAddrDelta();
212 SmallVectorImpl<char> &Data = DF.getContents();
213 SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
214 size_t OldSize = Data.size();
215
216 int64_t Value;
217 [[maybe_unused]] bool IsAbsolute =
218 AddrDelta.evaluateKnownAbsolute(Value, Asm);
219 assert(IsAbsolute && "CFA with invalid expression");
220
221 Data.clear();
222 Fixups.clear();
224
225 // INT64_MAX is a signal that this is actually a DW_LNE_end_sequence.
226 if (LineDelta != INT64_MAX) {
227 OS << uint8_t(dwarf::DW_LNS_advance_line);
228 encodeSLEB128(LineDelta, OS);
229 }
230
231 unsigned Offset;
232 std::pair<MCFixupKind, MCFixupKind> Fixup;
233
234 // According to the DWARF specification, the `DW_LNS_fixed_advance_pc` opcode
235 // takes a single unsigned half (unencoded) operand. The maximum encodable
236 // value is therefore 65535. Set a conservative upper bound for relaxation.
237 if (Value > 60000) {
238 unsigned PtrSize = C.getAsmInfo()->getCodePointerSize();
239
240 OS << uint8_t(dwarf::DW_LNS_extended_op);
241 encodeULEB128(PtrSize + 1, OS);
242
243 OS << uint8_t(dwarf::DW_LNE_set_address);
244 Offset = OS.tell();
245 assert((PtrSize == 4 || PtrSize == 8) && "Unexpected pointer size");
247 OS.write_zeros(PtrSize);
248 } else {
249 OS << uint8_t(dwarf::DW_LNS_fixed_advance_pc);
250 Offset = OS.tell();
252 support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
253 }
254
255 const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
256 Fixups.push_back(MCFixup::create(Offset, MBE.getLHS(), std::get<0>(Fixup)));
257 Fixups.push_back(MCFixup::create(Offset, MBE.getRHS(), std::get<1>(Fixup)));
258
259 if (LineDelta == INT64_MAX) {
260 OS << uint8_t(dwarf::DW_LNS_extended_op);
261 OS << uint8_t(1);
262 OS << uint8_t(dwarf::DW_LNE_end_sequence);
263 } else {
264 OS << uint8_t(dwarf::DW_LNS_copy);
265 }
266
267 WasRelaxed = OldSize != Data.size();
268 return true;
269}
270
273 bool &WasRelaxed) const {
274 const MCExpr &AddrDelta = DF.getAddrDelta();
275 SmallVectorImpl<char> &Data = DF.getContents();
276 SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
277 size_t OldSize = Data.size();
278
279 int64_t Value;
280 if (AddrDelta.evaluateAsAbsolute(Value, Asm))
281 return false;
282 [[maybe_unused]] bool IsAbsolute =
283 AddrDelta.evaluateKnownAbsolute(Value, Asm);
284 assert(IsAbsolute && "CFA with invalid expression");
285
286 Data.clear();
287 Fixups.clear();
289
290 assert(Asm.getContext().getAsmInfo()->getMinInstAlignment() == 1 &&
291 "expected 1-byte alignment");
292 if (Value == 0) {
293 WasRelaxed = OldSize != Data.size();
294 return true;
295 }
296
297 auto AddFixups = [&Fixups, &AddrDelta](unsigned Offset,
298 std::pair<unsigned, unsigned> Fixup) {
299 const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
300 Fixups.push_back(
303 std::get<0>(Fixup))));
304 Fixups.push_back(
307 std::get<1>(Fixup))));
308 };
309
310 if (isUIntN(6, Value)) {
311 OS << uint8_t(dwarf::DW_CFA_advance_loc);
312 AddFixups(0, {ELF::R_RISCV_SET6, ELF::R_RISCV_SUB6});
313 } else if (isUInt<8>(Value)) {
314 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
315 support::endian::write<uint8_t>(OS, 0, llvm::endianness::little);
316 AddFixups(1, {ELF::R_RISCV_SET8, ELF::R_RISCV_SUB8});
317 } else if (isUInt<16>(Value)) {
318 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
319 support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
320 AddFixups(1, {ELF::R_RISCV_SET16, ELF::R_RISCV_SUB16});
321 } else if (isUInt<32>(Value)) {
322 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
323 support::endian::write<uint32_t>(OS, 0, llvm::endianness::little);
324 AddFixups(1, {ELF::R_RISCV_SET32, ELF::R_RISCV_SUB32});
325 } else {
326 llvm_unreachable("unsupported CFA encoding");
327 }
328
329 WasRelaxed = OldSize != Data.size();
330 return true;
331}
332
333std::pair<bool, bool> RISCVAsmBackend::relaxLEB128(const MCAssembler &Asm,
334 MCLEBFragment &LF,
335 int64_t &Value) const {
336 if (LF.isSigned())
337 return std::make_pair(false, false);
338 const MCExpr &Expr = LF.getValue();
339 if (ULEB128Reloc) {
340 LF.getFixups().push_back(
341 MCFixup::create(0, &Expr, FK_Data_leb128, Expr.getLoc()));
342 }
343 return std::make_pair(Expr.evaluateKnownAbsolute(Value, Asm), false);
344}
345
346// Given a compressed control flow instruction this function returns
347// the expanded instruction.
348unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
349 switch (Op) {
350 default:
351 return Op;
352 case RISCV::C_BEQZ:
353 return RISCV::BEQ;
354 case RISCV::C_BNEZ:
355 return RISCV::BNE;
356 case RISCV::C_J:
357 case RISCV::C_JAL: // fall through.
358 return RISCV::JAL;
359 case RISCV::BEQ:
360 return RISCV::PseudoLongBEQ;
361 case RISCV::BNE:
362 return RISCV::PseudoLongBNE;
363 case RISCV::BLT:
364 return RISCV::PseudoLongBLT;
365 case RISCV::BGE:
366 return RISCV::PseudoLongBGE;
367 case RISCV::BLTU:
368 return RISCV::PseudoLongBLTU;
369 case RISCV::BGEU:
370 return RISCV::PseudoLongBGEU;
371 }
372}
373
375 const MCSubtargetInfo &STI) const {
376 return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
377}
378
380 const MCSubtargetInfo *STI) const {
381 // We mostly follow binutils' convention here: align to even boundary with a
382 // 0-fill padding. We emit up to 1 2-byte nop, though we use c.nop if RVC is
383 // enabled or 0-fill otherwise. The remainder is now padded with 4-byte nops.
384
385 // Instructions always are at even addresses. We must be in a data area or
386 // be unaligned due to some other reason.
387 if (Count % 2) {
388 OS.write("\0", 1);
389 Count -= 1;
390 }
391
392 bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
393 STI->hasFeature(RISCV::FeatureStdExtZca);
394 // The canonical nop on RVC is c.nop.
395 if (Count % 4 == 2) {
396 OS.write(UseCompressedNop ? "\x01\0" : "\0\0", 2);
397 Count -= 2;
398 }
399
400 // The canonical nop on RISC-V is addi x0, x0, 0.
401 for (; Count >= 4; Count -= 4)
402 OS.write("\x13\0\0\0", 4);
403
404 return true;
405}
406
408 MCContext &Ctx) {
409 switch (Fixup.getTargetKind()) {
410 default:
411 llvm_unreachable("Unknown fixup kind!");
416 llvm_unreachable("Relocation should be unconditionally forced\n");
417 case FK_Data_1:
418 case FK_Data_2:
419 case FK_Data_4:
420 case FK_Data_8:
421 case FK_Data_leb128:
422 return Value;
427 return Value & 0xfff;
429 if (!isInt<12>(Value)) {
430 Ctx.reportError(Fixup.getLoc(),
431 "operand must be a constant 12-bit integer");
432 }
433 return Value & 0xfff;
437 return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
441 // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
442 return ((Value + 0x800) >> 12) & 0xfffff;
444 if (!isInt<21>(Value))
445 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
446 if (Value & 0x1)
447 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
448 // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
449 unsigned Sbit = (Value >> 20) & 0x1;
450 unsigned Hi8 = (Value >> 12) & 0xff;
451 unsigned Mid1 = (Value >> 11) & 0x1;
452 unsigned Lo10 = (Value >> 1) & 0x3ff;
453 // Inst{31} = Sbit;
454 // Inst{30-21} = Lo10;
455 // Inst{20} = Mid1;
456 // Inst{19-12} = Hi8;
457 Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
458 return Value;
459 }
461 if (!isInt<13>(Value))
462 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
463 if (Value & 0x1)
464 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
465 // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
466 // Value.
467 unsigned Sbit = (Value >> 12) & 0x1;
468 unsigned Hi1 = (Value >> 11) & 0x1;
469 unsigned Mid6 = (Value >> 5) & 0x3f;
470 unsigned Lo4 = (Value >> 1) & 0xf;
471 // Inst{31} = Sbit;
472 // Inst{30-25} = Mid6;
473 // Inst{11-8} = Lo4;
474 // Inst{7} = Hi1;
475 Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
476 return Value;
477 }
480 // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
481 // we need to add 0x800ULL before extract upper bits to reflect the
482 // effect of the sign extension.
483 uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
484 uint64_t LowerImm = Value & 0xfffULL;
485 return UpperImm | ((LowerImm << 20) << 32);
486 }
488 if (!isInt<12>(Value))
489 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
490 // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
491 unsigned Bit11 = (Value >> 11) & 0x1;
492 unsigned Bit4 = (Value >> 4) & 0x1;
493 unsigned Bit9_8 = (Value >> 8) & 0x3;
494 unsigned Bit10 = (Value >> 10) & 0x1;
495 unsigned Bit6 = (Value >> 6) & 0x1;
496 unsigned Bit7 = (Value >> 7) & 0x1;
497 unsigned Bit3_1 = (Value >> 1) & 0x7;
498 unsigned Bit5 = (Value >> 5) & 0x1;
499 Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
500 (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
501 return Value;
502 }
504 if (!isInt<9>(Value))
505 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
506 // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
507 unsigned Bit8 = (Value >> 8) & 0x1;
508 unsigned Bit7_6 = (Value >> 6) & 0x3;
509 unsigned Bit5 = (Value >> 5) & 0x1;
510 unsigned Bit4_3 = (Value >> 3) & 0x3;
511 unsigned Bit2_1 = (Value >> 1) & 0x3;
512 Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
513 (Bit5 << 2);
514 return Value;
515 }
516
517 }
518}
519
521 const MCFixup &Fixup,
522 const MCFragment *DF,
523 const MCValue &Target,
524 const MCSubtargetInfo *STI,
525 uint64_t &Value, bool &WasForced) {
526 const MCFixup *AUIPCFixup;
527 const MCFragment *AUIPCDF;
528 MCValue AUIPCTarget;
529 switch (Fixup.getTargetKind()) {
530 default:
531 llvm_unreachable("Unexpected fixup kind!");
534 AUIPCFixup = &Fixup;
535 AUIPCDF = DF;
536 AUIPCTarget = Target;
537 break;
540 AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
541 if (!AUIPCFixup) {
542 Asm.getContext().reportError(Fixup.getLoc(),
543 "could not find corresponding %pcrel_hi");
544 return true;
545 }
546
547 // MCAssembler::evaluateFixup will emit an error for this case when it sees
548 // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
549 const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
550 if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Asm, AUIPCFixup))
551 return true;
552 break;
553 }
554 }
555
556 if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
557 return false;
558
559 const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
560 const MCSymbolELF &SA = cast<MCSymbolELF>(A->getSymbol());
561 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
562 return false;
563
564 bool IsResolved = &SA.getSection() == AUIPCDF->getParent() &&
565 SA.getBinding() == ELF::STB_LOCAL &&
567 if (!IsResolved)
568 return false;
569
570 Value = Asm.getSymbolOffset(SA) + AUIPCTarget.getConstant();
571 Value -= Asm.getFragmentOffset(*AUIPCDF) + AUIPCFixup->getOffset();
572
573 if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget, STI)) {
574 WasForced = true;
575 return false;
576 }
577
578 return true;
579}
580
582 const MCFragment &F,
583 const MCFixup &Fixup,
584 const MCValue &Target,
585 uint64_t &FixedValue) const {
586 uint64_t FixedValueA, FixedValueB;
587 unsigned TA = 0, TB = 0;
588 switch (Fixup.getKind()) {
589 case llvm::FK_Data_1:
590 TA = ELF::R_RISCV_ADD8;
591 TB = ELF::R_RISCV_SUB8;
592 break;
593 case llvm::FK_Data_2:
594 TA = ELF::R_RISCV_ADD16;
595 TB = ELF::R_RISCV_SUB16;
596 break;
597 case llvm::FK_Data_4:
598 TA = ELF::R_RISCV_ADD32;
599 TB = ELF::R_RISCV_SUB32;
600 break;
601 case llvm::FK_Data_8:
602 TA = ELF::R_RISCV_ADD64;
603 TB = ELF::R_RISCV_SUB64;
604 break;
606 TA = ELF::R_RISCV_SET_ULEB128;
607 TB = ELF::R_RISCV_SUB_ULEB128;
608 break;
609 default:
610 llvm_unreachable("unsupported fixup size");
611 }
612 MCValue A = MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
613 MCValue B = MCValue::get(Target.getSymB());
614 auto FA = MCFixup::create(
615 Fixup.getOffset(), nullptr,
616 static_cast<MCFixupKind>(FirstLiteralRelocationKind + TA));
617 auto FB = MCFixup::create(
618 Fixup.getOffset(), nullptr,
619 static_cast<MCFixupKind>(FirstLiteralRelocationKind + TB));
620 auto &Assembler = const_cast<MCAssembler &>(Asm);
621 Asm.getWriter().recordRelocation(Assembler, &F, FA, A, FixedValueA);
622 Asm.getWriter().recordRelocation(Assembler, &F, FB, B, FixedValueB);
623 FixedValue = FixedValueA - FixedValueB;
624 return true;
625}
626
628 const MCValue &Target,
630 bool IsResolved,
631 const MCSubtargetInfo *STI) const {
632 MCFixupKind Kind = Fixup.getKind();
633 if (Kind >= FirstLiteralRelocationKind)
634 return;
635 MCContext &Ctx = Asm.getContext();
637 if (!Value)
638 return; // Doesn't change encoding.
639 // Apply any target-specific value adjustments.
641
642 // Shift the value into position.
643 Value <<= Info.TargetOffset;
644
645 unsigned Offset = Fixup.getOffset();
646 unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
647
648 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
649
650 // For each byte of the fragment that the fixup touches, mask in the
651 // bits from the fixup value.
652 for (unsigned i = 0; i != NumBytes; ++i) {
653 Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
654 }
655}
656
657// Linker relaxation may change code size. We have to insert Nops
658// for .align directive when linker relaxation enabled. So then Linker
659// could satisfy alignment by removing Nops.
660// The function return the total Nops Size we need to insert.
662 const MCAlignFragment &AF, unsigned &Size) {
663 // Calculate Nops Size only when linker relaxation enabled.
664 const MCSubtargetInfo *STI = AF.getSubtargetInfo();
665 if (!STI->hasFeature(RISCV::FeatureRelax))
666 return false;
667
668 bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
669 STI->hasFeature(RISCV::FeatureStdExtZca);
670 unsigned MinNopLen = UseCompressedNop ? 2 : 4;
671
672 if (AF.getAlignment() <= MinNopLen) {
673 return false;
674 } else {
675 Size = AF.getAlignment().value() - MinNopLen;
676 return true;
677 }
678}
679
680// We need to insert R_RISCV_ALIGN relocation type to indicate the
681// position of Nops and the total bytes of the Nops have been inserted
682// when linker relaxation enabled.
683// The function insert fixup_riscv_align fixup which eventually will
684// transfer to R_RISCV_ALIGN relocation type.
686 MCAlignFragment &AF) {
687 // Insert the fixup only when linker relaxation enabled.
688 const MCSubtargetInfo *STI = AF.getSubtargetInfo();
689 if (!STI->hasFeature(RISCV::FeatureRelax))
690 return false;
691
692 // Calculate total Nops we need to insert. If there are none to insert
693 // then simply return.
694 unsigned Count;
695 if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
696 return false;
697
698 MCContext &Ctx = Asm.getContext();
699 const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
700 // Create fixup_riscv_align fixup.
701 MCFixup Fixup =
703
704 uint64_t FixedValue = 0;
705 MCValue NopBytes = MCValue::get(Count);
706
707 Asm.getWriter().recordRelocation(Asm, &AF, Fixup, NopBytes, FixedValue);
708
709 return true;
710}
711
712std::unique_ptr<MCObjectTargetWriter>
714 return createRISCVELFObjectWriter(OSABI, Is64Bit);
715}
716
718 const MCSubtargetInfo &STI,
719 const MCRegisterInfo &MRI,
720 const MCTargetOptions &Options) {
721 const Triple &TT = STI.getTargetTriple();
722 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
723 return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
724}
unsigned const MachineRegisterInfo * MRI
static uint64_t adjustFixupValue(const MCFixup &Fixup, const MCValue &Target, uint64_t Value, MCContext &Ctx, const Triple &TheTriple, bool IsResolved)
#define Success
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
std::string Name
uint64_t Size
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
PowerPC TLS Dynamic Call Fixup
static cl::opt< bool > RelaxBranches("riscv-asm-relax-branches", cl::init(true), cl::Hidden)
static cl::opt< bool > ULEB128Reloc("riscv-uleb128-reloc", cl::init(true), cl::Hidden, cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This class represents an Operation in the Expression.
Align getAlignment() const
Definition: MCFragment.h:277
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:291
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:42
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
Binary assembler expressions.
Definition: MCExpr.h:493
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:640
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:643
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:222
Context object for machine code objects.
Definition: MCContext.h:83
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1072
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:200
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
bool evaluateKnownAbsolute(int64_t &Res, const MCAssembler &Asm) const
Aggressive variant of evaluateAsRelocatable when relocations are unavailable (e.g.
Definition: MCExpr.cpp:596
bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:819
SMLoc getLoc() const
Definition: MCExpr.h:79
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
const MCExpr * getValue() const
Definition: MCFixup.h:105
uint32_t getOffset() const
Definition: MCFixup.h:102
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:87
MCSection * getParent() const
Definition: MCFragment.h:99
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:185
unsigned getOpcode() const
Definition: MCInst.h:199
void addOperand(const MCOperand Op)
Definition: MCInst.h:211
void setOpcode(unsigned Op)
Definition: MCInst.h:198
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:207
bool isSigned() const
Definition: MCFragment.h:397
const MCExpr & getValue() const
Definition: MCFragment.h:394
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:228
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
unsigned getType() const
unsigned getBinding() const
Definition: MCSymbolELF.cpp:66
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:259
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:269
This represents an "assembler immediate".
Definition: MCValue.h:36
int64_t getConstant() const
Definition: MCValue.h:43
static MCValue get(const MCSymbolRefExpr *SymA, const MCSymbolRefExpr *SymB=nullptr, int64_t Val=0, uint32_t RefKind=0)
Definition: MCValue.h:59
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:44
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
bool relaxDwarfLineAddr(const MCAssembler &Asm, MCDwarfLineAddrFragment &DF, bool &WasRelaxed) const override
std::pair< bool, bool > relaxLEB128(const MCAssembler &Asm, MCLEBFragment &LF, int64_t &Value) const override
std::unique_ptr< MCObjectTargetWriter > createObjectTargetWriter() const override
bool relaxDwarfCFA(const MCAssembler &Asm, MCDwarfCallFrameFragment &DF, bool &WasRelaxed) const override
void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target, MutableArrayRef< char > Data, uint64_t Value, bool IsResolved, const MCSubtargetInfo *STI) const override
Apply the Value for given Fixup into the provided data fragment, at the offset specified by the fixup...
void relaxInstruction(MCInst &Inst, const MCSubtargetInfo &STI) const override
Relax the instruction in the given fragment to the next wider instruction.
bool evaluateTargetFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, const MCSubtargetInfo *STI, uint64_t &Value, bool &WasForced) override
const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const override
Get information on a fixup kind.
bool fixupNeedsRelaxationAdvanced(const MCAssembler &Asm, const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const bool WasForced) const override
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
bool shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment &AF, unsigned &Size) override
Hook to check if extra nop bytes must be inserted for alignment directive.
bool mayNeedRelaxation(const MCInst &Inst, const MCSubtargetInfo &STI) const override
Check whether the given instruction may need relaxation.
bool writeNopData(raw_ostream &OS, uint64_t Count, const MCSubtargetInfo *STI) const override
Write an (optimal) nop sequence of Count bytes to the given output.
unsigned getRelaxedOpcode(unsigned Op) const
bool handleAddSubRelocations(const MCAssembler &Asm, const MCFragment &F, const MCFixup &Fixup, const MCValue &Target, uint64_t &FixedValue) const override
bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, MCAlignFragment &AF) override
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target, const MCSubtargetInfo *STI) override
Hook to check if a relocation is needed for some target specific reason.
unsigned getNumFixupKinds() const override
Get the number of target specific fixup kinds.
std::optional< MCFixupKind > getFixupKind(StringRef Name) const override
Map a relocation name used in .reloc to a fixup kind.
Represents a location in source code.
Definition: SMLoc.h:23
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:735
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define INT64_MAX
Definition: DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ STB_LOCAL
Definition: ELF.h:1349
@ STT_GNU_IFUNC
Definition: ELF.h:1368
bool uncompress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
static std::pair< MCFixupKind, MCFixupKind > getRelocPairForSize(unsigned Size)
@ fixup_riscv_tprel_lo12_s
@ fixup_riscv_tls_got_hi20
@ fixup_riscv_pcrel_lo12_i
@ fixup_riscv_pcrel_lo12_s
@ fixup_riscv_tprel_lo12_i
@ fixup_riscv_tlsdesc_load_lo12
@ fixup_riscv_tlsdesc_hi20
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::unique_ptr< MCObjectTargetWriter > createRISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
@ Offset
Definition: DWP.cpp:480
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:255
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:21
@ FirstTargetFixupKind
Definition: MCFixup.h:45
@ FirstLiteralRelocationKind
The range [FirstLiteralRelocationKind, MaxTargetFixupKind) is used for relocations coming from ....
Definition: MCFixup.h:50
@ FK_Data_8
A eight-byte fixup.
Definition: MCFixup.h:26
@ FK_Data_1
A one-byte fixup.
Definition: MCFixup.h:23
@ FK_Data_4
A four-byte fixup.
Definition: MCFixup.h:25
@ FK_NONE
A no-op fixup.
Definition: MCFixup.h:22
@ FK_Data_leb128
A leb128 fixup.
Definition: MCFixup.h:27
@ FK_Data_2
A two-byte fixup.
Definition: MCFixup.h:24
MCAsmBackend * createRISCVAsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
DWARFExpression::Operation Op
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
Target independent information on a fixup kind.
@ FKF_IsTarget
Should this fixup be evaluated in a target dependent manner?
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...