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