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