25#define DEBUG_TYPE "jitlink"
33class ELFJITLinker_loongarch :
public JITLinker<ELFJITLinker_loongarch> {
34 friend class JITLinker<ELFJITLinker_loongarch>;
37 ELFJITLinker_loongarch(std::unique_ptr<JITLinkContext> Ctx,
38 std::unique_ptr<LinkGraph>
G,
40 :
JITLinker(std::move(Ctx), std::move(
G), std::move(PassConfig)) {}
47 char *BlockWorkingMem =
B.getAlreadyMutableContent().data();
48 char *FixupPtr = BlockWorkingMem +
E.getOffset();
49 uint64_t FixupAddress = (
B.getAddress() +
E.getOffset()).getValue();
50 uint64_t TargetAddress =
E.getTarget().getAddress().getValue();
51 int64_t Addend =
E.getAddend();
53 switch (
E.getKind()) {
55 *(ulittle64_t *)FixupPtr = TargetAddress + Addend;
59 if (
Value > std::numeric_limits<uint32_t>::max())
61 *(ulittle32_t *)FixupPtr =
Value;
65 int64_t
Value = TargetAddress - FixupAddress + Addend;
73 uint32_t RawInstr = *(little32_t *)FixupPtr;
76 *(little32_t *)FixupPtr = RawInstr | Imm15_0;
80 int64_t
Value = TargetAddress - FixupAddress + Addend;
88 uint32_t RawInstr = *(little32_t *)FixupPtr;
92 *(little32_t *)FixupPtr = RawInstr | Imm15_0 | Imm20_16;
96 int64_t
Value = TargetAddress - FixupAddress + Addend;
104 uint32_t RawInstr = *(little32_t *)FixupPtr;
108 *(little32_t *)FixupPtr = RawInstr | Imm15_0 | Imm25_16;
112 int64_t
Value = TargetAddress - FixupAddress + Addend;
116 *(little32_t *)FixupPtr =
Value;
120 int64_t
Value = FixupAddress - TargetAddress + Addend;
123 *(little32_t *)FixupPtr =
Value;
127 *(little64_t *)FixupPtr = TargetAddress - FixupAddress + Addend;
133 uint64_t PCPage = FixupAddress & ~static_cast<uint64_t>(0xfff);
135 int64_t PageDelta = TargetPage - PCPage;
139 uint32_t RawInstr = *(little32_t *)FixupPtr;
141 *(little32_t *)FixupPtr = RawInstr | Imm31_12;
145 uint64_t TargetOffset = (TargetAddress + Addend) & 0xfff;
147 uint32_t RawInstr = *(ulittle32_t *)FixupPtr;
148 uint32_t Imm11_0 = TargetOffset << 10;
149 *(ulittle32_t *)FixupPtr = RawInstr | Imm11_0;
153 int64_t
Value = TargetAddress - FixupAddress + Addend;
161 uint32_t Pcaddu18i = *(little32_t *)FixupPtr;
163 *(little32_t *)FixupPtr = Pcaddu18i | Hi20;
164 uint32_t Jirl = *(little32_t *)(FixupPtr + 4);
166 *(little32_t *)(FixupPtr + 4) = Jirl | Lo16;
170 int64_t
Value = *(
reinterpret_cast<const int8_t *
>(FixupPtr));
171 Value += ((TargetAddress + Addend) & 0x3f);
172 *FixupPtr = (*FixupPtr & 0xc0) | (
static_cast<int8_t
>(
Value) & 0x3f);
176 int64_t
Value = TargetAddress +
177 *(
reinterpret_cast<const int8_t *
>(FixupPtr)) + Addend;
178 *FixupPtr =
static_cast<int8_t
>(
Value);
184 *(little16_t *)FixupPtr =
static_cast<int16_t
>(
Value);
190 *(little32_t *)FixupPtr =
static_cast<int32_t
>(
Value);
196 *(little64_t *)FixupPtr =
static_cast<int64_t
>(
Value);
200 const uint32_t Maxcount = 1 + 64 / 7;
202 const char *
Error =
nullptr;
210 ": extra space for uleb128");
218 int64_t
Value = *(
reinterpret_cast<const int8_t *
>(FixupPtr));
219 Value -= ((TargetAddress + Addend) & 0x3f);
220 *FixupPtr = (*FixupPtr & 0xc0) | (
static_cast<int8_t
>(
Value) & 0x3f);
224 int64_t
Value = *(
reinterpret_cast<const int8_t *
>(FixupPtr)) -
225 TargetAddress - Addend;
226 *FixupPtr =
static_cast<int8_t
>(
Value);
232 *(little16_t *)FixupPtr =
static_cast<int16_t
>(
Value);
238 *(little32_t *)FixupPtr =
static_cast<int32_t
>(
Value);
244 *(little64_t *)FixupPtr =
static_cast<int64_t
>(
Value);
248 const uint32_t Maxcount = 1 + 64 / 7;
250 const char *
Error =
nullptr;
258 ": extra space for uleb128");
270 "In graph " +
G.getName() +
", section " +
B.getSection().getName() +
286struct BlockRelaxAux {
314 switch (
E.getKind()) {
324 for (
auto &S :
G.sections()) {
328 auto BlockEmplaceResult = Aux.Blocks.try_emplace(
B);
329 assert(BlockEmplaceResult.second &&
"Block encountered twice");
330 auto &BlockAux = BlockEmplaceResult.first->second;
332 for (
auto &
E :
B->edges())
334 BlockAux.RelaxEdges.push_back(&
E);
336 if (BlockAux.RelaxEdges.empty()) {
337 Aux.Blocks.erase(BlockEmplaceResult.first);
341 const auto NumEdges = BlockAux.RelaxEdges.size();
342 BlockAux.RelocDeltas.resize(NumEdges, 0);
343 BlockAux.EdgeKinds.resize_for_overwrite(NumEdges);
346 for (
auto *Sym : S.
symbols()) {
347 if (!Sym->isDefined() || &Sym->getBlock() !=
B)
350 BlockAux.Anchors.push_back({Sym->getOffset(), Sym,
false});
351 BlockAux.Anchors.push_back(
352 {Sym->getOffset() + Sym->getSize(), Sym,
true});
361 for (
auto &BlockAuxIter : Aux.Blocks) {
362 llvm::sort(BlockAuxIter.second.Anchors, [](
auto &
A,
auto &
B) {
363 return std::make_pair(A.Offset, A.End) < std::make_pair(B.Offset, B.End);
371 Edge::Kind &NewEdgeKind) {
373 !
E.getTarget().isDefined() ?
Log2_64(
E.getAddend()) + 1 :
E.getAddend();
374 const uint64_t AllBytes = (1ULL << (Addend & 0xff)) - 4;
376 const uint64_t MaxBytes = Addend >> 8;
381 if (MaxBytes != 0 && CurBytes > MaxBytes)
384 Remove = AllBytes - CurBytes;
386 assert(
static_cast<int32_t
>(Remove) >= 0 &&
387 "R_LARCH_ALIGN needs expanding the content");
397 Aux.EdgeKinds.assign(Aux.EdgeKinds.size(), Edge::Invalid);
401 const auto Loc = BlockAddr +
E->getOffset() - Delta;
402 auto &Cur = Aux.RelocDeltas[
I];
404 switch (
E->getKind()) {
417 SA[0].Sym->setSize(SA[0].
Offset - Delta - SA[0].Sym->getOffset());
419 SA[0].Sym->setOffset(SA[0].
Offset - Delta);
429 for (
const SymbolAnchor &
A : SA) {
431 A.Sym->setSize(
A.Offset - Delta -
A.Sym->getOffset());
433 A.Sym->setOffset(
A.Offset - Delta);
442 for (
auto &[
B, BlockAux] : Aux.Blocks)
450 auto *Dest = Contents.
data();
457 uint32_t Remove = Aux.RelocDeltas[
I] - Delta;
458 Delta = Aux.RelocDeltas[
I];
459 if (Remove == 0 && Aux.EdgeKinds[
I] == Edge::Invalid)
464 std::memmove(Dest, Contents.data() +
Offset,
Size);
466 Offset =
E->getOffset() + Remove;
469 std::memmove(Dest, Contents.data() +
Offset, Contents.size() -
Offset);
475 E.setOffset(
E.getOffset() - Delta);
477 if (
I < Aux.RelaxEdges.size() && Aux.RelaxEdges[
I] == &
E) {
478 if (Aux.EdgeKinds[
I] != Edge::Invalid)
479 E.setKind(Aux.EdgeKinds[
I]);
481 Delta = Aux.RelocDeltas[
I];
498 for (
auto &[
B, BlockAux] : Aux.Blocks)
510template <
typename ELFT>
517 case ELF::R_LARCH_64:
519 case ELF::R_LARCH_32:
521 case ELF::R_LARCH_32_PCREL:
523 case ELF::R_LARCH_B16:
525 case ELF::R_LARCH_B21:
527 case ELF::R_LARCH_B26:
529 case ELF::R_LARCH_PCALA_HI20:
531 case ELF::R_LARCH_PCALA_LO12:
533 case ELF::R_LARCH_GOT_PC_HI20:
535 case ELF::R_LARCH_GOT_PC_LO12:
537 case ELF::R_LARCH_CALL36:
539 case ELF::R_LARCH_ADD6:
541 case ELF::R_LARCH_ADD8:
543 case ELF::R_LARCH_ADD16:
545 case ELF::R_LARCH_ADD32:
547 case ELF::R_LARCH_ADD64:
549 case ELF::R_LARCH_ADD_ULEB128:
551 case ELF::R_LARCH_SUB6:
553 case ELF::R_LARCH_SUB8:
555 case ELF::R_LARCH_SUB16:
557 case ELF::R_LARCH_SUB32:
559 case ELF::R_LARCH_SUB64:
561 case ELF::R_LARCH_SUB_ULEB128:
563 case ELF::R_LARCH_ALIGN:
568 "Unsupported loongarch relocation:" +
formatv(
"{0:d}: ",
Type) +
577 Error addRelocations()
override {
581 using Self = ELFLinkGraphBuilder_loongarch<ELFT>;
582 for (
const auto &RelSect : Base::Sections)
583 if (
Error Err = Base::forEachRelaRelocation(RelSect,
this,
584 &Self::addSingleRelocation))
590 Error addSingleRelocation(
const typename ELFT::Rela &Rel,
591 const typename ELFT::Shdr &FixupSect,
596 int64_t Addend = Rel.r_addend;
599 if (
Type == ELF::R_LARCH_MARK_LA)
602 if (
Type == ELF::R_LARCH_RELAX) {
605 "R_LARCH_RELAX without preceding relocation",
608 auto &PrevEdge = *std::prev(BlockToFix.
edges().end());
610 PrevEdge.setKind(getRelaxableRelocationKind(Kind));
616 return Kind.takeError();
618 uint32_t SymbolIndex = Rel.getSymbol(
false);
619 auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
621 return ObjSymbol.takeError();
623 Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
626 formatv(
"Could not find symbol at given index, did you add it to "
627 "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
628 SymbolIndex, (*ObjSymbol)->st_shndx,
629 Base::GraphSymbols.size()),
641 BlockToFix.
addEdge(std::move(GE));
647 ELFLinkGraphBuilder_loongarch(
StringRef FileName,
649 std::shared_ptr<orc::SymbolStringPool> SSP,
652 std::move(Features), FileName,
671 MemoryBufferRef ObjectBuffer, std::shared_ptr<orc::SymbolStringPool> SSP) {
673 dbgs() <<
"Building jitlink graph for new input "
679 return ELFObj.takeError();
681 auto Features = (*ELFObj)->getFeatures();
683 return Features.takeError();
687 return ELFLinkGraphBuilder_loongarch<object::ELF64LE>(
688 (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
689 std::move(SSP), (*ELFObj)->makeTriple(), std::move(*Features))
694 "Invalid triple for LoongArch ELF object file");
696 return ELFLinkGraphBuilder_loongarch<object::ELF32LE>(
697 (*ELFObj)->getFileName(), ELFObjFile.getELFFile(), std::move(SSP),
698 (*ELFObj)->makeTriple(), std::move(*Features))
703 std::unique_ptr<JITLinkContext> Ctx) {
705 const Triple &TT =
G->getTargetTriple();
706 if (Ctx->shouldAddDefaultTargetPasses(TT)) {
715 if (
auto MarkLive = Ctx->getMarkLivePass(TT))
727 if (
auto Err = Ctx->modifyPassConfig(*
G, Config))
728 return Ctx->notifyFailed(std::move(Err));
730 ELFJITLinker_loongarch::link(std::move(Ctx), std::move(
G), std::move(Config));
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
StringRef getBufferIdentifier() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Manages the enabling and disabling of subtarget specific features.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
orc::ExecutorAddr getAddress() const
An Addressable with content and edges.
edge_iterator removeEdge(edge_iterator I)
Remove the edge pointed to by the given iterator.
void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target, Edge::AddendT Addend)
Add an edge to this block.
iterator_range< edge_iterator > edges()
Return the list of edges attached to this content.
MutableArrayRef< char > getAlreadyMutableContent()
Get mutable content for this block.
bool edges_empty() const
Returns true if the list of edges is empty.
A LinkGraph pass that splits blocks in a section that follows the DWARF Record format into sub-blocks...
A LinkGraph pass that adds missing FDE-to-CIE, FDE-to-PC and FDE-to-LSDA edges.
LinkGraph building code that's specific to the given ELFT, but common across all architectures.
Represents fixups and constraints in the LinkGraph.
Represents an object file section.
iterator_range< symbol_iterator > symbols()
Returns an iterator over the symbols defined in this section.
iterator_range< block_iterator > blocks()
Returns an iterator over the blocks defined in this section.
orc::MemProt getMemProt() const
Returns the protection flags for this section.
Global Offset Table Builder.
Procedure Linkage Table Builder.
static Expected< std::unique_ptr< ObjectFile > > createELFObjectFile(MemoryBufferRef Object, bool InitContent=true)
Represents an address in the executor process.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI const char * getEdgeKindName(Edge::Kind K)
Returns a string name for the given loongarch edge.
EdgeKind_loongarch
Represents loongarch fixups.
@ Branch16PCRel
A 16-bit PC-relative branch.
@ Add16
16 bits label addition
@ AddUleb128
ULEB128 bits label addition.
@ RequestGOTAndTransformToPage20
A GOT entry getter/constructor, transformed to Page20 pointing at the GOT entry for the original targ...
@ Sub16
16 bits label subtraction
@ NegDelta32
A 32-bit negative delta.
@ SubUleb128
ULEB128 bits label subtraction.
@ Sub8
8 bits label subtraction
@ PageOffset12
The 12-bit offset of the target within its page.
@ Sub32
32 bits label subtraction
@ Add64
64 bits label addition
@ Sub6
low 6 bits label subtraction
@ Add8
8 bits label addition
@ Page20
The signed 20-bit delta from the fixup page to the page containing the target.
@ Pointer64
A plain 64-bit pointer value relocation.
@ RequestGOTAndTransformToPageOffset12
A GOT entry getter/constructor, transformed to Pageoffset12 pointing at the GOT entry for the origina...
@ Call36PCRel
A 36-bit PC-relative call.
@ Add6
low 6 bits label addition
@ Branch21PCRel
A 21-bit PC-relative branch.
@ Branch26PCRel
A 26-bit PC-relative branch.
@ Add32
32 bits label addition
@ Pointer32
A plain 32-bit pointer value relocation.
@ AlignRelaxable
Alignment requirement used by linker relaxation.
@ Sub64
64 bits label subtraction
uint32_t extractBits(uint64_t Val, unsigned Hi, unsigned Lo)
unique_function< Error(LinkGraph &)> LinkGraphPassFunction
A function for mutating LinkGraphs.
LLVM_ABI Error makeTargetOutOfRangeError(const LinkGraph &G, const Block &B, const Edge &E)
Create an out of range error for the given edge in the given block.
static bool shouldRelax(const Section &S)
static void finalizeBlockRelax(LinkGraph &G, Block &Block, BlockRelaxAux &Aux)
static void relaxAlign(orc::ExecutorAddr Loc, const Edge &E, uint32_t &Remove, Edge::Kind &NewEdgeKind)
static bool relaxOnce(LinkGraph &G, RelaxAux &Aux)
LLVM_ABI Error makeAlignmentError(llvm::orc::ExecutorAddr Loc, uint64_t Value, int N, const Edge &E)
static Error relax(LinkGraph &G)
static bool isRelaxable(const Edge &E)
void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs)
For each edge in the given graph, apply a list of visitors to the edge, stopping when the first visit...
LLVM_ABI Error markAllSymbolsLive(LinkGraph &G)
Marks all symbols in a graph live.
LinkGraphPassFunction createRelaxationPass_ELF_loongarch()
Returns a pass that performs linker relaxation.
static RelaxAux initRelaxAux(LinkGraph &G)
Expected< std::unique_ptr< LinkGraph > > createLinkGraphFromELFObject_loongarch(MemoryBufferRef ObjectBuffer, std::shared_ptr< orc::SymbolStringPool > SSP)
Create a LinkGraph from an ELF/loongarch relocatable object.
LLVM_ABI void printEdge(raw_ostream &OS, const Block &B, const Edge &E, StringRef EdgeKindName)
static bool relaxBlock(LinkGraph &G, Block &Block, BlockRelaxAux &Aux, const RelaxConfig &Config)
void link_ELF_loongarch(std::unique_ptr< LinkGraph > G, std::unique_ptr< JITLinkContext > Ctx)
jit-link the given object buffer, which must be an ELF loongarch object file.
static void finalizeRelax(LinkGraph &G, RelaxAux &Aux)
LLVM_ABI StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type)
uint64_t read64le(const void *P)
uint16_t read16le(const void *P)
uint32_t read32le(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionAddr VTableAddr Count
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
This struct is a compact representation of a valid (non-zero power of two) alignment.
An LinkGraph pass configuration, consisting of a list of pre-prune, post-prune, and post-fixup passes...
LinkGraphPassList PostAllocationPasses
Post-allocation passes.
LinkGraphPassList PostPrunePasses
Post-prune passes.
LinkGraphPassList PrePrunePasses
Pre-prune passes.