1 //! Parser for .clif files.
2 
3 use crate::error::{Location, ParseError, ParseResult};
4 use crate::isaspec;
5 use crate::lexer::{LexError, Lexer, LocatedError, LocatedToken, Token};
6 use crate::run_command::{Comparison, Invocation, RunCommand};
7 use crate::sourcemap::SourceMap;
8 use crate::testcommand::TestCommand;
9 use crate::testfile::{Comment, Details, Feature, TestFile};
10 use cranelift_codegen::data_value::DataValue;
11 use cranelift_codegen::entity::{EntityRef, PrimaryMap};
12 use cranelift_codegen::ir::entities::{AnyEntity, DynamicType, MemoryType};
13 use cranelift_codegen::ir::immediates::{Ieee32, Ieee64, Imm64, Offset32, Uimm32, Uimm64};
14 use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs};
15 use cranelift_codegen::ir::pcc::Fact;
16 use cranelift_codegen::ir::types;
17 use cranelift_codegen::ir::types::INVALID;
18 use cranelift_codegen::ir::types::*;
19 use cranelift_codegen::ir::{self, UserExternalNameRef};
20 use cranelift_codegen::ir::{
21     AbiParam, ArgumentExtension, ArgumentPurpose, Block, Constant, ConstantData, DynamicStackSlot,
22     DynamicStackSlotData, DynamicTypeData, ExtFuncData, ExternalName, FuncRef, Function,
23     GlobalValue, GlobalValueData, JumpTableData, MemFlags, MemoryTypeData, MemoryTypeField, Opcode,
24     SigRef, Signature, StackSlot, StackSlotData, StackSlotKind, Table, TableData, Type,
25     UserFuncName, Value,
26 };
27 use cranelift_codegen::isa::{self, CallConv};
28 use cranelift_codegen::packed_option::ReservedValue;
29 use cranelift_codegen::{settings, settings::Configurable, timing};
30 use smallvec::SmallVec;
31 use std::mem;
32 use std::str::FromStr;
33 use std::{u16, u32};
34 use target_lexicon::Triple;
35 
36 macro_rules! match_imm {
37     ($signed:ty, $unsigned:ty, $parser:expr, $err_msg:expr) => {{
38         if let Some(Token::Integer(text)) = $parser.token() {
39             $parser.consume();
40             let negative = text.starts_with('-');
41             let positive = text.starts_with('+');
42             let text = if negative || positive {
43                 // Strip sign prefix.
44                 &text[1..]
45             } else {
46                 text
47             };
48 
49             // Parse the text value; the lexer gives us raw text that looks like an integer.
50             let value = if text.starts_with("0x") {
51                 // Skip underscores.
52                 let text = text.replace("_", "");
53                 // Parse it in hexadecimal form.
54                 <$unsigned>::from_str_radix(&text[2..], 16).map_err(|_| {
55                     $parser.error(&format!(
56                         "unable to parse '{}' value as a hexadecimal {} immediate",
57                         &text[2..],
58                         stringify!($unsigned),
59                     ))
60                 })?
61             } else {
62                 // Parse it as a signed type to check for overflow and other issues.
63                 text.parse()
64                     .map_err(|_| $parser.error("expected decimal immediate"))?
65             };
66 
67             // Apply sign if necessary.
68             let signed = if negative {
69                 let value = value.wrapping_neg() as $signed;
70                 if value > 0 {
71                     return Err($parser.error("negative number too small"));
72                 }
73                 value
74             } else {
75                 value as $signed
76             };
77 
78             Ok(signed)
79         } else {
80             err!($parser.loc, $err_msg)
81         }
82     }};
83 }
84 
85 /// After some quick benchmarks a program should never have more than 100,000 blocks.
86 const MAX_BLOCKS_IN_A_FUNCTION: u32 = 100_000;
87 
88 /// Parse the entire `text` into a list of functions.
89 ///
90 /// Any test commands or target declarations are ignored.
91 pub fn parse_functions(text: &str) -> ParseResult<Vec<Function>> {
92     let _tt = timing::parse_text();
93     parse_test(text, ParseOptions::default())
94         .map(|file| file.functions.into_iter().map(|(func, _)| func).collect())
95 }
96 
97 /// Options for configuring the parsing of filetests.
98 pub struct ParseOptions<'a> {
99     /// Compiler passes to run on the parsed functions.
100     pub passes: Option<&'a [String]>,
101     /// Target ISA for compiling the parsed functions, e.g. "x86_64 skylake".
102     pub target: Option<&'a str>,
103     /// Default calling convention used when none is specified for a parsed function.
104     pub default_calling_convention: CallConv,
105     /// Default for unwind-info setting (enabled or disabled).
106     pub unwind_info: bool,
107     /// Default for machine_code_cfg_info setting (enabled or disabled).
108     pub machine_code_cfg_info: bool,
109 }
110 
111 impl Default for ParseOptions<'_> {
112     fn default() -> Self {
113         Self {
114             passes: None,
115             target: None,
116             default_calling_convention: CallConv::Fast,
117             unwind_info: false,
118             machine_code_cfg_info: false,
119         }
120     }
121 }
122 
123 /// Parse the entire `text` as a test case file.
124 ///
125 /// The returned `TestFile` contains direct references to substrings of `text`.
126 pub fn parse_test<'a>(text: &'a str, options: ParseOptions<'a>) -> ParseResult<TestFile<'a>> {
127     let _tt = timing::parse_text();
128     let mut parser = Parser::new(text);
129 
130     // Gather the preamble comments.
131     parser.start_gathering_comments();
132 
133     let isa_spec: isaspec::IsaSpec;
134     let commands: Vec<TestCommand<'a>>;
135 
136     // Check for specified passes and target, if present throw out test commands/targets specified
137     // in file.
138     match options.passes {
139         Some(pass_vec) => {
140             parser.parse_test_commands();
141             commands = parser.parse_cmdline_passes(pass_vec);
142             parser.parse_target_specs(&options)?;
143             isa_spec = parser.parse_cmdline_target(options.target)?;
144         }
145         None => {
146             commands = parser.parse_test_commands();
147             isa_spec = parser.parse_target_specs(&options)?;
148         }
149     };
150     let features = parser.parse_cranelift_features()?;
151 
152     // Decide between using the calling convention passed in the options or using the
153     // host's calling convention--if any tests are to be run on the host we should default to the
154     // host's calling convention.
155     parser = if commands.iter().any(|tc| tc.command == "run") {
156         let host_default_calling_convention = CallConv::triple_default(&Triple::host());
157         parser.with_default_calling_convention(host_default_calling_convention)
158     } else {
159         parser.with_default_calling_convention(options.default_calling_convention)
160     };
161 
162     parser.token();
163     parser.claim_gathered_comments(AnyEntity::Function);
164 
165     let preamble_comments = parser.take_comments();
166     let functions = parser.parse_function_list()?;
167 
168     Ok(TestFile {
169         commands,
170         isa_spec,
171         features,
172         preamble_comments,
173         functions,
174     })
175 }
176 
177 /// Parse a CLIF comment `text` as a run command.
178 ///
179 /// Return:
180 ///  - `Ok(None)` if the comment is not intended to be a `RunCommand` (i.e. does not start with `run`
181 ///    or `print`
182 ///  - `Ok(Some(command))` if the comment is intended as a `RunCommand` and can be parsed to one
183 ///  - `Err` otherwise.
184 pub fn parse_run_command<'a>(text: &str, signature: &Signature) -> ParseResult<Option<RunCommand>> {
185     let _tt = timing::parse_text();
186     // We remove leading spaces and semi-colons for convenience here instead of at the call sites
187     // since this function will be attempting to parse a RunCommand from a CLIF comment.
188     let trimmed_text = text.trim_start_matches(|c| c == ' ' || c == ';');
189     let mut parser = Parser::new(trimmed_text);
190     match parser.token() {
191         Some(Token::Identifier("run")) | Some(Token::Identifier("print")) => {
192             parser.parse_run_command(signature).map(|c| Some(c))
193         }
194         Some(_) | None => Ok(None),
195     }
196 }
197 
198 pub struct Parser<'a> {
199     lex: Lexer<'a>,
200 
201     lex_error: Option<LexError>,
202 
203     /// Current lookahead token.
204     lookahead: Option<Token<'a>>,
205 
206     /// Location of lookahead.
207     loc: Location,
208 
209     /// Are we gathering any comments that we encounter?
210     gathering_comments: bool,
211 
212     /// The gathered comments; claim them with `claim_gathered_comments`.
213     gathered_comments: Vec<&'a str>,
214 
215     /// Comments collected so far.
216     comments: Vec<Comment<'a>>,
217 
218     /// Maps inlined external names to a ref value, so they can be declared before parsing the rest
219     /// of the function later.
220     ///
221     /// This maintains backward compatibility with previous ways for declaring external names.
222     predeclared_external_names: PrimaryMap<UserExternalNameRef, ir::UserExternalName>,
223 
224     /// Default calling conventions; used when none is specified.
225     default_calling_convention: CallConv,
226 }
227 
228 /// Context for resolving references when parsing a single function.
229 struct Context {
230     function: Function,
231     map: SourceMap,
232 
233     /// Aliases to resolve once value definitions are known.
234     aliases: Vec<Value>,
235 }
236 
237 impl Context {
238     fn new(f: Function) -> Self {
239         Self {
240             function: f,
241             map: SourceMap::new(),
242             aliases: Vec::new(),
243         }
244     }
245 
246     // Allocate a new stack slot.
247     fn add_ss(&mut self, ss: StackSlot, data: StackSlotData, loc: Location) -> ParseResult<()> {
248         self.map.def_ss(ss, loc)?;
249         while self.function.sized_stack_slots.next_key().index() <= ss.index() {
250             self.function
251                 .create_sized_stack_slot(StackSlotData::new(StackSlotKind::ExplicitSlot, 0));
252         }
253         self.function.sized_stack_slots[ss] = data;
254         Ok(())
255     }
256 
257     // Resolve a reference to a stack slot.
258     fn check_ss(&self, ss: StackSlot, loc: Location) -> ParseResult<()> {
259         if !self.map.contains_ss(ss) {
260             err!(loc, "undefined stack slot {}", ss)
261         } else {
262             Ok(())
263         }
264     }
265 
266     // Allocate a new stack slot.
267     fn add_dss(
268         &mut self,
269         ss: DynamicStackSlot,
270         data: DynamicStackSlotData,
271         loc: Location,
272     ) -> ParseResult<()> {
273         self.map.def_dss(ss, loc)?;
274         while self.function.dynamic_stack_slots.next_key().index() <= ss.index() {
275             self.function
276                 .create_dynamic_stack_slot(DynamicStackSlotData::new(
277                     StackSlotKind::ExplicitDynamicSlot,
278                     data.dyn_ty,
279                 ));
280         }
281         self.function.dynamic_stack_slots[ss] = data;
282         Ok(())
283     }
284 
285     // Resolve a reference to a dynamic stack slot.
286     fn check_dss(&self, dss: DynamicStackSlot, loc: Location) -> ParseResult<()> {
287         if !self.map.contains_dss(dss) {
288             err!(loc, "undefined dynamic stack slot {}", dss)
289         } else {
290             Ok(())
291         }
292     }
293 
294     // Allocate a new dynamic type.
295     fn add_dt(&mut self, dt: DynamicType, data: DynamicTypeData, loc: Location) -> ParseResult<()> {
296         self.map.def_dt(dt, loc)?;
297         while self.function.dfg.dynamic_types.next_key().index() <= dt.index() {
298             self.function.dfg.make_dynamic_ty(DynamicTypeData::new(
299                 data.base_vector_ty,
300                 data.dynamic_scale,
301             ));
302         }
303         self.function.dfg.dynamic_types[dt] = data;
304         Ok(())
305     }
306 
307     // Allocate a global value slot.
308     fn add_gv(
309         &mut self,
310         gv: GlobalValue,
311         data: GlobalValueData,
312         maybe_fact: Option<Fact>,
313         loc: Location,
314     ) -> ParseResult<()> {
315         self.map.def_gv(gv, loc)?;
316         while self.function.global_values.next_key().index() <= gv.index() {
317             self.function.create_global_value(GlobalValueData::Symbol {
318                 name: ExternalName::testcase(""),
319                 offset: Imm64::new(0),
320                 colocated: false,
321                 tls: false,
322             });
323         }
324         self.function.global_values[gv] = data;
325         if let Some(fact) = maybe_fact {
326             self.function.global_value_facts[gv] = Some(fact);
327         }
328         Ok(())
329     }
330 
331     // Allocate a memory-type slot.
332     fn add_mt(&mut self, mt: MemoryType, data: MemoryTypeData, loc: Location) -> ParseResult<()> {
333         self.map.def_mt(mt, loc)?;
334         while self.function.memory_types.next_key().index() <= mt.index() {
335             self.function.create_memory_type(MemoryTypeData::default());
336         }
337         self.function.memory_types[mt] = data;
338         Ok(())
339     }
340 
341     // Resolve a reference to a global value.
342     fn check_gv(&self, gv: GlobalValue, loc: Location) -> ParseResult<()> {
343         if !self.map.contains_gv(gv) {
344             err!(loc, "undefined global value {}", gv)
345         } else {
346             Ok(())
347         }
348     }
349 
350     // Allocate a table slot.
351     fn add_table(&mut self, table: Table, data: TableData, loc: Location) -> ParseResult<()> {
352         while self.function.tables.next_key().index() <= table.index() {
353             self.function.create_table(TableData {
354                 base_gv: GlobalValue::reserved_value(),
355                 min_size: Uimm64::new(0),
356                 bound_gv: GlobalValue::reserved_value(),
357                 element_size: Uimm64::new(0),
358                 index_type: INVALID,
359             });
360         }
361         self.function.tables[table] = data;
362         self.map.def_table(table, loc)
363     }
364 
365     // Resolve a reference to a table.
366     fn check_table(&self, table: Table, loc: Location) -> ParseResult<()> {
367         if !self.map.contains_table(table) {
368             err!(loc, "undefined table {}", table)
369         } else {
370             Ok(())
371         }
372     }
373 
374     // Allocate a new signature.
375     fn add_sig(
376         &mut self,
377         sig: SigRef,
378         data: Signature,
379         loc: Location,
380         defaultcc: CallConv,
381     ) -> ParseResult<()> {
382         self.map.def_sig(sig, loc)?;
383         while self.function.dfg.signatures.next_key().index() <= sig.index() {
384             self.function.import_signature(Signature::new(defaultcc));
385         }
386         self.function.dfg.signatures[sig] = data;
387         Ok(())
388     }
389 
390     // Resolve a reference to a signature.
391     fn check_sig(&self, sig: SigRef, loc: Location) -> ParseResult<()> {
392         if !self.map.contains_sig(sig) {
393             err!(loc, "undefined signature {}", sig)
394         } else {
395             Ok(())
396         }
397     }
398 
399     // Allocate a new external function.
400     fn add_fn(&mut self, fn_: FuncRef, data: ExtFuncData, loc: Location) -> ParseResult<()> {
401         self.map.def_fn(fn_, loc)?;
402         while self.function.dfg.ext_funcs.next_key().index() <= fn_.index() {
403             self.function.import_function(ExtFuncData {
404                 name: ExternalName::testcase(""),
405                 signature: SigRef::reserved_value(),
406                 colocated: false,
407             });
408         }
409         self.function.dfg.ext_funcs[fn_] = data;
410         Ok(())
411     }
412 
413     // Resolve a reference to a function.
414     fn check_fn(&self, fn_: FuncRef, loc: Location) -> ParseResult<()> {
415         if !self.map.contains_fn(fn_) {
416             err!(loc, "undefined function {}", fn_)
417         } else {
418             Ok(())
419         }
420     }
421 
422     // Allocate a new constant.
423     fn add_constant(
424         &mut self,
425         constant: Constant,
426         data: ConstantData,
427         loc: Location,
428     ) -> ParseResult<()> {
429         self.map.def_constant(constant, loc)?;
430         self.function.dfg.constants.set(constant, data);
431         Ok(())
432     }
433 
434     // Configure the stack limit of the current function.
435     fn add_stack_limit(&mut self, limit: GlobalValue, loc: Location) -> ParseResult<()> {
436         if self.function.stack_limit.is_some() {
437             return err!(loc, "stack limit defined twice");
438         }
439         self.function.stack_limit = Some(limit);
440         Ok(())
441     }
442 
443     // Resolve a reference to a constant.
444     fn check_constant(&self, c: Constant, loc: Location) -> ParseResult<()> {
445         if !self.map.contains_constant(c) {
446             err!(loc, "undefined constant {}", c)
447         } else {
448             Ok(())
449         }
450     }
451 
452     // Allocate a new block.
453     fn add_block(&mut self, block: Block, loc: Location) -> ParseResult<Block> {
454         self.map.def_block(block, loc)?;
455         while self.function.dfg.num_blocks() <= block.index() {
456             self.function.dfg.make_block();
457         }
458         self.function.layout.append_block(block);
459         Ok(block)
460     }
461 
462     /// Set a block as cold.
463     fn set_cold_block(&mut self, block: Block) {
464         self.function.layout.set_cold(block);
465     }
466 }
467 
468 impl<'a> Parser<'a> {
469     /// Create a new `Parser` which reads `text`. The referenced text must outlive the parser.
470     pub fn new(text: &'a str) -> Self {
471         Self {
472             lex: Lexer::new(text),
473             lex_error: None,
474             lookahead: None,
475             loc: Location { line_number: 0 },
476             gathering_comments: false,
477             gathered_comments: Vec::new(),
478             comments: Vec::new(),
479             default_calling_convention: CallConv::Fast,
480             predeclared_external_names: Default::default(),
481         }
482     }
483 
484     /// Modify the default calling convention; returns a new parser with the changed calling
485     /// convention.
486     pub fn with_default_calling_convention(self, default_calling_convention: CallConv) -> Self {
487         Self {
488             default_calling_convention,
489             ..self
490         }
491     }
492 
493     // Consume the current lookahead token and return it.
494     fn consume(&mut self) -> Token<'a> {
495         self.lookahead.take().expect("No token to consume")
496     }
497 
498     // Consume the whole line following the current lookahead token.
499     // Return the text of the line tail.
500     fn consume_line(&mut self) -> &'a str {
501         let rest = self.lex.rest_of_line();
502         self.consume();
503         rest
504     }
505 
506     // Get the current lookahead token, after making sure there is one.
507     fn token(&mut self) -> Option<Token<'a>> {
508         while self.lookahead.is_none() {
509             match self.lex.next() {
510                 Some(Ok(LocatedToken { token, location })) => {
511                     match token {
512                         Token::Comment(text) => {
513                             if self.gathering_comments {
514                                 self.gathered_comments.push(text);
515                             }
516                         }
517                         _ => self.lookahead = Some(token),
518                     }
519                     self.loc = location;
520                 }
521                 Some(Err(LocatedError { error, location })) => {
522                     self.lex_error = Some(error);
523                     self.loc = location;
524                     break;
525                 }
526                 None => break,
527             }
528         }
529         self.lookahead
530     }
531 
532     // Enable gathering of all comments encountered.
533     fn start_gathering_comments(&mut self) {
534         debug_assert!(!self.gathering_comments);
535         self.gathering_comments = true;
536         debug_assert!(self.gathered_comments.is_empty());
537     }
538 
539     // Claim the comments gathered up to the current position for the
540     // given entity.
541     fn claim_gathered_comments<E: Into<AnyEntity>>(&mut self, entity: E) {
542         debug_assert!(self.gathering_comments);
543         let entity = entity.into();
544         self.comments.extend(
545             self.gathered_comments
546                 .drain(..)
547                 .map(|text| Comment { entity, text }),
548         );
549         self.gathering_comments = false;
550     }
551 
552     // Get the comments collected so far, clearing out the internal list.
553     fn take_comments(&mut self) -> Vec<Comment<'a>> {
554         debug_assert!(!self.gathering_comments);
555         mem::replace(&mut self.comments, Vec::new())
556     }
557 
558     // Match and consume a token without payload.
559     fn match_token(&mut self, want: Token<'a>, err_msg: &str) -> ParseResult<Token<'a>> {
560         if self.token() == Some(want) {
561             Ok(self.consume())
562         } else {
563             err!(self.loc, err_msg)
564         }
565     }
566 
567     // If the next token is a `want`, consume it, otherwise do nothing.
568     fn optional(&mut self, want: Token<'a>) -> bool {
569         if self.token() == Some(want) {
570             self.consume();
571             true
572         } else {
573             false
574         }
575     }
576 
577     // Match and consume a specific identifier string.
578     // Used for pseudo-keywords like "stack_slot" that only appear in certain contexts.
579     fn match_identifier(&mut self, want: &'static str, err_msg: &str) -> ParseResult<Token<'a>> {
580         if self.token() == Some(Token::Identifier(want)) {
581             Ok(self.consume())
582         } else {
583             err!(self.loc, err_msg)
584         }
585     }
586 
587     // Match and consume a type.
588     fn match_type(&mut self, err_msg: &str) -> ParseResult<Type> {
589         if let Some(Token::Type(t)) = self.token() {
590             self.consume();
591             Ok(t)
592         } else {
593             err!(self.loc, err_msg)
594         }
595     }
596 
597     // Match and consume a stack slot reference.
598     fn match_ss(&mut self, err_msg: &str) -> ParseResult<StackSlot> {
599         if let Some(Token::StackSlot(ss)) = self.token() {
600             self.consume();
601             if let Some(ss) = StackSlot::with_number(ss) {
602                 return Ok(ss);
603             }
604         }
605         err!(self.loc, err_msg)
606     }
607 
608     // Match and consume a dynamic stack slot reference.
609     fn match_dss(&mut self, err_msg: &str) -> ParseResult<DynamicStackSlot> {
610         if let Some(Token::DynamicStackSlot(ss)) = self.token() {
611             self.consume();
612             if let Some(ss) = DynamicStackSlot::with_number(ss) {
613                 return Ok(ss);
614             }
615         }
616         err!(self.loc, err_msg)
617     }
618 
619     // Match and consume a dynamic type reference.
620     fn match_dt(&mut self, err_msg: &str) -> ParseResult<DynamicType> {
621         if let Some(Token::DynamicType(dt)) = self.token() {
622             self.consume();
623             if let Some(dt) = DynamicType::with_number(dt) {
624                 return Ok(dt);
625             }
626         }
627         err!(self.loc, err_msg)
628     }
629 
630     // Extract Type from DynamicType
631     fn concrete_from_dt(&mut self, dt: DynamicType, ctx: &mut Context) -> Option<Type> {
632         ctx.function.get_concrete_dynamic_ty(dt)
633     }
634 
635     // Match and consume a global value reference.
636     fn match_gv(&mut self, err_msg: &str) -> ParseResult<GlobalValue> {
637         if let Some(Token::GlobalValue(gv)) = self.token() {
638             self.consume();
639             if let Some(gv) = GlobalValue::with_number(gv) {
640                 return Ok(gv);
641             }
642         }
643         err!(self.loc, err_msg)
644     }
645 
646     // Match and consume a function reference.
647     fn match_fn(&mut self, err_msg: &str) -> ParseResult<FuncRef> {
648         if let Some(Token::FuncRef(fnref)) = self.token() {
649             self.consume();
650             if let Some(fnref) = FuncRef::with_number(fnref) {
651                 return Ok(fnref);
652             }
653         }
654         err!(self.loc, err_msg)
655     }
656 
657     // Match and consume a signature reference.
658     fn match_sig(&mut self, err_msg: &str) -> ParseResult<SigRef> {
659         if let Some(Token::SigRef(sigref)) = self.token() {
660             self.consume();
661             if let Some(sigref) = SigRef::with_number(sigref) {
662                 return Ok(sigref);
663             }
664         }
665         err!(self.loc, err_msg)
666     }
667 
668     // Match and consume a table reference.
669     fn match_table(&mut self, err_msg: &str) -> ParseResult<Table> {
670         if let Some(Token::Table(table)) = self.token() {
671             self.consume();
672             if let Some(table) = Table::with_number(table) {
673                 return Ok(table);
674             }
675         }
676         err!(self.loc, err_msg)
677     }
678 
679     // Match and consume a memory-type reference.
680     fn match_mt(&mut self, err_msg: &str) -> ParseResult<MemoryType> {
681         if let Some(Token::MemoryType(mt)) = self.token() {
682             self.consume();
683             if let Some(mt) = MemoryType::with_number(mt) {
684                 return Ok(mt);
685             }
686         }
687         err!(self.loc, err_msg)
688     }
689 
690     // Match and consume a constant reference.
691     fn match_constant(&mut self) -> ParseResult<Constant> {
692         if let Some(Token::Constant(c)) = self.token() {
693             self.consume();
694             if let Some(c) = Constant::with_number(c) {
695                 return Ok(c);
696             }
697         }
698         err!(self.loc, "expected constant number: const«n»")
699     }
700 
701     // Match and consume a stack limit token
702     fn match_stack_limit(&mut self) -> ParseResult<()> {
703         if let Some(Token::Identifier("stack_limit")) = self.token() {
704             self.consume();
705             return Ok(());
706         }
707         err!(self.loc, "expected identifier: stack_limit")
708     }
709 
710     // Match and consume a block reference.
711     fn match_block(&mut self, err_msg: &str) -> ParseResult<Block> {
712         if let Some(Token::Block(block)) = self.token() {
713             self.consume();
714             Ok(block)
715         } else {
716             err!(self.loc, err_msg)
717         }
718     }
719 
720     // Match and consume a value reference.
721     fn match_value(&mut self, err_msg: &str) -> ParseResult<Value> {
722         if let Some(Token::Value(v)) = self.token() {
723             self.consume();
724             Ok(v)
725         } else {
726             err!(self.loc, err_msg)
727         }
728     }
729 
730     fn error(&self, message: &str) -> ParseError {
731         ParseError {
732             location: self.loc,
733             message: message.to_string(),
734             is_warning: false,
735         }
736     }
737 
738     // Match and consume an Imm64 immediate.
739     fn match_imm64(&mut self, err_msg: &str) -> ParseResult<Imm64> {
740         if let Some(Token::Integer(text)) = self.token() {
741             self.consume();
742             // Lexer just gives us raw text that looks like an integer.
743             // Parse it as an Imm64 to check for overflow and other issues.
744             text.parse().map_err(|e| self.error(e))
745         } else {
746             err!(self.loc, err_msg)
747         }
748     }
749 
750     // Match and consume a hexadeximal immediate
751     fn match_hexadecimal_constant(&mut self, err_msg: &str) -> ParseResult<ConstantData> {
752         if let Some(Token::Integer(text)) = self.token() {
753             self.consume();
754             text.parse().map_err(|e| {
755                 self.error(&format!(
756                     "expected hexadecimal immediate, failed to parse: {}",
757                     e
758                 ))
759             })
760         } else {
761             err!(self.loc, err_msg)
762         }
763     }
764 
765     // Match and consume either a hexadecimal Uimm128 immediate (e.g. 0x000102...) or its literal
766     // list form (e.g. [0 1 2...]). For convenience, since uimm128 values are stored in the
767     // `ConstantPool`, this returns `ConstantData`.
768     fn match_uimm128(&mut self, controlling_type: Type) -> ParseResult<ConstantData> {
769         let expected_size = controlling_type.bytes() as usize;
770         let constant_data = if self.optional(Token::LBracket) {
771             // parse using a list of values, e.g. vconst.i32x4 [0 1 2 3]
772             let uimm128 = self.parse_literals_to_constant_data(controlling_type)?;
773             self.match_token(Token::RBracket, "expected a terminating right bracket")?;
774             uimm128
775         } else {
776             // parse using a hexadecimal value, e.g. 0x000102...
777             let uimm128 =
778                 self.match_hexadecimal_constant("expected an immediate hexadecimal operand")?;
779             uimm128.expand_to(expected_size)
780         };
781 
782         if constant_data.len() == expected_size {
783             Ok(constant_data)
784         } else {
785             Err(self.error(&format!(
786                 "expected parsed constant to have {} bytes",
787                 expected_size
788             )))
789         }
790     }
791 
792     // Match and consume a Uimm64 immediate.
793     fn match_uimm64(&mut self, err_msg: &str) -> ParseResult<Uimm64> {
794         if let Some(Token::Integer(text)) = self.token() {
795             self.consume();
796             // Lexer just gives us raw text that looks like an integer.
797             // Parse it as an Uimm64 to check for overflow and other issues.
798             text.parse()
799                 .map_err(|_| self.error("expected u64 decimal immediate"))
800         } else {
801             err!(self.loc, err_msg)
802         }
803     }
804 
805     // Match and consume a Uimm32 immediate.
806     fn match_uimm32(&mut self, err_msg: &str) -> ParseResult<Uimm32> {
807         if let Some(Token::Integer(text)) = self.token() {
808             self.consume();
809             // Lexer just gives us raw text that looks like an integer.
810             // Parse it as an Uimm32 to check for overflow and other issues.
811             text.parse().map_err(|e| self.error(e))
812         } else {
813             err!(self.loc, err_msg)
814         }
815     }
816 
817     // Match and consume a u8 immediate.
818     // This is used for lane numbers in SIMD vectors.
819     fn match_uimm8(&mut self, err_msg: &str) -> ParseResult<u8> {
820         if let Some(Token::Integer(text)) = self.token() {
821             self.consume();
822             // Lexer just gives us raw text that looks like an integer.
823             if text.starts_with("0x") {
824                 // Parse it as a u8 in hexadecimal form.
825                 u8::from_str_radix(&text[2..], 16)
826                     .map_err(|_| self.error("unable to parse u8 as a hexadecimal immediate"))
827             } else {
828                 // Parse it as a u8 to check for overflow and other issues.
829                 text.parse()
830                     .map_err(|_| self.error("expected u8 decimal immediate"))
831             }
832         } else {
833             err!(self.loc, err_msg)
834         }
835     }
836 
837     // Match and consume an i8 immediate.
838     fn match_imm8(&mut self, err_msg: &str) -> ParseResult<i8> {
839         match_imm!(i8, u8, self, err_msg)
840     }
841 
842     // Match and consume a signed 16-bit immediate.
843     fn match_imm16(&mut self, err_msg: &str) -> ParseResult<i16> {
844         match_imm!(i16, u16, self, err_msg)
845     }
846 
847     // Match and consume an i32 immediate.
848     // This is used for stack argument byte offsets.
849     fn match_imm32(&mut self, err_msg: &str) -> ParseResult<i32> {
850         match_imm!(i32, u32, self, err_msg)
851     }
852 
853     // Match and consume an i128 immediate.
854     fn match_imm128(&mut self, err_msg: &str) -> ParseResult<i128> {
855         match_imm!(i128, u128, self, err_msg)
856     }
857 
858     // Match and consume an optional offset32 immediate.
859     //
860     // Note that this will match an empty string as an empty offset, and that if an offset is
861     // present, it must contain a sign.
862     fn optional_offset32(&mut self) -> ParseResult<Offset32> {
863         if let Some(Token::Integer(text)) = self.token() {
864             if text.starts_with('+') || text.starts_with('-') {
865                 self.consume();
866                 // Lexer just gives us raw text that looks like an integer.
867                 // Parse it as an `Offset32` to check for overflow and other issues.
868                 return text.parse().map_err(|e| self.error(e));
869             }
870         }
871         // An offset32 operand can be absent.
872         Ok(Offset32::new(0))
873     }
874 
875     // Match and consume an optional offset32 immediate.
876     //
877     // Note that this will match an empty string as an empty offset, and that if an offset is
878     // present, it must contain a sign.
879     fn optional_offset_imm64(&mut self) -> ParseResult<Imm64> {
880         if let Some(Token::Integer(text)) = self.token() {
881             if text.starts_with('+') || text.starts_with('-') {
882                 self.consume();
883                 // Lexer just gives us raw text that looks like an integer.
884                 // Parse it as an `Offset32` to check for overflow and other issues.
885                 return text.parse().map_err(|e| self.error(e));
886             }
887         }
888         // If no explicit offset is present, the offset is 0.
889         Ok(Imm64::new(0))
890     }
891 
892     // Match and consume an Ieee32 immediate.
893     fn match_ieee32(&mut self, err_msg: &str) -> ParseResult<Ieee32> {
894         if let Some(Token::Float(text)) = self.token() {
895             self.consume();
896             // Lexer just gives us raw text that looks like a float.
897             // Parse it as an Ieee32 to check for the right number of digits and other issues.
898             text.parse().map_err(|e| self.error(e))
899         } else {
900             err!(self.loc, err_msg)
901         }
902     }
903 
904     // Match and consume an Ieee64 immediate.
905     fn match_ieee64(&mut self, err_msg: &str) -> ParseResult<Ieee64> {
906         if let Some(Token::Float(text)) = self.token() {
907             self.consume();
908             // Lexer just gives us raw text that looks like a float.
909             // Parse it as an Ieee64 to check for the right number of digits and other issues.
910             text.parse().map_err(|e| self.error(e))
911         } else {
912             err!(self.loc, err_msg)
913         }
914     }
915 
916     // Match and consume an enumerated immediate, like one of the condition codes.
917     fn match_enum<T: FromStr>(&mut self, err_msg: &str) -> ParseResult<T> {
918         if let Some(Token::Identifier(text)) = self.token() {
919             self.consume();
920             text.parse().map_err(|_| self.error(err_msg))
921         } else {
922             err!(self.loc, err_msg)
923         }
924     }
925 
926     // Match and a consume a possibly empty sequence of memory operation flags.
927     fn optional_memflags(&mut self) -> MemFlags {
928         let mut flags = MemFlags::new();
929         while let Some(Token::Identifier(text)) = self.token() {
930             if flags.set_by_name(text) {
931                 self.consume();
932             } else {
933                 break;
934             }
935         }
936         flags
937     }
938 
939     // Match and consume an identifier.
940     fn match_any_identifier(&mut self, err_msg: &str) -> ParseResult<&'a str> {
941         if let Some(Token::Identifier(text)) = self.token() {
942             self.consume();
943             Ok(text)
944         } else {
945             err!(self.loc, err_msg)
946         }
947     }
948 
949     /// Parse an optional source location.
950     ///
951     /// Return an optional source location if no real location is present.
952     fn optional_srcloc(&mut self) -> ParseResult<ir::SourceLoc> {
953         if let Some(Token::SourceLoc(text)) = self.token() {
954             match u32::from_str_radix(text, 16) {
955                 Ok(num) => {
956                     self.consume();
957                     Ok(ir::SourceLoc::new(num))
958                 }
959                 Err(_) => return err!(self.loc, "invalid source location: {}", text),
960             }
961         } else {
962             Ok(Default::default())
963         }
964     }
965 
966     /// Parse a list of literals (i.e. integers, floats, booleans); e.g. `0 1 2 3`, usually as
967     /// part of something like `vconst.i32x4 [0 1 2 3]`.
968     fn parse_literals_to_constant_data(&mut self, ty: Type) -> ParseResult<ConstantData> {
969         macro_rules! consume {
970             ( $ty:ident, $match_fn:expr ) => {{
971                 assert!($ty.is_vector());
972                 let mut data = ConstantData::default();
973                 for _ in 0..$ty.lane_count() {
974                     data = data.append($match_fn);
975                 }
976                 data
977             }};
978         }
979 
980         if !ty.is_vector() && !ty.is_dynamic_vector() {
981             err!(self.loc, "Expected a controlling vector type, not {}", ty)
982         } else {
983             let constant_data = match ty.lane_type() {
984                 I8 => consume!(ty, self.match_imm8("Expected an 8-bit integer")?),
985                 I16 => consume!(ty, self.match_imm16("Expected a 16-bit integer")?),
986                 I32 => consume!(ty, self.match_imm32("Expected a 32-bit integer")?),
987                 I64 => consume!(ty, self.match_imm64("Expected a 64-bit integer")?),
988                 F32 => consume!(ty, self.match_ieee32("Expected a 32-bit float")?),
989                 F64 => consume!(ty, self.match_ieee64("Expected a 64-bit float")?),
990                 _ => return err!(self.loc, "Expected a type of: float, int, bool"),
991             };
992             Ok(constant_data)
993         }
994     }
995 
996     /// Parse a list of test command passes specified in command line.
997     pub fn parse_cmdline_passes(&mut self, passes: &'a [String]) -> Vec<TestCommand<'a>> {
998         let mut list = Vec::new();
999         for pass in passes {
1000             list.push(TestCommand::new(pass));
1001         }
1002         list
1003     }
1004 
1005     /// Parse a list of test commands.
1006     pub fn parse_test_commands(&mut self) -> Vec<TestCommand<'a>> {
1007         let mut list = Vec::new();
1008         while self.token() == Some(Token::Identifier("test")) {
1009             list.push(TestCommand::new(self.consume_line()));
1010         }
1011         list
1012     }
1013 
1014     /// Parse a target spec.
1015     ///
1016     /// Accept the target from the command line for pass command.
1017     ///
1018     fn parse_cmdline_target(&mut self, target_pass: Option<&str>) -> ParseResult<isaspec::IsaSpec> {
1019         // Were there any `target` commands specified?
1020         let mut specified_target = false;
1021 
1022         let mut targets = Vec::new();
1023         let flag_builder = settings::builder();
1024 
1025         if let Some(targ) = target_pass {
1026             let loc = self.loc;
1027             let triple = match Triple::from_str(targ) {
1028                 Ok(triple) => triple,
1029                 Err(err) => return err!(loc, err),
1030             };
1031             let isa_builder = match isa::lookup(triple) {
1032                 Err(isa::LookupError::SupportDisabled) => {
1033                     return err!(loc, "support disabled target '{}'", targ);
1034                 }
1035                 Err(isa::LookupError::Unsupported) => {
1036                     return warn!(loc, "unsupported target '{}'", targ);
1037                 }
1038                 Ok(b) => b,
1039             };
1040             specified_target = true;
1041 
1042             // Construct a trait object with the aggregate settings.
1043             targets.push(
1044                 isa_builder
1045                     .finish(settings::Flags::new(flag_builder.clone()))
1046                     .map_err(|e| ParseError {
1047                         location: loc,
1048                         message: format!("invalid ISA flags for '{}': {:?}", targ, e),
1049                         is_warning: false,
1050                     })?,
1051             );
1052         }
1053 
1054         if !specified_target {
1055             // No `target` commands.
1056             Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder)))
1057         } else {
1058             Ok(isaspec::IsaSpec::Some(targets))
1059         }
1060     }
1061 
1062     /// Parse a list of target specs.
1063     ///
1064     /// Accept a mix of `target` and `set` command lines. The `set` commands are cumulative.
1065     ///
1066     fn parse_target_specs(&mut self, options: &ParseOptions) -> ParseResult<isaspec::IsaSpec> {
1067         // Were there any `target` commands?
1068         let mut seen_target = false;
1069         // Location of last `set` command since the last `target`.
1070         let mut last_set_loc = None;
1071 
1072         let mut targets = Vec::new();
1073         let mut flag_builder = settings::builder();
1074 
1075         let bool_to_str = |val: bool| {
1076             if val {
1077                 "true"
1078             } else {
1079                 "false"
1080             }
1081         };
1082 
1083         // default to enabling cfg info
1084         flag_builder
1085             .set(
1086                 "machine_code_cfg_info",
1087                 bool_to_str(options.machine_code_cfg_info),
1088             )
1089             .expect("machine_code_cfg_info option should be present");
1090 
1091         flag_builder
1092             .set("unwind_info", bool_to_str(options.unwind_info))
1093             .expect("unwind_info option should be present");
1094 
1095         while let Some(Token::Identifier(command)) = self.token() {
1096             match command {
1097                 "set" => {
1098                     last_set_loc = Some(self.loc);
1099                     isaspec::parse_options(
1100                         self.consume_line().trim().split_whitespace(),
1101                         &mut flag_builder,
1102                         self.loc,
1103                     )
1104                     .map_err(|err| ParseError::from(err))?;
1105                 }
1106                 "target" => {
1107                     let loc = self.loc;
1108                     // Grab the whole line so the lexer won't go looking for tokens on the
1109                     // following lines.
1110                     let mut words = self.consume_line().trim().split_whitespace().peekable();
1111                     // Look for `target foo`.
1112                     let target_name = match words.next() {
1113                         Some(w) => w,
1114                         None => return err!(loc, "expected target triple"),
1115                     };
1116                     let triple = match Triple::from_str(target_name) {
1117                         Ok(triple) => triple,
1118                         Err(err) => return err!(loc, err),
1119                     };
1120                     let mut isa_builder = match isa::lookup(triple) {
1121                         Err(isa::LookupError::SupportDisabled) => {
1122                             continue;
1123                         }
1124                         Err(isa::LookupError::Unsupported) => {
1125                             return warn!(loc, "unsupported target '{}'", target_name);
1126                         }
1127                         Ok(b) => b,
1128                     };
1129                     last_set_loc = None;
1130                     seen_target = true;
1131                     // Apply the target-specific settings to `isa_builder`.
1132                     isaspec::parse_options(words, &mut isa_builder, self.loc)?;
1133 
1134                     // Construct a trait object with the aggregate settings.
1135                     targets.push(
1136                         isa_builder
1137                             .finish(settings::Flags::new(flag_builder.clone()))
1138                             .map_err(|e| ParseError {
1139                                 location: loc,
1140                                 message: format!(
1141                                     "invalid ISA flags for '{}': {:?}",
1142                                     target_name, e
1143                                 ),
1144                                 is_warning: false,
1145                             })?,
1146                     );
1147                 }
1148                 _ => break,
1149             }
1150         }
1151 
1152         if !seen_target {
1153             // No `target` commands, but we allow for `set` commands.
1154             Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder)))
1155         } else if let Some(loc) = last_set_loc {
1156             err!(
1157                 loc,
1158                 "dangling 'set' command after ISA specification has no effect."
1159             )
1160         } else {
1161             Ok(isaspec::IsaSpec::Some(targets))
1162         }
1163     }
1164 
1165     /// Parse a list of expected features that Cranelift should be compiled with, or without.
1166     pub fn parse_cranelift_features(&mut self) -> ParseResult<Vec<Feature<'a>>> {
1167         let mut list = Vec::new();
1168         while self.token() == Some(Token::Identifier("feature")) {
1169             self.consume();
1170             let has = !self.optional(Token::Bang);
1171             match (self.token(), has) {
1172                 (Some(Token::String(flag)), true) => list.push(Feature::With(flag)),
1173                 (Some(Token::String(flag)), false) => list.push(Feature::Without(flag)),
1174                 (tok, _) => {
1175                     return err!(
1176                         self.loc,
1177                         format!("Expected feature flag string, got {:?}", tok)
1178                     )
1179                 }
1180             }
1181             self.consume();
1182         }
1183         Ok(list)
1184     }
1185 
1186     /// Parse a list of function definitions.
1187     ///
1188     /// This is the top-level parse function matching the whole contents of a file.
1189     pub fn parse_function_list(&mut self) -> ParseResult<Vec<(Function, Details<'a>)>> {
1190         let mut list = Vec::new();
1191         while self.token().is_some() {
1192             list.push(self.parse_function()?);
1193         }
1194         if let Some(err) = self.lex_error {
1195             return match err {
1196                 LexError::InvalidChar => err!(self.loc, "invalid character"),
1197             };
1198         }
1199         Ok(list)
1200     }
1201 
1202     // Parse a whole function definition.
1203     //
1204     // function ::= * "function" name signature "{" preamble function-body "}"
1205     //
1206     fn parse_function(&mut self) -> ParseResult<(Function, Details<'a>)> {
1207         // Begin gathering comments.
1208         // Make sure we don't include any comments before the `function` keyword.
1209         self.token();
1210         debug_assert!(self.comments.is_empty());
1211         self.start_gathering_comments();
1212 
1213         self.match_identifier("function", "expected 'function'")?;
1214 
1215         let location = self.loc;
1216 
1217         // function ::= "function" * name signature "{" preamble function-body "}"
1218         let name = self.parse_user_func_name()?;
1219 
1220         // function ::= "function" name * signature "{" preamble function-body "}"
1221         let sig = self.parse_signature()?;
1222 
1223         let mut ctx = Context::new(Function::with_name_signature(name, sig));
1224 
1225         // function ::= "function" name signature * "{" preamble function-body "}"
1226         self.match_token(Token::LBrace, "expected '{' before function body")?;
1227 
1228         self.token();
1229         self.claim_gathered_comments(AnyEntity::Function);
1230 
1231         // function ::= "function" name signature "{" * preamble function-body "}"
1232         self.parse_preamble(&mut ctx)?;
1233         // function ::= "function" name signature "{"  preamble * function-body "}"
1234         self.parse_function_body(&mut ctx)?;
1235         // function ::= "function" name signature "{" preamble function-body * "}"
1236         self.match_token(Token::RBrace, "expected '}' after function body")?;
1237 
1238         // Collect any comments following the end of the function, then stop gathering comments.
1239         self.start_gathering_comments();
1240         self.token();
1241         self.claim_gathered_comments(AnyEntity::Function);
1242 
1243         // Claim all the declared user-defined function names.
1244         for (user_func_ref, user_external_name) in
1245             std::mem::take(&mut self.predeclared_external_names)
1246         {
1247             let actual_ref = ctx
1248                 .function
1249                 .declare_imported_user_function(user_external_name);
1250             assert_eq!(user_func_ref, actual_ref);
1251         }
1252 
1253         let details = Details {
1254             location,
1255             comments: self.take_comments(),
1256             map: ctx.map,
1257         };
1258 
1259         Ok((ctx.function, details))
1260     }
1261 
1262     // Parse a user-defined function name
1263     //
1264     // For example, in a function decl, the parser would be in this state:
1265     //
1266     // function ::= "function" * name signature { ... }
1267     //
1268     fn parse_user_func_name(&mut self) -> ParseResult<UserFuncName> {
1269         match self.token() {
1270             Some(Token::Name(s)) => {
1271                 self.consume();
1272                 Ok(UserFuncName::testcase(s))
1273             }
1274             Some(Token::UserRef(namespace)) => {
1275                 self.consume();
1276                 match self.token() {
1277                     Some(Token::Colon) => {
1278                         self.consume();
1279                         match self.token() {
1280                             Some(Token::Integer(index_str)) => {
1281                                 self.consume();
1282                                 let index: u32 =
1283                                     u32::from_str_radix(index_str, 10).map_err(|_| {
1284                                         self.error("the integer given overflows the u32 type")
1285                                     })?;
1286                                 Ok(UserFuncName::user(namespace, index))
1287                             }
1288                             _ => err!(self.loc, "expected integer"),
1289                         }
1290                     }
1291                     _ => {
1292                         err!(self.loc, "expected user function name in the form uX:Y")
1293                     }
1294                 }
1295             }
1296             _ => err!(self.loc, "expected external name"),
1297         }
1298     }
1299 
1300     // Parse an external name.
1301     //
1302     // For example, in a function reference decl, the parser would be in this state:
1303     //
1304     // fn0 = * name signature
1305     //
1306     fn parse_external_name(&mut self) -> ParseResult<ExternalName> {
1307         match self.token() {
1308             Some(Token::Name(s)) => {
1309                 self.consume();
1310                 s.parse()
1311                     .map_err(|_| self.error("invalid test case or libcall name"))
1312             }
1313 
1314             Some(Token::UserNameRef(name_ref)) => {
1315                 self.consume();
1316                 Ok(ExternalName::user(UserExternalNameRef::new(
1317                     name_ref as usize,
1318                 )))
1319             }
1320 
1321             Some(Token::UserRef(namespace)) => {
1322                 self.consume();
1323                 if let Some(Token::Colon) = self.token() {
1324                     self.consume();
1325                     match self.token() {
1326                         Some(Token::Integer(index_str)) => {
1327                             let index: u32 = u32::from_str_radix(index_str, 10).map_err(|_| {
1328                                 self.error("the integer given overflows the u32 type")
1329                             })?;
1330                             self.consume();
1331 
1332                             // Deduplicate the reference (O(n), but should be fine for tests),
1333                             // to follow `FunctionParameters::declare_imported_user_function`,
1334                             // otherwise this will cause ref mismatches when asserted below.
1335                             let name_ref = self
1336                                 .predeclared_external_names
1337                                 .iter()
1338                                 .find_map(|(reff, name)| {
1339                                     if name.index == index && name.namespace == namespace {
1340                                         Some(reff)
1341                                     } else {
1342                                         None
1343                                     }
1344                                 })
1345                                 .unwrap_or_else(|| {
1346                                     self.predeclared_external_names
1347                                         .push(ir::UserExternalName { namespace, index })
1348                                 });
1349 
1350                             Ok(ExternalName::user(name_ref))
1351                         }
1352                         _ => err!(self.loc, "expected integer"),
1353                     }
1354                 } else {
1355                     err!(self.loc, "expected colon")
1356                 }
1357             }
1358 
1359             _ => err!(self.loc, "expected external name"),
1360         }
1361     }
1362 
1363     // Parse a function signature.
1364     //
1365     // signature ::=  * "(" [paramlist] ")" ["->" retlist] [callconv]
1366     //
1367     fn parse_signature(&mut self) -> ParseResult<Signature> {
1368         // Calling convention defaults to `fast`, but can be changed.
1369         let mut sig = Signature::new(self.default_calling_convention);
1370 
1371         self.match_token(Token::LPar, "expected function signature: ( args... )")?;
1372         // signature ::=  "(" * [abi-param-list] ")" ["->" retlist] [callconv]
1373         if self.token() != Some(Token::RPar) {
1374             sig.params = self.parse_abi_param_list()?;
1375         }
1376         self.match_token(Token::RPar, "expected ')' after function arguments")?;
1377         if self.optional(Token::Arrow) {
1378             sig.returns = self.parse_abi_param_list()?;
1379         }
1380 
1381         // The calling convention is optional.
1382         if let Some(Token::Identifier(text)) = self.token() {
1383             match text.parse() {
1384                 Ok(cc) => {
1385                     self.consume();
1386                     sig.call_conv = cc;
1387                 }
1388                 _ => return err!(self.loc, "unknown calling convention: {}", text),
1389             }
1390         }
1391 
1392         Ok(sig)
1393     }
1394 
1395     // Parse list of function parameter / return value types.
1396     //
1397     // paramlist ::= * param { "," param }
1398     //
1399     fn parse_abi_param_list(&mut self) -> ParseResult<Vec<AbiParam>> {
1400         let mut list = Vec::new();
1401 
1402         // abi-param-list ::= * abi-param { "," abi-param }
1403         list.push(self.parse_abi_param()?);
1404 
1405         // abi-param-list ::= abi-param * { "," abi-param }
1406         while self.optional(Token::Comma) {
1407             // abi-param-list ::= abi-param { "," * abi-param }
1408             list.push(self.parse_abi_param()?);
1409         }
1410 
1411         Ok(list)
1412     }
1413 
1414     // Parse a single argument type with flags.
1415     fn parse_abi_param(&mut self) -> ParseResult<AbiParam> {
1416         // abi-param ::= * type { flag }
1417         let mut arg = AbiParam::new(self.match_type("expected parameter type")?);
1418 
1419         // abi-param ::= type * { flag }
1420         while let Some(Token::Identifier(s)) = self.token() {
1421             match s {
1422                 "uext" => arg.extension = ArgumentExtension::Uext,
1423                 "sext" => arg.extension = ArgumentExtension::Sext,
1424                 "sarg" => {
1425                     self.consume();
1426                     self.match_token(Token::LPar, "expected '(' to begin sarg size")?;
1427                     let size = self.match_uimm32("expected byte-size in sarg decl")?;
1428                     self.match_token(Token::RPar, "expected ')' to end sarg size")?;
1429                     arg.purpose = ArgumentPurpose::StructArgument(size.into());
1430                     continue;
1431                 }
1432                 _ => {
1433                     if let Ok(purpose) = s.parse() {
1434                         arg.purpose = purpose;
1435                     } else {
1436                         break;
1437                     }
1438                 }
1439             }
1440             self.consume();
1441         }
1442 
1443         Ok(arg)
1444     }
1445 
1446     // Parse the function preamble.
1447     //
1448     // preamble      ::= * { preamble-decl }
1449     // preamble-decl ::= * stack-slot-decl
1450     //                   * function-decl
1451     //                   * signature-decl
1452     //                   * jump-table-decl
1453     //                   * stack-limit-decl
1454     //
1455     // The parsed decls are added to `ctx` rather than returned.
1456     fn parse_preamble(&mut self, ctx: &mut Context) -> ParseResult<()> {
1457         loop {
1458             match self.token() {
1459                 Some(Token::StackSlot(..)) => {
1460                     self.start_gathering_comments();
1461                     let loc = self.loc;
1462                     self.parse_stack_slot_decl()
1463                         .and_then(|(ss, dat)| ctx.add_ss(ss, dat, loc))
1464                 }
1465                 Some(Token::DynamicStackSlot(..)) => {
1466                     self.start_gathering_comments();
1467                     let loc = self.loc;
1468                     self.parse_dynamic_stack_slot_decl()
1469                         .and_then(|(dss, dat)| ctx.add_dss(dss, dat, loc))
1470                 }
1471                 Some(Token::DynamicType(..)) => {
1472                     self.start_gathering_comments();
1473                     let loc = self.loc;
1474                     self.parse_dynamic_type_decl()
1475                         .and_then(|(dt, dat)| ctx.add_dt(dt, dat, loc))
1476                 }
1477                 Some(Token::GlobalValue(..)) => {
1478                     self.start_gathering_comments();
1479                     self.parse_global_value_decl()
1480                         .and_then(|(gv, dat, maybe_fact)| ctx.add_gv(gv, dat, maybe_fact, self.loc))
1481                 }
1482                 Some(Token::MemoryType(..)) => {
1483                     self.start_gathering_comments();
1484                     self.parse_memory_type_decl()
1485                         .and_then(|(mt, dat)| ctx.add_mt(mt, dat, self.loc))
1486                 }
1487                 Some(Token::Table(..)) => {
1488                     self.start_gathering_comments();
1489                     self.parse_table_decl()
1490                         .and_then(|(table, dat)| ctx.add_table(table, dat, self.loc))
1491                 }
1492                 Some(Token::SigRef(..)) => {
1493                     self.start_gathering_comments();
1494                     self.parse_signature_decl().and_then(|(sig, dat)| {
1495                         ctx.add_sig(sig, dat, self.loc, self.default_calling_convention)
1496                     })
1497                 }
1498                 Some(Token::FuncRef(..)) => {
1499                     self.start_gathering_comments();
1500                     self.parse_function_decl(ctx)
1501                         .and_then(|(fn_, dat)| ctx.add_fn(fn_, dat, self.loc))
1502                 }
1503                 Some(Token::Constant(..)) => {
1504                     self.start_gathering_comments();
1505                     self.parse_constant_decl()
1506                         .and_then(|(c, v)| ctx.add_constant(c, v, self.loc))
1507                 }
1508                 Some(Token::Identifier("stack_limit")) => {
1509                     self.start_gathering_comments();
1510                     self.parse_stack_limit_decl()
1511                         .and_then(|gv| ctx.add_stack_limit(gv, self.loc))
1512                 }
1513                 // More to come..
1514                 _ => return Ok(()),
1515             }?;
1516         }
1517     }
1518 
1519     // Parse a stack slot decl.
1520     //
1521     // stack-slot-decl ::= * StackSlot(ss) "=" stack-slot-kind Bytes {"," stack-slot-flag}
1522     // stack-slot-kind ::= "explicit_slot"
1523     //                   | "spill_slot"
1524     //                   | "incoming_arg"
1525     //                   | "outgoing_arg"
1526     fn parse_stack_slot_decl(&mut self) -> ParseResult<(StackSlot, StackSlotData)> {
1527         let ss = self.match_ss("expected stack slot number: ss«n»")?;
1528         self.match_token(Token::Equal, "expected '=' in stack slot declaration")?;
1529         let kind = self.match_enum("expected stack slot kind")?;
1530 
1531         // stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind * Bytes {"," stack-slot-flag}
1532         let bytes: i64 = self
1533             .match_imm64("expected byte-size in stack_slot decl")?
1534             .into();
1535         if bytes < 0 {
1536             return err!(self.loc, "negative stack slot size");
1537         }
1538         if bytes > i64::from(u32::MAX) {
1539             return err!(self.loc, "stack slot too large");
1540         }
1541         let data = StackSlotData::new(kind, bytes as u32);
1542 
1543         // Collect any trailing comments.
1544         self.token();
1545         self.claim_gathered_comments(ss);
1546 
1547         // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag}
1548         Ok((ss, data))
1549     }
1550 
1551     fn parse_dynamic_stack_slot_decl(
1552         &mut self,
1553     ) -> ParseResult<(DynamicStackSlot, DynamicStackSlotData)> {
1554         let dss = self.match_dss("expected stack slot number: dss«n»")?;
1555         self.match_token(Token::Equal, "expected '=' in stack slot declaration")?;
1556         let kind = self.match_enum("expected stack slot kind")?;
1557         let dt = self.match_dt("expected dynamic type")?;
1558         let data = DynamicStackSlotData::new(kind, dt);
1559         // Collect any trailing comments.
1560         self.token();
1561         self.claim_gathered_comments(dss);
1562 
1563         // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag}
1564         Ok((dss, data))
1565     }
1566 
1567     fn parse_dynamic_type_decl(&mut self) -> ParseResult<(DynamicType, DynamicTypeData)> {
1568         let dt = self.match_dt("expected dynamic type number: dt«n»")?;
1569         self.match_token(Token::Equal, "expected '=' in stack slot declaration")?;
1570         let vector_base_ty = self.match_type("expected base type")?;
1571         assert!(vector_base_ty.is_vector(), "expected vector type");
1572         self.match_token(
1573             Token::Multiply,
1574             "expected '*' followed by a dynamic scale value",
1575         )?;
1576         let dyn_scale = self.match_gv("expected dynamic scale global value")?;
1577         let data = DynamicTypeData::new(vector_base_ty, dyn_scale);
1578         // Collect any trailing comments.
1579         self.token();
1580         self.claim_gathered_comments(dt);
1581         Ok((dt, data))
1582     }
1583 
1584     // Parse a global value decl.
1585     //
1586     // global-val-decl ::= * GlobalValue(gv) [ "!" fact ] "=" global-val-desc
1587     // global-val-desc ::= "vmctx"
1588     //                   | "load" "." type "notrap" "aligned" GlobalValue(base) [offset]
1589     //                   | "iadd_imm" "(" GlobalValue(base) ")" imm64
1590     //                   | "symbol" ["colocated"] name + imm64
1591     //                   | "dyn_scale_target_const" "." type
1592     //
1593     fn parse_global_value_decl(
1594         &mut self,
1595     ) -> ParseResult<(GlobalValue, GlobalValueData, Option<Fact>)> {
1596         let gv = self.match_gv("expected global value number: gv«n»")?;
1597 
1598         let fact = if self.token() == Some(Token::Bang) {
1599             self.consume();
1600             Some(self.parse_fact()?)
1601         } else {
1602             None
1603         };
1604 
1605         self.match_token(Token::Equal, "expected '=' in global value declaration")?;
1606 
1607         let data = match self.match_any_identifier("expected global value kind")? {
1608             "vmctx" => GlobalValueData::VMContext,
1609             "load" => {
1610                 self.match_token(
1611                     Token::Dot,
1612                     "expected '.' followed by type in load global value decl",
1613                 )?;
1614                 let global_type = self.match_type("expected load type")?;
1615                 let flags = self.optional_memflags();
1616                 let base = self.match_gv("expected global value: gv«n»")?;
1617                 let offset = self.optional_offset32()?;
1618 
1619                 if !(flags.notrap() && flags.aligned()) {
1620                     return err!(self.loc, "global-value load must be notrap and aligned");
1621                 }
1622                 GlobalValueData::Load {
1623                     base,
1624                     offset,
1625                     global_type,
1626                     flags,
1627                 }
1628             }
1629             "iadd_imm" => {
1630                 self.match_token(
1631                     Token::Dot,
1632                     "expected '.' followed by type in iadd_imm global value decl",
1633                 )?;
1634                 let global_type = self.match_type("expected iadd type")?;
1635                 let base = self.match_gv("expected global value: gv«n»")?;
1636                 self.match_token(
1637                     Token::Comma,
1638                     "expected ',' followed by rhs in iadd_imm global value decl",
1639                 )?;
1640                 let offset = self.match_imm64("expected iadd_imm immediate")?;
1641                 GlobalValueData::IAddImm {
1642                     base,
1643                     offset,
1644                     global_type,
1645                 }
1646             }
1647             "symbol" => {
1648                 let colocated = self.optional(Token::Identifier("colocated"));
1649                 let tls = self.optional(Token::Identifier("tls"));
1650                 let name = self.parse_external_name()?;
1651                 let offset = self.optional_offset_imm64()?;
1652                 GlobalValueData::Symbol {
1653                     name,
1654                     offset,
1655                     colocated,
1656                     tls,
1657                 }
1658             }
1659             "dyn_scale_target_const" => {
1660                 self.match_token(
1661                     Token::Dot,
1662                     "expected '.' followed by type in dynamic scale global value decl",
1663                 )?;
1664                 let vector_type = self.match_type("expected load type")?;
1665                 assert!(vector_type.is_vector(), "Expected vector type");
1666                 GlobalValueData::DynScaleTargetConst { vector_type }
1667             }
1668             other => return err!(self.loc, "Unknown global value kind '{}'", other),
1669         };
1670 
1671         // Collect any trailing comments.
1672         self.token();
1673         self.claim_gathered_comments(gv);
1674 
1675         Ok((gv, data, fact))
1676     }
1677 
1678     // Parse one field definition in a memory-type struct decl.
1679     //
1680     // memory-type-field ::=  offset ":" type ["readonly"] [ "!" fact ]
1681     // offset ::= uimm64
1682     fn parse_memory_type_field(&mut self) -> ParseResult<MemoryTypeField> {
1683         let offset: u64 = self
1684             .match_uimm64(
1685                 "expected u64 constant value for field offset in struct memory-type declaration",
1686             )?
1687             .into();
1688         self.match_token(
1689             Token::Colon,
1690             "expected colon after field offset in struct memory-type declaration",
1691         )?;
1692         let ty = self.match_type("expected type for field in struct memory-type declaration")?;
1693         let readonly = if self.token() == Some(Token::Identifier("readonly")) {
1694             self.consume();
1695             true
1696         } else {
1697             false
1698         };
1699         let fact = if self.token() == Some(Token::Bang) {
1700             self.consume();
1701             let fact = self.parse_fact()?;
1702             Some(fact)
1703         } else {
1704             None
1705         };
1706         Ok(MemoryTypeField {
1707             offset,
1708             ty,
1709             readonly,
1710             fact,
1711         })
1712     }
1713 
1714     // Parse a memory-type decl.
1715     //
1716     // memory-type-decl ::= MemoryType(mt) "=" memory-type-desc
1717     // memory-type-desc ::= "struct" size "{" memory-type-field,* "}"
1718     //                    | "memory" size
1719     //                    | "empty"
1720     // size ::= uimm64
1721     fn parse_memory_type_decl(&mut self) -> ParseResult<(MemoryType, MemoryTypeData)> {
1722         let mt = self.match_mt("expected memory type number: mt«n»")?;
1723         self.match_token(Token::Equal, "expected '=' in memory type declaration")?;
1724 
1725         let data = match self.token() {
1726             Some(Token::Identifier("struct")) => {
1727                 self.consume();
1728                 let size: u64 = self.match_uimm64("expected u64 constant value for struct size in struct memory-type declaration")?.into();
1729                 self.match_token(Token::LBrace, "expected opening brace to start struct fields in struct memory-type declaration")?;
1730                 let mut fields = vec![];
1731                 while self.token() != Some(Token::RBrace) {
1732                     let field = self.parse_memory_type_field()?;
1733                     fields.push(field);
1734                     if self.token() == Some(Token::Comma) {
1735                         self.consume();
1736                     } else {
1737                         break;
1738                     }
1739                 }
1740                 self.match_token(
1741                     Token::RBrace,
1742                     "expected closing brace after struct fields in struct memory-type declaration",
1743                 )?;
1744                 MemoryTypeData::Struct { size, fields }
1745             }
1746             Some(Token::Identifier("memory")) => {
1747                 self.consume();
1748                 let size: u64 = self.match_uimm64("expected u64 constant value for size in static-memory memory-type declaration")?.into();
1749                 MemoryTypeData::Memory { size }
1750             }
1751             Some(Token::Identifier("empty")) => {
1752                 self.consume();
1753                 MemoryTypeData::Empty
1754             }
1755             other => {
1756                 return err!(
1757                     self.loc,
1758                     "Unknown memory type declaration kind '{:?}'",
1759                     other
1760                 )
1761             }
1762         };
1763 
1764         // Collect any trailing comments.
1765         self.token();
1766         self.claim_gathered_comments(mt);
1767 
1768         Ok((mt, data))
1769     }
1770 
1771     // Parse a table decl.
1772     //
1773     // table-decl ::= * Table(table) "=" table-desc
1774     // table-desc ::= table-style table-base { "," table-attr }
1775     // table-style ::= "dynamic"
1776     // table-base ::= GlobalValue(base)
1777     // table-attr ::= "min" Imm64(bytes)
1778     //              | "bound" Imm64(bytes)
1779     //              | "element_size" Imm64(bytes)
1780     //              | "index_type" type
1781     //
1782     fn parse_table_decl(&mut self) -> ParseResult<(Table, TableData)> {
1783         let table = self.match_table("expected table number: table«n»")?;
1784         self.match_token(Token::Equal, "expected '=' in table declaration")?;
1785 
1786         let style_name = self.match_any_identifier("expected 'static' or 'dynamic'")?;
1787 
1788         // table-desc ::= table-style * table-base { "," table-attr }
1789         // table-base ::= * GlobalValue(base)
1790         let base = match self.token() {
1791             Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) {
1792                 Some(gv) => gv,
1793                 None => return err!(self.loc, "invalid global value number for table base"),
1794             },
1795             _ => return err!(self.loc, "expected table base"),
1796         };
1797         self.consume();
1798 
1799         let mut data = TableData {
1800             base_gv: base,
1801             min_size: 0.into(),
1802             bound_gv: GlobalValue::reserved_value(),
1803             element_size: 0.into(),
1804             index_type: ir::types::I32,
1805         };
1806 
1807         // table-desc ::= * { "," table-attr }
1808         while self.optional(Token::Comma) {
1809             match self.match_any_identifier("expected table attribute name")? {
1810                 "min" => {
1811                     data.min_size = self.match_uimm64("expected integer min size")?;
1812                 }
1813                 "bound" => {
1814                     data.bound_gv = match style_name {
1815                         "dynamic" => self.match_gv("expected gv bound")?,
1816                         t => return err!(self.loc, "unknown table style '{}'", t),
1817                     };
1818                 }
1819                 "element_size" => {
1820                     data.element_size = self.match_uimm64("expected integer element size")?;
1821                 }
1822                 "index_type" => {
1823                     data.index_type = self.match_type("expected index type")?;
1824                 }
1825                 t => return err!(self.loc, "unknown table attribute '{}'", t),
1826             }
1827         }
1828 
1829         // Collect any trailing comments.
1830         self.token();
1831         self.claim_gathered_comments(table);
1832 
1833         Ok((table, data))
1834     }
1835 
1836     // Parse a signature decl.
1837     //
1838     // signature-decl ::= SigRef(sigref) "=" signature
1839     //
1840     fn parse_signature_decl(&mut self) -> ParseResult<(SigRef, Signature)> {
1841         let sig = self.match_sig("expected signature number: sig«n»")?;
1842         self.match_token(Token::Equal, "expected '=' in signature decl")?;
1843         let data = self.parse_signature()?;
1844 
1845         // Collect any trailing comments.
1846         self.token();
1847         self.claim_gathered_comments(sig);
1848 
1849         Ok((sig, data))
1850     }
1851 
1852     // Parse a function decl.
1853     //
1854     // Two variants:
1855     //
1856     // function-decl ::= FuncRef(fnref) "=" ["colocated"]" name function-decl-sig
1857     // function-decl-sig ::= SigRef(sig) | signature
1858     //
1859     // The first variant allocates a new signature reference. The second references an existing
1860     // signature which must be declared first.
1861     //
1862     fn parse_function_decl(&mut self, ctx: &mut Context) -> ParseResult<(FuncRef, ExtFuncData)> {
1863         let fn_ = self.match_fn("expected function number: fn«n»")?;
1864         self.match_token(Token::Equal, "expected '=' in function decl")?;
1865 
1866         let loc = self.loc;
1867 
1868         // function-decl ::= FuncRef(fnref) "=" * ["colocated"] name function-decl-sig
1869         let colocated = self.optional(Token::Identifier("colocated"));
1870 
1871         // function-decl ::= FuncRef(fnref) "=" ["colocated"] * name function-decl-sig
1872         let name = self.parse_external_name()?;
1873 
1874         // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * function-decl-sig
1875         let data = match self.token() {
1876             Some(Token::LPar) => {
1877                 // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * signature
1878                 let sig = self.parse_signature()?;
1879                 let sigref = ctx.function.import_signature(sig);
1880                 ctx.map
1881                     .def_entity(sigref.into(), loc)
1882                     .expect("duplicate SigRef entities created");
1883                 ExtFuncData {
1884                     name,
1885                     signature: sigref,
1886                     colocated,
1887                 }
1888             }
1889             Some(Token::SigRef(sig_src)) => {
1890                 let sig = match SigRef::with_number(sig_src) {
1891                     None => {
1892                         return err!(self.loc, "attempted to use invalid signature ss{}", sig_src);
1893                     }
1894                     Some(sig) => sig,
1895                 };
1896                 ctx.check_sig(sig, self.loc)?;
1897                 self.consume();
1898                 ExtFuncData {
1899                     name,
1900                     signature: sig,
1901                     colocated,
1902                 }
1903             }
1904             _ => return err!(self.loc, "expected 'function' or sig«n» in function decl"),
1905         };
1906 
1907         // Collect any trailing comments.
1908         self.token();
1909         self.claim_gathered_comments(fn_);
1910 
1911         Ok((fn_, data))
1912     }
1913 
1914     // Parse a jump table literal.
1915     //
1916     // jump-table-lit ::= "[" block(args) {"," block(args) } "]"
1917     //                  | "[]"
1918     fn parse_jump_table(
1919         &mut self,
1920         ctx: &mut Context,
1921         def: ir::BlockCall,
1922     ) -> ParseResult<ir::JumpTable> {
1923         self.match_token(Token::LBracket, "expected '[' before jump table contents")?;
1924 
1925         let mut data = Vec::new();
1926 
1927         match self.token() {
1928             Some(Token::Block(dest)) => {
1929                 self.consume();
1930                 let args = self.parse_opt_value_list()?;
1931                 data.push(ctx.function.dfg.block_call(dest, &args));
1932 
1933                 loop {
1934                     match self.token() {
1935                         Some(Token::Comma) => {
1936                             self.consume();
1937                             if let Some(Token::Block(dest)) = self.token() {
1938                                 self.consume();
1939                                 let args = self.parse_opt_value_list()?;
1940                                 data.push(ctx.function.dfg.block_call(dest, &args));
1941                             } else {
1942                                 return err!(self.loc, "expected jump_table entry");
1943                             }
1944                         }
1945                         Some(Token::RBracket) => break,
1946                         _ => return err!(self.loc, "expected ']' after jump table contents"),
1947                     }
1948                 }
1949             }
1950             Some(Token::RBracket) => (),
1951             _ => return err!(self.loc, "expected jump_table entry"),
1952         }
1953 
1954         self.consume();
1955 
1956         Ok(ctx
1957             .function
1958             .dfg
1959             .jump_tables
1960             .push(JumpTableData::new(def, &data)))
1961     }
1962 
1963     // Parse a constant decl.
1964     //
1965     // constant-decl ::= * Constant(c) "=" ty? "[" literal {"," literal} "]"
1966     fn parse_constant_decl(&mut self) -> ParseResult<(Constant, ConstantData)> {
1967         let name = self.match_constant()?;
1968         self.match_token(Token::Equal, "expected '=' in constant decl")?;
1969         let data = if let Some(Token::Type(_)) = self.token() {
1970             let ty = self.match_type("expected type of constant")?;
1971             self.match_uimm128(ty)
1972         } else {
1973             self.match_hexadecimal_constant("expected an immediate hexadecimal operand")
1974         }?;
1975 
1976         // Collect any trailing comments.
1977         self.token();
1978         self.claim_gathered_comments(name);
1979 
1980         Ok((name, data))
1981     }
1982 
1983     // Parse a stack limit decl
1984     //
1985     // stack-limit-decl ::= * StackLimit "=" GlobalValue(gv)
1986     fn parse_stack_limit_decl(&mut self) -> ParseResult<GlobalValue> {
1987         self.match_stack_limit()?;
1988         self.match_token(Token::Equal, "expected '=' in stack limit decl")?;
1989         let limit = match self.token() {
1990             Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) {
1991                 Some(gv) => gv,
1992                 None => return err!(self.loc, "invalid global value number for stack limit"),
1993             },
1994             _ => return err!(self.loc, "expected global value"),
1995         };
1996         self.consume();
1997 
1998         // Collect any trailing comments.
1999         self.token();
2000         self.claim_gathered_comments(AnyEntity::StackLimit);
2001 
2002         Ok(limit)
2003     }
2004 
2005     // Parse a function body, add contents to `ctx`.
2006     //
2007     // function-body ::= * { extended-basic-block }
2008     //
2009     fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> {
2010         while self.token() != Some(Token::RBrace) {
2011             self.parse_basic_block(ctx)?;
2012         }
2013 
2014         // Now that we've seen all defined values in the function, ensure that
2015         // all references refer to a definition.
2016         for block in &ctx.function.layout {
2017             for inst in ctx.function.layout.block_insts(block) {
2018                 for value in ctx.function.dfg.inst_values(inst) {
2019                     if !ctx.map.contains_value(value) {
2020                         return err!(
2021                             ctx.map.location(AnyEntity::Inst(inst)).unwrap(),
2022                             "undefined operand value {}",
2023                             value
2024                         );
2025                     }
2026                 }
2027             }
2028         }
2029 
2030         for alias in &ctx.aliases {
2031             if !ctx.function.dfg.set_alias_type_for_parser(*alias) {
2032                 let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap();
2033                 return err!(loc, "alias cycle involving {}", alias);
2034             }
2035         }
2036 
2037         Ok(())
2038     }
2039 
2040     // Parse a basic block, add contents to `ctx`.
2041     //
2042     // extended-basic-block ::= * block-header { instruction }
2043     // block-header         ::= Block(block) [block-params] [block-flags] ":"
2044     // block-flags          ::= [Cold]
2045     //
2046     fn parse_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> {
2047         // Collect comments for the next block.
2048         self.start_gathering_comments();
2049 
2050         let block_num = self.match_block("expected block header")?;
2051         let block = ctx.add_block(block_num, self.loc)?;
2052 
2053         if block_num.as_u32() >= MAX_BLOCKS_IN_A_FUNCTION {
2054             return Err(self.error("too many blocks"));
2055         }
2056 
2057         if self.token() == Some(Token::LPar) {
2058             self.parse_block_params(ctx, block)?;
2059         }
2060 
2061         if self.optional(Token::Cold) {
2062             ctx.set_cold_block(block);
2063         }
2064 
2065         self.match_token(Token::Colon, "expected ':' after block parameters")?;
2066 
2067         // Collect any trailing comments.
2068         self.token();
2069         self.claim_gathered_comments(block);
2070 
2071         // extended-basic-block ::= block-header * { instruction }
2072         while match self.token() {
2073             Some(Token::Value(_))
2074             | Some(Token::Identifier(_))
2075             | Some(Token::LBracket)
2076             | Some(Token::SourceLoc(_)) => true,
2077             _ => false,
2078         } {
2079             let srcloc = self.optional_srcloc()?;
2080 
2081             // We need to parse instruction results here because they are shared
2082             // between the parsing of value aliases and the parsing of instructions.
2083             //
2084             // inst-results ::= Value(v) { "," Value(v) }
2085             let results = self.parse_inst_results(ctx)?;
2086 
2087             for result in &results {
2088                 while ctx.function.dfg.num_values() <= result.index() {
2089                     ctx.function.dfg.make_invalid_value_for_parser();
2090                 }
2091             }
2092 
2093             match self.token() {
2094                 Some(Token::Arrow) => {
2095                     self.consume();
2096                     self.parse_value_alias(&results, ctx)?;
2097                 }
2098                 Some(Token::Equal) => {
2099                     self.consume();
2100                     self.parse_instruction(&results, srcloc, ctx, block)?;
2101                 }
2102                 _ if !results.is_empty() => return err!(self.loc, "expected -> or ="),
2103                 _ => self.parse_instruction(&results, srcloc, ctx, block)?,
2104             }
2105         }
2106 
2107         Ok(())
2108     }
2109 
2110     // Parse parenthesized list of block parameters. Returns a vector of (u32, Type) pairs with the
2111     // value numbers of the defined values and the defined types.
2112     //
2113     // block-params ::= * "(" block-param { "," block-param } ")"
2114     fn parse_block_params(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
2115         // block-params ::= * "(" block-param { "," block-param } ")"
2116         self.match_token(Token::LPar, "expected '(' before block parameters")?;
2117 
2118         // block-params ::= "(" * block-param { "," block-param } ")"
2119         self.parse_block_param(ctx, block)?;
2120 
2121         // block-params ::= "(" block-param * { "," block-param } ")"
2122         while self.optional(Token::Comma) {
2123             // block-params ::= "(" block-param { "," * block-param } ")"
2124             self.parse_block_param(ctx, block)?;
2125         }
2126 
2127         // block-params ::= "(" block-param { "," block-param } * ")"
2128         self.match_token(Token::RPar, "expected ')' after block parameters")?;
2129 
2130         Ok(())
2131     }
2132 
2133     // Parse a single block parameter declaration, and append it to `block`.
2134     //
2135     // block-param ::= * Value(v) [ "!" fact ]  ":" Type(t) arg-loc?
2136     // arg-loc ::= "[" value-location "]"
2137     //
2138     fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
2139         // block-param ::= * Value(v) [ "!" fact ] ":" Type(t) arg-loc?
2140         let v = self.match_value("block argument must be a value")?;
2141         let v_location = self.loc;
2142         // block-param ::= Value(v) * [ "!" fact ]  ":" Type(t) arg-loc?
2143         let fact = if self.token() == Some(Token::Bang) {
2144             self.consume();
2145             // block-param ::= Value(v) [ "!" * fact ]  ":" Type(t) arg-loc?
2146             Some(self.parse_fact()?)
2147         } else {
2148             None
2149         };
2150         self.match_token(Token::Colon, "expected ':' after block argument")?;
2151         // block-param ::= Value(v) [ "!" fact ] ":" * Type(t) arg-loc?
2152 
2153         while ctx.function.dfg.num_values() <= v.index() {
2154             ctx.function.dfg.make_invalid_value_for_parser();
2155         }
2156 
2157         let t = self.match_type("expected block argument type")?;
2158         // Allocate the block argument.
2159         ctx.function.dfg.append_block_param_for_parser(block, t, v);
2160         ctx.map.def_value(v, v_location)?;
2161         ctx.function.dfg.facts[v] = fact;
2162 
2163         Ok(())
2164     }
2165 
2166     // Parse a "fact" for proof-carrying code, attached to a value.
2167     //
2168     // fact ::= "range" "(" bit-width "," min-value "," max-value ")"
2169     //        | "mem" "(" memory-type "," mt-offset "," mt-offset ")"
2170     //        | "conflict"
2171     // bit-width ::= uimm64
2172     // min-value ::= uimm64
2173     // max-value ::= uimm64
2174     // valid-range ::= uimm64
2175     // mt-offset ::= uimm64
2176     fn parse_fact(&mut self) -> ParseResult<Fact> {
2177         match self.token() {
2178             Some(Token::Identifier("range")) => {
2179                 self.consume();
2180                 self.match_token(Token::LPar, "`range` fact needs an opening `(`")?;
2181                 let bit_width: u64 = self
2182                     .match_uimm64("expected a bit-width value for `range` fact")?
2183                     .into();
2184                 self.match_token(Token::Comma, "expected a comma")?;
2185                 let min: u64 = self
2186                     .match_uimm64("expected a min value for `range` fact")?
2187                     .into();
2188                 self.match_token(Token::Comma, "expected a comma")?;
2189                 let max: u64 = self
2190                     .match_uimm64("expected a max value for `range` fact")?
2191                     .into();
2192                 self.match_token(Token::RPar, "`range` fact needs a closing `)`")?;
2193                 let bit_width_max = match bit_width {
2194                     x if x > 64 => {
2195                         return Err(self.error("bitwidth must be <= 64 bits on a `range` fact"));
2196                     }
2197                     64 => u64::MAX,
2198                     x => (1u64 << x) - 1,
2199                 };
2200                 if min > max {
2201                     return Err(self.error(
2202                         "min value must be less than or equal to max value on a `range` fact",
2203                     ));
2204                 }
2205                 if max > bit_width_max {
2206                     return Err(
2207                         self.error("max value is out of range for bitwidth on a `range` fact")
2208                     );
2209                 }
2210                 Ok(Fact::Range {
2211                     bit_width: u16::try_from(bit_width).unwrap(),
2212                     min: min.into(),
2213                     max: max.into(),
2214                 })
2215             }
2216             Some(Token::Identifier("mem")) => {
2217                 self.consume();
2218                 self.match_token(Token::LPar, "expected a `(`")?;
2219                 let ty = self.match_mt("expected a memory type for `mem` fact")?;
2220                 self.match_token(
2221                     Token::Comma,
2222                     "expected a comma after memory type in `mem` fact",
2223                 )?;
2224                 let min_offset: u64 = self
2225                     .match_uimm64("expected a uimm64 minimum pointer offset for `mem` fact")?
2226                     .into();
2227                 self.match_token(
2228                     Token::Comma,
2229                     "expected a comma after memory type in `mem` fact",
2230                 )?;
2231                 let max_offset: u64 = self
2232                     .match_uimm64("expected a uimm64 maximum pointer offset for `mem` fact")?
2233                     .into();
2234                 self.match_token(Token::RPar, "expected a `)`")?;
2235                 Ok(Fact::Mem {
2236                     ty,
2237                     min_offset,
2238                     max_offset,
2239                 })
2240             }
2241             Some(Token::Identifier("conflict")) => {
2242                 self.consume();
2243                 Ok(Fact::Conflict)
2244             }
2245             _ => Err(self.error("expected a `range`, `mem` or `conflict` fact")),
2246         }
2247     }
2248 
2249     // Parse instruction results and return them.
2250     //
2251     // inst-results ::= Value(v) { "," Value(v) }
2252     //
2253     fn parse_inst_results(&mut self, ctx: &mut Context) -> ParseResult<SmallVec<[Value; 1]>> {
2254         // Result value numbers.
2255         let mut results = SmallVec::new();
2256 
2257         // instruction  ::=  * [inst-results "="] Opcode(opc) ["." Type] ...
2258         // inst-results ::= * Value(v) { "," Value(v) }
2259         if let Some(Token::Value(v)) = self.token() {
2260             self.consume();
2261 
2262             results.push(v);
2263 
2264             let fact = if self.token() == Some(Token::Bang) {
2265                 self.consume();
2266                 // block-param ::= Value(v) [ "!" * fact ]  ":" Type(t) arg-loc?
2267                 Some(self.parse_fact()?)
2268             } else {
2269                 None
2270             };
2271             ctx.function.dfg.facts[v] = fact;
2272 
2273             // inst-results ::= Value(v) * { "," Value(v) }
2274             while self.optional(Token::Comma) {
2275                 // inst-results ::= Value(v) { "," * Value(v) }
2276                 let v = self.match_value("expected result value")?;
2277                 results.push(v);
2278 
2279                 let fact = if self.token() == Some(Token::Bang) {
2280                     self.consume();
2281                     // block-param ::= Value(v) [ "!" * fact ]  ":" Type(t) arg-loc?
2282                     Some(self.parse_fact()?)
2283                 } else {
2284                     None
2285                 };
2286                 ctx.function.dfg.facts[v] = fact;
2287             }
2288         }
2289 
2290         Ok(results)
2291     }
2292 
2293     // Parse a value alias, and append it to `block`.
2294     //
2295     // value_alias ::= [inst-results] "->" Value(v)
2296     //
2297     fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> {
2298         if results.len() != 1 {
2299             return err!(self.loc, "wrong number of aliases");
2300         }
2301         let result = results[0];
2302         let dest = self.match_value("expected value alias")?;
2303 
2304         // Allow duplicate definitions of aliases, as long as they are identical.
2305         if ctx.map.contains_value(result) {
2306             if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) {
2307                 if old != dest {
2308                     return err!(
2309                         self.loc,
2310                         "value {} is already defined as an alias with destination {}",
2311                         result,
2312                         old
2313                     );
2314                 }
2315             } else {
2316                 return err!(self.loc, "value {} is already defined");
2317             }
2318         } else {
2319             ctx.map.def_value(result, self.loc)?;
2320         }
2321 
2322         if !ctx.map.contains_value(dest) {
2323             return err!(self.loc, "value {} is not yet defined", dest);
2324         }
2325 
2326         ctx.function
2327             .dfg
2328             .make_value_alias_for_serialization(dest, result);
2329 
2330         ctx.aliases.push(result);
2331         Ok(())
2332     }
2333 
2334     // Parse an instruction, append it to `block`.
2335     //
2336     // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ...
2337     //
2338     fn parse_instruction(
2339         &mut self,
2340         results: &[Value],
2341         srcloc: ir::SourceLoc,
2342         ctx: &mut Context,
2343         block: Block,
2344     ) -> ParseResult<()> {
2345         // Define the result values.
2346         for val in results {
2347             ctx.map.def_value(*val, self.loc)?;
2348         }
2349 
2350         // Collect comments for the next instruction.
2351         self.start_gathering_comments();
2352 
2353         // instruction ::=  [inst-results "="] * Opcode(opc) ["." Type] ...
2354         let opcode = if let Some(Token::Identifier(text)) = self.token() {
2355             match text.parse() {
2356                 Ok(opc) => opc,
2357                 Err(msg) => return err!(self.loc, "{}: '{}'", msg, text),
2358             }
2359         } else {
2360             return err!(self.loc, "expected instruction opcode");
2361         };
2362         let opcode_loc = self.loc;
2363         self.consume();
2364 
2365         // Look for a controlling type variable annotation.
2366         // instruction ::=  [inst-results "="] Opcode(opc) * ["." Type] ...
2367         let explicit_ctrl_type = if self.optional(Token::Dot) {
2368             if let Some(Token::Type(_t)) = self.token() {
2369                 Some(self.match_type("expected type after 'opcode.'")?)
2370             } else {
2371                 let dt = self.match_dt("expected dynamic type")?;
2372                 self.concrete_from_dt(dt, ctx)
2373             }
2374         } else {
2375             None
2376         };
2377 
2378         // instruction ::=  [inst-results "="] Opcode(opc) ["." Type] * ...
2379         let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?;
2380 
2381         // We're done parsing the instruction now.
2382         //
2383         // We still need to check that the number of result values in the source matches the opcode
2384         // or function call signature. We also need to create values with the right type for all
2385         // the instruction results.
2386         let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?;
2387         let inst = ctx.function.dfg.make_inst(inst_data);
2388         let num_results =
2389             ctx.function
2390                 .dfg
2391                 .make_inst_results_for_parser(inst, ctrl_typevar, results);
2392         ctx.function.layout.append_inst(inst, block);
2393         ctx.map
2394             .def_entity(inst.into(), opcode_loc)
2395             .expect("duplicate inst references created");
2396 
2397         if !srcloc.is_default() {
2398             ctx.function.set_srcloc(inst, srcloc);
2399         }
2400 
2401         if results.len() != num_results {
2402             return err!(
2403                 self.loc,
2404                 "instruction produces {} result values, {} given",
2405                 num_results,
2406                 results.len()
2407             );
2408         }
2409 
2410         // Collect any trailing comments.
2411         self.token();
2412         self.claim_gathered_comments(inst);
2413 
2414         Ok(())
2415     }
2416 
2417     // Type inference for polymorphic instructions.
2418     //
2419     // The controlling type variable can be specified explicitly as 'splat.i32x4 v5', or it can be
2420     // inferred from `inst_data.typevar_operand` for some opcodes.
2421     //
2422     // Returns the controlling typevar for a polymorphic opcode, or `INVALID` for a non-polymorphic
2423     // opcode.
2424     fn infer_typevar(
2425         &self,
2426         ctx: &Context,
2427         opcode: Opcode,
2428         explicit_ctrl_type: Option<Type>,
2429         inst_data: &InstructionData,
2430     ) -> ParseResult<Type> {
2431         let constraints = opcode.constraints();
2432         let ctrl_type = match explicit_ctrl_type {
2433             Some(t) => t,
2434             None => {
2435                 if constraints.use_typevar_operand() {
2436                     // This is an opcode that supports type inference, AND there was no
2437                     // explicit type specified. Look up `ctrl_value` to see if it was defined
2438                     // already.
2439                     // TBD: If it is defined in another block, the type should have been
2440                     // specified explicitly. It is unfortunate that the correctness of IR
2441                     // depends on the layout of the blocks.
2442                     let ctrl_src_value = inst_data
2443                         .typevar_operand(&ctx.function.dfg.value_lists)
2444                         .expect("Constraints <-> Format inconsistency");
2445                     if !ctx.map.contains_value(ctrl_src_value) {
2446                         return err!(
2447                             self.loc,
2448                             "type variable required for polymorphic opcode, e.g. '{}.{}'; \
2449                              can't infer from {} which is not yet defined",
2450                             opcode,
2451                             constraints.ctrl_typeset().unwrap().example(),
2452                             ctrl_src_value
2453                         );
2454                     }
2455                     if !ctx.function.dfg.value_is_valid_for_parser(ctrl_src_value) {
2456                         return err!(
2457                             self.loc,
2458                             "type variable required for polymorphic opcode, e.g. '{}.{}'; \
2459                              can't infer from {} which is not yet resolved",
2460                             opcode,
2461                             constraints.ctrl_typeset().unwrap().example(),
2462                             ctrl_src_value
2463                         );
2464                     }
2465                     ctx.function.dfg.value_type(ctrl_src_value)
2466                 } else if constraints.is_polymorphic() {
2467                     // This opcode does not support type inference, so the explicit type
2468                     // variable is required.
2469                     return err!(
2470                         self.loc,
2471                         "type variable required for polymorphic opcode, e.g. '{}.{}'",
2472                         opcode,
2473                         constraints.ctrl_typeset().unwrap().example()
2474                     );
2475                 } else {
2476                     // This is a non-polymorphic opcode. No typevar needed.
2477                     INVALID
2478                 }
2479             }
2480         };
2481 
2482         // Verify that `ctrl_type` is valid for the controlling type variable. We don't want to
2483         // attempt deriving types from an incorrect basis.
2484         // This is not a complete type check. The verifier does that.
2485         if let Some(typeset) = constraints.ctrl_typeset() {
2486             // This is a polymorphic opcode.
2487             if !typeset.contains(ctrl_type) {
2488                 return err!(
2489                     self.loc,
2490                     "{} is not a valid typevar for {}",
2491                     ctrl_type,
2492                     opcode
2493                 );
2494             }
2495         // Treat it as a syntax error to specify a typevar on a non-polymorphic opcode.
2496         } else if ctrl_type != INVALID {
2497             return err!(self.loc, "{} does not take a typevar", opcode);
2498         }
2499 
2500         Ok(ctrl_type)
2501     }
2502 
2503     // Parse comma-separated value list into a VariableArgs struct.
2504     //
2505     // value_list ::= [ value { "," value } ]
2506     //
2507     fn parse_value_list(&mut self) -> ParseResult<VariableArgs> {
2508         let mut args = VariableArgs::new();
2509 
2510         if let Some(Token::Value(v)) = self.token() {
2511             args.push(v);
2512             self.consume();
2513         } else {
2514             return Ok(args);
2515         }
2516 
2517         while self.optional(Token::Comma) {
2518             args.push(self.match_value("expected value in argument list")?);
2519         }
2520 
2521         Ok(args)
2522     }
2523 
2524     // Parse an optional value list enclosed in parentheses.
2525     fn parse_opt_value_list(&mut self) -> ParseResult<VariableArgs> {
2526         if !self.optional(Token::LPar) {
2527             return Ok(VariableArgs::new());
2528         }
2529 
2530         let args = self.parse_value_list()?;
2531 
2532         self.match_token(Token::RPar, "expected ')' after arguments")?;
2533 
2534         Ok(args)
2535     }
2536 
2537     /// Parse a CLIF run command.
2538     ///
2539     /// run-command ::= "run" [":" invocation comparison expected]
2540     ///               \ "print" [":" invocation]
2541     fn parse_run_command(&mut self, sig: &Signature) -> ParseResult<RunCommand> {
2542         // skip semicolon
2543         match self.token() {
2544             Some(Token::Identifier("run")) => {
2545                 self.consume();
2546                 if self.optional(Token::Colon) {
2547                     let invocation = self.parse_run_invocation(sig)?;
2548                     let comparison = self.parse_run_comparison()?;
2549                     let expected = self.parse_run_returns(sig)?;
2550                     Ok(RunCommand::Run(invocation, comparison, expected))
2551                 } else if sig.params.is_empty()
2552                     && sig.returns.len() == 1
2553                     && sig.returns[0].value_type.is_int()
2554                 {
2555                     // To match the existing run behavior that does not require an explicit
2556                     // invocation, we create an invocation from a function like `() -> i*` and
2557                     // require the result to be non-zero.
2558                     let invocation = Invocation::new("default", vec![]);
2559                     let expected = vec![DataValue::I8(0)];
2560                     let comparison = Comparison::NotEquals;
2561                     Ok(RunCommand::Run(invocation, comparison, expected))
2562                 } else {
2563                     Err(self.error("unable to parse the run command"))
2564                 }
2565             }
2566             Some(Token::Identifier("print")) => {
2567                 self.consume();
2568                 if self.optional(Token::Colon) {
2569                     Ok(RunCommand::Print(self.parse_run_invocation(sig)?))
2570                 } else if sig.params.is_empty() {
2571                     // To allow printing of functions like `() -> *`, we create a no-arg invocation.
2572                     let invocation = Invocation::new("default", vec![]);
2573                     Ok(RunCommand::Print(invocation))
2574                 } else {
2575                     Err(self.error("unable to parse the print command"))
2576                 }
2577             }
2578             _ => Err(self.error("expected a 'run:' or 'print:' command")),
2579         }
2580     }
2581 
2582     /// Parse the invocation of a CLIF function.
2583     ///
2584     /// This is different from parsing a CLIF `call`; it is used in parsing run commands like
2585     /// `run: %fn(42, 4.2) == false`.
2586     ///
2587     /// invocation ::= name "(" [data-value-list] ")"
2588     fn parse_run_invocation(&mut self, sig: &Signature) -> ParseResult<Invocation> {
2589         if let Some(Token::Name(name)) = self.token() {
2590             self.consume();
2591             self.match_token(
2592                 Token::LPar,
2593                 "expected invocation parentheses, e.g. %fn(...)",
2594             )?;
2595 
2596             let arg_types = sig
2597                 .params
2598                 .iter()
2599                 .map(|abi| abi.value_type)
2600                 .collect::<Vec<_>>();
2601             let args = self.parse_data_value_list(&arg_types)?;
2602 
2603             self.match_token(
2604                 Token::RPar,
2605                 "expected invocation parentheses, e.g. %fn(...)",
2606             )?;
2607             Ok(Invocation::new(name, args))
2608         } else {
2609             Err(self.error("expected a function name, e.g. %my_fn"))
2610         }
2611     }
2612 
2613     /// Parse a comparison operator for run commands.
2614     ///
2615     /// comparison ::= "==" | "!="
2616     fn parse_run_comparison(&mut self) -> ParseResult<Comparison> {
2617         if self.optional(Token::Equal) {
2618             self.match_token(Token::Equal, "expected another =")?;
2619             Ok(Comparison::Equals)
2620         } else if self.optional(Token::Bang) {
2621             self.match_token(Token::Equal, "expected a =")?;
2622             Ok(Comparison::NotEquals)
2623         } else {
2624             Err(self.error("unable to parse a valid comparison operator"))
2625         }
2626     }
2627 
2628     /// Parse the expected return values of a run invocation.
2629     ///
2630     /// expected ::= "[" "]"
2631     ///            | data-value
2632     ///            | "[" data-value-list "]"
2633     fn parse_run_returns(&mut self, sig: &Signature) -> ParseResult<Vec<DataValue>> {
2634         if sig.returns.len() != 1 {
2635             self.match_token(Token::LBracket, "expected a left bracket [")?;
2636         }
2637 
2638         let returns = self
2639             .parse_data_value_list(&sig.returns.iter().map(|a| a.value_type).collect::<Vec<_>>())?;
2640 
2641         if sig.returns.len() != 1 {
2642             self.match_token(Token::RBracket, "expected a right bracket ]")?;
2643         }
2644         Ok(returns)
2645     }
2646 
2647     /// Parse a comma-separated list of data values.
2648     ///
2649     /// data-value-list ::= [data-value {"," data-value-list}]
2650     fn parse_data_value_list(&mut self, types: &[Type]) -> ParseResult<Vec<DataValue>> {
2651         let mut values = vec![];
2652         for ty in types.iter().take(1) {
2653             values.push(self.parse_data_value(*ty)?);
2654         }
2655         for ty in types.iter().skip(1) {
2656             self.match_token(
2657                 Token::Comma,
2658                 "expected a comma between invocation arguments",
2659             )?;
2660             values.push(self.parse_data_value(*ty)?);
2661         }
2662         Ok(values)
2663     }
2664 
2665     /// Parse a data value; e.g. `42`, `4.2`, `true`.
2666     ///
2667     /// data-value-list ::= [data-value {"," data-value-list}]
2668     fn parse_data_value(&mut self, ty: Type) -> ParseResult<DataValue> {
2669         let dv = match ty {
2670             I8 => DataValue::from(self.match_imm8("expected a i8")?),
2671             I16 => DataValue::from(self.match_imm16("expected an i16")?),
2672             I32 => DataValue::from(self.match_imm32("expected an i32")?),
2673             I64 => DataValue::from(Into::<i64>::into(self.match_imm64("expected an i64")?)),
2674             I128 => DataValue::from(self.match_imm128("expected an i128")?),
2675             F32 => DataValue::from(self.match_ieee32("expected an f32")?),
2676             F64 => DataValue::from(self.match_ieee64("expected an f64")?),
2677             _ if (ty.is_vector() || ty.is_dynamic_vector()) => {
2678                 let as_vec = self.match_uimm128(ty)?.into_vec();
2679                 if as_vec.len() == 16 {
2680                     let mut as_array = [0; 16];
2681                     as_array.copy_from_slice(&as_vec[..]);
2682                     DataValue::from(as_array)
2683                 } else if as_vec.len() == 8 {
2684                     let mut as_array = [0; 8];
2685                     as_array.copy_from_slice(&as_vec[..]);
2686                     DataValue::from(as_array)
2687                 } else {
2688                     return Err(self.error("only 128-bit vectors are currently supported"));
2689                 }
2690             }
2691             _ => return Err(self.error(&format!("don't know how to parse data values of: {}", ty))),
2692         };
2693         Ok(dv)
2694     }
2695 
2696     // Parse the operands following the instruction opcode.
2697     // This depends on the format of the opcode.
2698     fn parse_inst_operands(
2699         &mut self,
2700         ctx: &mut Context,
2701         opcode: Opcode,
2702         explicit_control_type: Option<Type>,
2703     ) -> ParseResult<InstructionData> {
2704         let idata = match opcode.format() {
2705             InstructionFormat::Unary => InstructionData::Unary {
2706                 opcode,
2707                 arg: self.match_value("expected SSA value operand")?,
2708             },
2709             InstructionFormat::UnaryImm => {
2710                 let msg = |bits| format!("expected immediate {bits}-bit integer operand");
2711                 let unsigned = match explicit_control_type {
2712                     Some(types::I8) => self.match_imm8(&msg(8))? as u8 as i64,
2713                     Some(types::I16) => self.match_imm16(&msg(16))? as u16 as i64,
2714                     Some(types::I32) => self.match_imm32(&msg(32))? as u32 as i64,
2715                     Some(types::I64) => self.match_imm64(&msg(64))?.bits(),
2716                     _ => {
2717                         return err!(
2718                             self.loc,
2719                             "expected one of the following type: i8, i16, i32 or i64"
2720                         )
2721                     }
2722                 };
2723                 InstructionData::UnaryImm {
2724                     opcode,
2725                     imm: Imm64::new(unsigned),
2726                 }
2727             }
2728             InstructionFormat::UnaryIeee32 => InstructionData::UnaryIeee32 {
2729                 opcode,
2730                 imm: self.match_ieee32("expected immediate 32-bit float operand")?,
2731             },
2732             InstructionFormat::UnaryIeee64 => InstructionData::UnaryIeee64 {
2733                 opcode,
2734                 imm: self.match_ieee64("expected immediate 64-bit float operand")?,
2735             },
2736             InstructionFormat::UnaryConst => {
2737                 let constant_handle = if let Some(Token::Constant(_)) = self.token() {
2738                     // If handed a `const?`, use that.
2739                     let c = self.match_constant()?;
2740                     ctx.check_constant(c, self.loc)?;
2741                     c
2742                 } else if let Some(controlling_type) = explicit_control_type {
2743                     // If an explicit control type is present, we expect a sized value and insert
2744                     // it in the constant pool.
2745                     let uimm128 = self.match_uimm128(controlling_type)?;
2746                     ctx.function.dfg.constants.insert(uimm128)
2747                 } else {
2748                     return err!(
2749                         self.loc,
2750                         "Expected either a const entity or a typed value, e.g. inst.i32x4 [...]"
2751                     );
2752                 };
2753                 InstructionData::UnaryConst {
2754                     opcode,
2755                     constant_handle,
2756                 }
2757             }
2758             InstructionFormat::UnaryGlobalValue => {
2759                 let gv = self.match_gv("expected global value")?;
2760                 ctx.check_gv(gv, self.loc)?;
2761                 InstructionData::UnaryGlobalValue {
2762                     opcode,
2763                     global_value: gv,
2764                 }
2765             }
2766             InstructionFormat::Binary => {
2767                 let lhs = self.match_value("expected SSA value first operand")?;
2768                 self.match_token(Token::Comma, "expected ',' between operands")?;
2769                 let rhs = self.match_value("expected SSA value second operand")?;
2770                 InstructionData::Binary {
2771                     opcode,
2772                     args: [lhs, rhs],
2773                 }
2774             }
2775             InstructionFormat::BinaryImm8 => {
2776                 let arg = self.match_value("expected SSA value first operand")?;
2777                 self.match_token(Token::Comma, "expected ',' between operands")?;
2778                 let imm = self.match_uimm8("expected unsigned 8-bit immediate")?;
2779                 InstructionData::BinaryImm8 { opcode, arg, imm }
2780             }
2781             InstructionFormat::BinaryImm64 => {
2782                 let lhs = self.match_value("expected SSA value first operand")?;
2783                 self.match_token(Token::Comma, "expected ',' between operands")?;
2784                 let rhs = self.match_imm64("expected immediate integer second operand")?;
2785                 InstructionData::BinaryImm64 {
2786                     opcode,
2787                     arg: lhs,
2788                     imm: rhs,
2789                 }
2790             }
2791             InstructionFormat::Ternary => {
2792                 // Names here refer to the `select` instruction.
2793                 // This format is also use by `fma`.
2794                 let ctrl_arg = self.match_value("expected SSA value control operand")?;
2795                 self.match_token(Token::Comma, "expected ',' between operands")?;
2796                 let true_arg = self.match_value("expected SSA value true operand")?;
2797                 self.match_token(Token::Comma, "expected ',' between operands")?;
2798                 let false_arg = self.match_value("expected SSA value false operand")?;
2799                 InstructionData::Ternary {
2800                     opcode,
2801                     args: [ctrl_arg, true_arg, false_arg],
2802                 }
2803             }
2804             InstructionFormat::MultiAry => {
2805                 let args = self.parse_value_list()?;
2806                 InstructionData::MultiAry {
2807                     opcode,
2808                     args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists),
2809                 }
2810             }
2811             InstructionFormat::NullAry => InstructionData::NullAry { opcode },
2812             InstructionFormat::Jump => {
2813                 // Parse the destination block number.
2814                 let block_num = self.match_block("expected jump destination block")?;
2815                 let args = self.parse_opt_value_list()?;
2816                 let destination = ctx.function.dfg.block_call(block_num, &args);
2817                 InstructionData::Jump {
2818                     opcode,
2819                     destination,
2820                 }
2821             }
2822             InstructionFormat::Brif => {
2823                 let arg = self.match_value("expected SSA value control operand")?;
2824                 self.match_token(Token::Comma, "expected ',' between operands")?;
2825                 let block_then = {
2826                     let block_num = self.match_block("expected branch then block")?;
2827                     let args = self.parse_opt_value_list()?;
2828                     ctx.function.dfg.block_call(block_num, &args)
2829                 };
2830                 self.match_token(Token::Comma, "expected ',' between operands")?;
2831                 let block_else = {
2832                     let block_num = self.match_block("expected branch else block")?;
2833                     let args = self.parse_opt_value_list()?;
2834                     ctx.function.dfg.block_call(block_num, &args)
2835                 };
2836                 InstructionData::Brif {
2837                     opcode,
2838                     arg,
2839                     blocks: [block_then, block_else],
2840                 }
2841             }
2842             InstructionFormat::BranchTable => {
2843                 let arg = self.match_value("expected SSA value operand")?;
2844                 self.match_token(Token::Comma, "expected ',' between operands")?;
2845                 let block_num = self.match_block("expected branch destination block")?;
2846                 let args = self.parse_opt_value_list()?;
2847                 let destination = ctx.function.dfg.block_call(block_num, &args);
2848                 self.match_token(Token::Comma, "expected ',' between operands")?;
2849                 let table = self.parse_jump_table(ctx, destination)?;
2850                 InstructionData::BranchTable { opcode, arg, table }
2851             }
2852             InstructionFormat::TernaryImm8 => {
2853                 let lhs = self.match_value("expected SSA value first operand")?;
2854                 self.match_token(Token::Comma, "expected ',' between operands")?;
2855                 let rhs = self.match_value("expected SSA value last operand")?;
2856                 self.match_token(Token::Comma, "expected ',' between operands")?;
2857                 let imm = self.match_uimm8("expected 8-bit immediate")?;
2858                 InstructionData::TernaryImm8 {
2859                     opcode,
2860                     imm,
2861                     args: [lhs, rhs],
2862                 }
2863             }
2864             InstructionFormat::Shuffle => {
2865                 let a = self.match_value("expected SSA value first operand")?;
2866                 self.match_token(Token::Comma, "expected ',' between operands")?;
2867                 let b = self.match_value("expected SSA value second operand")?;
2868                 self.match_token(Token::Comma, "expected ',' between operands")?;
2869                 let uimm128 = self.match_uimm128(I8X16)?;
2870                 let imm = ctx.function.dfg.immediates.push(uimm128);
2871                 InstructionData::Shuffle {
2872                     opcode,
2873                     imm,
2874                     args: [a, b],
2875                 }
2876             }
2877             InstructionFormat::IntCompare => {
2878                 let cond = self.match_enum("expected intcc condition code")?;
2879                 let lhs = self.match_value("expected SSA value first operand")?;
2880                 self.match_token(Token::Comma, "expected ',' between operands")?;
2881                 let rhs = self.match_value("expected SSA value second operand")?;
2882                 InstructionData::IntCompare {
2883                     opcode,
2884                     cond,
2885                     args: [lhs, rhs],
2886                 }
2887             }
2888             InstructionFormat::IntCompareImm => {
2889                 let cond = self.match_enum("expected intcc condition code")?;
2890                 let lhs = self.match_value("expected SSA value first operand")?;
2891                 self.match_token(Token::Comma, "expected ',' between operands")?;
2892                 let rhs = self.match_imm64("expected immediate second operand")?;
2893                 InstructionData::IntCompareImm {
2894                     opcode,
2895                     cond,
2896                     arg: lhs,
2897                     imm: rhs,
2898                 }
2899             }
2900             InstructionFormat::FloatCompare => {
2901                 let cond = self.match_enum("expected floatcc condition code")?;
2902                 let lhs = self.match_value("expected SSA value first operand")?;
2903                 self.match_token(Token::Comma, "expected ',' between operands")?;
2904                 let rhs = self.match_value("expected SSA value second operand")?;
2905                 InstructionData::FloatCompare {
2906                     opcode,
2907                     cond,
2908                     args: [lhs, rhs],
2909                 }
2910             }
2911             InstructionFormat::Call => {
2912                 let func_ref = self.match_fn("expected function reference")?;
2913                 ctx.check_fn(func_ref, self.loc)?;
2914                 self.match_token(Token::LPar, "expected '(' before arguments")?;
2915                 let args = self.parse_value_list()?;
2916                 self.match_token(Token::RPar, "expected ')' after arguments")?;
2917                 InstructionData::Call {
2918                     opcode,
2919                     func_ref,
2920                     args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists),
2921                 }
2922             }
2923             InstructionFormat::CallIndirect => {
2924                 let sig_ref = self.match_sig("expected signature reference")?;
2925                 ctx.check_sig(sig_ref, self.loc)?;
2926                 self.match_token(Token::Comma, "expected ',' between operands")?;
2927                 let callee = self.match_value("expected SSA value callee operand")?;
2928                 self.match_token(Token::LPar, "expected '(' before arguments")?;
2929                 let args = self.parse_value_list()?;
2930                 self.match_token(Token::RPar, "expected ')' after arguments")?;
2931                 InstructionData::CallIndirect {
2932                     opcode,
2933                     sig_ref,
2934                     args: args.into_value_list(&[callee], &mut ctx.function.dfg.value_lists),
2935                 }
2936             }
2937             InstructionFormat::FuncAddr => {
2938                 let func_ref = self.match_fn("expected function reference")?;
2939                 ctx.check_fn(func_ref, self.loc)?;
2940                 InstructionData::FuncAddr { opcode, func_ref }
2941             }
2942             InstructionFormat::StackLoad => {
2943                 let ss = self.match_ss("expected stack slot number: ss«n»")?;
2944                 ctx.check_ss(ss, self.loc)?;
2945                 let offset = self.optional_offset32()?;
2946                 InstructionData::StackLoad {
2947                     opcode,
2948                     stack_slot: ss,
2949                     offset,
2950                 }
2951             }
2952             InstructionFormat::StackStore => {
2953                 let arg = self.match_value("expected SSA value operand")?;
2954                 self.match_token(Token::Comma, "expected ',' between operands")?;
2955                 let ss = self.match_ss("expected stack slot number: ss«n»")?;
2956                 ctx.check_ss(ss, self.loc)?;
2957                 let offset = self.optional_offset32()?;
2958                 InstructionData::StackStore {
2959                     opcode,
2960                     arg,
2961                     stack_slot: ss,
2962                     offset,
2963                 }
2964             }
2965             InstructionFormat::DynamicStackLoad => {
2966                 let dss = self.match_dss("expected dynamic stack slot number: dss«n»")?;
2967                 ctx.check_dss(dss, self.loc)?;
2968                 InstructionData::DynamicStackLoad {
2969                     opcode,
2970                     dynamic_stack_slot: dss,
2971                 }
2972             }
2973             InstructionFormat::DynamicStackStore => {
2974                 let arg = self.match_value("expected SSA value operand")?;
2975                 self.match_token(Token::Comma, "expected ',' between operands")?;
2976                 let dss = self.match_dss("expected dynamic stack slot number: dss«n»")?;
2977                 ctx.check_dss(dss, self.loc)?;
2978                 InstructionData::DynamicStackStore {
2979                     opcode,
2980                     arg,
2981                     dynamic_stack_slot: dss,
2982                 }
2983             }
2984             InstructionFormat::TableAddr => {
2985                 let table = self.match_table("expected table identifier")?;
2986                 ctx.check_table(table, self.loc)?;
2987                 self.match_token(Token::Comma, "expected ',' between operands")?;
2988                 let arg = self.match_value("expected SSA value table address")?;
2989                 let offset = self.optional_offset32()?;
2990                 InstructionData::TableAddr {
2991                     opcode,
2992                     table,
2993                     arg,
2994                     offset,
2995                 }
2996             }
2997             InstructionFormat::Load => {
2998                 let flags = self.optional_memflags();
2999                 let addr = self.match_value("expected SSA value address")?;
3000                 let offset = self.optional_offset32()?;
3001                 InstructionData::Load {
3002                     opcode,
3003                     flags,
3004                     arg: addr,
3005                     offset,
3006                 }
3007             }
3008             InstructionFormat::Store => {
3009                 let flags = self.optional_memflags();
3010                 let arg = self.match_value("expected SSA value operand")?;
3011                 self.match_token(Token::Comma, "expected ',' between operands")?;
3012                 let addr = self.match_value("expected SSA value address")?;
3013                 let offset = self.optional_offset32()?;
3014                 InstructionData::Store {
3015                     opcode,
3016                     flags,
3017                     args: [arg, addr],
3018                     offset,
3019                 }
3020             }
3021             InstructionFormat::Trap => {
3022                 let code = self.match_enum("expected trap code")?;
3023                 InstructionData::Trap { opcode, code }
3024             }
3025             InstructionFormat::CondTrap => {
3026                 let arg = self.match_value("expected SSA value operand")?;
3027                 self.match_token(Token::Comma, "expected ',' between operands")?;
3028                 let code = self.match_enum("expected trap code")?;
3029                 InstructionData::CondTrap { opcode, arg, code }
3030             }
3031             InstructionFormat::AtomicCas => {
3032                 let flags = self.optional_memflags();
3033                 let addr = self.match_value("expected SSA value address")?;
3034                 self.match_token(Token::Comma, "expected ',' between operands")?;
3035                 let expected = self.match_value("expected SSA value address")?;
3036                 self.match_token(Token::Comma, "expected ',' between operands")?;
3037                 let replacement = self.match_value("expected SSA value address")?;
3038                 InstructionData::AtomicCas {
3039                     opcode,
3040                     flags,
3041                     args: [addr, expected, replacement],
3042                 }
3043             }
3044             InstructionFormat::AtomicRmw => {
3045                 let flags = self.optional_memflags();
3046                 let op = self.match_enum("expected AtomicRmwOp")?;
3047                 let addr = self.match_value("expected SSA value address")?;
3048                 self.match_token(Token::Comma, "expected ',' between operands")?;
3049                 let arg2 = self.match_value("expected SSA value address")?;
3050                 InstructionData::AtomicRmw {
3051                     opcode,
3052                     flags,
3053                     op,
3054                     args: [addr, arg2],
3055                 }
3056             }
3057             InstructionFormat::LoadNoOffset => {
3058                 let flags = self.optional_memflags();
3059                 let addr = self.match_value("expected SSA value address")?;
3060                 InstructionData::LoadNoOffset {
3061                     opcode,
3062                     flags,
3063                     arg: addr,
3064                 }
3065             }
3066             InstructionFormat::StoreNoOffset => {
3067                 let flags = self.optional_memflags();
3068                 let arg = self.match_value("expected SSA value operand")?;
3069                 self.match_token(Token::Comma, "expected ',' between operands")?;
3070                 let addr = self.match_value("expected SSA value address")?;
3071                 InstructionData::StoreNoOffset {
3072                     opcode,
3073                     flags,
3074                     args: [arg, addr],
3075                 }
3076             }
3077             InstructionFormat::IntAddTrap => {
3078                 let a = self.match_value("expected SSA value operand")?;
3079                 self.match_token(Token::Comma, "expected ',' between operands")?;
3080                 let b = self.match_value("expected SSA value operand")?;
3081                 self.match_token(Token::Comma, "expected ',' between operands")?;
3082                 let code = self.match_enum("expected trap code")?;
3083                 InstructionData::IntAddTrap {
3084                     opcode,
3085                     args: [a, b],
3086                     code,
3087                 }
3088             }
3089         };
3090         Ok(idata)
3091     }
3092 }
3093 
3094 #[cfg(test)]
3095 mod tests {
3096     use super::*;
3097     use crate::error::ParseError;
3098     use crate::isaspec::IsaSpec;
3099     use crate::testfile::{Comment, Details};
3100     use cranelift_codegen::ir::entities::AnyEntity;
3101     use cranelift_codegen::ir::types;
3102     use cranelift_codegen::ir::StackSlotKind;
3103     use cranelift_codegen::ir::{ArgumentExtension, ArgumentPurpose};
3104     use cranelift_codegen::isa::CallConv;
3105 
3106     #[test]
3107     fn argument_type() {
3108         let mut p = Parser::new("i32 sext");
3109         let arg = p.parse_abi_param().unwrap();
3110         assert_eq!(arg.value_type, types::I32);
3111         assert_eq!(arg.extension, ArgumentExtension::Sext);
3112         assert_eq!(arg.purpose, ArgumentPurpose::Normal);
3113         let ParseError {
3114             location,
3115             message,
3116             is_warning,
3117         } = p.parse_abi_param().unwrap_err();
3118         assert_eq!(location.line_number, 1);
3119         assert_eq!(message, "expected parameter type");
3120         assert!(!is_warning);
3121     }
3122 
3123     #[test]
3124     fn aliases() {
3125         let (func, details) = Parser::new(
3126             "function %qux() system_v {
3127                                            block0:
3128                                              v4 = iconst.i8 6
3129                                              v3 -> v4
3130                                              v1 = iadd_imm v3, 17
3131                                            }",
3132         )
3133         .parse_function()
3134         .unwrap();
3135         assert_eq!(func.name.to_string(), "%qux");
3136         let v4 = details.map.lookup_str("v4").unwrap();
3137         assert_eq!(v4.to_string(), "v4");
3138         let v3 = details.map.lookup_str("v3").unwrap();
3139         assert_eq!(v3.to_string(), "v3");
3140         match v3 {
3141             AnyEntity::Value(v3) => {
3142                 let aliased_to = func.dfg.resolve_aliases(v3);
3143                 assert_eq!(aliased_to.to_string(), "v4");
3144             }
3145             _ => panic!("expected value: {}", v3),
3146         }
3147     }
3148 
3149     #[test]
3150     fn signature() {
3151         let sig = Parser::new("()system_v").parse_signature().unwrap();
3152         assert_eq!(sig.params.len(), 0);
3153         assert_eq!(sig.returns.len(), 0);
3154         assert_eq!(sig.call_conv, CallConv::SystemV);
3155 
3156         let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 system_v")
3157             .parse_signature()
3158             .unwrap();
3159         assert_eq!(
3160             sig2.to_string(),
3161             "(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 system_v"
3162         );
3163         assert_eq!(sig2.call_conv, CallConv::SystemV);
3164 
3165         // Old-style signature without a calling convention.
3166         assert_eq!(
3167             Parser::new("()").parse_signature().unwrap().to_string(),
3168             "() fast"
3169         );
3170         assert_eq!(
3171             Parser::new("() notacc")
3172                 .parse_signature()
3173                 .unwrap_err()
3174                 .to_string(),
3175             "1: unknown calling convention: notacc"
3176         );
3177 
3178         // `void` is not recognized as a type by the lexer. It should not appear in files.
3179         assert_eq!(
3180             Parser::new("() -> void")
3181                 .parse_signature()
3182                 .unwrap_err()
3183                 .to_string(),
3184             "1: expected parameter type"
3185         );
3186         assert_eq!(
3187             Parser::new("i8 -> i8")
3188                 .parse_signature()
3189                 .unwrap_err()
3190                 .to_string(),
3191             "1: expected function signature: ( args... )"
3192         );
3193         assert_eq!(
3194             Parser::new("(i8 -> i8")
3195                 .parse_signature()
3196                 .unwrap_err()
3197                 .to_string(),
3198             "1: expected ')' after function arguments"
3199         );
3200     }
3201 
3202     #[test]
3203     fn stack_slot_decl() {
3204         let (func, _) = Parser::new(
3205             "function %foo() system_v {
3206                                        ss3 = explicit_slot 13
3207                                        ss1 = explicit_slot 1
3208                                      }",
3209         )
3210         .parse_function()
3211         .unwrap();
3212         assert_eq!(func.name.to_string(), "%foo");
3213         let mut iter = func.sized_stack_slots.keys();
3214         let _ss0 = iter.next().unwrap();
3215         let ss1 = iter.next().unwrap();
3216         assert_eq!(ss1.to_string(), "ss1");
3217         assert_eq!(
3218             func.sized_stack_slots[ss1].kind,
3219             StackSlotKind::ExplicitSlot
3220         );
3221         assert_eq!(func.sized_stack_slots[ss1].size, 1);
3222         let _ss2 = iter.next().unwrap();
3223         let ss3 = iter.next().unwrap();
3224         assert_eq!(ss3.to_string(), "ss3");
3225         assert_eq!(
3226             func.sized_stack_slots[ss3].kind,
3227             StackSlotKind::ExplicitSlot
3228         );
3229         assert_eq!(func.sized_stack_slots[ss3].size, 13);
3230         assert_eq!(iter.next(), None);
3231 
3232         // Catch duplicate definitions.
3233         assert_eq!(
3234             Parser::new(
3235                 "function %bar() system_v {
3236                                     ss1  = explicit_slot 13
3237                                     ss1  = explicit_slot 1
3238                                 }",
3239             )
3240             .parse_function()
3241             .unwrap_err()
3242             .to_string(),
3243             "3: duplicate entity: ss1"
3244         );
3245     }
3246 
3247     #[test]
3248     fn block_header() {
3249         let (func, _) = Parser::new(
3250             "function %blocks() system_v {
3251                                      block0:
3252                                      block4(v3: i32):
3253                                      }",
3254         )
3255         .parse_function()
3256         .unwrap();
3257         assert_eq!(func.name.to_string(), "%blocks");
3258 
3259         let mut blocks = func.layout.blocks();
3260 
3261         let block0 = blocks.next().unwrap();
3262         assert_eq!(func.dfg.block_params(block0), &[]);
3263 
3264         let block4 = blocks.next().unwrap();
3265         let block4_args = func.dfg.block_params(block4);
3266         assert_eq!(block4_args.len(), 1);
3267         assert_eq!(func.dfg.value_type(block4_args[0]), types::I32);
3268     }
3269 
3270     #[test]
3271     fn duplicate_block() {
3272         let ParseError {
3273             location,
3274             message,
3275             is_warning,
3276         } = Parser::new(
3277             "function %blocks() system_v {
3278                 block0:
3279                 block0:
3280                     return 2",
3281         )
3282         .parse_function()
3283         .unwrap_err();
3284 
3285         assert_eq!(location.line_number, 3);
3286         assert_eq!(message, "duplicate entity: block0");
3287         assert!(!is_warning);
3288     }
3289 
3290     #[test]
3291     fn number_of_blocks() {
3292         let ParseError {
3293             location,
3294             message,
3295             is_warning,
3296         } = Parser::new(
3297             "function %a() {
3298                 block100000:",
3299         )
3300         .parse_function()
3301         .unwrap_err();
3302 
3303         assert_eq!(location.line_number, 2);
3304         assert_eq!(message, "too many blocks");
3305         assert!(!is_warning);
3306     }
3307 
3308     #[test]
3309     fn duplicate_ss() {
3310         let ParseError {
3311             location,
3312             message,
3313             is_warning,
3314         } = Parser::new(
3315             "function %blocks() system_v {
3316                 ss0 = explicit_slot 8
3317                 ss0 = explicit_slot 8",
3318         )
3319         .parse_function()
3320         .unwrap_err();
3321 
3322         assert_eq!(location.line_number, 3);
3323         assert_eq!(message, "duplicate entity: ss0");
3324         assert!(!is_warning);
3325     }
3326 
3327     #[test]
3328     fn duplicate_gv() {
3329         let ParseError {
3330             location,
3331             message,
3332             is_warning,
3333         } = Parser::new(
3334             "function %blocks() system_v {
3335                 gv0 = vmctx
3336                 gv0 = vmctx",
3337         )
3338         .parse_function()
3339         .unwrap_err();
3340 
3341         assert_eq!(location.line_number, 3);
3342         assert_eq!(message, "duplicate entity: gv0");
3343         assert!(!is_warning);
3344     }
3345 
3346     #[test]
3347     fn duplicate_sig() {
3348         let ParseError {
3349             location,
3350             message,
3351             is_warning,
3352         } = Parser::new(
3353             "function %blocks() system_v {
3354                 sig0 = ()
3355                 sig0 = ()",
3356         )
3357         .parse_function()
3358         .unwrap_err();
3359 
3360         assert_eq!(location.line_number, 3);
3361         assert_eq!(message, "duplicate entity: sig0");
3362         assert!(!is_warning);
3363     }
3364 
3365     #[test]
3366     fn duplicate_fn() {
3367         let ParseError {
3368             location,
3369             message,
3370             is_warning,
3371         } = Parser::new(
3372             "function %blocks() system_v {
3373                 sig0 = ()
3374                 fn0 = %foo sig0
3375                 fn0 = %foo sig0",
3376         )
3377         .parse_function()
3378         .unwrap_err();
3379 
3380         assert_eq!(location.line_number, 4);
3381         assert_eq!(message, "duplicate entity: fn0");
3382         assert!(!is_warning);
3383     }
3384 
3385     #[test]
3386     fn comments() {
3387         let (func, Details { comments, .. }) = Parser::new(
3388             "; before
3389                          function %comment() system_v { ; decl
3390                             ss10  = explicit_slot 13 ; stackslot.
3391                             ; Still stackslot.
3392                          block0: ; Basic block
3393                          trap user42; Instruction
3394                          } ; Trailing.
3395                          ; More trailing.",
3396         )
3397         .parse_function()
3398         .unwrap();
3399         assert_eq!(func.name.to_string(), "%comment");
3400         assert_eq!(comments.len(), 7); // no 'before' comment.
3401         assert_eq!(
3402             comments[0],
3403             Comment {
3404                 entity: AnyEntity::Function,
3405                 text: "; decl",
3406             }
3407         );
3408         assert_eq!(comments[1].entity.to_string(), "ss10");
3409         assert_eq!(comments[2].entity.to_string(), "ss10");
3410         assert_eq!(comments[2].text, "; Still stackslot.");
3411         assert_eq!(comments[3].entity.to_string(), "block0");
3412         assert_eq!(comments[3].text, "; Basic block");
3413 
3414         assert_eq!(comments[4].entity.to_string(), "inst0");
3415         assert_eq!(comments[4].text, "; Instruction");
3416 
3417         assert_eq!(comments[5].entity, AnyEntity::Function);
3418         assert_eq!(comments[6].entity, AnyEntity::Function);
3419     }
3420 
3421     #[test]
3422     fn test_file() {
3423         let tf = parse_test(
3424             r#"; before
3425                              test cfg option=5
3426                              test verify
3427                              set enable_float=false
3428                              feature "foo"
3429                              feature !"bar"
3430                              ; still preamble
3431                              function %comment() system_v {}"#,
3432             ParseOptions::default(),
3433         )
3434         .unwrap();
3435         assert_eq!(tf.commands.len(), 2);
3436         assert_eq!(tf.commands[0].command, "cfg");
3437         assert_eq!(tf.commands[1].command, "verify");
3438         match tf.isa_spec {
3439             IsaSpec::None(s) => {
3440                 assert!(s.enable_verifier());
3441                 assert!(!s.enable_float());
3442             }
3443             _ => panic!("unexpected ISAs"),
3444         }
3445         assert_eq!(tf.features[0], Feature::With(&"foo"));
3446         assert_eq!(tf.features[1], Feature::Without(&"bar"));
3447         assert_eq!(tf.preamble_comments.len(), 2);
3448         assert_eq!(tf.preamble_comments[0].text, "; before");
3449         assert_eq!(tf.preamble_comments[1].text, "; still preamble");
3450         assert_eq!(tf.functions.len(), 1);
3451         assert_eq!(tf.functions[0].0.name.to_string(), "%comment");
3452     }
3453 
3454     #[test]
3455     fn isa_spec() {
3456         assert!(parse_test(
3457             "target
3458                             function %foo() system_v {}",
3459             ParseOptions::default()
3460         )
3461         .is_err());
3462 
3463         assert!(parse_test(
3464             "target x86_64
3465                             set enable_float=false
3466                             function %foo() system_v {}",
3467             ParseOptions::default()
3468         )
3469         .is_err());
3470 
3471         match parse_test(
3472             "set enable_float=false
3473                           target x86_64
3474                           function %foo() system_v {}",
3475             ParseOptions::default(),
3476         )
3477         .unwrap()
3478         .isa_spec
3479         {
3480             IsaSpec::None(_) => panic!("Expected some ISA"),
3481             IsaSpec::Some(v) => {
3482                 assert_eq!(v.len(), 1);
3483                 assert!(v[0].name() == "x64" || v[0].name() == "x86");
3484             }
3485         }
3486     }
3487 
3488     #[test]
3489     fn user_function_name() {
3490         // Valid characters in the name:
3491         let func = Parser::new(
3492             "function u1:2() system_v {
3493                                            block0:
3494                                              trap int_divz
3495                                            }",
3496         )
3497         .parse_function()
3498         .unwrap()
3499         .0;
3500         assert_eq!(func.name.to_string(), "u1:2");
3501 
3502         // Invalid characters in the name:
3503         let mut parser = Parser::new(
3504             "function u123:abc() system_v {
3505                                            block0:
3506                                              trap stk_ovf
3507                                            }",
3508         );
3509         assert!(parser.parse_function().is_err());
3510 
3511         // Incomplete function names should not be valid:
3512         let mut parser = Parser::new(
3513             "function u() system_v {
3514                                            block0:
3515                                              trap int_ovf
3516                                            }",
3517         );
3518         assert!(parser.parse_function().is_err());
3519 
3520         let mut parser = Parser::new(
3521             "function u0() system_v {
3522                                            block0:
3523                                              trap int_ovf
3524                                            }",
3525         );
3526         assert!(parser.parse_function().is_err());
3527 
3528         let mut parser = Parser::new(
3529             "function u0:() system_v {
3530                                            block0:
3531                                              trap int_ovf
3532                                            }",
3533         );
3534         assert!(parser.parse_function().is_err());
3535     }
3536 
3537     #[test]
3538     fn change_default_calling_convention() {
3539         let code = "function %test() {
3540         block0:
3541             return
3542         }";
3543 
3544         // By default the parser will use the fast calling convention if none is specified.
3545         let mut parser = Parser::new(code);
3546         assert_eq!(
3547             parser.parse_function().unwrap().0.signature.call_conv,
3548             CallConv::Fast
3549         );
3550 
3551         // However, we can specify a different calling convention to be the default.
3552         let mut parser = Parser::new(code).with_default_calling_convention(CallConv::Cold);
3553         assert_eq!(
3554             parser.parse_function().unwrap().0.signature.call_conv,
3555             CallConv::Cold
3556         );
3557     }
3558 
3559     #[test]
3560     fn u8_as_hex() {
3561         fn parse_as_uimm8(text: &str) -> ParseResult<u8> {
3562             Parser::new(text).match_uimm8("unable to parse u8")
3563         }
3564 
3565         assert_eq!(parse_as_uimm8("0").unwrap(), 0);
3566         assert_eq!(parse_as_uimm8("0xff").unwrap(), 255);
3567         assert!(parse_as_uimm8("-1").is_err());
3568         assert!(parse_as_uimm8("0xffa").is_err());
3569     }
3570 
3571     #[test]
3572     fn i16_as_hex() {
3573         fn parse_as_imm16(text: &str) -> ParseResult<i16> {
3574             Parser::new(text).match_imm16("unable to parse i16")
3575         }
3576 
3577         assert_eq!(parse_as_imm16("0x8000").unwrap(), -32768);
3578         assert_eq!(parse_as_imm16("0xffff").unwrap(), -1);
3579         assert_eq!(parse_as_imm16("0").unwrap(), 0);
3580         assert_eq!(parse_as_imm16("0x7fff").unwrap(), 32767);
3581         assert_eq!(
3582             parse_as_imm16("-0x0001").unwrap(),
3583             parse_as_imm16("0xffff").unwrap()
3584         );
3585         assert_eq!(
3586             parse_as_imm16("-0x7fff").unwrap(),
3587             parse_as_imm16("0x8001").unwrap()
3588         );
3589         assert!(parse_as_imm16("0xffffa").is_err());
3590     }
3591 
3592     #[test]
3593     fn i32_as_hex() {
3594         fn parse_as_imm32(text: &str) -> ParseResult<i32> {
3595             Parser::new(text).match_imm32("unable to parse i32")
3596         }
3597 
3598         assert_eq!(parse_as_imm32("0x80000000").unwrap(), -2147483648);
3599         assert_eq!(parse_as_imm32("0xffffffff").unwrap(), -1);
3600         assert_eq!(parse_as_imm32("0").unwrap(), 0);
3601         assert_eq!(parse_as_imm32("0x7fffffff").unwrap(), 2147483647);
3602         assert_eq!(
3603             parse_as_imm32("-0x00000001").unwrap(),
3604             parse_as_imm32("0xffffffff").unwrap()
3605         );
3606         assert_eq!(
3607             parse_as_imm32("-0x7fffffff").unwrap(),
3608             parse_as_imm32("0x80000001").unwrap()
3609         );
3610         assert!(parse_as_imm32("0xffffffffa").is_err());
3611     }
3612 
3613     #[test]
3614     fn i64_as_hex() {
3615         fn parse_as_imm64(text: &str) -> ParseResult<Imm64> {
3616             Parser::new(text).match_imm64("unable to parse Imm64")
3617         }
3618 
3619         assert_eq!(
3620             parse_as_imm64("0x8000000000000000").unwrap(),
3621             Imm64::new(-9223372036854775808)
3622         );
3623         assert_eq!(
3624             parse_as_imm64("0xffffffffffffffff").unwrap(),
3625             Imm64::new(-1)
3626         );
3627         assert_eq!(parse_as_imm64("0").unwrap(), Imm64::new(0));
3628         assert_eq!(
3629             parse_as_imm64("0x7fffffffffffffff").unwrap(),
3630             Imm64::new(9223372036854775807)
3631         );
3632         assert_eq!(
3633             parse_as_imm64("-0x0000000000000001").unwrap(),
3634             parse_as_imm64("0xffffffffffffffff").unwrap()
3635         );
3636         assert_eq!(
3637             parse_as_imm64("-0x7fffffffffffffff").unwrap(),
3638             parse_as_imm64("0x8000000000000001").unwrap()
3639         );
3640         assert!(parse_as_imm64("0xffffffffffffffffa").is_err());
3641     }
3642 
3643     #[test]
3644     fn uimm128() {
3645         macro_rules! parse_as_constant_data {
3646             ($text:expr, $type:expr) => {{
3647                 Parser::new($text).parse_literals_to_constant_data($type)
3648             }};
3649         }
3650         macro_rules! can_parse_as_constant_data {
3651             ($text:expr, $type:expr) => {{
3652                 assert!(parse_as_constant_data!($text, $type).is_ok())
3653             }};
3654         }
3655         macro_rules! cannot_parse_as_constant_data {
3656             ($text:expr, $type:expr) => {{
3657                 assert!(parse_as_constant_data!($text, $type).is_err())
3658             }};
3659         }
3660 
3661         can_parse_as_constant_data!("1 2 3 4", I32X4);
3662         can_parse_as_constant_data!("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", I8X16);
3663         can_parse_as_constant_data!("0x1.1 0x2.2 0x3.3 0x4.4", F32X4);
3664         can_parse_as_constant_data!("0x0 0x1 0x2 0x3", I32X4);
3665         can_parse_as_constant_data!("-1 0 -1 0 -1 0 -1 0", I16X8);
3666         can_parse_as_constant_data!("0 -1", I64X2);
3667         can_parse_as_constant_data!("-1 0", I64X2);
3668         can_parse_as_constant_data!("-1 -1 -1 -1 -1", I32X4); // note that parse_literals_to_constant_data will leave extra tokens unconsumed
3669 
3670         cannot_parse_as_constant_data!("1 2 3", I32X4);
3671         cannot_parse_as_constant_data!(" ", F32X4);
3672     }
3673 
3674     #[test]
3675     fn parse_constant_from_booleans() {
3676         let c = Parser::new("-1 0 -1 0")
3677             .parse_literals_to_constant_data(I32X4)
3678             .unwrap();
3679         assert_eq!(
3680             c.into_vec(),
3681             [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0]
3682         )
3683     }
3684 
3685     #[test]
3686     fn parse_unbounded_constants() {
3687         // Unlike match_uimm128, match_hexadecimal_constant can parse byte sequences of any size:
3688         assert_eq!(
3689             Parser::new("0x0100")
3690                 .match_hexadecimal_constant("err message")
3691                 .unwrap(),
3692             vec![0, 1].into()
3693         );
3694 
3695         // Only parse hexadecimal constants:
3696         assert!(Parser::new("228")
3697             .match_hexadecimal_constant("err message")
3698             .is_err());
3699     }
3700 
3701     #[test]
3702     fn parse_run_commands() {
3703         // Helper for creating signatures.
3704         fn sig(ins: &[Type], outs: &[Type]) -> Signature {
3705             let mut sig = Signature::new(CallConv::Fast);
3706             for i in ins {
3707                 sig.params.push(AbiParam::new(*i));
3708             }
3709             for o in outs {
3710                 sig.returns.push(AbiParam::new(*o));
3711             }
3712             sig
3713         }
3714 
3715         // Helper for parsing run commands.
3716         fn parse(text: &str, sig: &Signature) -> ParseResult<RunCommand> {
3717             Parser::new(text).parse_run_command(sig)
3718         }
3719 
3720         // Check that we can parse and display the same set of run commands.
3721         fn assert_roundtrip(text: &str, sig: &Signature) {
3722             assert_eq!(parse(text, sig).unwrap().to_string(), text);
3723         }
3724         assert_roundtrip("run: %fn0() == 42", &sig(&[], &[I32]));
3725         assert_roundtrip(
3726             "run: %fn0(8, 16, 32, 64) == 1",
3727             &sig(&[I8, I16, I32, I64], &[I8]),
3728         );
3729         assert_roundtrip(
3730             "run: %my_func(1) == 0x0f0e0d0c0b0a09080706050403020100",
3731             &sig(&[I32], &[I8X16]),
3732         );
3733 
3734         // Verify that default invocations are created when not specified.
3735         assert_eq!(
3736             parse("run", &sig(&[], &[I32])).unwrap().to_string(),
3737             "run: %default() != 0"
3738         );
3739         assert_eq!(
3740             parse("print", &sig(&[], &[F32X4, I16X8]))
3741                 .unwrap()
3742                 .to_string(),
3743             "print: %default()"
3744         );
3745 
3746         // Demonstrate some unparseable cases.
3747         assert!(parse("print", &sig(&[I32], &[I32])).is_err());
3748         assert!(parse("print:", &sig(&[], &[])).is_err());
3749         assert!(parse("run: ", &sig(&[], &[])).is_err());
3750     }
3751 
3752     #[test]
3753     fn parse_data_values() {
3754         fn parse(text: &str, ty: Type) -> DataValue {
3755             Parser::new(text).parse_data_value(ty).unwrap()
3756         }
3757 
3758         assert_eq!(parse("8", I8).to_string(), "8");
3759         assert_eq!(parse("16", I16).to_string(), "16");
3760         assert_eq!(parse("32", I32).to_string(), "32");
3761         assert_eq!(parse("64", I64).to_string(), "64");
3762         assert_eq!(
3763             parse("0x01234567_01234567_01234567_01234567", I128).to_string(),
3764             "1512366032949150931280199141537564007"
3765         );
3766         assert_eq!(parse("1234567", I128).to_string(), "1234567");
3767         assert_eq!(parse("0x32.32", F32).to_string(), "0x1.919000p5");
3768         assert_eq!(parse("0x64.64", F64).to_string(), "0x1.9190000000000p6");
3769         assert_eq!(
3770             parse("[0 1 2 3]", I32X4).to_string(),
3771             "0x00000003000000020000000100000000"
3772         );
3773     }
3774 
3775     #[test]
3776     fn parse_cold_blocks() {
3777         let code = "function %test() {
3778         block0 cold:
3779             return
3780         block1(v0: i32) cold:
3781             return
3782         block2(v1: i32):
3783             return
3784         }";
3785 
3786         let mut parser = Parser::new(code);
3787         let func = parser.parse_function().unwrap().0;
3788         assert_eq!(func.layout.blocks().count(), 3);
3789         assert!(func.layout.is_cold(Block::from_u32(0)));
3790         assert!(func.layout.is_cold(Block::from_u32(1)));
3791         assert!(!func.layout.is_cold(Block::from_u32(2)));
3792     }
3793 }
3794