|
| 1 | +use rustc_attr::InstructionSetAttr; |
| 2 | +use rustc_middle::mir::mono::{Linkage, MonoItem, MonoItemData, Visibility}; |
| 3 | +use rustc_middle::mir::{Body, InlineAsmOperand}; |
| 4 | +use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf}; |
| 5 | +use rustc_middle::ty::{Instance, TyCtxt}; |
| 6 | +use rustc_middle::{bug, ty}; |
| 7 | +use rustc_span::sym; |
| 8 | + |
| 9 | +use crate::common; |
| 10 | +use crate::traits::{AsmCodegenMethods, BuilderMethods, GlobalAsmOperandRef, MiscCodegenMethods}; |
| 11 | + |
| 12 | +pub(crate) fn codegen_naked_asm<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( |
| 13 | + cx: &'a Bx::CodegenCx, |
| 14 | + mir: &Body<'tcx>, |
| 15 | + instance: Instance<'tcx>, |
| 16 | +) { |
| 17 | + let rustc_middle::mir::TerminatorKind::InlineAsm { |
| 18 | + asm_macro: _, |
| 19 | + template, |
| 20 | + ref operands, |
| 21 | + options, |
| 22 | + line_spans, |
| 23 | + targets: _, |
| 24 | + unwind: _, |
| 25 | + } = mir.basic_blocks.iter().next().unwrap().terminator().kind |
| 26 | + else { |
| 27 | + bug!("#[naked] functions should always terminate with an asm! block") |
| 28 | + }; |
| 29 | + |
| 30 | + let operands: Vec<_> = |
| 31 | + operands.iter().map(|op| inline_to_global_operand::<Bx>(cx, instance, op)).collect(); |
| 32 | + |
| 33 | + let item_data = cx.codegen_unit().items().get(&MonoItem::Fn(instance)).unwrap(); |
| 34 | + let name = cx.mangled_name(instance); |
| 35 | + let (begin, end) = prefix_and_suffix(cx.tcx(), instance, &name, item_data); |
| 36 | + |
| 37 | + let mut template_vec = Vec::new(); |
| 38 | + template_vec.push(rustc_ast::ast::InlineAsmTemplatePiece::String(begin.into())); |
| 39 | + template_vec.extend(template.iter().cloned()); |
| 40 | + template_vec.push(rustc_ast::ast::InlineAsmTemplatePiece::String(end.into())); |
| 41 | + |
| 42 | + cx.codegen_global_asm(&template_vec, &operands, options, line_spans); |
| 43 | +} |
| 44 | + |
| 45 | +fn inline_to_global_operand<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( |
| 46 | + cx: &'a Bx::CodegenCx, |
| 47 | + instance: Instance<'tcx>, |
| 48 | + op: &InlineAsmOperand<'tcx>, |
| 49 | +) -> GlobalAsmOperandRef<'tcx> { |
| 50 | + match op { |
| 51 | + InlineAsmOperand::Const { value } => { |
| 52 | + let const_value = instance |
| 53 | + .instantiate_mir_and_normalize_erasing_regions( |
| 54 | + cx.tcx(), |
| 55 | + cx.typing_env(), |
| 56 | + ty::EarlyBinder::bind(value.const_), |
| 57 | + ) |
| 58 | + .eval(cx.tcx(), cx.typing_env(), value.span) |
| 59 | + .expect("erroneous constant missed by mono item collection"); |
| 60 | + |
| 61 | + let mono_type = instance.instantiate_mir_and_normalize_erasing_regions( |
| 62 | + cx.tcx(), |
| 63 | + cx.typing_env(), |
| 64 | + ty::EarlyBinder::bind(value.ty()), |
| 65 | + ); |
| 66 | + |
| 67 | + let string = common::asm_const_to_str( |
| 68 | + cx.tcx(), |
| 69 | + value.span, |
| 70 | + const_value, |
| 71 | + cx.layout_of(mono_type), |
| 72 | + ); |
| 73 | + |
| 74 | + GlobalAsmOperandRef::Const { string } |
| 75 | + } |
| 76 | + InlineAsmOperand::SymFn { value } => { |
| 77 | + let mono_type = instance.instantiate_mir_and_normalize_erasing_regions( |
| 78 | + cx.tcx(), |
| 79 | + cx.typing_env(), |
| 80 | + ty::EarlyBinder::bind(value.ty()), |
| 81 | + ); |
| 82 | + |
| 83 | + let instance = match mono_type.kind() { |
| 84 | + &ty::FnDef(def_id, args) => Instance::new(def_id, args), |
| 85 | + _ => bug!("asm sym is not a function"), |
| 86 | + }; |
| 87 | + |
| 88 | + GlobalAsmOperandRef::SymFn { instance } |
| 89 | + } |
| 90 | + InlineAsmOperand::SymStatic { def_id } => { |
| 91 | + GlobalAsmOperandRef::SymStatic { def_id: *def_id } |
| 92 | + } |
| 93 | + InlineAsmOperand::In { .. } |
| 94 | + | InlineAsmOperand::Out { .. } |
| 95 | + | InlineAsmOperand::InOut { .. } |
| 96 | + | InlineAsmOperand::Label { .. } => { |
| 97 | + bug!("invalid operand type for naked_asm!") |
| 98 | + } |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +enum AsmBinaryFormat { |
| 103 | + Elf, |
| 104 | + Macho, |
| 105 | + Coff, |
| 106 | +} |
| 107 | + |
| 108 | +impl AsmBinaryFormat { |
| 109 | + fn from_target(target: &rustc_target::spec::Target) -> Self { |
| 110 | + if target.is_like_windows { |
| 111 | + Self::Coff |
| 112 | + } else if target.is_like_osx { |
| 113 | + Self::Macho |
| 114 | + } else { |
| 115 | + Self::Elf |
| 116 | + } |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +fn prefix_and_suffix<'tcx>( |
| 121 | + tcx: TyCtxt<'tcx>, |
| 122 | + instance: Instance<'tcx>, |
| 123 | + asm_name: &str, |
| 124 | + item_data: &MonoItemData, |
| 125 | +) -> (String, String) { |
| 126 | + use std::fmt::Write; |
| 127 | + |
| 128 | + let asm_binary_format = AsmBinaryFormat::from_target(&tcx.sess.target); |
| 129 | + |
| 130 | + let is_arm = tcx.sess.target.arch == "arm"; |
| 131 | + let is_thumb = tcx.sess.unstable_target_features.contains(&sym::thumb_mode); |
| 132 | + |
| 133 | + let attrs = tcx.codegen_fn_attrs(instance.def_id()); |
| 134 | + let link_section = attrs.link_section.map(|symbol| symbol.as_str().to_string()); |
| 135 | + let align = attrs.alignment.map(|a| a.bytes()).unwrap_or(4); |
| 136 | + |
| 137 | + // See https://sourceware.org/binutils/docs/as/ARM-Directives.html for info on these directives. |
| 138 | + // In particular, `.arm` can also be written `.code 32` and `.thumb` as `.code 16`. |
| 139 | + let (arch_prefix, arch_suffix) = if is_arm { |
| 140 | + ( |
| 141 | + match attrs.instruction_set { |
| 142 | + None => match is_thumb { |
| 143 | + true => ".thumb\n.thumb_func", |
| 144 | + false => ".arm", |
| 145 | + }, |
| 146 | + Some(InstructionSetAttr::ArmT32) => ".thumb\n.thumb_func", |
| 147 | + Some(InstructionSetAttr::ArmA32) => ".arm", |
| 148 | + }, |
| 149 | + match is_thumb { |
| 150 | + true => ".thumb", |
| 151 | + false => ".arm", |
| 152 | + }, |
| 153 | + ) |
| 154 | + } else { |
| 155 | + ("", "") |
| 156 | + }; |
| 157 | + |
| 158 | + let emit_fatal = |msg| tcx.dcx().span_fatal(tcx.def_span(instance.def_id()), msg); |
| 159 | + |
| 160 | + // see https://godbolt.org/z/cPK4sxKor. |
| 161 | + let write_linkage = |w: &mut String| -> std::fmt::Result { |
| 162 | + match item_data.linkage { |
| 163 | + Linkage::External => { |
| 164 | + writeln!(w, ".globl {asm_name}")?; |
| 165 | + } |
| 166 | + Linkage::LinkOnceAny | Linkage::LinkOnceODR | Linkage::WeakAny | Linkage::WeakODR => { |
| 167 | + match asm_binary_format { |
| 168 | + AsmBinaryFormat::Elf | AsmBinaryFormat::Coff => { |
| 169 | + writeln!(w, ".weak {asm_name}")?; |
| 170 | + } |
| 171 | + AsmBinaryFormat::Macho => { |
| 172 | + writeln!(w, ".globl {asm_name}")?; |
| 173 | + writeln!(w, ".weak_definition {asm_name}")?; |
| 174 | + } |
| 175 | + } |
| 176 | + } |
| 177 | + Linkage::Internal | Linkage::Private => { |
| 178 | + // write nothing |
| 179 | + } |
| 180 | + Linkage::Appending => emit_fatal("Only global variables can have appending linkage!"), |
| 181 | + Linkage::Common => emit_fatal("Functions may not have common linkage"), |
| 182 | + Linkage::AvailableExternally => { |
| 183 | + // this would make the function equal an extern definition |
| 184 | + emit_fatal("Functions may not have available_externally linkage") |
| 185 | + } |
| 186 | + Linkage::ExternalWeak => { |
| 187 | + // FIXME: actually this causes a SIGILL in LLVM |
| 188 | + emit_fatal("Functions may not have external weak linkage") |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + Ok(()) |
| 193 | + }; |
| 194 | + |
| 195 | + let mut begin = String::new(); |
| 196 | + let mut end = String::new(); |
| 197 | + match asm_binary_format { |
| 198 | + AsmBinaryFormat::Elf => { |
| 199 | + let section = link_section.unwrap_or(format!(".text.{asm_name}")); |
| 200 | + |
| 201 | + let progbits = match is_arm { |
| 202 | + true => "%progbits", |
| 203 | + false => "@progbits", |
| 204 | + }; |
| 205 | + |
| 206 | + let function = match is_arm { |
| 207 | + true => "%function", |
| 208 | + false => "@function", |
| 209 | + }; |
| 210 | + |
| 211 | + writeln!(begin, ".pushsection {section},\"ax\", {progbits}").unwrap(); |
| 212 | + writeln!(begin, ".balign {align}").unwrap(); |
| 213 | + write_linkage(&mut begin).unwrap(); |
| 214 | + if let Visibility::Hidden = item_data.visibility { |
| 215 | + writeln!(begin, ".hidden {asm_name}").unwrap(); |
| 216 | + } |
| 217 | + writeln!(begin, ".type {asm_name}, {function}").unwrap(); |
| 218 | + if !arch_prefix.is_empty() { |
| 219 | + writeln!(begin, "{}", arch_prefix).unwrap(); |
| 220 | + } |
| 221 | + writeln!(begin, "{asm_name}:").unwrap(); |
| 222 | + |
| 223 | + writeln!(end).unwrap(); |
| 224 | + writeln!(end, ".size {asm_name}, . - {asm_name}").unwrap(); |
| 225 | + writeln!(end, ".popsection").unwrap(); |
| 226 | + if !arch_suffix.is_empty() { |
| 227 | + writeln!(end, "{}", arch_suffix).unwrap(); |
| 228 | + } |
| 229 | + } |
| 230 | + AsmBinaryFormat::Macho => { |
| 231 | + let section = link_section.unwrap_or("__TEXT,__text".to_string()); |
| 232 | + writeln!(begin, ".pushsection {},regular,pure_instructions", section).unwrap(); |
| 233 | + writeln!(begin, ".balign {align}").unwrap(); |
| 234 | + write_linkage(&mut begin).unwrap(); |
| 235 | + if let Visibility::Hidden = item_data.visibility { |
| 236 | + writeln!(begin, ".private_extern {asm_name}").unwrap(); |
| 237 | + } |
| 238 | + writeln!(begin, "{asm_name}:").unwrap(); |
| 239 | + |
| 240 | + writeln!(end).unwrap(); |
| 241 | + writeln!(end, ".popsection").unwrap(); |
| 242 | + if !arch_suffix.is_empty() { |
| 243 | + writeln!(end, "{}", arch_suffix).unwrap(); |
| 244 | + } |
| 245 | + } |
| 246 | + AsmBinaryFormat::Coff => { |
| 247 | + let section = link_section.unwrap_or(format!(".text.{asm_name}")); |
| 248 | + writeln!(begin, ".pushsection {},\"xr\"", section).unwrap(); |
| 249 | + writeln!(begin, ".balign {align}").unwrap(); |
| 250 | + write_linkage(&mut begin).unwrap(); |
| 251 | + writeln!(begin, ".def {asm_name}").unwrap(); |
| 252 | + writeln!(begin, ".scl 2").unwrap(); |
| 253 | + writeln!(begin, ".type 32").unwrap(); |
| 254 | + writeln!(begin, ".endef {asm_name}").unwrap(); |
| 255 | + writeln!(begin, "{asm_name}:").unwrap(); |
| 256 | + |
| 257 | + writeln!(end).unwrap(); |
| 258 | + writeln!(end, ".popsection").unwrap(); |
| 259 | + if !arch_suffix.is_empty() { |
| 260 | + writeln!(end, "{}", arch_suffix).unwrap(); |
| 261 | + } |
| 262 | + } |
| 263 | + } |
| 264 | + |
| 265 | + (begin, end) |
| 266 | +} |
0 commit comments