]> git.lizzy.rs Git - rust.git/blob - src/inline_asm.rs
Skeleton for multiple arch support
[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_span::Symbol;
10 use rustc_target::asm::*;
11
12 pub(crate) fn codegen_inline_asm<'tcx>(
13     fx: &mut FunctionCx<'_, '_, 'tcx>,
14     _span: Span,
15     template: &[InlineAsmTemplatePiece],
16     operands: &[InlineAsmOperand<'tcx>],
17     options: InlineAsmOptions,
18 ) {
19     // FIXME add .eh_frame unwind info directives
20
21     if template.is_empty() {
22         // Black box
23         return;
24     } else if template[0] == InlineAsmTemplatePiece::String("int $$0x29".to_string()) {
25         let true_ = fx.bcx.ins().iconst(types::I32, 1);
26         fx.bcx.ins().trapnz(true_, TrapCode::User(1));
27         return;
28     } else if template[0] == InlineAsmTemplatePiece::String("movq %rbx, ".to_string())
29         && matches!(
30             template[1],
31             InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: Some('r'), span: _ }
32         )
33         && template[2] == InlineAsmTemplatePiece::String("\n".to_string())
34         && template[3] == InlineAsmTemplatePiece::String("cpuid".to_string())
35         && template[4] == InlineAsmTemplatePiece::String("\n".to_string())
36         && template[5] == InlineAsmTemplatePiece::String("xchgq %rbx, ".to_string())
37         && matches!(
38             template[6],
39             InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: Some('r'), span: _ }
40         )
41     {
42         assert_eq!(operands.len(), 4);
43         let (leaf, eax_place) = match operands[1] {
44             InlineAsmOperand::InOut { reg, late: true, ref in_value, out_place } => {
45                 assert_eq!(
46                     reg,
47                     InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax))
48                 );
49                 (
50                     crate::base::codegen_operand(fx, in_value).load_scalar(fx),
51                     crate::base::codegen_place(fx, out_place.unwrap()),
52                 )
53             }
54             _ => unreachable!(),
55         };
56         let ebx_place = match operands[0] {
57             InlineAsmOperand::Out { reg, late: true, place } => {
58                 assert_eq!(
59                     reg,
60                     InlineAsmRegOrRegClass::RegClass(InlineAsmRegClass::X86(
61                         X86InlineAsmRegClass::reg
62                     ))
63                 );
64                 crate::base::codegen_place(fx, place.unwrap())
65             }
66             _ => unreachable!(),
67         };
68         let (sub_leaf, ecx_place) = match operands[2] {
69             InlineAsmOperand::InOut { reg, late: true, ref in_value, out_place } => {
70                 assert_eq!(
71                     reg,
72                     InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::cx))
73                 );
74                 (
75                     crate::base::codegen_operand(fx, in_value).load_scalar(fx),
76                     crate::base::codegen_place(fx, out_place.unwrap()),
77                 )
78             }
79             _ => unreachable!(),
80         };
81         let edx_place = match operands[3] {
82             InlineAsmOperand::Out { reg, late: true, place } => {
83                 assert_eq!(
84                     reg,
85                     InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::dx))
86                 );
87                 crate::base::codegen_place(fx, place.unwrap())
88             }
89             _ => unreachable!(),
90         };
91
92         let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, sub_leaf);
93
94         eax_place.write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32)));
95         ebx_place.write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32)));
96         ecx_place.write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32)));
97         edx_place.write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32)));
98         return;
99     } else if fx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") {
100         // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
101         crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
102     } else if fx.tcx.symbol_name(fx.instance).name == "__alloca" {
103         crate::trap::trap_unimplemented(fx, "Alloca is not supported");
104     }
105
106     let mut inputs = Vec::new();
107     let mut outputs = Vec::new();
108
109     let mut asm_gen = InlineAssemblyGenerator {
110         tcx: fx.tcx,
111         arch: InlineAsmArch::X86_64,
112         template,
113         operands,
114         options,
115         registers: Vec::new(),
116         stack_slots_clobber: Vec::new(),
117         stack_slots_input: Vec::new(),
118         stack_slots_output: Vec::new(),
119         stack_slot_size: Size::from_bytes(0),
120     };
121     asm_gen.allocate_registers();
122     asm_gen.allocate_stack_slots();
123
124     let inline_asm_index = fx.inline_asm_index;
125     fx.inline_asm_index += 1;
126     let asm_name = format!("{}__inline_asm_{}", fx.symbol_name, inline_asm_index);
127
128     let generated_asm = asm_gen.generate_asm_wrapper(&asm_name);
129     fx.cx.global_asm.push_str(&generated_asm);
130
131     for (i, operand) in operands.iter().enumerate() {
132         match *operand {
133             InlineAsmOperand::In { reg: _, ref value } => {
134                 inputs.push((
135                     asm_gen.stack_slots_input[i].unwrap(),
136                     crate::base::codegen_operand(fx, value).load_scalar(fx),
137                 ));
138             }
139             InlineAsmOperand::Out { reg: _, late: _, place } => {
140                 if let Some(place) = place {
141                     outputs.push((
142                         asm_gen.stack_slots_output[i].unwrap(),
143                         crate::base::codegen_place(fx, place),
144                     ));
145                 }
146             }
147             InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
148                 inputs.push((
149                     asm_gen.stack_slots_input[i].unwrap(),
150                     crate::base::codegen_operand(fx, in_value).load_scalar(fx),
151                 ));
152                 if let Some(out_place) = out_place {
153                     outputs.push((
154                         asm_gen.stack_slots_output[i].unwrap(),
155                         crate::base::codegen_place(fx, out_place),
156                     ));
157                 }
158             }
159             InlineAsmOperand::Const { value: _ } => todo!(),
160             InlineAsmOperand::SymFn { value: _ } => todo!(),
161             InlineAsmOperand::SymStatic { def_id: _ } => todo!(),
162         }
163     }
164
165     call_inline_asm(fx, &asm_name, asm_gen.stack_slot_size, inputs, outputs);
166 }
167
168 struct InlineAssemblyGenerator<'a, 'tcx> {
169     tcx: TyCtxt<'tcx>,
170     arch: InlineAsmArch,
171     template: &'a [InlineAsmTemplatePiece],
172     operands: &'a [InlineAsmOperand<'tcx>],
173     options: InlineAsmOptions,
174     registers: Vec<Option<InlineAsmReg>>,
175     stack_slots_clobber: Vec<Option<Size>>,
176     stack_slots_input: Vec<Option<Size>>,
177     stack_slots_output: Vec<Option<Size>>,
178     stack_slot_size: Size,
179 }
180
181 impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
182     fn allocate_registers(&mut self) {
183         let sess = self.tcx.sess;
184         let map = allocatable_registers(
185             self.arch,
186             |feature| sess.target_features.contains(&Symbol::intern(feature)),
187             &sess.target,
188         );
189         let mut allocated = FxHashMap::<_, (bool, bool)>::default();
190         let mut regs = vec![None; self.operands.len()];
191
192         // Add explicit registers to the allocated set.
193         for (i, operand) in self.operands.iter().enumerate() {
194             match *operand {
195                 InlineAsmOperand::In { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => {
196                     regs[i] = Some(reg);
197                     allocated.entry(reg).or_default().0 = true;
198                 }
199                 InlineAsmOperand::Out {
200                     reg: InlineAsmRegOrRegClass::Reg(reg), late: true, ..
201                 } => {
202                     regs[i] = Some(reg);
203                     allocated.entry(reg).or_default().1 = true;
204                 }
205                 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(reg), .. }
206                 | InlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => {
207                     regs[i] = Some(reg);
208                     allocated.insert(reg, (true, true));
209                 }
210                 _ => (),
211             }
212         }
213
214         // Allocate out/inout/inlateout registers first because they are more constrained.
215         for (i, operand) in self.operands.iter().enumerate() {
216             match *operand {
217                 InlineAsmOperand::Out {
218                     reg: InlineAsmRegOrRegClass::RegClass(class),
219                     late: false,
220                     ..
221                 }
222                 | InlineAsmOperand::InOut {
223                     reg: InlineAsmRegOrRegClass::RegClass(class), ..
224                 } => {
225                     let mut alloc_reg = None;
226                     for &reg in &map[&class] {
227                         let mut used = false;
228                         reg.overlapping_regs(|r| {
229                             if allocated.contains_key(&r) {
230                                 used = true;
231                             }
232                         });
233
234                         if !used {
235                             alloc_reg = Some(reg);
236                             break;
237                         }
238                     }
239
240                     let reg = alloc_reg.expect("cannot allocate registers");
241                     regs[i] = Some(reg);
242                     allocated.insert(reg, (true, true));
243                 }
244                 _ => (),
245             }
246         }
247
248         // Allocate in/lateout.
249         for (i, operand) in self.operands.iter().enumerate() {
250             match *operand {
251                 InlineAsmOperand::In { reg: InlineAsmRegOrRegClass::RegClass(class), .. } => {
252                     let mut alloc_reg = None;
253                     for &reg in &map[&class] {
254                         let mut used = false;
255                         reg.overlapping_regs(|r| {
256                             if allocated.get(&r).copied().unwrap_or_default().0 {
257                                 used = true;
258                             }
259                         });
260
261                         if !used {
262                             alloc_reg = Some(reg);
263                             break;
264                         }
265                     }
266
267                     let reg = alloc_reg.expect("cannot allocate registers");
268                     regs[i] = Some(reg);
269                     allocated.entry(reg).or_default().0 = true;
270                 }
271                 InlineAsmOperand::Out {
272                     reg: InlineAsmRegOrRegClass::RegClass(class),
273                     late: true,
274                     ..
275                 } => {
276                     let mut alloc_reg = None;
277                     for &reg in &map[&class] {
278                         let mut used = false;
279                         reg.overlapping_regs(|r| {
280                             if allocated.get(&r).copied().unwrap_or_default().1 {
281                                 used = true;
282                             }
283                         });
284
285                         if !used {
286                             alloc_reg = Some(reg);
287                             break;
288                         }
289                     }
290
291                     let reg = alloc_reg.expect("cannot allocate registers");
292                     regs[i] = Some(reg);
293                     allocated.entry(reg).or_default().1 = true;
294                 }
295                 _ => (),
296             }
297         }
298
299         self.registers = regs;
300     }
301
302     fn allocate_stack_slots(&mut self) {
303         let mut slot_size = Size::from_bytes(0);
304         let mut slots_clobber = vec![None; self.operands.len()];
305         let mut slots_input = vec![None; self.operands.len()];
306         let mut slots_output = vec![None; self.operands.len()];
307
308         let new_slot_fn = |slot_size: &mut Size, reg_class: InlineAsmRegClass| {
309             let reg_size = reg_class
310                 .supported_types(InlineAsmArch::X86_64)
311                 .iter()
312                 .map(|(ty, _)| ty.size())
313                 .max()
314                 .unwrap();
315             let align = rustc_target::abi::Align::from_bytes(reg_size.bytes()).unwrap();
316             let offset = slot_size.align_to(align);
317             *slot_size = offset + reg_size;
318             offset
319         };
320         let mut new_slot = |x| new_slot_fn(&mut slot_size, x);
321
322         // Allocate stack slots for saving clobbered registers
323         let abi_clobber =
324             InlineAsmClobberAbi::parse(self.arch, &self.tcx.sess.target, Symbol::intern("C"))
325                 .unwrap()
326                 .clobbered_regs();
327         for (i, reg) in self.registers.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))) {
328             let mut need_save = true;
329             // If the register overlaps with a register clobbered by function call, then
330             // we don't need to save it.
331             for r in abi_clobber {
332                 r.overlapping_regs(|r| {
333                     if r == reg {
334                         need_save = false;
335                     }
336                 });
337
338                 if !need_save {
339                     break;
340                 }
341             }
342
343             if need_save {
344                 slots_clobber[i] = Some(new_slot(reg.reg_class()));
345             }
346         }
347
348         // Allocate stack slots for inout
349         for (i, operand) in self.operands.iter().enumerate() {
350             match *operand {
351                 InlineAsmOperand::InOut { reg, out_place: Some(_), .. } => {
352                     let slot = new_slot(reg.reg_class());
353                     slots_input[i] = Some(slot);
354                     slots_output[i] = Some(slot);
355                 }
356                 _ => (),
357             }
358         }
359
360         let slot_size_before_input = slot_size;
361         let mut new_slot = |x| new_slot_fn(&mut slot_size, x);
362
363         // Allocate stack slots for input
364         for (i, operand) in self.operands.iter().enumerate() {
365             match *operand {
366                 InlineAsmOperand::In { reg, .. }
367                 | InlineAsmOperand::InOut { reg, out_place: None, .. } => {
368                     slots_input[i] = Some(new_slot(reg.reg_class()));
369                 }
370                 _ => (),
371             }
372         }
373
374         // Reset slot size to before input so that input and output operands can overlap
375         // and save some memory.
376         let slot_size_after_input = slot_size;
377         slot_size = slot_size_before_input;
378         let mut new_slot = |x| new_slot_fn(&mut slot_size, x);
379
380         // Allocate stack slots for output
381         for (i, operand) in self.operands.iter().enumerate() {
382             match *operand {
383                 InlineAsmOperand::Out { reg, place: Some(_), .. } => {
384                     slots_output[i] = Some(new_slot(reg.reg_class()));
385                 }
386                 _ => (),
387             }
388         }
389
390         slot_size = slot_size.max(slot_size_after_input);
391
392         self.stack_slots_clobber = slots_clobber;
393         self.stack_slots_input = slots_input;
394         self.stack_slots_output = slots_output;
395         self.stack_slot_size = slot_size;
396     }
397
398     fn generate_asm_wrapper(&self, asm_name: &str) -> String {
399         let mut generated_asm = String::new();
400         writeln!(generated_asm, ".globl {}", asm_name).unwrap();
401         writeln!(generated_asm, ".type {},@function", asm_name).unwrap();
402         writeln!(generated_asm, ".section .text.{},\"ax\",@progbits", asm_name).unwrap();
403         writeln!(generated_asm, "{}:", asm_name).unwrap();
404
405         let is_x86 = matches!(self.arch, InlineAsmArch::X86 | InlineAsmArch::X86_64);
406
407         if is_x86 {
408             generated_asm.push_str(".intel_syntax noprefix\n");
409         }
410         Self::prologue(&mut generated_asm, self.arch);
411
412         // Save clobbered registers
413         if !self.options.contains(InlineAsmOptions::NORETURN) {
414             for (reg, slot) in self
415                 .registers
416                 .iter()
417                 .zip(self.stack_slots_clobber.iter().copied())
418                 .filter_map(|(r, s)| r.zip(s))
419             {
420                 Self::save_register(&mut generated_asm, self.arch, reg, slot);
421             }
422         }
423
424         // Write input registers
425         for (reg, slot) in self
426             .registers
427             .iter()
428             .zip(self.stack_slots_input.iter().copied())
429             .filter_map(|(r, s)| r.zip(s))
430         {
431             Self::restore_register(&mut generated_asm, self.arch, reg, slot);
432         }
433
434         if is_x86 && self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
435             generated_asm.push_str(".att_syntax\n");
436         }
437
438         // The actual inline asm
439         for piece in self.template {
440             match piece {
441                 InlineAsmTemplatePiece::String(s) => {
442                     generated_asm.push_str(s);
443                 }
444                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
445                     self.registers[*operand_idx]
446                         .unwrap()
447                         .emit(&mut generated_asm, self.arch, *modifier)
448                         .unwrap();
449                 }
450             }
451         }
452         generated_asm.push('\n');
453
454         if is_x86 && self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
455             generated_asm.push_str(".intel_syntax noprefix\n");
456         }
457
458         if !self.options.contains(InlineAsmOptions::NORETURN) {
459             // Read output registers
460             for (reg, slot) in self
461                 .registers
462                 .iter()
463                 .zip(self.stack_slots_output.iter().copied())
464                 .filter_map(|(r, s)| r.zip(s))
465             {
466                 Self::save_register(&mut generated_asm, self.arch, reg, slot);
467             }
468
469             // Restore clobbered registers
470             for (reg, slot) in self
471                 .registers
472                 .iter()
473                 .zip(self.stack_slots_clobber.iter().copied())
474                 .filter_map(|(r, s)| r.zip(s))
475             {
476                 Self::restore_register(&mut generated_asm, self.arch, reg, slot);
477             }
478
479             Self::epilogue(&mut generated_asm, self.arch);
480         } else {
481             Self::epilogue_noreturn(&mut generated_asm, self.arch);
482         }
483
484         if is_x86 {
485             generated_asm.push_str(".att_syntax\n");
486         }
487         writeln!(generated_asm, ".size {name}, .-{name}", name = asm_name).unwrap();
488         generated_asm.push_str(".text\n");
489         generated_asm.push_str("\n\n");
490
491         generated_asm
492     }
493
494     fn prologue(generated_asm: &mut String, arch: InlineAsmArch) {
495         match arch {
496             InlineAsmArch::X86_64 => {
497                 generated_asm.push_str("    push rbp\n");
498                 generated_asm.push_str("    mov rbp,rdi\n");
499             }
500             _ => unimplemented!("prologue for {:?}", arch),
501         }
502     }
503
504     fn epilogue(generated_asm: &mut String, arch: InlineAsmArch) {
505         match arch {
506             InlineAsmArch::X86_64 => {
507                 generated_asm.push_str("    pop rbp\n");
508                 generated_asm.push_str("    ret\n");
509             }
510             _ => unimplemented!("epilogue for {:?}", arch),
511         }
512     }
513
514     fn epilogue_noreturn(generated_asm: &mut String, arch: InlineAsmArch) {
515         match arch {
516             InlineAsmArch::X86_64 => {
517                 generated_asm.push_str("    ud2\n");
518             }
519             _ => unimplemented!("epilogue_noreturn for {:?}", arch),
520         }
521     }
522
523     fn save_register(
524         generated_asm: &mut String,
525         arch: InlineAsmArch,
526         reg: InlineAsmReg,
527         offset: Size,
528     ) {
529         match arch {
530             InlineAsmArch::X86_64 => {
531                 write!(generated_asm, "    mov [rbp+0x{:x}], ", offset.bytes()).unwrap();
532                 reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
533                 generated_asm.push('\n');
534             }
535             _ => unimplemented!("save_register for {:?}", arch),
536         }
537     }
538
539     fn restore_register(
540         generated_asm: &mut String,
541         arch: InlineAsmArch,
542         reg: InlineAsmReg,
543         offset: Size,
544     ) {
545         match arch {
546             InlineAsmArch::X86_64 => {
547                 generated_asm.push_str("    mov ");
548                 reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
549                 writeln!(generated_asm, ", [rbp+0x{:x}]", offset.bytes()).unwrap();
550             }
551             _ => unimplemented!("restore_register for {:?}", arch),
552         }
553     }
554 }
555
556 fn call_inline_asm<'tcx>(
557     fx: &mut FunctionCx<'_, '_, 'tcx>,
558     asm_name: &str,
559     slot_size: Size,
560     inputs: Vec<(Size, Value)>,
561     outputs: Vec<(Size, CPlace<'tcx>)>,
562 ) {
563     let stack_slot = fx.bcx.func.create_stack_slot(StackSlotData {
564         kind: StackSlotKind::ExplicitSlot,
565         size: u32::try_from(slot_size.bytes()).unwrap(),
566     });
567     if fx.clif_comments.enabled() {
568         fx.add_comment(stack_slot, "inline asm scratch slot");
569     }
570
571     let inline_asm_func = fx
572         .module
573         .declare_function(
574             asm_name,
575             Linkage::Import,
576             &Signature {
577                 call_conv: CallConv::SystemV,
578                 params: vec![AbiParam::new(fx.pointer_type)],
579                 returns: vec![],
580             },
581         )
582         .unwrap();
583     let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
584     if fx.clif_comments.enabled() {
585         fx.add_comment(inline_asm_func, asm_name);
586     }
587
588     for (offset, value) in inputs {
589         fx.bcx.ins().stack_store(value, stack_slot, i32::try_from(offset.bytes()).unwrap());
590     }
591
592     let stack_slot_addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0);
593     fx.bcx.ins().call(inline_asm_func, &[stack_slot_addr]);
594
595     for (offset, place) in outputs {
596         let ty = fx.clif_type(place.layout().ty).unwrap();
597         let value = fx.bcx.ins().stack_load(ty, stack_slot, i32::try_from(offset.bytes()).unwrap());
598         place.write_cvalue(fx, CValue::by_val(value, place.layout()));
599     }
600 }