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