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