Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit c73b9d2

Browse files
authored
Merge pull request rust-lang#1064 from bjorn3/inline_asm
Basic inline asm support
2 parents 548c46f + 726e329 commit c73b9d2

File tree

8 files changed

+262
-41
lines changed

8 files changed

+262
-41
lines changed

Readme.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,5 +76,8 @@ function jit_calc() {
7676

7777
* Good non-rust abi support ([several problems](https://github.com/bjorn3/rustc_codegen_cranelift/issues/10))
7878
* Proc macros
79-
* Inline assembly ([no cranelift support](https://github.com/bytecodealliance/wasmtime/issues/1041), not coming soon)
79+
* Inline assembly ([no cranelift support](https://github.com/bytecodealliance/wasmtime/issues/1041)
80+
* On Linux there is support for invoking an external assembler for `global_asm!` and `asm!`.
81+
`llvm_asm!` will remain unimplemented forever. `asm!` doesn't yet support reg classes. You
82+
have to specify specific registers instead.
8083
* SIMD ([tracked here](https://github.com/bjorn3/rustc_codegen_cranelift/issues/171), some basic things work)

src/base.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
3636
let mut fx = FunctionCx {
3737
tcx,
3838
module: &mut cx.module,
39+
global_asm: &mut cx.global_asm,
3940
pointer_type,
4041

4142
instance,
@@ -307,24 +308,26 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
307308
TerminatorKind::InlineAsm {
308309
template,
309310
operands,
310-
options: _,
311+
options,
311312
destination,
312313
line_spans: _,
313314
} => {
314-
match template {
315-
&[] => {
316-
assert_eq!(operands, &[]);
317-
match *destination {
318-
Some(destination) => {
319-
let destination_block = fx.get_block(destination);
320-
fx.bcx.ins().jump(destination_block, &[]);
321-
}
322-
None => bug!(),
323-
}
315+
crate::inline_asm::codegen_inline_asm(
316+
fx,
317+
bb_data.terminator().source_info.span,
318+
template,
319+
operands,
320+
*options,
321+
);
324322

325-
// Black box
323+
match *destination {
324+
Some(destination) => {
325+
let destination_block = fx.get_block(destination);
326+
fx.bcx.ins().jump(destination_block, &[]);
327+
}
328+
None => {
329+
crate::trap::trap_unreachable(fx, "[corruption] Returned from noreturn inline asm");
326330
}
327-
_ => fx.tcx.sess.span_fatal(bb_data.terminator().source_info.span, "Inline assembly is not supported"),
328331
}
329332
}
330333
TerminatorKind::Resume | TerminatorKind::Abort => {

src/common.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ pub(crate) struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
254254
// FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
255255
pub(crate) tcx: TyCtxt<'tcx>,
256256
pub(crate) module: &'clif mut Module<B>,
257+
pub(crate) global_asm: &'clif mut String,
257258
pub(crate) pointer_type: Type, // Cached from module
258259

259260
pub(crate) instance: Instance<'tcx>,

src/driver/aot.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -112,21 +112,11 @@ fn module_codegen(tcx: TyCtxt<'_>, cgu_name: rustc_span::Symbol) -> ModuleCodege
112112

113113
let module = new_module(tcx, cgu_name.as_str().to_string());
114114

115-
let mut global_asm = Vec::new();
116115
let mut cx = crate::CodegenCx::new(tcx, module, tcx.sess.opts.debuginfo != DebugInfo::None);
117-
super::codegen_mono_items(&mut cx, &mut global_asm, mono_items);
118-
let (mut module, debug, mut unwind_context) = tcx.sess.time("finalize CodegenCx", || cx.finalize());
116+
super::codegen_mono_items(&mut cx, mono_items);
117+
let (mut module, global_asm, debug, mut unwind_context) = tcx.sess.time("finalize CodegenCx", || cx.finalize());
119118
crate::main_shim::maybe_create_entry_wrapper(tcx, &mut module, &mut unwind_context);
120119

121-
let global_asm = global_asm.into_iter().map(|hir_id| {
122-
let item = tcx.hir().expect_item(hir_id);
123-
if let rustc_hir::ItemKind::GlobalAsm(rustc_hir::GlobalAsm { asm }) = item.kind {
124-
asm.as_str().to_string()
125-
} else {
126-
bug!("Expected GlobalAsm found {:?}", item);
127-
}
128-
}).collect::<Vec<String>>().join("\n");
129-
130120
let codegen_result = emit_module(
131121
tcx,
132122
cgu.name().as_str().to_string(),
@@ -283,7 +273,7 @@ fn codegen_global_asm(tcx: TyCtxt<'_>, cgu_name: &str, global_asm: &str) {
283273
}
284274

285275
// FIXME fix linker error on macOS
286-
tcx.sess.fatal("global_asm! is not yet supported on macOS and Windows");
276+
tcx.sess.fatal("asm! and global_asm! are not yet supported on macOS and Windows");
287277
}
288278

289279
let assembler = crate::toolchain::get_toolchain_binary(tcx.sess, "as");

src/driver/jit.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,15 +54,13 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>) -> ! {
5454

5555
let mut cx = crate::CodegenCx::new(tcx, jit_module, false);
5656

57-
let (mut jit_module, _debug, mut unwind_context) = super::time(tcx, "codegen mono items", || {
58-
let mut global_asm = Vec::new();
59-
super::codegen_mono_items(&mut cx, &mut global_asm, mono_items);
60-
for hir_id in global_asm {
61-
let item = tcx.hir().expect_item(hir_id);
62-
tcx.sess.span_err(item.span, "Global asm is not supported in JIT mode");
63-
}
57+
let (mut jit_module, global_asm, _debug, mut unwind_context) = super::time(tcx, "codegen mono items", || {
58+
super::codegen_mono_items(&mut cx, mono_items);
6459
tcx.sess.time("finalize CodegenCx", || cx.finalize())
6560
});
61+
if !global_asm.is_empty() {
62+
tcx.sess.fatal("Global asm is not supported in JIT mode");
63+
}
6664
crate::main_shim::maybe_create_entry_wrapper(tcx, &mut jit_module, &mut unwind_context);
6765
crate::allocator::codegen(tcx, &mut jit_module, &mut unwind_context);
6866

src/driver/mod.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::any::Any;
22

3-
use rustc_hir::HirId;
43
use rustc_middle::middle::cstore::EncodedMetadata;
54
use rustc_middle::mir::mono::{Linkage as RLinkage, MonoItem, Visibility};
65

@@ -32,7 +31,6 @@ pub(crate) fn codegen_crate(
3231

3332
fn codegen_mono_items<'tcx>(
3433
cx: &mut crate::CodegenCx<'tcx, impl Backend + 'static>,
35-
global_asm: &mut Vec<HirId>,
3634
mono_items: Vec<(MonoItem<'tcx>, (RLinkage, Visibility))>,
3735
) {
3836
cx.tcx.sess.time("predefine functions", || {
@@ -51,13 +49,12 @@ fn codegen_mono_items<'tcx>(
5149

5250
for (mono_item, (linkage, visibility)) in mono_items {
5351
let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
54-
trans_mono_item(cx, global_asm, mono_item, linkage);
52+
trans_mono_item(cx, mono_item, linkage);
5553
}
5654
}
5755

5856
fn trans_mono_item<'tcx, B: Backend + 'static>(
5957
cx: &mut crate::CodegenCx<'tcx, B>,
60-
global_asm: &mut Vec<HirId>,
6158
mono_item: MonoItem<'tcx>,
6259
linkage: Linkage,
6360
) {
@@ -94,7 +91,13 @@ fn trans_mono_item<'tcx, B: Backend + 'static>(
9491
crate::constant::codegen_static(&mut cx.constants_cx, def_id);
9592
}
9693
MonoItem::GlobalAsm(hir_id) => {
97-
global_asm.push(hir_id);
94+
let item = tcx.hir().expect_item(hir_id);
95+
if let rustc_hir::ItemKind::GlobalAsm(rustc_hir::GlobalAsm { asm }) = item.kind {
96+
cx.global_asm.push_str(&*asm.as_str());
97+
cx.global_asm.push_str("\n\n");
98+
} else {
99+
bug!("Expected GlobalAsm found {:?}", item);
100+
}
98101
}
99102
}
100103
}

src/inline_asm.rs

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
use crate::prelude::*;
2+
3+
use std::fmt::Write;
4+
5+
use rustc_ast::ast::{InlineAsmTemplatePiece, InlineAsmOptions};
6+
use rustc_middle::mir::InlineAsmOperand;
7+
use rustc_target::asm::*;
8+
9+
pub(crate) fn codegen_inline_asm<'tcx>(
10+
fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
11+
_span: Span,
12+
template: &[InlineAsmTemplatePiece],
13+
operands: &[InlineAsmOperand<'tcx>],
14+
options: InlineAsmOptions,
15+
) {
16+
// FIXME add .eh_frame unwind info directives
17+
18+
if template.is_empty() {
19+
// Black box
20+
return;
21+
}
22+
23+
let mut slot_size = Size::from_bytes(0);
24+
let mut clobbered_regs = Vec::new();
25+
let mut inputs = Vec::new();
26+
let mut outputs = Vec::new();
27+
28+
let mut new_slot = |reg_class: InlineAsmRegClass| {
29+
let reg_size = reg_class
30+
.supported_types(InlineAsmArch::X86_64)
31+
.iter()
32+
.map(|(ty, _)| ty.size())
33+
.max()
34+
.unwrap();
35+
let align = rustc_target::abi::Align::from_bytes(reg_size.bytes()).unwrap();
36+
slot_size = slot_size.align_to(align);
37+
let offset = slot_size;
38+
slot_size += reg_size;
39+
offset
40+
};
41+
42+
// FIXME overlap input and output slots to save stack space
43+
for operand in operands {
44+
match *operand {
45+
InlineAsmOperand::In { reg, ref value } => {
46+
let reg = expect_reg(reg);
47+
clobbered_regs.push((reg, new_slot(reg.reg_class())));
48+
inputs.push((reg, new_slot(reg.reg_class()), crate::base::trans_operand(fx, value).load_scalar(fx)));
49+
}
50+
InlineAsmOperand::Out { reg, late: _, place } => {
51+
let reg = expect_reg(reg);
52+
clobbered_regs.push((reg, new_slot(reg.reg_class())));
53+
if let Some(place) = place {
54+
outputs.push((reg, new_slot(reg.reg_class()), crate::base::trans_place(fx, place)));
55+
}
56+
}
57+
InlineAsmOperand::InOut { reg, late: _, ref in_value, out_place } => {
58+
let reg = expect_reg(reg);
59+
clobbered_regs.push((reg, new_slot(reg.reg_class())));
60+
inputs.push((reg, new_slot(reg.reg_class()), crate::base::trans_operand(fx, in_value).load_scalar(fx)));
61+
if let Some(out_place) = out_place {
62+
outputs.push((reg, new_slot(reg.reg_class()), crate::base::trans_place(fx, out_place)));
63+
}
64+
}
65+
InlineAsmOperand::Const { value: _ } => todo!(),
66+
InlineAsmOperand::SymFn { value: _ } => todo!(),
67+
InlineAsmOperand::SymStatic { def_id: _ } => todo!(),
68+
}
69+
}
70+
71+
let asm_name = format!("{}__inline_asm_{}", fx.tcx.symbol_name(fx.instance).name, /*FIXME*/0);
72+
73+
let generated_asm = generate_asm_wrapper(&asm_name, InlineAsmArch::X86_64, options, template, clobbered_regs, &inputs, &outputs);
74+
fx.global_asm.push_str(&generated_asm);
75+
76+
call_inline_asm(fx, &asm_name, slot_size, inputs, outputs);
77+
}
78+
79+
fn generate_asm_wrapper(
80+
asm_name: &str,
81+
arch: InlineAsmArch,
82+
options: InlineAsmOptions,
83+
template: &[InlineAsmTemplatePiece],
84+
clobbered_regs: Vec<(InlineAsmReg, Size)>,
85+
inputs: &[(InlineAsmReg, Size, Value)],
86+
outputs: &[(InlineAsmReg, Size, CPlace<'_>)],
87+
) -> String {
88+
let mut generated_asm = String::new();
89+
writeln!(generated_asm, ".globl {}", asm_name).unwrap();
90+
writeln!(generated_asm, ".type {},@function", asm_name).unwrap();
91+
writeln!(generated_asm, ".section .text.{},\"ax\",@progbits", asm_name).unwrap();
92+
writeln!(generated_asm, "{}:", asm_name).unwrap();
93+
94+
generated_asm.push_str(".intel_syntax noprefix\n");
95+
generated_asm.push_str(" push rbp\n");
96+
generated_asm.push_str(" mov rbp,rdi\n");
97+
98+
// Save clobbered registers
99+
if !options.contains(InlineAsmOptions::NORETURN) {
100+
// FIXME skip registers saved by the calling convention
101+
for &(reg, offset) in &clobbered_regs {
102+
save_register(&mut generated_asm, arch, reg, offset);
103+
}
104+
}
105+
106+
// Write input registers
107+
for &(reg, offset, _value) in inputs {
108+
restore_register(&mut generated_asm, arch, reg, offset);
109+
}
110+
111+
if options.contains(InlineAsmOptions::ATT_SYNTAX) {
112+
generated_asm.push_str(".att_syntax\n");
113+
}
114+
115+
// The actual inline asm
116+
for piece in template {
117+
match piece {
118+
InlineAsmTemplatePiece::String(s) => {
119+
generated_asm.push_str(s);
120+
}
121+
InlineAsmTemplatePiece::Placeholder { operand_idx: _, modifier: _, span: _ } => todo!(),
122+
}
123+
}
124+
generated_asm.push('\n');
125+
126+
if options.contains(InlineAsmOptions::ATT_SYNTAX) {
127+
generated_asm.push_str(".intel_syntax noprefix\n");
128+
}
129+
130+
if !options.contains(InlineAsmOptions::NORETURN) {
131+
// Read output registers
132+
for &(reg, offset, _place) in outputs {
133+
save_register(&mut generated_asm, arch, reg, offset);
134+
}
135+
136+
// Restore clobbered registers
137+
for &(reg, offset) in clobbered_regs.iter().rev() {
138+
restore_register(&mut generated_asm, arch, reg, offset);
139+
}
140+
141+
generated_asm.push_str(" pop rbp\n");
142+
generated_asm.push_str(" ret\n");
143+
} else {
144+
generated_asm.push_str(" ud2\n");
145+
}
146+
147+
generated_asm.push_str(".att_syntax\n");
148+
writeln!(generated_asm, ".size {name}, .-{name}", name=asm_name).unwrap();
149+
generated_asm.push_str(".text\n");
150+
generated_asm.push_str("\n\n");
151+
152+
generated_asm
153+
}
154+
155+
fn call_inline_asm<'tcx>(
156+
fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
157+
asm_name: &str,
158+
slot_size: Size,
159+
inputs: Vec<(InlineAsmReg, Size, Value)>,
160+
outputs: Vec<(InlineAsmReg, Size, CPlace<'tcx>)>,
161+
) {
162+
let stack_slot = fx.bcx.func.create_stack_slot(StackSlotData {
163+
kind: StackSlotKind::ExplicitSlot,
164+
offset: None,
165+
size: u32::try_from(slot_size.bytes()).unwrap(),
166+
});
167+
#[cfg(debug_assertions)]
168+
fx.add_comment(stack_slot, "inline asm scratch slot");
169+
170+
let inline_asm_func = fx.module.declare_function(asm_name, Linkage::Import, &Signature {
171+
call_conv: CallConv::SystemV,
172+
params: vec![AbiParam::new(fx.pointer_type)],
173+
returns: vec![],
174+
}).unwrap();
175+
let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
176+
#[cfg(debug_assertions)]
177+
fx.add_comment(inline_asm_func, asm_name);
178+
179+
for (_reg, offset, value) in inputs {
180+
fx.bcx.ins().stack_store(value, stack_slot, i32::try_from(offset.bytes()).unwrap());
181+
}
182+
183+
let stack_slot_addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0);
184+
fx.bcx.ins().call(inline_asm_func, &[stack_slot_addr]);
185+
186+
for (_reg, offset, place) in outputs {
187+
let ty = fx.clif_type(place.layout().ty).unwrap();
188+
let value = fx.bcx.ins().stack_load(ty, stack_slot, i32::try_from(offset.bytes()).unwrap());
189+
place.write_cvalue(fx, CValue::by_val(value, place.layout()));
190+
}
191+
}
192+
193+
fn expect_reg(reg_or_class: InlineAsmRegOrRegClass) -> InlineAsmReg {
194+
match reg_or_class {
195+
InlineAsmRegOrRegClass::Reg(reg) => reg,
196+
InlineAsmRegOrRegClass::RegClass(class) => unimplemented!("{:?}", class),
197+
}
198+
}
199+
200+
fn save_register(generated_asm: &mut String, arch: InlineAsmArch, reg: InlineAsmReg, offset: Size) {
201+
match arch {
202+
InlineAsmArch::X86_64 => {
203+
write!(generated_asm, " mov [rbp+0x{:x}], ", offset.bytes()).unwrap();
204+
reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
205+
generated_asm.push('\n');
206+
}
207+
_ => unimplemented!("save_register for {:?}", arch),
208+
}
209+
}
210+
211+
fn restore_register(generated_asm: &mut String, arch: InlineAsmArch, reg: InlineAsmReg, offset: Size) {
212+
match arch {
213+
InlineAsmArch::X86_64 => {
214+
generated_asm.push_str(" mov ");
215+
reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
216+
writeln!(generated_asm, ", [rbp+0x{:x}]", offset.bytes()).unwrap();
217+
}
218+
_ => unimplemented!("restore_register for {:?}", arch),
219+
}
220+
}

0 commit comments

Comments
 (0)