LLVM 19.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/MCAsmLayout.h"
14#include "llvm/MC/MCAssembler.h"
15#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCExpr.h"
20#include "llvm/MC/MCSymbol.h"
21#include "llvm/MC/MCValue.h"
23#include "llvm/Support/Endian.h"
26#include "llvm/Support/LEB128.h"
28
29using namespace llvm;
30
31static cl::opt<bool> RelaxBranches("riscv-asm-relax-branches", cl::init(true),
33// Temporary workaround for old linkers that do not support ULEB128 relocations,
34// which are abused by DWARF v5 DW_LLE_offset_pair/DW_RLE_offset_pair
35// implemented in Clang/LLVM.
37 "riscv-uleb128-reloc", cl::init(true), cl::Hidden,
38 cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"));
39
40std::optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
42 unsigned Type;
44#define ELF_RELOC(X, Y) .Case(#X, Y)
45#include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
46#undef ELF_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 bool Resolved,
145 const MCRelaxableFragment *DF,
146 const MCAsmLayout &Layout,
147 const bool WasForced) const {
148 if (!RelaxBranches)
149 return false;
150
151 int64_t Offset = int64_t(Value);
152 unsigned Kind = Fixup.getTargetKind();
153
154 // Return true if the symbol is actually unresolved.
155 // Resolved could be always false when shouldForceRelocation return true.
156 // We use !WasForced to indicate that the symbol is unresolved and not forced
157 // by shouldForceRelocation.
158 if (!Resolved && !WasForced)
159 return true;
160
161 switch (Kind) {
162 default:
163 return false;
165 // For compressed branch instructions the immediate must be
166 // in the range [-256, 254].
167 return Offset > 254 || Offset < -256;
169 // For compressed jump instructions the immediate must be
170 // in the range [-2048, 2046].
171 return Offset > 2046 || Offset < -2048;
173 // For conditional branch instructions the immediate must be
174 // in the range [-4096, 4095].
175 return !isInt<13>(Offset);
176 }
177}
178
180 const MCSubtargetInfo &STI) const {
181 MCInst Res;
182 switch (Inst.getOpcode()) {
183 default:
184 llvm_unreachable("Opcode not expected!");
185 case RISCV::C_BEQZ:
186 case RISCV::C_BNEZ:
187 case RISCV::C_J:
188 case RISCV::C_JAL: {
189 [[maybe_unused]] bool Success = RISCVRVC::uncompress(Res, Inst, STI);
190 assert(Success && "Can't uncompress instruction");
191 break;
192 }
193 case RISCV::BEQ:
194 case RISCV::BNE:
195 case RISCV::BLT:
196 case RISCV::BGE:
197 case RISCV::BLTU:
198 case RISCV::BGEU:
200 Res.addOperand(Inst.getOperand(0));
201 Res.addOperand(Inst.getOperand(1));
202 Res.addOperand(Inst.getOperand(2));
203 break;
204 }
205 Inst = std::move(Res);
206}
207
209 MCAsmLayout &Layout,
210 bool &WasRelaxed) const {
211 MCContext &C = Layout.getAssembler().getContext();
212
213 int64_t LineDelta = DF.getLineDelta();
214 const MCExpr &AddrDelta = DF.getAddrDelta();
215 SmallVectorImpl<char> &Data = DF.getContents();
216 SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
217 size_t OldSize = Data.size();
218
219 int64_t Value;
220 [[maybe_unused]] bool IsAbsolute =
221 AddrDelta.evaluateKnownAbsolute(Value, Layout);
222 assert(IsAbsolute && "CFA with invalid expression");
223
224 Data.clear();
225 Fixups.clear();
227
228 // INT64_MAX is a signal that this is actually a DW_LNE_end_sequence.
229 if (LineDelta != INT64_MAX) {
230 OS << uint8_t(dwarf::DW_LNS_advance_line);
231 encodeSLEB128(LineDelta, OS);
232 }
233
234 unsigned Offset;
235 std::pair<MCFixupKind, MCFixupKind> Fixup;
236
237 // According to the DWARF specification, the `DW_LNS_fixed_advance_pc` opcode
238 // takes a single unsigned half (unencoded) operand. The maximum encodable
239 // value is therefore 65535. Set a conservative upper bound for relaxation.
240 if (Value > 60000) {
241 unsigned PtrSize = C.getAsmInfo()->getCodePointerSize();
242
243 OS << uint8_t(dwarf::DW_LNS_extended_op);
244 encodeULEB128(PtrSize + 1, OS);
245
246 OS << uint8_t(dwarf::DW_LNE_set_address);
247 Offset = OS.tell();
248 assert((PtrSize == 4 || PtrSize == 8) && "Unexpected pointer size");
250 OS.write_zeros(PtrSize);
251 } else {
252 OS << uint8_t(dwarf::DW_LNS_fixed_advance_pc);
253 Offset = OS.tell();
255 support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
256 }
257
258 const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
259 Fixups.push_back(MCFixup::create(Offset, MBE.getLHS(), std::get<0>(Fixup)));
260 Fixups.push_back(MCFixup::create(Offset, MBE.getRHS(), std::get<1>(Fixup)));
261
262 if (LineDelta == INT64_MAX) {
263 OS << uint8_t(dwarf::DW_LNS_extended_op);
264 OS << uint8_t(1);
265 OS << uint8_t(dwarf::DW_LNE_end_sequence);
266 } else {
267 OS << uint8_t(dwarf::DW_LNS_copy);
268 }
269
270 WasRelaxed = OldSize != Data.size();
271 return true;
272}
273
275 MCAsmLayout &Layout,
276 bool &WasRelaxed) const {
277 const MCExpr &AddrDelta = DF.getAddrDelta();
278 SmallVectorImpl<char> &Data = DF.getContents();
279 SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
280 size_t OldSize = Data.size();
281
282 int64_t Value;
283 if (AddrDelta.evaluateAsAbsolute(Value, Layout.getAssembler()))
284 return false;
285 [[maybe_unused]] bool IsAbsolute =
286 AddrDelta.evaluateKnownAbsolute(Value, Layout);
287 assert(IsAbsolute && "CFA with invalid expression");
288
289 Data.clear();
290 Fixups.clear();
292
293 assert(
295 1 &&
296 "expected 1-byte alignment");
297 if (Value == 0) {
298 WasRelaxed = OldSize != Data.size();
299 return true;
300 }
301
302 auto AddFixups = [&Fixups, &AddrDelta](unsigned Offset,
303 std::pair<unsigned, unsigned> Fixup) {
304 const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
305 Fixups.push_back(
308 std::get<0>(Fixup))));
309 Fixups.push_back(
312 std::get<1>(Fixup))));
313 };
314
315 if (isUIntN(6, Value)) {
316 OS << uint8_t(dwarf::DW_CFA_advance_loc);
317 AddFixups(0, {ELF::R_RISCV_SET6, ELF::R_RISCV_SUB6});
318 } else if (isUInt<8>(Value)) {
319 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
320 support::endian::write<uint8_t>(OS, 0, llvm::endianness::little);
321 AddFixups(1, {ELF::R_RISCV_SET8, ELF::R_RISCV_SUB8});
322 } else if (isUInt<16>(Value)) {
323 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
324 support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
325 AddFixups(1, {ELF::R_RISCV_SET16, ELF::R_RISCV_SUB16});
326 } else if (isUInt<32>(Value)) {
327 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
328 support::endian::write<uint32_t>(OS, 0, llvm::endianness::little);
329 AddFixups(1, {ELF::R_RISCV_SET32, ELF::R_RISCV_SUB32});
330 } else {
331 llvm_unreachable("unsupported CFA encoding");
332 }
333
334 WasRelaxed = OldSize != Data.size();
335 return true;
336}
337
339 MCAsmLayout &Layout,
340 int64_t &Value) const {
341 if (LF.isSigned())
342 return std::make_pair(false, false);
343 const MCExpr &Expr = LF.getValue();
344 if (ULEB128Reloc) {
345 LF.getFixups().push_back(
346 MCFixup::create(0, &Expr, FK_Data_leb128, Expr.getLoc()));
347 }
348 return std::make_pair(Expr.evaluateKnownAbsolute(Value, Layout), false);
349}
350
351// Given a compressed control flow instruction this function returns
352// the expanded instruction.
353unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
354 switch (Op) {
355 default:
356 return Op;
357 case RISCV::C_BEQZ:
358 return RISCV::BEQ;
359 case RISCV::C_BNEZ:
360 return RISCV::BNE;
361 case RISCV::C_J:
362 case RISCV::C_JAL: // fall through.
363 return RISCV::JAL;
364 case RISCV::BEQ:
365 return RISCV::PseudoLongBEQ;
366 case RISCV::BNE:
367 return RISCV::PseudoLongBNE;
368 case RISCV::BLT:
369 return RISCV::PseudoLongBLT;
370 case RISCV::BGE:
371 return RISCV::PseudoLongBGE;
372 case RISCV::BLTU:
373 return RISCV::PseudoLongBLTU;
374 case RISCV::BGEU:
375 return RISCV::PseudoLongBGEU;
376 }
377}
378
380 const MCSubtargetInfo &STI) const {
381 return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
382}
383
385 const MCSubtargetInfo *STI) const {
386 // We mostly follow binutils' convention here: align to even boundary with a
387 // 0-fill padding. We emit up to 1 2-byte nop, though we use c.nop if RVC is
388 // enabled or 0-fill otherwise. The remainder is now padded with 4-byte nops.
389
390 // Instructions always are at even addresses. We must be in a data area or
391 // be unaligned due to some other reason.
392 if (Count % 2) {
393 OS.write("\0", 1);
394 Count -= 1;
395 }
396
397 bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
398 STI->hasFeature(RISCV::FeatureStdExtZca);
399 // The canonical nop on RVC is c.nop.
400 if (Count % 4 == 2) {
401 OS.write(UseCompressedNop ? "\x01\0" : "\0\0", 2);
402 Count -= 2;
403 }
404
405 // The canonical nop on RISC-V is addi x0, x0, 0.
406 for (; Count >= 4; Count -= 4)
407 OS.write("\x13\0\0\0", 4);
408
409 return true;
410}
411
413 MCContext &Ctx) {
414 switch (Fixup.getTargetKind()) {
415 default:
416 llvm_unreachable("Unknown fixup kind!");
421 llvm_unreachable("Relocation should be unconditionally forced\n");
422 case FK_Data_1:
423 case FK_Data_2:
424 case FK_Data_4:
425 case FK_Data_8:
426 case FK_Data_leb128:
427 return Value;
432 return Value & 0xfff;
434 if (!isInt<12>(Value)) {
435 Ctx.reportError(Fixup.getLoc(),
436 "operand must be a constant 12-bit integer");
437 }
438 return Value & 0xfff;
442 return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
446 // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
447 return ((Value + 0x800) >> 12) & 0xfffff;
449 if (!isInt<21>(Value))
450 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
451 if (Value & 0x1)
452 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
453 // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
454 unsigned Sbit = (Value >> 20) & 0x1;
455 unsigned Hi8 = (Value >> 12) & 0xff;
456 unsigned Mid1 = (Value >> 11) & 0x1;
457 unsigned Lo10 = (Value >> 1) & 0x3ff;
458 // Inst{31} = Sbit;
459 // Inst{30-21} = Lo10;
460 // Inst{20} = Mid1;
461 // Inst{19-12} = Hi8;
462 Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
463 return Value;
464 }
466 if (!isInt<13>(Value))
467 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
468 if (Value & 0x1)
469 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
470 // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
471 // Value.
472 unsigned Sbit = (Value >> 12) & 0x1;
473 unsigned Hi1 = (Value >> 11) & 0x1;
474 unsigned Mid6 = (Value >> 5) & 0x3f;
475 unsigned Lo4 = (Value >> 1) & 0xf;
476 // Inst{31} = Sbit;
477 // Inst{30-25} = Mid6;
478 // Inst{11-8} = Lo4;
479 // Inst{7} = Hi1;
480 Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
481 return Value;
482 }
485 // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
486 // we need to add 0x800ULL before extract upper bits to reflect the
487 // effect of the sign extension.
488 uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
489 uint64_t LowerImm = Value & 0xfffULL;
490 return UpperImm | ((LowerImm << 20) << 32);
491 }
493 if (!isInt<12>(Value))
494 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
495 // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
496 unsigned Bit11 = (Value >> 11) & 0x1;
497 unsigned Bit4 = (Value >> 4) & 0x1;
498 unsigned Bit9_8 = (Value >> 8) & 0x3;
499 unsigned Bit10 = (Value >> 10) & 0x1;
500 unsigned Bit6 = (Value >> 6) & 0x1;
501 unsigned Bit7 = (Value >> 7) & 0x1;
502 unsigned Bit3_1 = (Value >> 1) & 0x7;
503 unsigned Bit5 = (Value >> 5) & 0x1;
504 Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
505 (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
506 return Value;
507 }
509 if (!isInt<9>(Value))
510 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
511 // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
512 unsigned Bit8 = (Value >> 8) & 0x1;
513 unsigned Bit7_6 = (Value >> 6) & 0x3;
514 unsigned Bit5 = (Value >> 5) & 0x1;
515 unsigned Bit4_3 = (Value >> 3) & 0x3;
516 unsigned Bit2_1 = (Value >> 1) & 0x3;
517 Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
518 (Bit5 << 2);
519 return Value;
520 }
521
522 }
523}
524
526 const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
527 const MCFragment *DF, const MCValue &Target, const MCSubtargetInfo *STI,
528 uint64_t &Value, bool &WasForced) {
529 const MCFixup *AUIPCFixup;
530 const MCFragment *AUIPCDF;
531 MCValue AUIPCTarget;
532 switch (Fixup.getTargetKind()) {
533 default:
534 llvm_unreachable("Unexpected fixup kind!");
537 AUIPCFixup = &Fixup;
538 AUIPCDF = DF;
539 AUIPCTarget = Target;
540 break;
543 AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
544 if (!AUIPCFixup) {
545 Asm.getContext().reportError(Fixup.getLoc(),
546 "could not find corresponding %pcrel_hi");
547 return true;
548 }
549
550 // MCAssembler::evaluateFixup will emit an error for this case when it sees
551 // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
552 const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
553 if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Layout, AUIPCFixup))
554 return true;
555 break;
556 }
557 }
558
559 if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
560 return false;
561
562 const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
563 const MCSymbol &SA = A->getSymbol();
564 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
565 return false;
566
567 auto *Writer = Asm.getWriterPtr();
568 if (!Writer)
569 return false;
570
571 bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
572 Asm, SA, *AUIPCDF, false, true);
573 if (!IsResolved)
574 return false;
575
576 Value = Layout.getSymbolOffset(SA) + AUIPCTarget.getConstant();
577 Value -= Layout.getFragmentOffset(AUIPCDF) + AUIPCFixup->getOffset();
578
579 if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget, STI)) {
580 WasForced = true;
581 return false;
582 }
583
584 return true;
585}
586
588 const MCFragment &F,
589 const MCFixup &Fixup,
590 const MCValue &Target,
591 uint64_t &FixedValue) const {
592 uint64_t FixedValueA, FixedValueB;
593 unsigned TA = 0, TB = 0;
594 switch (Fixup.getKind()) {
595 case llvm::FK_Data_1:
596 TA = ELF::R_RISCV_ADD8;
597 TB = ELF::R_RISCV_SUB8;
598 break;
599 case llvm::FK_Data_2:
600 TA = ELF::R_RISCV_ADD16;
601 TB = ELF::R_RISCV_SUB16;
602 break;
603 case llvm::FK_Data_4:
604 TA = ELF::R_RISCV_ADD32;
605 TB = ELF::R_RISCV_SUB32;
606 break;
607 case llvm::FK_Data_8:
608 TA = ELF::R_RISCV_ADD64;
609 TB = ELF::R_RISCV_SUB64;
610 break;
612 TA = ELF::R_RISCV_SET_ULEB128;
613 TB = ELF::R_RISCV_SUB_ULEB128;
614 break;
615 default:
616 llvm_unreachable("unsupported fixup size");
617 }
618 MCValue A = MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
619 MCValue B = MCValue::get(Target.getSymB());
620 auto FA = MCFixup::create(
621 Fixup.getOffset(), nullptr,
622 static_cast<MCFixupKind>(FirstLiteralRelocationKind + TA));
623 auto FB = MCFixup::create(
624 Fixup.getOffset(), nullptr,
625 static_cast<MCFixupKind>(FirstLiteralRelocationKind + TB));
626 auto &Asm = Layout.getAssembler();
627 Asm.getWriter().recordRelocation(Asm, Layout, &F, FA, A, FixedValueA);
628 Asm.getWriter().recordRelocation(Asm, Layout, &F, FB, B, FixedValueB);
629 FixedValue = FixedValueA - FixedValueB;
630 return true;
631}
632
634 const MCValue &Target,
636 bool IsResolved,
637 const MCSubtargetInfo *STI) const {
638 MCFixupKind Kind = Fixup.getKind();
639 if (Kind >= FirstLiteralRelocationKind)
640 return;
641 MCContext &Ctx = Asm.getContext();
643 if (!Value)
644 return; // Doesn't change encoding.
645 // Apply any target-specific value adjustments.
647
648 // Shift the value into position.
649 Value <<= Info.TargetOffset;
650
651 unsigned Offset = Fixup.getOffset();
652 unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
653
654 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
655
656 // For each byte of the fragment that the fixup touches, mask in the
657 // bits from the fixup value.
658 for (unsigned i = 0; i != NumBytes; ++i) {
659 Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
660 }
661}
662
663// Linker relaxation may change code size. We have to insert Nops
664// for .align directive when linker relaxation enabled. So then Linker
665// could satisfy alignment by removing Nops.
666// The function return the total Nops Size we need to insert.
668 const MCAlignFragment &AF, unsigned &Size) {
669 // Calculate Nops Size only when linker relaxation enabled.
670 const MCSubtargetInfo *STI = AF.getSubtargetInfo();
671 if (!STI->hasFeature(RISCV::FeatureRelax))
672 return false;
673
674 bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
675 STI->hasFeature(RISCV::FeatureStdExtZca);
676 unsigned MinNopLen = UseCompressedNop ? 2 : 4;
677
678 if (AF.getAlignment() <= MinNopLen) {
679 return false;
680 } else {
681 Size = AF.getAlignment().value() - MinNopLen;
682 return true;
683 }
684}
685
686// We need to insert R_RISCV_ALIGN relocation type to indicate the
687// position of Nops and the total bytes of the Nops have been inserted
688// when linker relaxation enabled.
689// The function insert fixup_riscv_align fixup which eventually will
690// transfer to R_RISCV_ALIGN relocation type.
692 const MCAsmLayout &Layout,
693 MCAlignFragment &AF) {
694 // Insert the fixup only when linker relaxation enabled.
695 const MCSubtargetInfo *STI = AF.getSubtargetInfo();
696 if (!STI->hasFeature(RISCV::FeatureRelax))
697 return false;
698
699 // Calculate total Nops we need to insert. If there are none to insert
700 // then simply return.
701 unsigned Count;
702 if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
703 return false;
704
705 MCContext &Ctx = Asm.getContext();
706 const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
707 // Create fixup_riscv_align fixup.
708 MCFixup Fixup =
710
711 uint64_t FixedValue = 0;
712 MCValue NopBytes = MCValue::get(Count);
713
714 Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
715 FixedValue);
716
717 return true;
718}
719
720std::unique_ptr<MCObjectTargetWriter>
722 return createRISCVELFObjectWriter(OSABI, Is64Bit);
723}
724
726 const MCSubtargetInfo &STI,
727 const MCRegisterInfo &MRI,
728 const MCTargetOptions &Options) {
729 const Triple &TT = STI.getTargetTriple();
730 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
731 return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
732}
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:326
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:340
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:43
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
unsigned getMinInstAlignment() const
Definition: MCAsmInfo.h:648
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:28
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
Definition: MCFragment.cpp:152
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
Definition: MCFragment.cpp:96
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:50
MCContext & getContext() const
Definition: MCAssembler.h:326
Binary assembler expressions.
Definition: MCExpr.h:490
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:637
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:640
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:76
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:446
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1064
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:223
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const
Definition: MCExpr.cpp:568
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:810
SMLoc getLoc() const
Definition: MCExpr.h:82
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
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
unsigned getOpcode() const
Definition: MCInst.h:198
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
void setOpcode(unsigned Op)
Definition: MCInst.h:197
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
bool isSigned() const
Definition: MCFragment.h:448
const MCExpr & getValue() const
Definition: MCFragment.h:445
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:274
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:259
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:307
std::unique_ptr< MCObjectTargetWriter > createObjectTargetWriter() 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.
std::pair< bool, bool > relaxLEB128(MCLEBFragment &LF, MCAsmLayout &Layout, int64_t &Value) const override
bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, const MCAsmLayout &Layout, MCAlignFragment &AF) override
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
bool relaxDwarfLineAddr(MCDwarfLineAddrFragment &DF, MCAsmLayout &Layout, bool &WasRelaxed) const override
bool relaxDwarfCFA(MCDwarfCallFrameFragment &DF, MCAsmLayout &Layout, bool &WasRelaxed) const override
const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const override
Get information on a fixup kind.
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.
bool handleAddSubRelocations(const MCAsmLayout &Layout, const MCFragment &F, const MCFixup &Fixup, const MCValue &Target, uint64_t &FixedValue) const override
unsigned getRelaxedOpcode(unsigned Op) const
bool evaluateTargetFixup(const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, const MCSubtargetInfo *STI, uint64_t &Value, bool &WasForced) override
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.
bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout, const bool WasForced) const override
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
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:586
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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:703
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:150
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:690
#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
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:450
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:456
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:228
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...