Skip to content

Commit c6c2ae3

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

File tree

3 files changed

+240
-0
lines changed

3 files changed

+240
-0
lines changed
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
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+
# The Problem We're Solving
13+
14+
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.
15+
16+
Here's what that looks like in practice:
17+
```cpp
18+
struct Point { float x, y; };
19+
struct Point add_points(struct Point a, struct Point b);
20+
```
21+
22+
Seems innocent enough, right? But generating correct LLVM IR for this requires knowing:
23+
- Are the struct arguments passed in registers or memory?
24+
- If in registers, what register class is used?
25+
- Are multiple values packed into a single register?
26+
- Is the struct returned in registers or using a hidden return parameter?
27+
28+
> [This godbolt link](https://clang.godbolt.org/z/P4fMj7hjY) shows the same simple struct using six different calling conventions across six different targets. And crucially: a frontend generating IR needs to know ALL of this before it can emit the right function signature.
29+
30+
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.
31+
32+
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.
33+
34+
# The Design
35+
36+
<div style="margin:0 auto;">
37+
<img src="/img/abi_flow.png"><br/>
38+
</div>
39+
40+
41+
42+
## Independent ABI Type System
43+
44+
At the heart of the library is `llvm::abi::Type`, a type system designed specifically for ABI decisions:
45+
46+
```cpp
47+
class Type {
48+
protected:
49+
TypeKind Kind;
50+
TypeSize SizeInBits;
51+
Align ABIAlignment;
52+
53+
public:
54+
TypeKind getKind() const { return Kind; }
55+
TypeSize getSizeInBits() const { return SizeInBits; }
56+
Align getAlignment() const { return ABIAlignment; }
57+
58+
bool isInteger() const { return Kind == TypeKind::Integer; }
59+
bool isStruct() const { return Kind == TypeKind::Struct; }
60+
// ... other predicates that matter for ABI
61+
};
62+
```
63+
64+
It contains **more information than LLVM IR types** (which for instance doesn't distinguish between `__int128` and `_BitInt(128)`, both just `i128`), but **less information than frontend types** like Clang's QualType (which carry parsing context, sugar, and other frontend-specific concerns that don't matter for calling conventions).
65+
```cpp
66+
class IntegerType : public Type {
67+
private:
68+
bool IsSigned;
69+
bool IsBitInt; // Crucially different from __int128!
70+
71+
public:
72+
IntegerType(uint64_t BitWidth, Align Align, bool Signed,
73+
bool BitInt = false);
74+
};
75+
```
76+
77+
## Frontend-to-ABI Mapping
78+
79+
The QualTypeMapper class handles the complex job of converting frontend types to ABI types. Here's how it tackles C++ inheritance:
80+
81+
```cpp
82+
const llvm::abi::StructType *
83+
QualTypeMapper::convertCXXRecordType(const CXXRecordDecl *RD,
84+
bool canPassInRegs) {
85+
const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
86+
SmallVector<llvm::abi::FieldInfo, 16> Fields;
87+
SmallVector<llvm::abi::FieldInfo, 8> BaseClasses;
88+
SmallVector<llvm::abi::FieldInfo, 8> VirtualBaseClasses;
89+
90+
// Handle vtable pointer for polymorphic classes
91+
if (RD->isPolymorphic()) {
92+
const llvm::abi::Type *VtablePointer =
93+
createPointerTypeForPointee(ASTCtx.VoidPtrTy);
94+
Fields.emplace_back(VtablePointer, 0);
95+
}
96+
97+
// Process base classes with proper offset calculation
98+
for (const auto &Base : RD->bases()) {
99+
const llvm::abi::Type *BaseType = convertType(Base.getType());
100+
uint64_t BaseOffset = Layout.getBaseClassOffset(
101+
Base.getType()->castAs<RecordType>()->getAsCXXRecordDecl()
102+
).getQuantity() * 8;
103+
104+
if (Base.isVirtual())
105+
VirtualBaseClasses.emplace_back(BaseType, BaseOffset);
106+
else
107+
BaseClasses.emplace_back(BaseType, BaseOffset);
108+
}
109+
110+
// ... field processing and final struct creation
111+
}
112+
```
113+
114+
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.
115+
116+
## Target-Specific Classification
117+
118+
Each target implements the ABIInfo interface. Here's the argument classification implementation for BPF:
119+
120+
```cpp
121+
class BPFABIInfo : public ABIInfo {
122+
private:
123+
TypeBuilder &TB;
124+
125+
public:
126+
ABIArgInfo classifyArgumentType(const Type *ArgTy) const {
127+
if (isAggregateType(ArgTy)) {
128+
auto SizeInBits = ArgTy->getSizeInBits().getFixedValue();
129+
if (SizeInBits == 0)
130+
return ABIArgInfo::getIgnore();
131+
132+
if (SizeInBits <= 128) {
133+
const Type *CoerceTy;
134+
if (SizeInBits <= 64) {
135+
auto AlignedBits = alignTo(SizeInBits, 8);
136+
CoerceTy = TB.getIntegerType(AlignedBits, Align(8), false);
137+
} else {
138+
// Two 64-bit registers for larger aggregates
139+
const Type *RegTy = TB.getIntegerType(64, Align(8), false);
140+
CoerceTy = TB.getArrayType(RegTy, 2);
141+
}
142+
return ABIArgInfo::getDirect(CoerceTy);
143+
}
144+
145+
return ABIArgInfo::getIndirect(ArgTy->getAlignment().value());
146+
}
147+
148+
// Handle integer promotion elegantly
149+
if (const auto *IntTy = dyn_cast<IntegerType>(ArgTy)) {
150+
if (IntTy->isPromotableIntegerType())
151+
return ABIArgInfo::getExtend(ArgTy);
152+
}
153+
154+
return ABIArgInfo::getDirect();
155+
}
156+
};
157+
158+
```
159+
The key difference is that the ABI classification logic itself is **completely independent of Clang**. Any LLVM frontend can use it by implementing a mapper from their types to `llvm::abi::Type`. The library then performs ABI classification and outputs `llvm::abi::ABIFunctionInfo` with all the lowering decisions.
160+
161+
For Clang specifically, the `ABITypeMapper` converts those `llvm::abi::Type` results back into `llvm::Type` and populates `clang::CGFunctionInfo`, which then continues through the normal IR generation pipeline.
162+
# Results
163+
The library and the new type system are implemented and working in the [PR #140112](https://github.com/llvm/llvm-project/pull/140112), currently enabled for BPF and X86-64 Linux targets. You can find the implementation under `llvm/lib/ABI/` with Clang integration in `clang/lib/CodeGen/CGCall.cpp`. Here's what we've achieved so far:
164+
165+
## Clean Architecture
166+
167+
The three-layer separation is working beautifully. Frontend concerns, ABI classification, and IR generation are now properly separated:
168+
169+
```cpp
170+
// Integration point in Clang
171+
if (CGM.shouldUseLLVMABI()) {
172+
SmallVector<const llvm::abi::Type *, 8> MappedArgTypes;
173+
for (CanQualType ArgType : argTypes)
174+
MappedArgTypes.push_back(getMapper().convertType(ArgType));
175+
176+
tempFI.reset(llvm::abi::ABIFunctionInfo::create(
177+
CC, getMapper().convertType(resultType), MappedArgTypes));
178+
179+
CGM.fetchABIInfo(getTypeBuilder()).computeInfo(*tempFI);
180+
} else {
181+
CGM.getABIInfo().computeInfo(*FI); // Legacy path
182+
}
183+
```
184+
185+
## Performance Considerations Addressed
186+
187+
My earlier blog post worried about the overhead of "an additional type system." The caching strategy handles this elegantly:
188+
189+
```cpp
190+
const llvm::abi::Type *QualTypeMapper::convertType(QualType QT) {
191+
QT = QT.getCanonicalType().getUnqualifiedType();
192+
193+
auto It = TypeCache.find(QT);
194+
if (It != TypeCache.end())
195+
return It->second; // Cache hit - no recomputation
196+
197+
const llvm::abi::Type *Result = /* conversion logic */;
198+
199+
if (Result)
200+
TypeCache[QT] = Result;
201+
return Result;
202+
}
203+
```
204+
205+
Combined with `BumpPtrAllocator` for type storage, the performance impact is minimal in practice.
206+
207+
<div style="margin:0 auto;">
208+
<img src="/img/abi_library_benchmarks.png"><br/>
209+
</div>
210+
211+
The results are encouraging. Most compilation stages show essentially no performance difference (well within measurement noise). The 0.20% regression in the final Clang build times is expected - we've added new code to the codebase. But the actual compilation performance impact is negligible.
212+
213+
# Future Work
214+
215+
There's still plenty to explore:
216+
217+
## Upstreaming the progress so far...
218+
219+
The work is being upstreamed to LLVM in stages, starting with [PR #158329](https://github.com/llvm/llvm-project/pull/158329). This involves addressing reviewer feedback, ensuring compatibility with existing code, and validating that the new system produces identical results to the current implementation for all supported targets.
220+
221+
## Extended Target Support
222+
223+
Currently the ABI library supports the BPF and X86-64 SysV ABIs, but the architecture makes adding ARM, Windows calling conventions, and other targets straightforward.
224+
225+
## Cross-Frontend Compatibility
226+
227+
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.
228+
229+
230+
## Better Integration
231+
232+
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.
233+
234+
# Acknowledgements
235+
236+
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.
237+
238+
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.
239+
240+
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

82.3 KB
Loading
53.6 KB
Loading

0 commit comments

Comments
 (0)