1 use crate::{ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt};
4 AbiSpecifiedMultipleTimes, AttSyntaxOnlyX86, ClobberAbiNotSupported,
5 InlineAsmUnsupportedTarget, InvalidAbiClobberAbi, InvalidAsmTemplateModifierConst,
6 InvalidAsmTemplateModifierRegClass, InvalidAsmTemplateModifierRegClassSub,
7 InvalidAsmTemplateModifierSym, InvalidRegister, InvalidRegisterClass, RegisterClassOnlyClobber,
10 use super::LoweringContext;
12 use rustc_ast::ptr::P;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::definitions::DefPathData;
18 use rustc_session::parse::feature_err;
19 use rustc_span::{sym, Span};
20 use rustc_target::asm;
21 use std::collections::hash_map::Entry;
24 impl<'a, 'hir> LoweringContext<'a, 'hir> {
25 pub(crate) fn lower_inline_asm(
29 ) -> &'hir hir::InlineAsm<'hir> {
30 // Rustdoc needs to support asm! from foreign architectures: don't try
31 // lowering the register constraints in this case.
33 if self.tcx.sess.opts.actually_rustdoc { None } else { self.tcx.sess.asm_arch };
34 if asm_arch.is_none() && !self.tcx.sess.opts.actually_rustdoc {
35 self.tcx.sess.emit_err(InlineAsmUnsupportedTarget { span: sp });
37 if let Some(asm_arch) = asm_arch {
38 // Inline assembly is currently only stable for these architectures.
39 let is_stable = matches!(
41 asm::InlineAsmArch::X86
42 | asm::InlineAsmArch::X86_64
43 | asm::InlineAsmArch::Arm
44 | asm::InlineAsmArch::AArch64
45 | asm::InlineAsmArch::RiscV32
46 | asm::InlineAsmArch::RiscV64
48 if !is_stable && !self.tcx.features().asm_experimental_arch {
50 &self.tcx.sess.parse_sess,
51 sym::asm_experimental_arch,
53 "inline assembly is not stable yet on this architecture",
58 if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
59 && !matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64))
60 && !self.tcx.sess.opts.actually_rustdoc
62 self.tcx.sess.emit_err(AttSyntaxOnlyX86 { span: sp });
64 if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind {
66 &self.tcx.sess.parse_sess,
69 "the `may_unwind` option is unstable",
74 let mut clobber_abis = FxIndexMap::default();
75 if let Some(asm_arch) = asm_arch {
76 for (abi_name, abi_span) in &asm.clobber_abis {
77 match asm::InlineAsmClobberAbi::parse(asm_arch, &self.tcx.sess.target, *abi_name) {
79 // If the abi was already in the list, emit an error
80 match clobber_abis.get(&abi) {
81 Some((prev_name, prev_sp)) => {
82 // Multiple different abi names may actually be the same ABI
83 // If the specified ABIs are not the same name, alert the user that they resolve to the same ABI
84 let source_map = self.tcx.sess.source_map();
85 let equivalent = (source_map.span_to_snippet(*prev_sp)
86 != source_map.span_to_snippet(*abi_span))
89 self.tcx.sess.emit_err(AbiSpecifiedMultipleTimes {
91 prev_name: *prev_name,
97 clobber_abis.insert(abi, (*abi_name, *abi_span));
102 self.tcx.sess.emit_err(ClobberAbiNotSupported { abi_span: *abi_span });
104 Err(supported_abis) => {
105 let mut abis = format!("`{}`", supported_abis[0]);
106 for m in &supported_abis[1..] {
107 let _ = write!(abis, ", `{}`", m);
109 self.tcx.sess.emit_err(InvalidAbiClobberAbi {
111 supported_abis: abis,
118 // Lower operands to HIR. We use dummy register classes if an error
119 // occurs during lowering because we still need to be able to produce a
121 let sess = self.tcx.sess;
122 let mut operands: Vec<_> = asm
126 let lower_reg = |®: &_| match reg {
127 InlineAsmRegOrRegClass::Reg(reg) => {
128 asm::InlineAsmRegOrRegClass::Reg(if let Some(asm_arch) = asm_arch {
129 asm::InlineAsmReg::parse(asm_arch, reg).unwrap_or_else(|error| {
130 sess.emit_err(InvalidRegister { op_span: *op_sp, reg, error });
131 asm::InlineAsmReg::Err
134 asm::InlineAsmReg::Err
137 InlineAsmRegOrRegClass::RegClass(reg_class) => {
138 asm::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch {
139 asm::InlineAsmRegClass::parse(asm_arch, reg_class).unwrap_or_else(
141 sess.emit_err(InvalidRegisterClass {
146 asm::InlineAsmRegClass::Err
150 asm::InlineAsmRegClass::Err
156 InlineAsmOperand::In { reg, expr } => hir::InlineAsmOperand::In {
158 expr: self.lower_expr(expr),
160 InlineAsmOperand::Out { reg, late, expr } => hir::InlineAsmOperand::Out {
163 expr: expr.as_ref().map(|expr| self.lower_expr(expr)),
165 InlineAsmOperand::InOut { reg, late, expr } => hir::InlineAsmOperand::InOut {
168 expr: self.lower_expr(expr),
170 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
171 hir::InlineAsmOperand::SplitInOut {
174 in_expr: self.lower_expr(in_expr),
175 out_expr: out_expr.as_ref().map(|expr| self.lower_expr(expr)),
178 InlineAsmOperand::Const { anon_const } => {
179 if !self.tcx.features().asm_const {
184 "const operands for inline assembly are unstable",
188 hir::InlineAsmOperand::Const {
189 anon_const: self.lower_anon_const(anon_const),
192 InlineAsmOperand::Sym { sym } => {
193 let static_def_id = self
195 .get_partial_res(sym.id)
196 .and_then(|res| res.full_res())
197 .and_then(|res| match res {
198 Res::Def(DefKind::Static(_), def_id) => Some(def_id),
202 if let Some(def_id) = static_def_id {
203 let path = self.lower_qpath(
208 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
210 hir::InlineAsmOperand::SymStatic { path, def_id }
212 // Replace the InlineAsmSym AST node with an
213 // Expr using the name node id.
216 kind: ExprKind::Path(sym.qself.clone(), sym.path.clone()),
218 attrs: AttrVec::new(),
222 // Wrap the expression in an AnonConst.
223 let parent_def_id = self.current_hir_id_owner;
224 let node_id = self.next_node_id();
226 parent_def_id.def_id,
228 DefPathData::AnonConst,
231 let anon_const = AnonConst { id: node_id, value: P(expr) };
232 hir::InlineAsmOperand::SymFn {
233 anon_const: self.lower_anon_const(&anon_const),
238 (op, self.lower_span(*op_sp))
242 // Validate template modifiers against the register classes for the operands
243 for p in &asm.template {
244 if let InlineAsmTemplatePiece::Placeholder {
246 modifier: Some(modifier),
247 span: placeholder_span,
250 let op_sp = asm.operands[operand_idx].1;
251 match &operands[operand_idx].0 {
252 hir::InlineAsmOperand::In { reg, .. }
253 | hir::InlineAsmOperand::Out { reg, .. }
254 | hir::InlineAsmOperand::InOut { reg, .. }
255 | hir::InlineAsmOperand::SplitInOut { reg, .. } => {
256 let class = reg.reg_class();
257 if class == asm::InlineAsmRegClass::Err {
260 let valid_modifiers = class.valid_modifiers(asm_arch.unwrap());
261 if !valid_modifiers.contains(&modifier) {
262 let sub = if !valid_modifiers.is_empty() {
263 let mut mods = format!("`{}`", valid_modifiers[0]);
264 for m in &valid_modifiers[1..] {
265 let _ = write!(mods, ", `{}`", m);
267 InvalidAsmTemplateModifierRegClassSub::SupportModifier {
268 class_name: class.name(),
272 InvalidAsmTemplateModifierRegClassSub::DoesNotSupportModifier {
273 class_name: class.name(),
276 sess.emit_err(InvalidAsmTemplateModifierRegClass {
283 hir::InlineAsmOperand::Const { .. } => {
284 sess.emit_err(InvalidAsmTemplateModifierConst {
289 hir::InlineAsmOperand::SymFn { .. }
290 | hir::InlineAsmOperand::SymStatic { .. } => {
291 sess.emit_err(InvalidAsmTemplateModifierSym {
300 let mut used_input_regs = FxHashMap::default();
301 let mut used_output_regs = FxHashMap::default();
303 for (idx, &(ref op, op_sp)) in operands.iter().enumerate() {
304 if let Some(reg) = op.reg() {
305 let reg_class = reg.reg_class();
306 if reg_class == asm::InlineAsmRegClass::Err {
310 // Some register classes can only be used as clobbers. This
311 // means that we disallow passing a value in/out of the asm and
312 // require that the operand name an explicit register, not a
314 if reg_class.is_clobber_only(asm_arch.unwrap()) && !op.is_clobber() {
315 sess.emit_err(RegisterClassOnlyClobber {
317 reg_class_name: reg_class.name(),
322 // Check for conflicts between explicit register operands.
323 if let asm::InlineAsmRegOrRegClass::Reg(reg) = reg {
324 let (input, output) = match op {
325 hir::InlineAsmOperand::In { .. } => (true, false),
327 // Late output do not conflict with inputs, but normal outputs do
328 hir::InlineAsmOperand::Out { late, .. } => (!late, true),
330 hir::InlineAsmOperand::InOut { .. }
331 | hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
333 hir::InlineAsmOperand::Const { .. }
334 | hir::InlineAsmOperand::SymFn { .. }
335 | hir::InlineAsmOperand::SymStatic { .. } => {
340 // Flag to output the error only once per operand
341 let mut skip = false;
342 reg.overlapping_regs(|r| {
343 let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
345 match used_regs.entry(r) {
346 Entry::Occupied(o) => {
353 let (ref op2, op_sp2) = operands[idx2];
354 let Some(asm::InlineAsmRegOrRegClass::Reg(reg2)) = op2.reg() else {
358 let in_out = match (op, op2) {
360 hir::InlineAsmOperand::In { .. },
361 hir::InlineAsmOperand::Out { late, .. },
364 hir::InlineAsmOperand::Out { late, .. },
365 hir::InlineAsmOperand::In { .. },
368 let out_op_sp = if input { op_sp2 } else { op_sp };
374 sess.emit_err(RegisterConflict {
377 reg1_name: reg.name(),
378 reg2_name: reg2.name(),
382 Entry::Vacant(v) => {
390 check(&mut used_input_regs, true);
393 check(&mut used_output_regs, false);
400 // If a clobber_abi is specified, add the necessary clobbers to the
402 let mut clobbered = FxHashSet::default();
403 for (abi, (_, abi_span)) in clobber_abis {
404 for &clobber in abi.clobbered_regs() {
405 // Don't emit a clobber for a register already clobbered
406 if clobbered.contains(&clobber) {
410 let mut output_used = false;
411 clobber.overlapping_regs(|reg| {
412 if used_output_regs.contains_key(®) {
419 hir::InlineAsmOperand::Out {
420 reg: asm::InlineAsmRegOrRegClass::Reg(clobber),
424 self.lower_span(abi_span),
426 clobbered.insert(clobber);
431 let operands = self.arena.alloc_from_iter(operands);
432 let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
433 let template_strs = self.arena.alloc_from_iter(
436 .map(|(sym, snippet, span)| (*sym, *snippet, self.lower_span(*span))),
439 self.arena.alloc_from_iter(asm.line_spans.iter().map(|span| self.lower_span(*span)));
441 hir::InlineAsm { template, template_strs, operands, options: asm.options, line_spans };
442 self.arena.alloc(hir_asm)