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