]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/asm.rs
more clippy fixes
[rust.git] / compiler / rustc_ast_lowering / src / asm.rs
1 use super::LoweringContext;
2
3 use rustc_ast::*;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::struct_span_err;
6 use rustc_hir as hir;
7 use rustc_span::{Span, Symbol};
8 use rustc_target::asm;
9 use std::collections::hash_map::Entry;
10 use std::fmt::Write;
11
12 impl<'a, 'hir> LoweringContext<'a, 'hir> {
13     crate fn lower_inline_asm(&mut self, sp: Span, asm: &InlineAsm) -> &'hir hir::InlineAsm<'hir> {
14         // Rustdoc needs to support asm! from foreign architectures: don't try
15         // lowering the register constraints in this case.
16         let asm_arch = if self.sess.opts.actually_rustdoc { None } else { self.sess.asm_arch };
17         if asm_arch.is_none() && !self.sess.opts.actually_rustdoc {
18             struct_span_err!(self.sess, sp, E0472, "inline assembly is unsupported on this target")
19                 .emit();
20         }
21         if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
22             && !matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64))
23             && !self.sess.opts.actually_rustdoc
24         {
25             self.sess
26                 .struct_span_err(sp, "the `att_syntax` option is only supported on x86")
27                 .emit();
28         }
29
30         let mut clobber_abi = None;
31         if let Some(asm_arch) = asm_arch {
32             if let Some((abi_name, abi_span)) = asm.clobber_abi {
33                 match asm::InlineAsmClobberAbi::parse(asm_arch, &self.sess.target, abi_name) {
34                     Ok(abi) => clobber_abi = Some((abi, abi_span)),
35                     Err(&[]) => {
36                         self.sess
37                             .struct_span_err(
38                                 abi_span,
39                                 "`clobber_abi` is not supported on this target",
40                             )
41                             .emit();
42                     }
43                     Err(supported_abis) => {
44                         let mut err =
45                             self.sess.struct_span_err(abi_span, "invalid ABI for `clobber_abi`");
46                         let mut abis = format!("`{}`", supported_abis[0]);
47                         for m in &supported_abis[1..] {
48                             let _ = write!(abis, ", `{}`", m);
49                         }
50                         err.note(&format!(
51                             "the following ABIs are supported on this target: {}",
52                             abis
53                         ));
54                         err.emit();
55                     }
56                 }
57             }
58         }
59
60         // Lower operands to HIR. We use dummy register classes if an error
61         // occurs during lowering because we still need to be able to produce a
62         // valid HIR.
63         let sess = self.sess;
64         let mut operands: Vec<_> = asm
65             .operands
66             .iter()
67             .map(|(op, op_sp)| {
68                 let lower_reg = |reg| match reg {
69                     InlineAsmRegOrRegClass::Reg(s) => {
70                         asm::InlineAsmRegOrRegClass::Reg(if let Some(asm_arch) = asm_arch {
71                             asm::InlineAsmReg::parse(
72                                 asm_arch,
73                                 |feature| sess.target_features.contains(&Symbol::intern(feature)),
74                                 &sess.target,
75                                 s,
76                             )
77                             .unwrap_or_else(|e| {
78                                 let msg = format!("invalid register `{}`: {}", s.as_str(), e);
79                                 sess.struct_span_err(*op_sp, &msg).emit();
80                                 asm::InlineAsmReg::Err
81                             })
82                         } else {
83                             asm::InlineAsmReg::Err
84                         })
85                     }
86                     InlineAsmRegOrRegClass::RegClass(s) => {
87                         asm::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch {
88                             asm::InlineAsmRegClass::parse(asm_arch, s).unwrap_or_else(|e| {
89                                 let msg = format!("invalid register class `{}`: {}", s.as_str(), e);
90                                 sess.struct_span_err(*op_sp, &msg).emit();
91                                 asm::InlineAsmRegClass::Err
92                             })
93                         } else {
94                             asm::InlineAsmRegClass::Err
95                         })
96                     }
97                 };
98
99                 let op = match *op {
100                     InlineAsmOperand::In { reg, ref expr } => hir::InlineAsmOperand::In {
101                         reg: lower_reg(reg),
102                         expr: self.lower_expr_mut(expr),
103                     },
104                     InlineAsmOperand::Out { reg, late, ref expr } => hir::InlineAsmOperand::Out {
105                         reg: lower_reg(reg),
106                         late,
107                         expr: expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
108                     },
109                     InlineAsmOperand::InOut { reg, late, ref expr } => {
110                         hir::InlineAsmOperand::InOut {
111                             reg: lower_reg(reg),
112                             late,
113                             expr: self.lower_expr_mut(expr),
114                         }
115                     }
116                     InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
117                         hir::InlineAsmOperand::SplitInOut {
118                             reg: lower_reg(reg),
119                             late,
120                             in_expr: self.lower_expr_mut(in_expr),
121                             out_expr: out_expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
122                         }
123                     }
124                     InlineAsmOperand::Const { ref anon_const } => hir::InlineAsmOperand::Const {
125                         anon_const: self.lower_anon_const(anon_const),
126                     },
127                     InlineAsmOperand::Sym { ref expr } => {
128                         hir::InlineAsmOperand::Sym { expr: self.lower_expr_mut(expr) }
129                     }
130                 };
131                 (op, self.lower_span(*op_sp))
132             })
133             .collect();
134
135         // Validate template modifiers against the register classes for the operands
136         for p in &asm.template {
137             if let InlineAsmTemplatePiece::Placeholder {
138                 operand_idx,
139                 modifier: Some(modifier),
140                 span: placeholder_span,
141             } = *p
142             {
143                 let op_sp = asm.operands[operand_idx].1;
144                 match &operands[operand_idx].0 {
145                     hir::InlineAsmOperand::In { reg, .. }
146                     | hir::InlineAsmOperand::Out { reg, .. }
147                     | hir::InlineAsmOperand::InOut { reg, .. }
148                     | hir::InlineAsmOperand::SplitInOut { reg, .. } => {
149                         let class = reg.reg_class();
150                         if class == asm::InlineAsmRegClass::Err {
151                             continue;
152                         }
153                         let valid_modifiers = class.valid_modifiers(asm_arch.unwrap());
154                         if !valid_modifiers.contains(&modifier) {
155                             let mut err = sess.struct_span_err(
156                                 placeholder_span,
157                                 "invalid asm template modifier for this register class",
158                             );
159                             err.span_label(placeholder_span, "template modifier");
160                             err.span_label(op_sp, "argument");
161                             if !valid_modifiers.is_empty() {
162                                 let mut mods = format!("`{}`", valid_modifiers[0]);
163                                 for m in &valid_modifiers[1..] {
164                                     let _ = write!(mods, ", `{}`", m);
165                                 }
166                                 err.note(&format!(
167                                     "the `{}` register class supports \
168                                      the following template modifiers: {}",
169                                     class.name(),
170                                     mods
171                                 ));
172                             } else {
173                                 err.note(&format!(
174                                     "the `{}` register class does not support template modifiers",
175                                     class.name()
176                                 ));
177                             }
178                             err.emit();
179                         }
180                     }
181                     hir::InlineAsmOperand::Const { .. } => {
182                         let mut err = sess.struct_span_err(
183                             placeholder_span,
184                             "asm template modifiers are not allowed for `const` arguments",
185                         );
186                         err.span_label(placeholder_span, "template modifier");
187                         err.span_label(op_sp, "argument");
188                         err.emit();
189                     }
190                     hir::InlineAsmOperand::Sym { .. } => {
191                         let mut err = sess.struct_span_err(
192                             placeholder_span,
193                             "asm template modifiers are not allowed for `sym` arguments",
194                         );
195                         err.span_label(placeholder_span, "template modifier");
196                         err.span_label(op_sp, "argument");
197                         err.emit();
198                     }
199                 }
200             }
201         }
202
203         let mut used_input_regs = FxHashMap::default();
204         let mut used_output_regs = FxHashMap::default();
205
206         for (idx, &(ref op, op_sp)) in operands.iter().enumerate() {
207             if let Some(reg) = op.reg() {
208                 let reg_class = reg.reg_class();
209                 if reg_class == asm::InlineAsmRegClass::Err {
210                     continue;
211                 }
212
213                 // Some register classes can only be used as clobbers. This
214                 // means that we disallow passing a value in/out of the asm and
215                 // require that the operand name an explicit register, not a
216                 // register class.
217                 if reg_class.is_clobber_only(asm_arch.unwrap()) && !op.is_clobber() {
218                     let msg = format!(
219                         "register class `{}` can only be used as a clobber, \
220                              not as an input or output",
221                         reg_class.name()
222                     );
223                     sess.struct_span_err(op_sp, &msg).emit();
224                     continue;
225                 }
226
227                 // Check for conflicts between explicit register operands.
228                 if let asm::InlineAsmRegOrRegClass::Reg(reg) = reg {
229                     let (input, output) = match op {
230                         hir::InlineAsmOperand::In { .. } => (true, false),
231
232                         // Late output do not conflict with inputs, but normal outputs do
233                         hir::InlineAsmOperand::Out { late, .. } => (!late, true),
234
235                         hir::InlineAsmOperand::InOut { .. }
236                         | hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
237
238                         hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {
239                             unreachable!()
240                         }
241                     };
242
243                     // Flag to output the error only once per operand
244                     let mut skip = false;
245                     reg.overlapping_regs(|r| {
246                         let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
247                                          input| {
248                             match used_regs.entry(r) {
249                                 Entry::Occupied(o) => {
250                                     if skip {
251                                         return;
252                                     }
253                                     skip = true;
254
255                                     let idx2 = *o.get();
256                                     let &(ref op2, op_sp2) = &operands[idx2];
257                                     let reg2 = match op2.reg() {
258                                         Some(asm::InlineAsmRegOrRegClass::Reg(r)) => r,
259                                         _ => unreachable!(),
260                                     };
261
262                                     let msg = format!(
263                                         "register `{}` conflicts with register `{}`",
264                                         reg.name(),
265                                         reg2.name()
266                                     );
267                                     let mut err = sess.struct_span_err(op_sp, &msg);
268                                     err.span_label(op_sp, &format!("register `{}`", reg.name()));
269                                     err.span_label(op_sp2, &format!("register `{}`", reg2.name()));
270
271                                     match (op, op2) {
272                                         (
273                                             hir::InlineAsmOperand::In { .. },
274                                             hir::InlineAsmOperand::Out { late, .. },
275                                         )
276                                         | (
277                                             hir::InlineAsmOperand::Out { late, .. },
278                                             hir::InlineAsmOperand::In { .. },
279                                         ) => {
280                                             assert!(!*late);
281                                             let out_op_sp = if input { op_sp2 } else { op_sp };
282                                             let msg = "use `lateout` instead of \
283                                                        `out` to avoid conflict";
284                                             err.span_help(out_op_sp, msg);
285                                         }
286                                         _ => {}
287                                     }
288
289                                     err.emit();
290                                 }
291                                 Entry::Vacant(v) => {
292                                     v.insert(idx);
293                                 }
294                             }
295                         };
296                         if input {
297                             check(&mut used_input_regs, true);
298                         }
299                         if output {
300                             check(&mut used_output_regs, false);
301                         }
302                     });
303                 }
304             }
305         }
306
307         // If a clobber_abi is specified, add the necessary clobbers to the
308         // operands list.
309         if let Some((abi, abi_span)) = clobber_abi {
310             for &clobber in abi.clobbered_regs() {
311                 let mut output_used = false;
312                 clobber.overlapping_regs(|reg| {
313                     if used_output_regs.contains_key(&reg) {
314                         output_used = true;
315                     }
316                 });
317
318                 if !output_used {
319                     operands.push((
320                         hir::InlineAsmOperand::Out {
321                             reg: asm::InlineAsmRegOrRegClass::Reg(clobber),
322                             late: true,
323                             expr: None,
324                         },
325                         self.lower_span(abi_span),
326                     ));
327                 }
328             }
329         }
330
331         let operands = self.arena.alloc_from_iter(operands);
332         let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
333         let template_strs = self.arena.alloc_from_iter(
334             asm.template_strs
335                 .iter()
336                 .map(|(sym, snippet, span)| (*sym, *snippet, self.lower_span(*span))),
337         );
338         let line_spans =
339             self.arena.alloc_from_iter(asm.line_spans.iter().map(|span| self.lower_span(*span)));
340         let hir_asm =
341             hir::InlineAsm { template, template_strs, operands, options: asm.options, line_spans };
342         self.arena.alloc(hir_asm)
343     }
344 }