Skip to content

Commit fa70417

Browse files
committed
GSoC 2025 blog on the ABI lowering library
1 parent 98af07b commit fa70417

File tree

3 files changed

+237
-0
lines changed

3 files changed

+237
-0
lines changed
Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
---
2+
author: "Narayan Sreekumar (vortex73)"
3+
date: "2025-08-25"
4+
tags: ["GSoC", "abi", "codegen", "sysv"]
5+
title: "GSoC 2025: Introducing an ABI Lowering Library"
6+
---
7+
8+
# Introduction
9+
10+
In this post I'm going to outline details about a new ABI lowering library I've been developing for LLVM as part of GSoC 2025!. The aim was to extract the ABI logic from clang and create a reusable library that any LLVM frontend can use for correct C interoperability.
11+
12+
# Get the Code
13+
Let's get the obvious out of the way first. You can find the implementation in the LLVM repository under `llvm/lib/ABI/` with Clang integration in `clang/lib/CodeGen/CGCall.cpp`. A list of all the major components can be found scattered across multiple files in [this PR](https://github.com/llvm/llvm-project/pull/140112).
14+
15+
# The Problem We're Solving
16+
17+
At the start of the program, I wrote about the [fundamental gap in LLVM's target abstraction](https://vortex73.github.io/rendered/GSOC_BLOG1.html). The promise is simple: frontends emit LLVM IR, and LLVM handles everything else. But this promise completely breaks down when it comes to Application Binary Interface (ABI) lowering. Every LLVM frontend that wants C interoperability has to reimplement thousands of lines of target-specific ABI logic.
18+
19+
Here's what that looks like in practice:
20+
```cpp
21+
struct Point { double x, y; };
22+
struct Point add_points(struct Point a, struct Point b);
23+
```
24+
Seems innocent enough, right? But generating correct LLVM IR for this requires knowing:
25+
26+
- Does x86-64 pass this in registers or memory?
27+
- What about ARM? PowerPC? WebAssembly?
28+
- Should it be scalarized to `(double, double, double, double)`?
29+
- Or does it need a hidden return parameter?
30+
31+
The answer depends on subtle ABI rules that are target-specific, constantly evolving, and absolutely critical to get right. Miss one detail and you get silent memory corruption that only shows up in release builds.
32+
33+
As I outlined in my earlier blog post, LLVM's type system simply can't express all the information needed for correct ABI decisions. Two otherwise identical structs with different explicit alignment attributes have different ABIs. `__int128` and `_BitInt(128)` look similar but follow completely different rules.
34+
35+
# The Design
36+
37+
<div style="margin:0 auto;">
38+
<img src="/img/abi_flow.png"><br/>
39+
</div>
40+
41+
## Independent ABI Type System
42+
43+
At the heart of the library is `llvm::abi::Type`, a type system designed specifically for ABI decisions:
44+
45+
```cpp
46+
class Type {
47+
protected:
48+
TypeKind Kind;
49+
TypeSize SizeInBits;
50+
Align ABIAlignment;
51+
52+
public:
53+
TypeKind getKind() const { return Kind; }
54+
TypeSize getSizeInBits() const { return SizeInBits; }
55+
Align getAlignment() const { return ABIAlignment; }
56+
57+
bool isInteger() const { return Kind == TypeKind::Integer; }
58+
bool isStruct() const { return Kind == TypeKind::Struct; }
59+
// ... other predicates that matter for ABI
60+
};
61+
```
62+
This isn't just another type system, in that, it's carefully designed to capture exactly the information that ABI rules care about:
63+
64+
```cpp
65+
class IntegerType : public Type {
66+
private:
67+
bool IsSigned;
68+
bool IsBoolean;
69+
bool IsBitInt; // Crucially different from __int128!
70+
bool IsPromotable; // For C integer promotion rules
71+
72+
public:
73+
IntegerType(uint64_t BitWidth, Align Align, bool Signed,
74+
bool IsBool = false, bool BitInt = false,
75+
bool IsPromotableInt = false);
76+
};
77+
```
78+
79+
## Frontend-to-ABI Mapping
80+
81+
The QualTypeMapper class handles the complex job of converting frontend types to ABI types. Here's how it tackles C++ inheritance:
82+
83+
```cpp
84+
const llvm::abi::StructType *
85+
QualTypeMapper::convertCXXRecordType(const CXXRecordDecl *RD,
86+
bool canPassInRegs) {
87+
const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
88+
SmallVector<llvm::abi::FieldInfo, 16> Fields;
89+
SmallVector<llvm::abi::FieldInfo, 8> BaseClasses;
90+
SmallVector<llvm::abi::FieldInfo, 8> VirtualBaseClasses;
91+
92+
// Handle vtable pointer for polymorphic classes
93+
if (RD->isPolymorphic()) {
94+
const llvm::abi::Type *VtablePointer =
95+
createPointerTypeForPointee(ASTCtx.VoidPtrTy);
96+
Fields.emplace_back(VtablePointer, 0);
97+
}
98+
99+
// Process base classes with proper offset calculation
100+
for (const auto &Base : RD->bases()) {
101+
const llvm::abi::Type *BaseType = convertType(Base.getType());
102+
uint64_t BaseOffset = Layout.getBaseClassOffset(
103+
Base.getType()->castAs<RecordType>()->getAsCXXRecordDecl()
104+
).getQuantity() * 8;
105+
106+
if (Base.isVirtual())
107+
VirtualBaseClasses.emplace_back(BaseType, BaseOffset);
108+
else
109+
BaseClasses.emplace_back(BaseType, BaseOffset);
110+
}
111+
112+
// ... field processing and final struct creation
113+
}
114+
```
115+
116+
This was significantly more complex than I initially anticipated. C++ object layout involves vtables, base class subobjects, virtual inheritance, and all sorts of edge cases that need to be preserved for correct ABI decisions.
117+
118+
## Target-Specific Classification
119+
120+
Each target implements the ABIInfo interface. Here's the complete BPF implementation:
121+
122+
```cpp
123+
class BPFABIInfo : public ABIInfo {
124+
private:
125+
TypeBuilder &TB;
126+
127+
public:
128+
ABIArgInfo classifyArgumentType(const Type *ArgTy) const {
129+
if (isAggregateType(ArgTy)) {
130+
auto SizeInBits = ArgTy->getSizeInBits().getFixedValue();
131+
if (SizeInBits == 0)
132+
return ABIArgInfo::getIgnore();
133+
134+
if (SizeInBits <= 128) {
135+
const Type *CoerceTy;
136+
if (SizeInBits <= 64) {
137+
auto AlignedBits = alignTo(SizeInBits, 8);
138+
CoerceTy = TB.getIntegerType(AlignedBits, Align(8), false);
139+
} else {
140+
// Two 64-bit registers for larger aggregates
141+
const Type *RegTy = TB.getIntegerType(64, Align(8), false);
142+
CoerceTy = TB.getArrayType(RegTy, 2);
143+
}
144+
return ABIArgInfo::getDirect(CoerceTy);
145+
}
146+
147+
return ABIArgInfo::getIndirect(ArgTy->getAlignment().value());
148+
}
149+
150+
// Handle integer promotion elegantly
151+
if (const auto *IntTy = dyn_cast<IntegerType>(ArgTy)) {
152+
if (IntTy->isPromotableIntegerType())
153+
return ABIArgInfo::getExtend(ArgTy);
154+
}
155+
156+
return ABIArgInfo::getDirect();
157+
}
158+
};
159+
160+
```
161+
Compare this to the old approach where BPF ABI logic would be scattered across multiple files, mixed with Clang-specific assumptions!
162+
163+
# Results
164+
165+
The library and the new typesystem are now successfully integrated into Clang, as part of the PR, and are enabled for BPF and X86-64 Linux targets. Here's what we achieved:
166+
## Clean Architecture
167+
168+
The three-layer separation is working beautifully. Frontend concerns, ABI classification, and IR generation are now properly separated:
169+
170+
```cpp
171+
// Integration point in Clang
172+
if (CGM.shouldUseLLVMABI()) {
173+
SmallVector<const llvm::abi::Type *, 8> MappedArgTypes;
174+
for (CanQualType ArgType : argTypes)
175+
MappedArgTypes.push_back(getMapper().convertType(ArgType));
176+
177+
tempFI.reset(llvm::abi::ABIFunctionInfo::create(
178+
CC, getMapper().convertType(resultType), MappedArgTypes));
179+
180+
CGM.fetchABIInfo(getTypeBuilder()).computeInfo(*tempFI);
181+
} else {
182+
CGM.getABIInfo().computeInfo(*FI); // Legacy path
183+
}
184+
```
185+
186+
## Performance Considerations Addressed
187+
188+
My earlier blog post worried about the overhead of "an additional type system." The caching strategy handles this elegantly:
189+
190+
```cpp
191+
const llvm::abi::Type *QualTypeMapper::convertType(QualType QT) {
192+
QT = QT.getCanonicalType().getUnqualifiedType();
193+
194+
auto It = TypeCache.find(QT);
195+
if (It != TypeCache.end())
196+
return It->second; // Cache hit - no recomputation
197+
198+
const llvm::abi::Type *Result = /* conversion logic */;
199+
200+
if (Result)
201+
TypeCache[QT] = Result;
202+
return Result;
203+
}
204+
```
205+
206+
Combined with `BumpPtrAllocator` for type storage, the performance impact is minimal in practice.
207+
208+
<div style="margin:0 auto;">
209+
<img src="/img/abi_library_benchmarks.png"><br/>
210+
</div>
211+
212+
The results are encouraging. Most compilation stages show essentially no performance difference (well within measurement noise). The 0.20% regression in the final Clang binary size is expected - we've added new code to the codebase. But the actual compilation performance impact is negligible.
213+
214+
# Future Work
215+
216+
There's still plenty to explore:
217+
218+
## Extended Target Support
219+
220+
Currently supporting BPF and X86-64 SysV, but the architecture makes adding ARM, Windows calling conventions, and other targets straightforward.
221+
222+
## Cross-Frontend Compatibility
223+
224+
The real test will be when other frontends start using the library. We need to ensure that all frontends generate identical calling conventions for the same C function signature.
225+
226+
227+
## Better Integration
228+
229+
There are still some rough edges in the Clang integration that could be smoothed out. And other LLVM projects could benefit from adopting the library.
230+
231+
# Acknowledgements
232+
233+
This work wouldn't have been possible without my amazing mentors, Nikita Popov and Maksim Levental, who provided invaluable guidance throughout the project. The LLVM community's feedback on the [original RFC](https://discourse.llvm.org/t/rfc-an-abi-lowering-library-for-llvm/84495) was instrumental in shaping the design.
234+
235+
Special thanks to everyone who reviewed the code, provided feedback, and helped navigate all the ABI corner cases. The architecture only works because it's built on decades of accumulated ABI knowledge that was already present in LLVM and Clang.
236+
237+
Looking back at my precursor blog post from earlier this year, I'm amazed at how much the design evolved during implementation. What started as a relatively straightforward "extract Clang's ABI code" became a much more ambitious architectural rework. But the result is something that's genuinely useful for the entire LLVM ecosystem.

static/img/abi_flow.png

52.5 KB
Loading
53.6 KB
Loading

0 commit comments

Comments
 (0)