]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_builtin_macros/src/asm.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_builtin_macros / src / asm.rs
CommitLineData
3dfed10e 1use rustc_ast as ast;
f9f354fc 2use rustc_ast::ptr::P;
04454e1e 3use rustc_ast::token::{self, Delimiter};
f9f354fc
XL
4use rustc_ast::tokenstream::TokenStream;
5use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5e7ed085 6use rustc_errors::{Applicability, PResult};
f9f354fc
XL
7use rustc_expand::base::{self, *};
8use rustc_parse::parser::Parser;
f035d41b 9use rustc_parse_format as parse;
cdc7bbd5 10use rustc_session::lint;
a2a8927a 11use rustc_session::parse::ParseSess;
17df50a5 12use rustc_span::symbol::Ident;
cdc7bbd5 13use rustc_span::symbol::{kw, sym, Symbol};
f9f354fc 14use rustc_span::{InnerSpan, Span};
cdc7bbd5 15use rustc_target::asm::InlineAsmArch;
17df50a5 16use smallvec::smallvec;
f9f354fc 17
a2a8927a 18pub struct AsmArgs {
5099ac24
FG
19 pub templates: Vec<P<ast::Expr>>,
20 pub operands: Vec<(ast::InlineAsmOperand, Span)>,
f9f354fc
XL
21 named_args: FxHashMap<Symbol, usize>,
22 reg_args: FxHashSet<usize>,
5099ac24 23 pub clobber_abis: Vec<(Symbol, Span)>,
f9f354fc 24 options: ast::InlineAsmOptions,
5099ac24 25 pub options_spans: Vec<Span>,
f9f354fc
XL
26}
27
28fn parse_args<'a>(
29 ecx: &mut ExtCtxt<'a>,
30 sp: Span,
31 tts: TokenStream,
17df50a5 32 is_global_asm: bool,
5e7ed085 33) -> PResult<'a, AsmArgs> {
f9f354fc 34 let mut p = ecx.new_parser_from_tts(tts);
a2a8927a
XL
35 let sess = &ecx.sess.parse_sess;
36 parse_asm_args(&mut p, sess, sp, is_global_asm)
37}
38
39// Primarily public for rustfmt consumption.
40// Internal consumers should continue to leverage `expand_asm`/`expand__global_asm`
41pub fn parse_asm_args<'a>(
42 p: &mut Parser<'a>,
43 sess: &'a ParseSess,
44 sp: Span,
45 is_global_asm: bool,
5e7ed085 46) -> PResult<'a, AsmArgs> {
a2a8927a 47 let diag = &sess.span_diagnostic;
f9f354fc
XL
48
49 if p.token == token::Eof {
a2a8927a 50 return Err(diag.struct_span_err(sp, "requires at least a template string argument"));
f9f354fc
XL
51 }
52
f035d41b 53 let first_template = p.parse_expr()?;
f9f354fc 54 let mut args = AsmArgs {
f035d41b 55 templates: vec![first_template],
f9f354fc
XL
56 operands: vec![],
57 named_args: FxHashMap::default(),
58 reg_args: FxHashSet::default(),
3c0e092e 59 clobber_abis: Vec::new(),
f9f354fc 60 options: ast::InlineAsmOptions::empty(),
f035d41b 61 options_spans: vec![],
f9f354fc
XL
62 };
63
f035d41b 64 let mut allow_templates = true;
f9f354fc
XL
65 while p.token != token::Eof {
66 if !p.eat(&token::Comma) {
f035d41b
XL
67 if allow_templates {
68 // After a template string, we always expect *only* a comma...
a2a8927a 69 let mut err = diag.struct_span_err(p.token.span, "expected token: `,`");
f9f354fc
XL
70 err.span_label(p.token.span, "expected `,`");
71 p.maybe_annotate_with_ascription(&mut err, false);
72 return Err(err);
73 } else {
74 // ...after that delegate to `expect` to also include the other expected tokens.
75 return Err(p.expect(&token::Comma).err().unwrap());
76 }
77 }
f9f354fc
XL
78 if p.token == token::Eof {
79 break;
80 } // accept trailing commas
81
94222f64
XL
82 // Parse clobber_abi
83 if p.eat_keyword(sym::clobber_abi) {
a2a8927a 84 parse_clobber_abi(p, &mut args)?;
94222f64
XL
85 allow_templates = false;
86 continue;
87 }
88
f9f354fc 89 // Parse options
29967ef6 90 if p.eat_keyword(sym::options) {
a2a8927a 91 parse_options(p, &mut args, is_global_asm)?;
f035d41b 92 allow_templates = false;
f9f354fc
XL
93 continue;
94 }
95
96 let span_start = p.token.span;
97
98 // Parse operand names
99 let name = if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
100 let (ident, _) = p.token.ident().unwrap();
101 p.bump();
102 p.expect(&token::Eq)?;
f035d41b 103 allow_templates = false;
f9f354fc
XL
104 Some(ident.name)
105 } else {
106 None
107 };
108
109 let mut explicit_reg = false;
17df50a5 110 let op = if !is_global_asm && p.eat_keyword(kw::In) {
a2a8927a 111 let reg = parse_reg(p, &mut explicit_reg)?;
c295e0f8 112 if p.eat_keyword(kw::Underscore) {
a2a8927a 113 let err = diag.struct_span_err(p.token.span, "_ cannot be used for input operands");
c295e0f8
XL
114 return Err(err);
115 }
f9f354fc
XL
116 let expr = p.parse_expr()?;
117 ast::InlineAsmOperand::In { reg, expr }
17df50a5 118 } else if !is_global_asm && p.eat_keyword(sym::out) {
a2a8927a 119 let reg = parse_reg(p, &mut explicit_reg)?;
f9f354fc
XL
120 let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
121 ast::InlineAsmOperand::Out { reg, expr, late: false }
17df50a5 122 } else if !is_global_asm && p.eat_keyword(sym::lateout) {
a2a8927a 123 let reg = parse_reg(p, &mut explicit_reg)?;
f9f354fc
XL
124 let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
125 ast::InlineAsmOperand::Out { reg, expr, late: true }
17df50a5 126 } else if !is_global_asm && p.eat_keyword(sym::inout) {
a2a8927a 127 let reg = parse_reg(p, &mut explicit_reg)?;
c295e0f8 128 if p.eat_keyword(kw::Underscore) {
a2a8927a 129 let err = diag.struct_span_err(p.token.span, "_ cannot be used for input operands");
c295e0f8
XL
130 return Err(err);
131 }
f9f354fc
XL
132 let expr = p.parse_expr()?;
133 if p.eat(&token::FatArrow) {
134 let out_expr =
135 if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
136 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: false }
137 } else {
138 ast::InlineAsmOperand::InOut { reg, expr, late: false }
139 }
17df50a5 140 } else if !is_global_asm && p.eat_keyword(sym::inlateout) {
a2a8927a 141 let reg = parse_reg(p, &mut explicit_reg)?;
c295e0f8 142 if p.eat_keyword(kw::Underscore) {
a2a8927a 143 let err = diag.struct_span_err(p.token.span, "_ cannot be used for input operands");
c295e0f8
XL
144 return Err(err);
145 }
f9f354fc
XL
146 let expr = p.parse_expr()?;
147 if p.eat(&token::FatArrow) {
148 let out_expr =
149 if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
150 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: true }
151 } else {
152 ast::InlineAsmOperand::InOut { reg, expr, late: true }
153 }
29967ef6 154 } else if p.eat_keyword(kw::Const) {
cdc7bbd5
XL
155 let anon_const = p.parse_anon_const_expr()?;
156 ast::InlineAsmOperand::Const { anon_const }
04454e1e 157 } else if p.eat_keyword(sym::sym) {
f9f354fc 158 let expr = p.parse_expr()?;
04454e1e
FG
159 let ast::ExprKind::Path(qself, path) = &expr.kind else {
160 let err = diag
161 .struct_span_err(expr.span, "expected a path for argument to `sym`");
162 return Err(err);
163 };
164 let sym = ast::InlineAsmSym {
165 id: ast::DUMMY_NODE_ID,
166 qself: qself.clone(),
167 path: path.clone(),
168 };
169 ast::InlineAsmOperand::Sym { sym }
f035d41b
XL
170 } else if allow_templates {
171 let template = p.parse_expr()?;
172 // If it can't possibly expand to a string, provide diagnostics here to include other
173 // things it could have been.
174 match template.kind {
175 ast::ExprKind::Lit(ast::Lit { kind: ast::LitKind::Str(..), .. }) => {}
176 ast::ExprKind::MacCall(..) => {}
177 _ => {
94222f64
XL
178 let errstr = if is_global_asm {
179 "expected operand, options, or additional template string"
180 } else {
181 "expected operand, clobber_abi, options, or additional template string"
182 };
a2a8927a 183 let mut err = diag.struct_span_err(template.span, errstr);
f035d41b
XL
184 err.span_label(template.span, errstr);
185 return Err(err);
186 }
187 }
188 args.templates.push(template);
189 continue;
190 } else {
29967ef6 191 return p.unexpected();
f9f354fc
XL
192 };
193
f035d41b 194 allow_templates = false;
f9f354fc
XL
195 let span = span_start.to(p.prev_token.span);
196 let slot = args.operands.len();
197 args.operands.push((op, span));
198
94222f64
XL
199 // Validate the order of named, positional & explicit register operands and
200 // clobber_abi/options. We do this at the end once we have the full span
201 // of the argument available.
f035d41b 202 if !args.options_spans.is_empty() {
a2a8927a 203 diag.struct_span_err(span, "arguments are not allowed after options")
f035d41b 204 .span_labels(args.options_spans.clone(), "previous options")
f9f354fc
XL
205 .span_label(span, "argument")
206 .emit();
3c0e092e 207 } else if let Some((_, abi_span)) = args.clobber_abis.last() {
a2a8927a 208 diag.struct_span_err(span, "arguments are not allowed after clobber_abi")
3c0e092e 209 .span_label(*abi_span, "clobber_abi")
94222f64
XL
210 .span_label(span, "argument")
211 .emit();
f9f354fc
XL
212 }
213 if explicit_reg {
214 if name.is_some() {
a2a8927a 215 diag.struct_span_err(span, "explicit register arguments cannot have names").emit();
f9f354fc
XL
216 }
217 args.reg_args.insert(slot);
218 } else if let Some(name) = name {
219 if let Some(&prev) = args.named_args.get(&name) {
a2a8927a 220 diag.struct_span_err(span, &format!("duplicate argument named `{}`", name))
f9f354fc
XL
221 .span_label(args.operands[prev].1, "previously here")
222 .span_label(span, "duplicate argument")
223 .emit();
224 continue;
225 }
226 if !args.reg_args.is_empty() {
a2a8927a 227 let mut err = diag.struct_span_err(
f9f354fc
XL
228 span,
229 "named arguments cannot follow explicit register arguments",
230 );
231 err.span_label(span, "named argument");
232 for pos in &args.reg_args {
233 err.span_label(args.operands[*pos].1, "explicit register argument");
234 }
235 err.emit();
236 }
237 args.named_args.insert(name, slot);
238 } else {
239 if !args.named_args.is_empty() || !args.reg_args.is_empty() {
a2a8927a 240 let mut err = diag.struct_span_err(
f9f354fc
XL
241 span,
242 "positional arguments cannot follow named arguments \
243 or explicit register arguments",
244 );
245 err.span_label(span, "positional argument");
246 for pos in args.named_args.values() {
247 err.span_label(args.operands[*pos].1, "named argument");
248 }
249 for pos in &args.reg_args {
250 err.span_label(args.operands[*pos].1, "explicit register argument");
251 }
252 err.emit();
253 }
254 }
255 }
256
257 if args.options.contains(ast::InlineAsmOptions::NOMEM)
258 && args.options.contains(ast::InlineAsmOptions::READONLY)
259 {
f035d41b 260 let spans = args.options_spans.clone();
a2a8927a 261 diag.struct_span_err(spans, "the `nomem` and `readonly` options are mutually exclusive")
f9f354fc
XL
262 .emit();
263 }
264 if args.options.contains(ast::InlineAsmOptions::PURE)
265 && args.options.contains(ast::InlineAsmOptions::NORETURN)
266 {
f035d41b 267 let spans = args.options_spans.clone();
a2a8927a 268 diag.struct_span_err(spans, "the `pure` and `noreturn` options are mutually exclusive")
f9f354fc
XL
269 .emit();
270 }
271 if args.options.contains(ast::InlineAsmOptions::PURE)
272 && !args.options.intersects(ast::InlineAsmOptions::NOMEM | ast::InlineAsmOptions::READONLY)
273 {
f035d41b 274 let spans = args.options_spans.clone();
a2a8927a 275 diag.struct_span_err(
f035d41b 276 spans,
f9f354fc
XL
277 "the `pure` option must be combined with either `nomem` or `readonly`",
278 )
279 .emit();
280 }
281
282 let mut have_real_output = false;
283 let mut outputs_sp = vec![];
94222f64 284 let mut regclass_outputs = vec![];
f9f354fc
XL
285 for (op, op_sp) in &args.operands {
286 match op {
94222f64
XL
287 ast::InlineAsmOperand::Out { reg, expr, .. }
288 | ast::InlineAsmOperand::SplitInOut { reg, out_expr: expr, .. } => {
f9f354fc
XL
289 outputs_sp.push(*op_sp);
290 have_real_output |= expr.is_some();
94222f64
XL
291 if let ast::InlineAsmRegOrRegClass::RegClass(_) = reg {
292 regclass_outputs.push(*op_sp);
293 }
f9f354fc 294 }
94222f64 295 ast::InlineAsmOperand::InOut { reg, .. } => {
f9f354fc
XL
296 outputs_sp.push(*op_sp);
297 have_real_output = true;
94222f64
XL
298 if let ast::InlineAsmRegOrRegClass::RegClass(_) = reg {
299 regclass_outputs.push(*op_sp);
300 }
f9f354fc
XL
301 }
302 _ => {}
303 }
304 }
305 if args.options.contains(ast::InlineAsmOptions::PURE) && !have_real_output {
a2a8927a 306 diag.struct_span_err(
f035d41b 307 args.options_spans.clone(),
94222f64 308 "asm with the `pure` option must have at least one output",
f9f354fc
XL
309 )
310 .emit();
311 }
312 if args.options.contains(ast::InlineAsmOptions::NORETURN) && !outputs_sp.is_empty() {
a2a8927a 313 let err = diag
f9f354fc
XL
314 .struct_span_err(outputs_sp, "asm outputs are not allowed with the `noreturn` option");
315
316 // Bail out now since this is likely to confuse MIR
317 return Err(err);
318 }
3c0e092e
XL
319
320 if args.clobber_abis.len() > 0 {
94222f64 321 if is_global_asm {
a2a8927a 322 let err = diag.struct_span_err(
3c0e092e
XL
323 args.clobber_abis.iter().map(|(_, span)| *span).collect::<Vec<Span>>(),
324 "`clobber_abi` cannot be used with `global_asm!`",
325 );
94222f64
XL
326
327 // Bail out now since this is likely to confuse later stages
328 return Err(err);
329 }
330 if !regclass_outputs.is_empty() {
a2a8927a 331 diag.struct_span_err(
94222f64
XL
332 regclass_outputs.clone(),
333 "asm with `clobber_abi` must specify explicit registers for outputs",
334 )
3c0e092e
XL
335 .span_labels(
336 args.clobber_abis.iter().map(|(_, span)| *span).collect::<Vec<Span>>(),
337 "clobber_abi",
338 )
94222f64
XL
339 .span_labels(regclass_outputs, "generic outputs")
340 .emit();
341 }
342 }
f9f354fc
XL
343
344 Ok(args)
345}
346
f035d41b
XL
347/// Report a duplicate option error.
348///
349/// This function must be called immediately after the option token is parsed.
350/// Otherwise, the suggestion will be incorrect.
351fn err_duplicate_option<'a>(p: &mut Parser<'a>, symbol: Symbol, span: Span) {
352 let mut err = p
353 .sess
354 .span_diagnostic
355 .struct_span_err(span, &format!("the `{}` option was already provided", symbol));
356 err.span_label(span, "this option was already provided");
357
358 // Tool-only output
359 let mut full_span = span;
360 if p.token.kind == token::Comma {
361 full_span = full_span.to(p.token.span);
362 }
363 err.tool_only_span_suggestion(
364 full_span,
365 "remove this option",
923072b8 366 "",
f035d41b
XL
367 Applicability::MachineApplicable,
368 );
369
370 err.emit();
371}
372
373/// Try to set the provided option in the provided `AsmArgs`.
374/// If it is already set, report a duplicate option error.
375///
376/// This function must be called immediately after the option token is parsed.
377/// Otherwise, the error will not point to the correct spot.
378fn try_set_option<'a>(
379 p: &mut Parser<'a>,
380 args: &mut AsmArgs,
381 symbol: Symbol,
382 option: ast::InlineAsmOptions,
383) {
384 if !args.options.contains(option) {
385 args.options |= option;
386 } else {
387 err_duplicate_option(p, symbol, p.prev_token.span);
388 }
389}
390
17df50a5
XL
391fn parse_options<'a>(
392 p: &mut Parser<'a>,
393 args: &mut AsmArgs,
394 is_global_asm: bool,
5e7ed085 395) -> PResult<'a, ()> {
f9f354fc
XL
396 let span_start = p.prev_token.span;
397
04454e1e 398 p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
f9f354fc 399
04454e1e 400 while !p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
17df50a5 401 if !is_global_asm && p.eat_keyword(sym::pure) {
f035d41b 402 try_set_option(p, args, sym::pure, ast::InlineAsmOptions::PURE);
17df50a5 403 } else if !is_global_asm && p.eat_keyword(sym::nomem) {
f035d41b 404 try_set_option(p, args, sym::nomem, ast::InlineAsmOptions::NOMEM);
17df50a5 405 } else if !is_global_asm && p.eat_keyword(sym::readonly) {
f035d41b 406 try_set_option(p, args, sym::readonly, ast::InlineAsmOptions::READONLY);
17df50a5 407 } else if !is_global_asm && p.eat_keyword(sym::preserves_flags) {
f035d41b 408 try_set_option(p, args, sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS);
17df50a5 409 } else if !is_global_asm && p.eat_keyword(sym::noreturn) {
f035d41b 410 try_set_option(p, args, sym::noreturn, ast::InlineAsmOptions::NORETURN);
17df50a5 411 } else if !is_global_asm && p.eat_keyword(sym::nostack) {
f035d41b 412 try_set_option(p, args, sym::nostack, ast::InlineAsmOptions::NOSTACK);
29967ef6 413 } else if p.eat_keyword(sym::att_syntax) {
f035d41b 414 try_set_option(p, args, sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX);
136023e0
XL
415 } else if p.eat_keyword(kw::Raw) {
416 try_set_option(p, args, kw::Raw, ast::InlineAsmOptions::RAW);
a2a8927a
XL
417 } else if p.eat_keyword(sym::may_unwind) {
418 try_set_option(p, args, kw::Raw, ast::InlineAsmOptions::MAY_UNWIND);
29967ef6
XL
419 } else {
420 return p.unexpected();
f9f354fc
XL
421 }
422
423 // Allow trailing commas
04454e1e 424 if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
f9f354fc
XL
425 break;
426 }
427 p.expect(&token::Comma)?;
428 }
429
430 let new_span = span_start.to(p.prev_token.span);
f035d41b 431 args.options_spans.push(new_span);
f9f354fc
XL
432
433 Ok(())
434}
435
5e7ed085 436fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a, ()> {
94222f64
XL
437 let span_start = p.prev_token.span;
438
04454e1e 439 p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
94222f64 440
04454e1e 441 if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
3c0e092e
XL
442 let err = p.sess.span_diagnostic.struct_span_err(
443 p.token.span,
444 "at least one abi must be provided as an argument to `clobber_abi`",
445 );
446 return Err(err);
447 }
94222f64 448
3c0e092e
XL
449 let mut new_abis = Vec::new();
450 loop {
451 match p.parse_str_lit() {
452 Ok(str_lit) => {
453 new_abis.push((str_lit.symbol_unescaped, str_lit.span));
454 }
455 Err(opt_lit) => {
456 // If the non-string literal is a closing paren then it's the end of the list and is fine
04454e1e 457 if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
3c0e092e
XL
458 break;
459 }
460 let span = opt_lit.map_or(p.token.span, |lit| lit.span);
461 let mut err =
462 p.sess.span_diagnostic.struct_span_err(span, "expected string literal");
463 err.span_label(span, "not a string literal");
464 return Err(err);
465 }
466 };
94222f64 467
3c0e092e 468 // Allow trailing commas
04454e1e 469 if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
3c0e092e
XL
470 break;
471 }
472 p.expect(&token::Comma)?;
473 }
94222f64 474
3c0e092e
XL
475 let full_span = span_start.to(p.prev_token.span);
476
477 if !args.options_spans.is_empty() {
94222f64
XL
478 let mut err = p
479 .sess
480 .span_diagnostic
3c0e092e 481 .struct_span_err(full_span, "clobber_abi is not allowed after options");
94222f64
XL
482 err.span_labels(args.options_spans.clone(), "options");
483 return Err(err);
484 }
485
3c0e092e
XL
486 match &new_abis[..] {
487 // should have errored above during parsing
488 [] => unreachable!(),
489 [(abi, _span)] => args.clobber_abis.push((*abi, full_span)),
490 [abis @ ..] => {
491 for (abi, span) in abis {
492 args.clobber_abis.push((*abi, *span));
493 }
494 }
495 }
94222f64
XL
496
497 Ok(())
498}
499
f9f354fc
XL
500fn parse_reg<'a>(
501 p: &mut Parser<'a>,
502 explicit_reg: &mut bool,
5e7ed085 503) -> PResult<'a, ast::InlineAsmRegOrRegClass> {
04454e1e 504 p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1b1a35ee 505 let result = match p.token.uninterpolate().kind {
f9f354fc
XL
506 token::Ident(name, false) => ast::InlineAsmRegOrRegClass::RegClass(name),
507 token::Literal(token::Lit { kind: token::LitKind::Str, symbol, suffix: _ }) => {
508 *explicit_reg = true;
509 ast::InlineAsmRegOrRegClass::Reg(symbol)
510 }
511 _ => {
512 return Err(
513 p.struct_span_err(p.token.span, "expected register class or explicit register")
514 );
515 }
516 };
517 p.bump();
04454e1e 518 p.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
f9f354fc
XL
519 Ok(result)
520}
521
17df50a5 522fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::InlineAsm> {
f035d41b 523 let mut template = vec![];
f9f354fc
XL
524 // Register operands are implicitly used since they are not allowed to be
525 // referenced in the template string.
526 let mut used = vec![false; args.operands.len()];
527 for pos in &args.reg_args {
528 used[*pos] = true;
529 }
f035d41b
XL
530 let named_pos: FxHashMap<usize, Symbol> =
531 args.named_args.iter().map(|(&sym, &idx)| (idx, sym)).collect();
532 let mut line_spans = Vec::with_capacity(args.templates.len());
533 let mut curarg = 0;
534
94222f64
XL
535 let mut template_strs = Vec::with_capacity(args.templates.len());
536
f035d41b
XL
537 for template_expr in args.templates.into_iter() {
538 if !template.is_empty() {
539 template.push(ast::InlineAsmTemplatePiece::String("\n".to_string()));
540 }
f9f354fc 541
f035d41b
XL
542 let msg = "asm template must be a string literal";
543 let template_sp = template_expr.span;
544 let (template_str, template_style, template_span) =
545 match expr_to_spanned_string(ecx, template_expr, msg) {
546 Ok(template_part) => template_part,
547 Err(err) => {
c295e0f8 548 if let Some((mut err, _)) = err {
f035d41b
XL
549 err.emit();
550 }
17df50a5 551 return None;
f035d41b
XL
552 }
553 };
554
555 let str_style = match template_style {
556 ast::StrStyle::Cooked => None,
557 ast::StrStyle::Raw(raw) => Some(raw as usize),
558 };
559
f035d41b 560 let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
94222f64
XL
561 template_strs.push((
562 template_str,
563 template_snippet.as_ref().map(|s| Symbol::intern(s)),
564 template_sp,
565 ));
a2a8927a 566 let template_str = template_str.as_str();
6a06907d 567
cdc7bbd5
XL
568 if let Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) = ecx.sess.asm_arch {
569 let find_span = |needle: &str| -> Span {
570 if let Some(snippet) = &template_snippet {
571 if let Some(pos) = snippet.find(needle) {
572 let end = pos
3c0e092e 573 + snippet[pos..]
cdc7bbd5
XL
574 .find(|c| matches!(c, '\n' | ';' | '\\' | '"'))
575 .unwrap_or(snippet[pos..].len() - 1);
576 let inner = InnerSpan::new(pos, end);
577 return template_sp.from_inner(inner);
6a06907d
XL
578 }
579 }
cdc7bbd5
XL
580 template_sp
581 };
6a06907d 582
cdc7bbd5
XL
583 if template_str.contains(".intel_syntax") {
584 ecx.parse_sess().buffer_lint(
585 lint::builtin::BAD_ASM_STYLE,
586 find_span(".intel_syntax"),
136023e0 587 ecx.current_expansion.lint_node_id,
cdc7bbd5
XL
588 "avoid using `.intel_syntax`, Intel syntax is the default",
589 );
590 }
591 if template_str.contains(".att_syntax") {
592 ecx.parse_sess().buffer_lint(
593 lint::builtin::BAD_ASM_STYLE,
594 find_span(".att_syntax"),
136023e0 595 ecx.current_expansion.lint_node_id,
cdc7bbd5
XL
596 "avoid using `.att_syntax`, prefer using `options(att_syntax)` instead",
597 );
6a06907d
XL
598 }
599 }
600
136023e0
XL
601 // Don't treat raw asm as a format string.
602 if args.options.contains(ast::InlineAsmOptions::RAW) {
603 template.push(ast::InlineAsmTemplatePiece::String(template_str.to_string()));
604 let template_num_lines = 1 + template_str.matches('\n').count();
605 line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines));
606 continue;
607 }
608
f035d41b
XL
609 let mut parser = parse::Parser::new(
610 template_str,
611 str_style,
612 template_snippet,
613 false,
614 parse::ParseMode::InlineAsm,
615 );
616 parser.curarg = curarg;
617
618 let mut unverified_pieces = Vec::new();
619 while let Some(piece) = parser.next() {
620 if !parser.errors.is_empty() {
621 break;
622 } else {
623 unverified_pieces.push(piece);
f9f354fc 624 }
f035d41b
XL
625 }
626
627 if !parser.errors.is_empty() {
628 let err = parser.errors.remove(0);
04454e1e 629 let err_sp = template_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
f035d41b
XL
630 let msg = &format!("invalid asm template string: {}", err.description);
631 let mut e = ecx.struct_span_err(err_sp, msg);
632 e.span_label(err_sp, err.label + " in asm template string");
633 if let Some(note) = err.note {
634 e.note(&note);
635 }
636 if let Some((label, span)) = err.secondary_label {
04454e1e 637 let err_sp = template_span.from_inner(InnerSpan::new(span.start, span.end));
f035d41b
XL
638 e.span_label(err_sp, label);
639 }
640 e.emit();
17df50a5 641 return None;
f035d41b
XL
642 }
643
644 curarg = parser.curarg;
645
04454e1e
FG
646 let mut arg_spans = parser
647 .arg_places
648 .iter()
649 .map(|span| template_span.from_inner(InnerSpan::new(span.start, span.end)));
f035d41b
XL
650 for piece in unverified_pieces {
651 match piece {
652 parse::Piece::String(s) => {
653 template.push(ast::InlineAsmTemplatePiece::String(s.to_string()))
654 }
655 parse::Piece::NextArgument(arg) => {
656 let span = arg_spans.next().unwrap_or(template_sp);
657
658 let operand_idx = match arg.position {
659 parse::ArgumentIs(idx) | parse::ArgumentImplicitlyIs(idx) => {
660 if idx >= args.operands.len()
661 || named_pos.contains_key(&idx)
662 || args.reg_args.contains(&idx)
663 {
664 let msg = format!("invalid reference to argument at index {}", idx);
665 let mut err = ecx.struct_span_err(span, &msg);
666 err.span_label(span, "from here");
667
668 let positional_args = args.operands.len()
669 - args.named_args.len()
670 - args.reg_args.len();
671 let positional = if positional_args != args.operands.len() {
672 "positional "
673 } else {
674 ""
675 };
676 let msg = match positional_args {
677 0 => format!("no {}arguments were given", positional),
678 1 => format!("there is 1 {}argument", positional),
679 x => format!("there are {} {}arguments", x, positional),
680 };
681 err.note(&msg);
682
683 if named_pos.contains_key(&idx) {
684 err.span_label(args.operands[idx].1, "named argument");
685 err.span_note(
686 args.operands[idx].1,
687 "named arguments cannot be referenced by position",
688 );
689 } else if args.reg_args.contains(&idx) {
690 err.span_label(
691 args.operands[idx].1,
692 "explicit register argument",
693 );
694 err.span_note(
695 args.operands[idx].1,
696 "explicit register arguments cannot be used in the asm template",
697 );
698 }
699 err.emit();
700 None
f9f354fc 701 } else {
f035d41b 702 Some(idx)
f9f354fc 703 }
f9f354fc 704 }
04454e1e
FG
705 parse::ArgumentNamed(name, span) => {
706 match args.named_args.get(&Symbol::intern(name)) {
707 Some(&idx) => Some(idx),
708 None => {
709 let msg = format!("there is no argument named `{}`", name);
710 ecx.struct_span_err(
711 template_span
712 .from_inner(InnerSpan::new(span.start, span.end)),
713 &msg,
714 )
715 .emit();
716 None
717 }
f035d41b 718 }
04454e1e 719 }
f035d41b
XL
720 };
721
722 let mut chars = arg.format.ty.chars();
723 let mut modifier = chars.next();
724 if chars.next().is_some() {
725 let span = arg
726 .format
727 .ty_span
04454e1e 728 .map(|sp| template_sp.from_inner(InnerSpan::new(sp.start, sp.end)))
f035d41b
XL
729 .unwrap_or(template_sp);
730 ecx.struct_span_err(
731 span,
732 "asm template modifier must be a single character",
733 )
f9f354fc 734 .emit();
f035d41b
XL
735 modifier = None;
736 }
f9f354fc 737
f035d41b
XL
738 if let Some(operand_idx) = operand_idx {
739 used[operand_idx] = true;
740 template.push(ast::InlineAsmTemplatePiece::Placeholder {
741 operand_idx,
742 modifier,
743 span,
744 });
745 }
f9f354fc
XL
746 }
747 }
748 }
f035d41b
XL
749
750 if parser.line_spans.is_empty() {
751 let template_num_lines = 1 + template_str.matches('\n').count();
752 line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines));
753 } else {
04454e1e
FG
754 line_spans.extend(
755 parser
756 .line_spans
757 .iter()
758 .map(|span| template_span.from_inner(InnerSpan::new(span.start, span.end))),
759 );
f035d41b 760 };
f9f354fc
XL
761 }
762
f035d41b
XL
763 let mut unused_operands = vec![];
764 let mut help_str = String::new();
765 for (idx, used) in used.into_iter().enumerate() {
766 if !used {
767 let msg = if let Some(sym) = named_pos.get(&idx) {
768 help_str.push_str(&format!(" {{{}}}", sym));
769 "named argument never used"
f9f354fc 770 } else {
f035d41b
XL
771 help_str.push_str(&format!(" {{{}}}", idx));
772 "argument never used"
773 };
774 unused_operands.push((args.operands[idx].1, msg));
775 }
776 }
f9f354fc
XL
777 match unused_operands.len() {
778 0 => {}
779 1 => {
780 let (sp, msg) = unused_operands.into_iter().next().unwrap();
781 let mut err = ecx.struct_span_err(sp, msg);
782 err.span_label(sp, msg);
f035d41b
XL
783 err.help(&format!(
784 "if this argument is intentionally unused, \
785 consider using it in an asm comment: `\"/*{} */\"`",
786 help_str
787 ));
f9f354fc
XL
788 err.emit();
789 }
790 _ => {
791 let mut err = ecx.struct_span_err(
792 unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
793 "multiple unused asm arguments",
794 );
795 for (sp, msg) in unused_operands {
796 err.span_label(sp, msg);
797 }
f035d41b
XL
798 err.help(&format!(
799 "if these arguments are intentionally unused, \
800 consider using them in an asm comment: `\"/*{} */\"`",
801 help_str
802 ));
f9f354fc
XL
803 err.emit();
804 }
805 }
806
94222f64
XL
807 Some(ast::InlineAsm {
808 template,
809 template_strs: template_strs.into_boxed_slice(),
810 operands: args.operands,
3c0e092e 811 clobber_abis: args.clobber_abis,
94222f64
XL
812 options: args.options,
813 line_spans,
814 })
f9f354fc
XL
815}
816
a2a8927a 817pub(super) fn expand_asm<'cx>(
f9f354fc
XL
818 ecx: &'cx mut ExtCtxt<'_>,
819 sp: Span,
820 tts: TokenStream,
821) -> Box<dyn base::MacResult + 'cx> {
17df50a5
XL
822 match parse_args(ecx, sp, tts, false) {
823 Ok(args) => {
824 let expr = if let Some(inline_asm) = expand_preparsed_asm(ecx, args) {
825 P(ast::Expr {
826 id: ast::DUMMY_NODE_ID,
827 kind: ast::ExprKind::InlineAsm(P(inline_asm)),
828 span: sp,
829 attrs: ast::AttrVec::new(),
830 tokens: None,
831 })
832 } else {
833 DummyResult::raw_expr(sp, true)
834 };
835 MacEager::expr(expr)
836 }
837 Err(mut err) => {
838 err.emit();
839 DummyResult::any(sp)
840 }
841 }
842}
843
a2a8927a 844pub(super) fn expand_global_asm<'cx>(
17df50a5
XL
845 ecx: &'cx mut ExtCtxt<'_>,
846 sp: Span,
847 tts: TokenStream,
848) -> Box<dyn base::MacResult + 'cx> {
849 match parse_args(ecx, sp, tts, true) {
850 Ok(args) => {
851 if let Some(inline_asm) = expand_preparsed_asm(ecx, args) {
852 MacEager::items(smallvec![P(ast::Item {
3c0e092e 853 ident: Ident::empty(),
17df50a5
XL
854 attrs: Vec::new(),
855 id: ast::DUMMY_NODE_ID,
3c0e092e 856 kind: ast::ItemKind::GlobalAsm(Box::new(inline_asm)),
17df50a5
XL
857 vis: ast::Visibility {
858 span: sp.shrink_to_lo(),
859 kind: ast::VisibilityKind::Inherited,
860 tokens: None,
861 },
862 span: ecx.with_def_site_ctxt(sp),
863 tokens: None,
864 })])
865 } else {
866 DummyResult::any(sp)
867 }
868 }
f9f354fc
XL
869 Err(mut err) => {
870 err.emit();
871 DummyResult::any(sp)
872 }
873 }
874}