1 //! A verifier for ensuring that functions are well formed. 2 //! It verifies: 3 //! 4 //! block integrity 5 //! 6 //! - All instructions reached from the `block_insts` iterator must belong to 7 //! the block as reported by `inst_block()`. 8 //! - Every block must end in a terminator instruction, and no other instruction 9 //! can be a terminator. 10 //! - Every value in the `block_params` iterator belongs to the block as reported by `value_block`. 11 //! 12 //! Instruction integrity 13 //! 14 //! - The instruction format must match the opcode. 15 //! - All result values must be created for multi-valued instructions. 16 //! - All referenced entities must exist. (Values, blocks, stack slots, ...) 17 //! - Instructions must not reference (eg. branch to) the entry block. 18 //! 19 //! SSA form 20 //! 21 //! - Values must be defined by an instruction that exists and that is inserted in 22 //! a block, or be an argument of an existing block. 23 //! - Values used by an instruction must dominate the instruction. 24 //! 25 //! Control flow graph and dominator tree integrity: 26 //! 27 //! - All predecessors in the CFG must be branches to the block. 28 //! - All branches to a block must be present in the CFG. 29 //! - A recomputed dominator tree is identical to the existing one. 30 //! - The entry block must not be a cold block. 31 //! 32 //! Type checking 33 //! 34 //! - Compare input and output values against the opcode's type constraints. 35 //! For polymorphic opcodes, determine the controlling type variable first. 36 //! - Branches and jumps must pass arguments to destination blocks that match the 37 //! expected types exactly. The number of arguments must match. 38 //! - All blocks in a jump table must take no arguments. 39 //! - Function calls are type checked against their signature. 40 //! - The entry block must take arguments that match the signature of the current 41 //! function. 42 //! - All return instructions must have return value operands matching the current 43 //! function signature. 44 //! 45 //! Global values 46 //! 47 //! - Detect cycles in global values. 48 //! - Detect use of 'vmctx' global value when no corresponding parameter is defined. 49 //! 50 //! TODO: 51 //! Ad hoc checking 52 //! 53 //! - Stack slot loads and stores must be in-bounds. 54 //! - Immediate constraints for certain opcodes, like `udiv_imm v3, 0`. 55 //! - `Insertlane` and `extractlane` instructions have immediate lane numbers that must be in 56 //! range for their polymorphic type. 57 //! - Swizzle and shuffle instructions take a variable number of lane arguments. The number 58 //! of arguments must match the destination type, and the lane indexes must be in range. 59 60 use self::flags::verify_flags; 61 use crate::dbg::DisplayList; 62 use crate::dominator_tree::DominatorTree; 63 use crate::entity::SparseSet; 64 use crate::flowgraph::{BlockPredecessor, ControlFlowGraph}; 65 use crate::ir; 66 use crate::ir::entities::AnyEntity; 67 use crate::ir::instructions::{BranchInfo, CallInfo, InstructionFormat, ResolvedConstraint}; 68 use crate::ir::{ 69 types, ArgumentPurpose, Block, Constant, DynamicStackSlot, FuncRef, Function, GlobalValue, 70 Inst, JumpTable, Opcode, SigRef, StackSlot, Type, Value, ValueDef, ValueList, 71 }; 72 use crate::isa::TargetIsa; 73 use crate::iterators::IteratorExtras; 74 use crate::print_errors::pretty_verifier_error; 75 use crate::settings::FlagsOrIsa; 76 use crate::timing; 77 use alloc::collections::BTreeSet; 78 use alloc::string::{String, ToString}; 79 use alloc::vec::Vec; 80 use core::cmp::Ordering; 81 use core::fmt::{self, Display, Formatter}; 82 83 mod flags; 84 85 /// A verifier error. 86 #[derive(Debug, PartialEq, Eq, Clone)] 87 pub struct VerifierError { 88 /// The entity causing the verifier error. 89 pub location: AnyEntity, 90 /// Optionally provide some context for the given location; e.g., for `inst42` provide 91 /// `Some("v3 = iconst.i32 0")` for more comprehensible errors. 92 pub context: Option<String>, 93 /// The error message. 94 pub message: String, 95 } 96 97 // This is manually implementing Error and Display instead of using thiserror to reduce the amount 98 // of dependencies used by Cranelift. 99 impl std::error::Error for VerifierError {} 100 101 impl Display for VerifierError { 102 fn fmt(&self, f: &mut Formatter) -> fmt::Result { 103 match &self.context { 104 None => write!(f, "{}: {}", self.location, self.message), 105 Some(context) => write!(f, "{} ({}): {}", self.location, context, self.message), 106 } 107 } 108 } 109 110 /// Convenience converter for making error-reporting less verbose. 111 /// 112 /// Converts a tuple of `(location, context, message)` to a `VerifierError`. 113 /// ``` 114 /// use cranelift_codegen::verifier::VerifierErrors; 115 /// use cranelift_codegen::ir::Inst; 116 /// let mut errors = VerifierErrors::new(); 117 /// errors.report((Inst::from_u32(42), "v3 = iadd v1, v2", "iadd cannot be used with values of this type")); 118 /// // note the double parenthenses to use this syntax 119 /// ``` 120 impl<L, C, M> From<(L, C, M)> for VerifierError 121 where 122 L: Into<AnyEntity>, 123 C: Into<String>, 124 M: Into<String>, 125 { 126 fn from(items: (L, C, M)) -> Self { 127 let (location, context, message) = items; 128 Self { 129 location: location.into(), 130 context: Some(context.into()), 131 message: message.into(), 132 } 133 } 134 } 135 136 /// Convenience converter for making error-reporting less verbose. 137 /// 138 /// Same as above but without `context`. 139 impl<L, M> From<(L, M)> for VerifierError 140 where 141 L: Into<AnyEntity>, 142 M: Into<String>, 143 { 144 fn from(items: (L, M)) -> Self { 145 let (location, message) = items; 146 Self { 147 location: location.into(), 148 context: None, 149 message: message.into(), 150 } 151 } 152 } 153 154 /// Result of a step in the verification process. 155 /// 156 /// Functions that return `VerifierStepResult<()>` should also take a 157 /// mutable reference to `VerifierErrors` as argument in order to report 158 /// errors. 159 /// 160 /// Here, `Ok` represents a step that **did not lead to a fatal error**, 161 /// meaning that the verification process may continue. However, other (non-fatal) 162 /// errors might have been reported through the previously mentioned `VerifierErrors` 163 /// argument. 164 pub type VerifierStepResult<T> = Result<T, ()>; 165 166 /// Result of a verification operation. 167 /// 168 /// Unlike `VerifierStepResult<()>` which may be `Ok` while still having reported 169 /// errors, this type always returns `Err` if an error (fatal or not) was reported. 170 pub type VerifierResult<T> = Result<T, VerifierErrors>; 171 172 /// List of verifier errors. 173 #[derive(Debug, Default, PartialEq, Eq, Clone)] 174 pub struct VerifierErrors(pub Vec<VerifierError>); 175 176 // This is manually implementing Error and Display instead of using thiserror to reduce the amount 177 // of dependencies used by Cranelift. 178 impl std::error::Error for VerifierErrors {} 179 180 impl VerifierErrors { 181 /// Return a new `VerifierErrors` struct. 182 #[inline] 183 pub fn new() -> Self { 184 Self(Vec::new()) 185 } 186 187 /// Return whether no errors were reported. 188 #[inline] 189 pub fn is_empty(&self) -> bool { 190 self.0.is_empty() 191 } 192 193 /// Return whether one or more errors were reported. 194 #[inline] 195 pub fn has_error(&self) -> bool { 196 !self.0.is_empty() 197 } 198 199 /// Return a `VerifierStepResult` that is fatal if at least one error was reported, 200 /// and non-fatal otherwise. 201 #[inline] 202 pub fn as_result(&self) -> VerifierStepResult<()> { 203 if self.is_empty() { 204 Ok(()) 205 } else { 206 Err(()) 207 } 208 } 209 210 /// Report an error, adding it to the list of errors. 211 pub fn report(&mut self, error: impl Into<VerifierError>) { 212 self.0.push(error.into()); 213 } 214 215 /// Report a fatal error and return `Err`. 216 pub fn fatal(&mut self, error: impl Into<VerifierError>) -> VerifierStepResult<()> { 217 self.report(error); 218 Err(()) 219 } 220 221 /// Report a non-fatal error and return `Ok`. 222 pub fn nonfatal(&mut self, error: impl Into<VerifierError>) -> VerifierStepResult<()> { 223 self.report(error); 224 Ok(()) 225 } 226 } 227 228 impl From<Vec<VerifierError>> for VerifierErrors { 229 fn from(v: Vec<VerifierError>) -> Self { 230 Self(v) 231 } 232 } 233 234 impl Into<Vec<VerifierError>> for VerifierErrors { 235 fn into(self) -> Vec<VerifierError> { 236 self.0 237 } 238 } 239 240 impl Into<VerifierResult<()>> for VerifierErrors { 241 fn into(self) -> VerifierResult<()> { 242 if self.is_empty() { 243 Ok(()) 244 } else { 245 Err(self) 246 } 247 } 248 } 249 250 impl Display for VerifierErrors { 251 fn fmt(&self, f: &mut Formatter) -> fmt::Result { 252 for err in &self.0 { 253 writeln!(f, "- {}", err)?; 254 } 255 Ok(()) 256 } 257 } 258 259 /// Verify `func`. 260 pub fn verify_function<'a, FOI: Into<FlagsOrIsa<'a>>>( 261 func: &Function, 262 fisa: FOI, 263 ) -> VerifierResult<()> { 264 let _tt = timing::verifier(); 265 let mut errors = VerifierErrors::default(); 266 let verifier = Verifier::new(func, fisa.into()); 267 let result = verifier.run(&mut errors); 268 if errors.is_empty() { 269 result.unwrap(); 270 Ok(()) 271 } else { 272 Err(errors) 273 } 274 } 275 276 /// Verify `func` after checking the integrity of associated context data structures `cfg` and 277 /// `domtree`. 278 pub fn verify_context<'a, FOI: Into<FlagsOrIsa<'a>>>( 279 func: &Function, 280 cfg: &ControlFlowGraph, 281 domtree: &DominatorTree, 282 fisa: FOI, 283 errors: &mut VerifierErrors, 284 ) -> VerifierStepResult<()> { 285 let _tt = timing::verifier(); 286 let verifier = Verifier::new(func, fisa.into()); 287 if cfg.is_valid() { 288 verifier.cfg_integrity(cfg, errors)?; 289 } 290 if domtree.is_valid() { 291 verifier.domtree_integrity(domtree, errors)?; 292 } 293 verifier.run(errors) 294 } 295 296 struct Verifier<'a> { 297 func: &'a Function, 298 expected_cfg: ControlFlowGraph, 299 expected_domtree: DominatorTree, 300 isa: Option<&'a dyn TargetIsa>, 301 } 302 303 impl<'a> Verifier<'a> { 304 pub fn new(func: &'a Function, fisa: FlagsOrIsa<'a>) -> Self { 305 let expected_cfg = ControlFlowGraph::with_function(func); 306 let expected_domtree = DominatorTree::with_function(func, &expected_cfg); 307 Self { 308 func, 309 expected_cfg, 310 expected_domtree, 311 isa: fisa.isa, 312 } 313 } 314 315 /// Determine a contextual error string for an instruction. 316 #[inline] 317 fn context(&self, inst: Inst) -> String { 318 self.func.dfg.display_inst(inst).to_string() 319 } 320 321 // Check for: 322 // - cycles in the global value declarations. 323 // - use of 'vmctx' when no special parameter declares it. 324 fn verify_global_values(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 325 let mut cycle_seen = false; 326 let mut seen = SparseSet::new(); 327 328 'gvs: for gv in self.func.global_values.keys() { 329 seen.clear(); 330 seen.insert(gv); 331 332 let mut cur = gv; 333 loop { 334 match self.func.global_values[cur] { 335 ir::GlobalValueData::Load { base, .. } 336 | ir::GlobalValueData::IAddImm { base, .. } => { 337 if seen.insert(base).is_some() { 338 if !cycle_seen { 339 errors.report(( 340 gv, 341 format!("global value cycle: {}", DisplayList(seen.as_slice())), 342 )); 343 // ensures we don't report the cycle multiple times 344 cycle_seen = true; 345 } 346 continue 'gvs; 347 } 348 349 cur = base; 350 } 351 _ => break, 352 } 353 } 354 355 match self.func.global_values[gv] { 356 ir::GlobalValueData::VMContext { .. } => { 357 if self 358 .func 359 .special_param(ir::ArgumentPurpose::VMContext) 360 .is_none() 361 { 362 errors.report((gv, format!("undeclared vmctx reference {}", gv))); 363 } 364 } 365 ir::GlobalValueData::IAddImm { 366 base, global_type, .. 367 } => { 368 if !global_type.is_int() { 369 errors.report(( 370 gv, 371 format!("iadd_imm global value with non-int type {}", global_type), 372 )); 373 } else if let Some(isa) = self.isa { 374 let base_type = self.func.global_values[base].global_type(isa); 375 if global_type != base_type { 376 errors.report(( 377 gv, 378 format!( 379 "iadd_imm type {} differs from operand type {}", 380 global_type, base_type 381 ), 382 )); 383 } 384 } 385 } 386 ir::GlobalValueData::Load { base, .. } => { 387 if let Some(isa) = self.isa { 388 let base_type = self.func.global_values[base].global_type(isa); 389 let pointer_type = isa.pointer_type(); 390 if base_type != pointer_type { 391 errors.report(( 392 gv, 393 format!( 394 "base {} has type {}, which is not the pointer type {}", 395 base, base_type, pointer_type 396 ), 397 )); 398 } 399 } 400 } 401 _ => {} 402 } 403 } 404 405 // Invalid global values shouldn't stop us from verifying the rest of the function 406 Ok(()) 407 } 408 409 fn verify_heaps(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 410 if let Some(isa) = self.isa { 411 for (heap, heap_data) in &self.func.heaps { 412 let base = heap_data.base; 413 if !self.func.global_values.is_valid(base) { 414 return errors.nonfatal((heap, format!("invalid base global value {}", base))); 415 } 416 417 let pointer_type = isa.pointer_type(); 418 let base_type = self.func.global_values[base].global_type(isa); 419 if base_type != pointer_type { 420 errors.report(( 421 heap, 422 format!( 423 "heap base has type {}, which is not the pointer type {}", 424 base_type, pointer_type 425 ), 426 )); 427 } 428 429 if let ir::HeapStyle::Dynamic { bound_gv, .. } = heap_data.style { 430 if !self.func.global_values.is_valid(bound_gv) { 431 return errors 432 .nonfatal((heap, format!("invalid bound global value {}", bound_gv))); 433 } 434 435 let bound_type = self.func.global_values[bound_gv].global_type(isa); 436 if pointer_type != bound_type { 437 errors.report(( 438 heap, 439 format!( 440 "heap pointer type {} differs from the type of its bound, {}", 441 pointer_type, bound_type 442 ), 443 )); 444 } 445 } 446 } 447 } 448 449 Ok(()) 450 } 451 452 fn verify_tables(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 453 if let Some(isa) = self.isa { 454 for (table, table_data) in &self.func.tables { 455 let base = table_data.base_gv; 456 if !self.func.global_values.is_valid(base) { 457 return errors.nonfatal((table, format!("invalid base global value {}", base))); 458 } 459 460 let pointer_type = isa.pointer_type(); 461 let base_type = self.func.global_values[base].global_type(isa); 462 if base_type != pointer_type { 463 errors.report(( 464 table, 465 format!( 466 "table base has type {}, which is not the pointer type {}", 467 base_type, pointer_type 468 ), 469 )); 470 } 471 472 let bound_gv = table_data.bound_gv; 473 if !self.func.global_values.is_valid(bound_gv) { 474 return errors 475 .nonfatal((table, format!("invalid bound global value {}", bound_gv))); 476 } 477 478 let index_type = table_data.index_type; 479 let bound_type = self.func.global_values[bound_gv].global_type(isa); 480 if index_type != bound_type { 481 errors.report(( 482 table, 483 format!( 484 "table index type {} differs from the type of its bound, {}", 485 index_type, bound_type 486 ), 487 )); 488 } 489 } 490 } 491 492 Ok(()) 493 } 494 495 fn verify_jump_tables(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 496 for (jt, jt_data) in &self.func.jump_tables { 497 for &block in jt_data.iter() { 498 self.verify_block(jt, block, errors)?; 499 } 500 } 501 Ok(()) 502 } 503 504 /// Check that the given block can be encoded as a BB, by checking that only 505 /// branching instructions are ending the block. 506 fn encodable_as_bb(&self, block: Block, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 507 match self.func.is_block_basic(block) { 508 Ok(()) => Ok(()), 509 Err((inst, message)) => errors.fatal((inst, self.context(inst), message)), 510 } 511 } 512 513 fn block_integrity( 514 &self, 515 block: Block, 516 inst: Inst, 517 errors: &mut VerifierErrors, 518 ) -> VerifierStepResult<()> { 519 let is_terminator = self.func.dfg[inst].opcode().is_terminator(); 520 let is_last_inst = self.func.layout.last_inst(block) == Some(inst); 521 522 if is_terminator && !is_last_inst { 523 // Terminating instructions only occur at the end of blocks. 524 return errors.fatal(( 525 inst, 526 self.context(inst), 527 format!( 528 "a terminator instruction was encountered before the end of {}", 529 block 530 ), 531 )); 532 } 533 if is_last_inst && !is_terminator { 534 return errors.fatal((block, "block does not end in a terminator instruction")); 535 } 536 537 // Instructions belong to the correct block. 538 let inst_block = self.func.layout.inst_block(inst); 539 if inst_block != Some(block) { 540 return errors.fatal(( 541 inst, 542 self.context(inst), 543 format!("should belong to {} not {:?}", block, inst_block), 544 )); 545 } 546 547 // Parameters belong to the correct block. 548 for &arg in self.func.dfg.block_params(block) { 549 match self.func.dfg.value_def(arg) { 550 ValueDef::Param(arg_block, _) => { 551 if block != arg_block { 552 return errors.fatal((arg, format!("does not belong to {}", block))); 553 } 554 } 555 _ => { 556 return errors.fatal((arg, "expected an argument, found a result")); 557 } 558 } 559 } 560 561 Ok(()) 562 } 563 564 fn instruction_integrity( 565 &self, 566 inst: Inst, 567 errors: &mut VerifierErrors, 568 ) -> VerifierStepResult<()> { 569 let inst_data = &self.func.dfg[inst]; 570 let dfg = &self.func.dfg; 571 572 // The instruction format matches the opcode 573 if inst_data.opcode().format() != InstructionFormat::from(inst_data) { 574 return errors.fatal(( 575 inst, 576 self.context(inst), 577 "instruction opcode doesn't match instruction format", 578 )); 579 } 580 581 let num_fixed_results = inst_data.opcode().constraints().num_fixed_results(); 582 // var_results is 0 if we aren't a call instruction 583 let var_results = dfg 584 .call_signature(inst) 585 .map_or(0, |sig| dfg.signatures[sig].returns.len()); 586 let total_results = num_fixed_results + var_results; 587 588 // All result values for multi-valued instructions are created 589 let got_results = dfg.inst_results(inst).len(); 590 if got_results != total_results { 591 return errors.fatal(( 592 inst, 593 self.context(inst), 594 format!( 595 "expected {} result values, found {}", 596 total_results, got_results, 597 ), 598 )); 599 } 600 601 self.verify_entity_references(inst, errors) 602 } 603 604 fn verify_entity_references( 605 &self, 606 inst: Inst, 607 errors: &mut VerifierErrors, 608 ) -> VerifierStepResult<()> { 609 use crate::ir::instructions::InstructionData::*; 610 611 for &arg in self.func.dfg.inst_args(inst) { 612 self.verify_inst_arg(inst, arg, errors)?; 613 614 // All used values must be attached to something. 615 let original = self.func.dfg.resolve_aliases(arg); 616 if !self.func.dfg.value_is_attached(original) { 617 errors.report(( 618 inst, 619 self.context(inst), 620 format!("argument {} -> {} is not attached", arg, original), 621 )); 622 } 623 } 624 625 for &res in self.func.dfg.inst_results(inst) { 626 self.verify_inst_result(inst, res, errors)?; 627 } 628 629 match self.func.dfg[inst] { 630 MultiAry { ref args, .. } => { 631 self.verify_value_list(inst, args, errors)?; 632 } 633 Jump { 634 destination, 635 ref args, 636 .. 637 } 638 | Branch { 639 destination, 640 ref args, 641 .. 642 } 643 | BranchInt { 644 destination, 645 ref args, 646 .. 647 } 648 | BranchFloat { 649 destination, 650 ref args, 651 .. 652 } 653 | BranchIcmp { 654 destination, 655 ref args, 656 .. 657 } => { 658 self.verify_block(inst, destination, errors)?; 659 self.verify_value_list(inst, args, errors)?; 660 } 661 BranchTable { 662 table, destination, .. 663 } => { 664 self.verify_block(inst, destination, errors)?; 665 self.verify_jump_table(inst, table, errors)?; 666 } 667 Call { 668 func_ref, ref args, .. 669 } => { 670 self.verify_func_ref(inst, func_ref, errors)?; 671 self.verify_value_list(inst, args, errors)?; 672 } 673 CallIndirect { 674 sig_ref, ref args, .. 675 } => { 676 self.verify_sig_ref(inst, sig_ref, errors)?; 677 self.verify_value_list(inst, args, errors)?; 678 } 679 FuncAddr { func_ref, .. } => { 680 self.verify_func_ref(inst, func_ref, errors)?; 681 } 682 StackLoad { stack_slot, .. } | StackStore { stack_slot, .. } => { 683 self.verify_stack_slot(inst, stack_slot, errors)?; 684 } 685 DynamicStackLoad { 686 dynamic_stack_slot, .. 687 } 688 | DynamicStackStore { 689 dynamic_stack_slot, .. 690 } => { 691 self.verify_dynamic_stack_slot(inst, dynamic_stack_slot, errors)?; 692 } 693 UnaryGlobalValue { global_value, .. } => { 694 self.verify_global_value(inst, global_value, errors)?; 695 } 696 HeapAddr { heap, .. } => { 697 self.verify_heap(inst, heap, errors)?; 698 } 699 TableAddr { table, .. } => { 700 self.verify_table(inst, table, errors)?; 701 } 702 NullAry { 703 opcode: Opcode::GetPinnedReg, 704 } 705 | Unary { 706 opcode: Opcode::SetPinnedReg, 707 .. 708 } => { 709 if let Some(isa) = &self.isa { 710 if !isa.flags().enable_pinned_reg() { 711 return errors.fatal(( 712 inst, 713 self.context(inst), 714 "GetPinnedReg/SetPinnedReg cannot be used without enable_pinned_reg", 715 )); 716 } 717 } else { 718 return errors.fatal(( 719 inst, 720 self.context(inst), 721 "GetPinnedReg/SetPinnedReg need an ISA!", 722 )); 723 } 724 } 725 NullAry { 726 opcode: Opcode::GetFramePointer | Opcode::GetReturnAddress, 727 } => { 728 if let Some(isa) = &self.isa { 729 if !isa.flags().preserve_frame_pointers() { 730 return errors.fatal(( 731 inst, 732 self.context(inst), 733 "`get_frame_pointer`/`get_return_address` cannot be used without \ 734 enabling `preserve_frame_pointers`", 735 )); 736 } 737 } else { 738 return errors.fatal(( 739 inst, 740 self.context(inst), 741 "`get_frame_pointer`/`get_return_address` require an ISA!", 742 )); 743 } 744 } 745 Unary { 746 opcode: Opcode::Bitcast, 747 arg, 748 } => { 749 self.verify_bitcast(inst, arg, errors)?; 750 } 751 UnaryConst { 752 opcode: Opcode::Vconst, 753 constant_handle, 754 .. 755 } => { 756 self.verify_constant_size(inst, constant_handle, errors)?; 757 } 758 759 // Exhaustive list so we can't forget to add new formats 760 AtomicCas { .. } 761 | AtomicRmw { .. } 762 | LoadNoOffset { .. } 763 | StoreNoOffset { .. } 764 | Unary { .. } 765 | UnaryConst { .. } 766 | UnaryImm { .. } 767 | UnaryIeee32 { .. } 768 | UnaryIeee64 { .. } 769 | UnaryBool { .. } 770 | Binary { .. } 771 | BinaryImm8 { .. } 772 | BinaryImm64 { .. } 773 | Ternary { .. } 774 | TernaryImm8 { .. } 775 | Shuffle { .. } 776 | IntCompare { .. } 777 | IntCompareImm { .. } 778 | IntCond { .. } 779 | FloatCompare { .. } 780 | FloatCond { .. } 781 | IntSelect { .. } 782 | Load { .. } 783 | Store { .. } 784 | Trap { .. } 785 | CondTrap { .. } 786 | IntCondTrap { .. } 787 | FloatCondTrap { .. } 788 | NullAry { .. } => {} 789 } 790 791 Ok(()) 792 } 793 794 fn verify_block( 795 &self, 796 loc: impl Into<AnyEntity>, 797 e: Block, 798 errors: &mut VerifierErrors, 799 ) -> VerifierStepResult<()> { 800 if !self.func.dfg.block_is_valid(e) || !self.func.layout.is_block_inserted(e) { 801 return errors.fatal((loc, format!("invalid block reference {}", e))); 802 } 803 if let Some(entry_block) = self.func.layout.entry_block() { 804 if e == entry_block { 805 return errors.fatal((loc, format!("invalid reference to entry block {}", e))); 806 } 807 } 808 Ok(()) 809 } 810 811 fn verify_sig_ref( 812 &self, 813 inst: Inst, 814 s: SigRef, 815 errors: &mut VerifierErrors, 816 ) -> VerifierStepResult<()> { 817 if !self.func.dfg.signatures.is_valid(s) { 818 errors.fatal(( 819 inst, 820 self.context(inst), 821 format!("invalid signature reference {}", s), 822 )) 823 } else { 824 Ok(()) 825 } 826 } 827 828 fn verify_func_ref( 829 &self, 830 inst: Inst, 831 f: FuncRef, 832 errors: &mut VerifierErrors, 833 ) -> VerifierStepResult<()> { 834 if !self.func.dfg.ext_funcs.is_valid(f) { 835 errors.nonfatal(( 836 inst, 837 self.context(inst), 838 format!("invalid function reference {}", f), 839 )) 840 } else { 841 Ok(()) 842 } 843 } 844 845 fn verify_stack_slot( 846 &self, 847 inst: Inst, 848 ss: StackSlot, 849 errors: &mut VerifierErrors, 850 ) -> VerifierStepResult<()> { 851 if !self.func.sized_stack_slots.is_valid(ss) { 852 errors.nonfatal(( 853 inst, 854 self.context(inst), 855 format!("invalid stack slot {}", ss), 856 )) 857 } else { 858 Ok(()) 859 } 860 } 861 862 fn verify_dynamic_stack_slot( 863 &self, 864 inst: Inst, 865 ss: DynamicStackSlot, 866 errors: &mut VerifierErrors, 867 ) -> VerifierStepResult<()> { 868 if !self.func.dynamic_stack_slots.is_valid(ss) { 869 errors.nonfatal(( 870 inst, 871 self.context(inst), 872 format!("invalid dynamic stack slot {}", ss), 873 )) 874 } else { 875 Ok(()) 876 } 877 } 878 879 fn verify_global_value( 880 &self, 881 inst: Inst, 882 gv: GlobalValue, 883 errors: &mut VerifierErrors, 884 ) -> VerifierStepResult<()> { 885 if !self.func.global_values.is_valid(gv) { 886 errors.nonfatal(( 887 inst, 888 self.context(inst), 889 format!("invalid global value {}", gv), 890 )) 891 } else { 892 Ok(()) 893 } 894 } 895 896 fn verify_heap( 897 &self, 898 inst: Inst, 899 heap: ir::Heap, 900 errors: &mut VerifierErrors, 901 ) -> VerifierStepResult<()> { 902 if !self.func.heaps.is_valid(heap) { 903 errors.nonfatal((inst, self.context(inst), format!("invalid heap {}", heap))) 904 } else { 905 Ok(()) 906 } 907 } 908 909 fn verify_table( 910 &self, 911 inst: Inst, 912 table: ir::Table, 913 errors: &mut VerifierErrors, 914 ) -> VerifierStepResult<()> { 915 if !self.func.tables.is_valid(table) { 916 errors.nonfatal((inst, self.context(inst), format!("invalid table {}", table))) 917 } else { 918 Ok(()) 919 } 920 } 921 922 fn verify_value_list( 923 &self, 924 inst: Inst, 925 l: &ValueList, 926 errors: &mut VerifierErrors, 927 ) -> VerifierStepResult<()> { 928 if !l.is_valid(&self.func.dfg.value_lists) { 929 errors.nonfatal(( 930 inst, 931 self.context(inst), 932 format!("invalid value list reference {:?}", l), 933 )) 934 } else { 935 Ok(()) 936 } 937 } 938 939 fn verify_jump_table( 940 &self, 941 inst: Inst, 942 j: JumpTable, 943 errors: &mut VerifierErrors, 944 ) -> VerifierStepResult<()> { 945 if !self.func.jump_tables.is_valid(j) { 946 errors.nonfatal(( 947 inst, 948 self.context(inst), 949 format!("invalid jump table reference {}", j), 950 )) 951 } else { 952 Ok(()) 953 } 954 } 955 956 fn verify_value( 957 &self, 958 loc_inst: Inst, 959 v: Value, 960 errors: &mut VerifierErrors, 961 ) -> VerifierStepResult<()> { 962 let dfg = &self.func.dfg; 963 if !dfg.value_is_valid(v) { 964 errors.nonfatal(( 965 loc_inst, 966 self.context(loc_inst), 967 format!("invalid value reference {}", v), 968 )) 969 } else { 970 Ok(()) 971 } 972 } 973 974 fn verify_inst_arg( 975 &self, 976 loc_inst: Inst, 977 v: Value, 978 errors: &mut VerifierErrors, 979 ) -> VerifierStepResult<()> { 980 self.verify_value(loc_inst, v, errors)?; 981 982 let dfg = &self.func.dfg; 983 let loc_block = self.func.layout.pp_block(loc_inst); 984 let is_reachable = self.expected_domtree.is_reachable(loc_block); 985 986 // SSA form 987 match dfg.value_def(v) { 988 ValueDef::Result(def_inst, _) => { 989 // Value is defined by an instruction that exists. 990 if !dfg.inst_is_valid(def_inst) { 991 return errors.fatal(( 992 loc_inst, 993 self.context(loc_inst), 994 format!("{} is defined by invalid instruction {}", v, def_inst), 995 )); 996 } 997 // Defining instruction is inserted in a block. 998 if self.func.layout.inst_block(def_inst) == None { 999 return errors.fatal(( 1000 loc_inst, 1001 self.context(loc_inst), 1002 format!("{} is defined by {} which has no block", v, def_inst), 1003 )); 1004 } 1005 // Defining instruction dominates the instruction that uses the value. 1006 if is_reachable { 1007 if !self 1008 .expected_domtree 1009 .dominates(def_inst, loc_inst, &self.func.layout) 1010 { 1011 return errors.fatal(( 1012 loc_inst, 1013 self.context(loc_inst), 1014 format!("uses value {} from non-dominating {}", v, def_inst), 1015 )); 1016 } 1017 if def_inst == loc_inst { 1018 return errors.fatal(( 1019 loc_inst, 1020 self.context(loc_inst), 1021 format!("uses value {} from itself", v), 1022 )); 1023 } 1024 } 1025 } 1026 ValueDef::Param(block, _) => { 1027 // Value is defined by an existing block. 1028 if !dfg.block_is_valid(block) { 1029 return errors.fatal(( 1030 loc_inst, 1031 self.context(loc_inst), 1032 format!("{} is defined by invalid block {}", v, block), 1033 )); 1034 } 1035 // Defining block is inserted in the layout 1036 if !self.func.layout.is_block_inserted(block) { 1037 return errors.fatal(( 1038 loc_inst, 1039 self.context(loc_inst), 1040 format!("{} is defined by {} which is not in the layout", v, block), 1041 )); 1042 } 1043 // The defining block dominates the instruction using this value. 1044 if is_reachable 1045 && !self 1046 .expected_domtree 1047 .dominates(block, loc_inst, &self.func.layout) 1048 { 1049 return errors.fatal(( 1050 loc_inst, 1051 self.context(loc_inst), 1052 format!("uses value arg from non-dominating {}", block), 1053 )); 1054 } 1055 } 1056 } 1057 Ok(()) 1058 } 1059 1060 fn verify_inst_result( 1061 &self, 1062 loc_inst: Inst, 1063 v: Value, 1064 errors: &mut VerifierErrors, 1065 ) -> VerifierStepResult<()> { 1066 self.verify_value(loc_inst, v, errors)?; 1067 1068 match self.func.dfg.value_def(v) { 1069 ValueDef::Result(def_inst, _) => { 1070 if def_inst != loc_inst { 1071 errors.fatal(( 1072 loc_inst, 1073 self.context(loc_inst), 1074 format!("instruction result {} is not defined by the instruction", v), 1075 )) 1076 } else { 1077 Ok(()) 1078 } 1079 } 1080 ValueDef::Param(_, _) => errors.fatal(( 1081 loc_inst, 1082 self.context(loc_inst), 1083 format!("instruction result {} is not defined by the instruction", v), 1084 )), 1085 } 1086 } 1087 1088 fn verify_bitcast( 1089 &self, 1090 inst: Inst, 1091 arg: Value, 1092 errors: &mut VerifierErrors, 1093 ) -> VerifierStepResult<()> { 1094 let typ = self.func.dfg.ctrl_typevar(inst); 1095 let value_type = self.func.dfg.value_type(arg); 1096 1097 if typ.lane_bits() < value_type.lane_bits() { 1098 errors.fatal(( 1099 inst, 1100 format!( 1101 "The bitcast argument {} doesn't fit in a type of {} bits", 1102 arg, 1103 typ.lane_bits() 1104 ), 1105 )) 1106 } else { 1107 Ok(()) 1108 } 1109 } 1110 1111 fn verify_constant_size( 1112 &self, 1113 inst: Inst, 1114 constant: Constant, 1115 errors: &mut VerifierErrors, 1116 ) -> VerifierStepResult<()> { 1117 let type_size = self.func.dfg.ctrl_typevar(inst).bytes() as usize; 1118 let constant_size = self.func.dfg.constants.get(constant).len(); 1119 if type_size != constant_size { 1120 errors.fatal(( 1121 inst, 1122 format!( 1123 "The instruction expects {} to have a size of {} bytes but it has {}", 1124 constant, type_size, constant_size 1125 ), 1126 )) 1127 } else { 1128 Ok(()) 1129 } 1130 } 1131 1132 fn domtree_integrity( 1133 &self, 1134 domtree: &DominatorTree, 1135 errors: &mut VerifierErrors, 1136 ) -> VerifierStepResult<()> { 1137 // We consider two `DominatorTree`s to be equal if they return the same immediate 1138 // dominator for each block. Therefore the current domtree is valid if it matches the freshly 1139 // computed one. 1140 for block in self.func.layout.blocks() { 1141 let expected = self.expected_domtree.idom(block); 1142 let got = domtree.idom(block); 1143 if got != expected { 1144 return errors.fatal(( 1145 block, 1146 format!( 1147 "invalid domtree, expected idom({}) = {:?}, got {:?}", 1148 block, expected, got 1149 ), 1150 )); 1151 } 1152 } 1153 // We also verify if the postorder defined by `DominatorTree` is sane 1154 if domtree.cfg_postorder().len() != self.expected_domtree.cfg_postorder().len() { 1155 return errors.fatal(( 1156 AnyEntity::Function, 1157 "incorrect number of Blocks in postorder traversal", 1158 )); 1159 } 1160 for (index, (&test_block, &true_block)) in domtree 1161 .cfg_postorder() 1162 .iter() 1163 .zip(self.expected_domtree.cfg_postorder().iter()) 1164 .enumerate() 1165 { 1166 if test_block != true_block { 1167 return errors.fatal(( 1168 test_block, 1169 format!( 1170 "invalid domtree, postorder block number {} should be {}, got {}", 1171 index, true_block, test_block 1172 ), 1173 )); 1174 } 1175 } 1176 // We verify rpo_cmp on pairs of adjacent blocks in the postorder 1177 for (&prev_block, &next_block) in domtree.cfg_postorder().iter().adjacent_pairs() { 1178 if self 1179 .expected_domtree 1180 .rpo_cmp(prev_block, next_block, &self.func.layout) 1181 != Ordering::Greater 1182 { 1183 return errors.fatal(( 1184 next_block, 1185 format!( 1186 "invalid domtree, rpo_cmp does not says {} is greater than {}", 1187 prev_block, next_block 1188 ), 1189 )); 1190 } 1191 } 1192 Ok(()) 1193 } 1194 1195 fn typecheck_entry_block_params(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 1196 if let Some(block) = self.func.layout.entry_block() { 1197 let expected_types = &self.func.signature.params; 1198 let block_param_count = self.func.dfg.num_block_params(block); 1199 1200 if block_param_count != expected_types.len() { 1201 return errors.fatal(( 1202 block, 1203 format!( 1204 "entry block parameters ({}) must match function signature ({})", 1205 block_param_count, 1206 expected_types.len() 1207 ), 1208 )); 1209 } 1210 1211 for (i, &arg) in self.func.dfg.block_params(block).iter().enumerate() { 1212 let arg_type = self.func.dfg.value_type(arg); 1213 if arg_type != expected_types[i].value_type { 1214 errors.report(( 1215 block, 1216 format!( 1217 "entry block parameter {} expected to have type {}, got {}", 1218 i, expected_types[i], arg_type 1219 ), 1220 )); 1221 } 1222 } 1223 } 1224 1225 errors.as_result() 1226 } 1227 1228 fn check_entry_not_cold(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 1229 if let Some(entry_block) = self.func.layout.entry_block() { 1230 if self.func.layout.is_cold(entry_block) { 1231 return errors 1232 .fatal((entry_block, format!("entry block cannot be marked as cold"))); 1233 } 1234 } 1235 errors.as_result() 1236 } 1237 1238 fn typecheck(&self, inst: Inst, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 1239 let inst_data = &self.func.dfg[inst]; 1240 let constraints = inst_data.opcode().constraints(); 1241 1242 let ctrl_type = if let Some(value_typeset) = constraints.ctrl_typeset() { 1243 // For polymorphic opcodes, determine the controlling type variable first. 1244 let ctrl_type = self.func.dfg.ctrl_typevar(inst); 1245 1246 if !value_typeset.contains(ctrl_type) { 1247 errors.report(( 1248 inst, 1249 self.context(inst), 1250 format!("has an invalid controlling type {}", ctrl_type), 1251 )); 1252 } 1253 1254 ctrl_type 1255 } else { 1256 // Non-polymorphic instructions don't check the controlling type variable, so `Option` 1257 // is unnecessary and we can just make it `INVALID`. 1258 types::INVALID 1259 }; 1260 1261 // Typechecking instructions is never fatal 1262 let _ = self.typecheck_results(inst, ctrl_type, errors); 1263 let _ = self.typecheck_fixed_args(inst, ctrl_type, errors); 1264 let _ = self.typecheck_variable_args(inst, errors); 1265 let _ = self.typecheck_return(inst, errors); 1266 let _ = self.typecheck_special(inst, ctrl_type, errors); 1267 1268 Ok(()) 1269 } 1270 1271 fn typecheck_results( 1272 &self, 1273 inst: Inst, 1274 ctrl_type: Type, 1275 errors: &mut VerifierErrors, 1276 ) -> VerifierStepResult<()> { 1277 let mut i = 0; 1278 for &result in self.func.dfg.inst_results(inst) { 1279 let result_type = self.func.dfg.value_type(result); 1280 let expected_type = self.func.dfg.compute_result_type(inst, i, ctrl_type); 1281 if let Some(expected_type) = expected_type { 1282 if result_type != expected_type { 1283 errors.report(( 1284 inst, 1285 self.context(inst), 1286 format!( 1287 "expected result {} ({}) to have type {}, found {}", 1288 i, result, expected_type, result_type 1289 ), 1290 )); 1291 } 1292 } else { 1293 return errors.nonfatal(( 1294 inst, 1295 self.context(inst), 1296 "has more result values than expected", 1297 )); 1298 } 1299 i += 1; 1300 } 1301 1302 // There aren't any more result types left. 1303 if self.func.dfg.compute_result_type(inst, i, ctrl_type) != None { 1304 return errors.nonfatal(( 1305 inst, 1306 self.context(inst), 1307 "has fewer result values than expected", 1308 )); 1309 } 1310 Ok(()) 1311 } 1312 1313 fn typecheck_fixed_args( 1314 &self, 1315 inst: Inst, 1316 ctrl_type: Type, 1317 errors: &mut VerifierErrors, 1318 ) -> VerifierStepResult<()> { 1319 let constraints = self.func.dfg[inst].opcode().constraints(); 1320 1321 for (i, &arg) in self.func.dfg.inst_fixed_args(inst).iter().enumerate() { 1322 let arg_type = self.func.dfg.value_type(arg); 1323 match constraints.value_argument_constraint(i, ctrl_type) { 1324 ResolvedConstraint::Bound(expected_type) => { 1325 if arg_type != expected_type { 1326 errors.report(( 1327 inst, 1328 self.context(inst), 1329 format!( 1330 "arg {} ({}) has type {}, expected {}", 1331 i, arg, arg_type, expected_type 1332 ), 1333 )); 1334 } 1335 } 1336 ResolvedConstraint::Free(type_set) => { 1337 if !type_set.contains(arg_type) { 1338 errors.report(( 1339 inst, 1340 self.context(inst), 1341 format!( 1342 "arg {} ({}) with type {} failed to satisfy type set {:?}", 1343 i, arg, arg_type, type_set 1344 ), 1345 )); 1346 } 1347 } 1348 } 1349 } 1350 Ok(()) 1351 } 1352 1353 fn typecheck_variable_args( 1354 &self, 1355 inst: Inst, 1356 errors: &mut VerifierErrors, 1357 ) -> VerifierStepResult<()> { 1358 match self.func.dfg.analyze_branch(inst) { 1359 BranchInfo::SingleDest(block, _) => { 1360 let iter = self 1361 .func 1362 .dfg 1363 .block_params(block) 1364 .iter() 1365 .map(|&v| self.func.dfg.value_type(v)); 1366 self.typecheck_variable_args_iterator(inst, iter, errors)?; 1367 } 1368 BranchInfo::Table(table, block) => { 1369 if let Some(block) = block { 1370 let arg_count = self.func.dfg.num_block_params(block); 1371 if arg_count != 0 { 1372 return errors.nonfatal(( 1373 inst, 1374 self.context(inst), 1375 format!( 1376 "takes no arguments, but had target {} with {} arguments", 1377 block, arg_count, 1378 ), 1379 )); 1380 } 1381 } 1382 for block in self.func.jump_tables[table].iter() { 1383 let arg_count = self.func.dfg.num_block_params(*block); 1384 if arg_count != 0 { 1385 return errors.nonfatal(( 1386 inst, 1387 self.context(inst), 1388 format!( 1389 "takes no arguments, but had target {} with {} arguments", 1390 block, arg_count, 1391 ), 1392 )); 1393 } 1394 } 1395 } 1396 BranchInfo::NotABranch => {} 1397 } 1398 1399 match self.func.dfg[inst].analyze_call(&self.func.dfg.value_lists) { 1400 CallInfo::Direct(func_ref, _) => { 1401 let sig_ref = self.func.dfg.ext_funcs[func_ref].signature; 1402 let arg_types = self.func.dfg.signatures[sig_ref] 1403 .params 1404 .iter() 1405 .map(|a| a.value_type); 1406 self.typecheck_variable_args_iterator(inst, arg_types, errors)?; 1407 } 1408 CallInfo::Indirect(sig_ref, _) => { 1409 let arg_types = self.func.dfg.signatures[sig_ref] 1410 .params 1411 .iter() 1412 .map(|a| a.value_type); 1413 self.typecheck_variable_args_iterator(inst, arg_types, errors)?; 1414 } 1415 CallInfo::NotACall => {} 1416 } 1417 Ok(()) 1418 } 1419 1420 fn typecheck_variable_args_iterator<I: Iterator<Item = Type>>( 1421 &self, 1422 inst: Inst, 1423 iter: I, 1424 errors: &mut VerifierErrors, 1425 ) -> VerifierStepResult<()> { 1426 let variable_args = self.func.dfg.inst_variable_args(inst); 1427 let mut i = 0; 1428 1429 for expected_type in iter { 1430 if i >= variable_args.len() { 1431 // Result count mismatch handled below, we want the full argument count first though 1432 i += 1; 1433 continue; 1434 } 1435 let arg = variable_args[i]; 1436 let arg_type = self.func.dfg.value_type(arg); 1437 if expected_type != arg_type { 1438 errors.report(( 1439 inst, 1440 self.context(inst), 1441 format!( 1442 "arg {} ({}) has type {}, expected {}", 1443 i, variable_args[i], arg_type, expected_type 1444 ), 1445 )); 1446 } 1447 i += 1; 1448 } 1449 if i != variable_args.len() { 1450 return errors.nonfatal(( 1451 inst, 1452 self.context(inst), 1453 format!( 1454 "mismatched argument count for `{}`: got {}, expected {}", 1455 self.func.dfg.display_inst(inst), 1456 variable_args.len(), 1457 i, 1458 ), 1459 )); 1460 } 1461 Ok(()) 1462 } 1463 1464 fn typecheck_return(&self, inst: Inst, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 1465 if self.func.dfg[inst].opcode().is_return() { 1466 let args = self.func.dfg.inst_variable_args(inst); 1467 let expected_types = &self.func.signature.returns; 1468 if args.len() != expected_types.len() { 1469 return errors.nonfatal(( 1470 inst, 1471 self.context(inst), 1472 "arguments of return must match function signature", 1473 )); 1474 } 1475 for (i, (&arg, &expected_type)) in args.iter().zip(expected_types).enumerate() { 1476 let arg_type = self.func.dfg.value_type(arg); 1477 if arg_type != expected_type.value_type { 1478 errors.report(( 1479 inst, 1480 self.context(inst), 1481 format!( 1482 "arg {} ({}) has type {}, must match function signature of {}", 1483 i, arg, arg_type, expected_type 1484 ), 1485 )); 1486 } 1487 } 1488 } 1489 Ok(()) 1490 } 1491 1492 // Check special-purpose type constraints that can't be expressed in the normal opcode 1493 // constraints. 1494 fn typecheck_special( 1495 &self, 1496 inst: Inst, 1497 ctrl_type: Type, 1498 errors: &mut VerifierErrors, 1499 ) -> VerifierStepResult<()> { 1500 match self.func.dfg[inst] { 1501 ir::InstructionData::Unary { opcode, arg } => { 1502 let arg_type = self.func.dfg.value_type(arg); 1503 match opcode { 1504 Opcode::Bextend | Opcode::Uextend | Opcode::Sextend | Opcode::Fpromote => { 1505 if arg_type.lane_count() != ctrl_type.lane_count() { 1506 return errors.nonfatal(( 1507 inst, 1508 self.context(inst), 1509 format!( 1510 "input {} and output {} must have same number of lanes", 1511 arg_type, ctrl_type, 1512 ), 1513 )); 1514 } 1515 if arg_type.lane_bits() >= ctrl_type.lane_bits() { 1516 return errors.nonfatal(( 1517 inst, 1518 self.context(inst), 1519 format!( 1520 "input {} must be smaller than output {}", 1521 arg_type, ctrl_type, 1522 ), 1523 )); 1524 } 1525 } 1526 Opcode::Breduce | Opcode::Ireduce | Opcode::Fdemote => { 1527 if arg_type.lane_count() != ctrl_type.lane_count() { 1528 return errors.nonfatal(( 1529 inst, 1530 self.context(inst), 1531 format!( 1532 "input {} and output {} must have same number of lanes", 1533 arg_type, ctrl_type, 1534 ), 1535 )); 1536 } 1537 if arg_type.lane_bits() <= ctrl_type.lane_bits() { 1538 return errors.nonfatal(( 1539 inst, 1540 self.context(inst), 1541 format!( 1542 "input {} must be larger than output {}", 1543 arg_type, ctrl_type, 1544 ), 1545 )); 1546 } 1547 } 1548 _ => {} 1549 } 1550 } 1551 ir::InstructionData::HeapAddr { heap, arg, .. } => { 1552 let index_type = self.func.dfg.value_type(arg); 1553 let heap_index_type = self.func.heaps[heap].index_type; 1554 if index_type != heap_index_type { 1555 return errors.nonfatal(( 1556 inst, 1557 self.context(inst), 1558 format!( 1559 "index type {} differs from heap index type {}", 1560 index_type, heap_index_type, 1561 ), 1562 )); 1563 } 1564 } 1565 ir::InstructionData::TableAddr { table, arg, .. } => { 1566 let index_type = self.func.dfg.value_type(arg); 1567 let table_index_type = self.func.tables[table].index_type; 1568 if index_type != table_index_type { 1569 return errors.nonfatal(( 1570 inst, 1571 self.context(inst), 1572 format!( 1573 "index type {} differs from table index type {}", 1574 index_type, table_index_type, 1575 ), 1576 )); 1577 } 1578 } 1579 ir::InstructionData::UnaryGlobalValue { global_value, .. } => { 1580 if let Some(isa) = self.isa { 1581 let inst_type = self.func.dfg.value_type(self.func.dfg.first_result(inst)); 1582 let global_type = self.func.global_values[global_value].global_type(isa); 1583 if inst_type != global_type { 1584 return errors.nonfatal(( 1585 inst, self.context(inst), 1586 format!( 1587 "global_value instruction with type {} references global value with type {}", 1588 inst_type, global_type 1589 )), 1590 ); 1591 } 1592 } 1593 } 1594 _ => {} 1595 } 1596 Ok(()) 1597 } 1598 1599 fn cfg_integrity( 1600 &self, 1601 cfg: &ControlFlowGraph, 1602 errors: &mut VerifierErrors, 1603 ) -> VerifierStepResult<()> { 1604 let mut expected_succs = BTreeSet::<Block>::new(); 1605 let mut got_succs = BTreeSet::<Block>::new(); 1606 let mut expected_preds = BTreeSet::<Inst>::new(); 1607 let mut got_preds = BTreeSet::<Inst>::new(); 1608 1609 for block in self.func.layout.blocks() { 1610 expected_succs.extend(self.expected_cfg.succ_iter(block)); 1611 got_succs.extend(cfg.succ_iter(block)); 1612 1613 let missing_succs: Vec<Block> = 1614 expected_succs.difference(&got_succs).cloned().collect(); 1615 if !missing_succs.is_empty() { 1616 errors.report(( 1617 block, 1618 format!("cfg lacked the following successor(s) {:?}", missing_succs), 1619 )); 1620 continue; 1621 } 1622 1623 let excess_succs: Vec<Block> = got_succs.difference(&expected_succs).cloned().collect(); 1624 if !excess_succs.is_empty() { 1625 errors.report(( 1626 block, 1627 format!("cfg had unexpected successor(s) {:?}", excess_succs), 1628 )); 1629 continue; 1630 } 1631 1632 expected_preds.extend( 1633 self.expected_cfg 1634 .pred_iter(block) 1635 .map(|BlockPredecessor { inst, .. }| inst), 1636 ); 1637 got_preds.extend( 1638 cfg.pred_iter(block) 1639 .map(|BlockPredecessor { inst, .. }| inst), 1640 ); 1641 1642 let missing_preds: Vec<Inst> = expected_preds.difference(&got_preds).cloned().collect(); 1643 if !missing_preds.is_empty() { 1644 errors.report(( 1645 block, 1646 format!( 1647 "cfg lacked the following predecessor(s) {:?}", 1648 missing_preds 1649 ), 1650 )); 1651 continue; 1652 } 1653 1654 let excess_preds: Vec<Inst> = got_preds.difference(&expected_preds).cloned().collect(); 1655 if !excess_preds.is_empty() { 1656 errors.report(( 1657 block, 1658 format!("cfg had unexpected predecessor(s) {:?}", excess_preds), 1659 )); 1660 continue; 1661 } 1662 1663 expected_succs.clear(); 1664 got_succs.clear(); 1665 expected_preds.clear(); 1666 got_preds.clear(); 1667 } 1668 errors.as_result() 1669 } 1670 1671 fn immediate_constraints( 1672 &self, 1673 inst: Inst, 1674 errors: &mut VerifierErrors, 1675 ) -> VerifierStepResult<()> { 1676 let inst_data = &self.func.dfg[inst]; 1677 1678 match *inst_data { 1679 ir::InstructionData::Store { flags, .. } => { 1680 if flags.readonly() { 1681 errors.fatal(( 1682 inst, 1683 self.context(inst), 1684 "A store instruction cannot have the `readonly` MemFlag", 1685 )) 1686 } else { 1687 Ok(()) 1688 } 1689 } 1690 ir::InstructionData::BinaryImm8 { 1691 opcode: ir::instructions::Opcode::Extractlane, 1692 imm: lane, 1693 arg, 1694 .. 1695 } 1696 | ir::InstructionData::TernaryImm8 { 1697 opcode: ir::instructions::Opcode::Insertlane, 1698 imm: lane, 1699 args: [arg, _], 1700 .. 1701 } => { 1702 // We must be specific about the opcodes above because other instructions are using 1703 // the same formats. 1704 let ty = self.func.dfg.value_type(arg); 1705 if lane as u32 >= ty.lane_count() { 1706 errors.fatal(( 1707 inst, 1708 self.context(inst), 1709 format!("The lane {} does not index into the type {}", lane, ty,), 1710 )) 1711 } else { 1712 Ok(()) 1713 } 1714 } 1715 _ => Ok(()), 1716 } 1717 } 1718 1719 fn typecheck_function_signature(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 1720 self.func 1721 .signature 1722 .params 1723 .iter() 1724 .enumerate() 1725 .filter(|(_, ¶m)| param.value_type == types::INVALID) 1726 .for_each(|(i, _)| { 1727 errors.report(( 1728 AnyEntity::Function, 1729 format!("Parameter at position {} has an invalid type", i), 1730 )); 1731 }); 1732 1733 self.func 1734 .signature 1735 .returns 1736 .iter() 1737 .enumerate() 1738 .filter(|(_, &ret)| ret.value_type == types::INVALID) 1739 .for_each(|(i, _)| { 1740 errors.report(( 1741 AnyEntity::Function, 1742 format!("Return value at position {} has an invalid type", i), 1743 )) 1744 }); 1745 1746 self.func 1747 .signature 1748 .returns 1749 .iter() 1750 .enumerate() 1751 .for_each(|(i, ret)| { 1752 if let ArgumentPurpose::StructArgument(_) = ret.purpose { 1753 errors.report(( 1754 AnyEntity::Function, 1755 format!("Return value at position {} can't be an struct argument", i), 1756 )) 1757 } 1758 }); 1759 1760 if errors.has_error() { 1761 Err(()) 1762 } else { 1763 Ok(()) 1764 } 1765 } 1766 1767 pub fn run(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> { 1768 self.verify_global_values(errors)?; 1769 self.verify_heaps(errors)?; 1770 self.verify_tables(errors)?; 1771 self.verify_jump_tables(errors)?; 1772 self.typecheck_entry_block_params(errors)?; 1773 self.check_entry_not_cold(errors)?; 1774 self.typecheck_function_signature(errors)?; 1775 1776 for block in self.func.layout.blocks() { 1777 if self.func.layout.first_inst(block).is_none() { 1778 return errors.fatal((block, format!("{} cannot be empty", block))); 1779 } 1780 for inst in self.func.layout.block_insts(block) { 1781 self.block_integrity(block, inst, errors)?; 1782 self.instruction_integrity(inst, errors)?; 1783 self.typecheck(inst, errors)?; 1784 self.immediate_constraints(inst, errors)?; 1785 } 1786 1787 self.encodable_as_bb(block, errors)?; 1788 } 1789 1790 verify_flags(self.func, &self.expected_cfg, errors)?; 1791 1792 if !errors.is_empty() { 1793 log::warn!( 1794 "Found verifier errors in function:\n{}", 1795 pretty_verifier_error(self.func, None, errors.clone()) 1796 ); 1797 } 1798 1799 Ok(()) 1800 } 1801 } 1802 1803 #[cfg(test)] 1804 mod tests { 1805 use super::{Verifier, VerifierError, VerifierErrors}; 1806 use crate::entity::EntityList; 1807 use crate::ir::instructions::{InstructionData, Opcode}; 1808 use crate::ir::{types, AbiParam, Function}; 1809 use crate::settings; 1810 1811 macro_rules! assert_err_with_msg { 1812 ($e:expr, $msg:expr) => { 1813 match $e.0.get(0) { 1814 None => panic!("Expected an error"), 1815 Some(&VerifierError { ref message, .. }) => { 1816 if !message.contains($msg) { 1817 #[cfg(feature = "std")] 1818 panic!("'{}' did not contain the substring '{}'", message, $msg); 1819 #[cfg(not(feature = "std"))] 1820 panic!("error message did not contain the expected substring"); 1821 } 1822 } 1823 } 1824 }; 1825 } 1826 1827 #[test] 1828 fn empty() { 1829 let func = Function::new(); 1830 let flags = &settings::Flags::new(settings::builder()); 1831 let verifier = Verifier::new(&func, flags.into()); 1832 let mut errors = VerifierErrors::default(); 1833 1834 assert_eq!(verifier.run(&mut errors), Ok(())); 1835 assert!(errors.0.is_empty()); 1836 } 1837 1838 #[test] 1839 fn bad_instruction_format() { 1840 let mut func = Function::new(); 1841 let block0 = func.dfg.make_block(); 1842 func.layout.append_block(block0); 1843 let nullary_with_bad_opcode = func.dfg.make_inst(InstructionData::UnaryImm { 1844 opcode: Opcode::F32const, 1845 imm: 0.into(), 1846 }); 1847 func.layout.append_inst(nullary_with_bad_opcode, block0); 1848 func.layout.append_inst( 1849 func.dfg.make_inst(InstructionData::Jump { 1850 opcode: Opcode::Jump, 1851 destination: block0, 1852 args: EntityList::default(), 1853 }), 1854 block0, 1855 ); 1856 let flags = &settings::Flags::new(settings::builder()); 1857 let verifier = Verifier::new(&func, flags.into()); 1858 let mut errors = VerifierErrors::default(); 1859 1860 let _ = verifier.run(&mut errors); 1861 1862 assert_err_with_msg!(errors, "instruction format"); 1863 } 1864 1865 #[test] 1866 fn test_function_invalid_param() { 1867 let mut func = Function::new(); 1868 func.signature.params.push(AbiParam::new(types::INVALID)); 1869 1870 let mut errors = VerifierErrors::default(); 1871 let flags = &settings::Flags::new(settings::builder()); 1872 let verifier = Verifier::new(&func, flags.into()); 1873 1874 let _ = verifier.typecheck_function_signature(&mut errors); 1875 assert_err_with_msg!(errors, "Parameter at position 0 has an invalid type"); 1876 } 1877 1878 #[test] 1879 fn test_function_invalid_return_value() { 1880 let mut func = Function::new(); 1881 func.signature.returns.push(AbiParam::new(types::INVALID)); 1882 1883 let mut errors = VerifierErrors::default(); 1884 let flags = &settings::Flags::new(settings::builder()); 1885 let verifier = Verifier::new(&func, flags.into()); 1886 1887 let _ = verifier.typecheck_function_signature(&mut errors); 1888 assert_err_with_msg!(errors, "Return value at position 0 has an invalid type"); 1889 } 1890 1891 #[test] 1892 fn test_printing_contextual_errors() { 1893 // Build function. 1894 let mut func = Function::new(); 1895 let block0 = func.dfg.make_block(); 1896 func.layout.append_block(block0); 1897 1898 // Build instruction: v0, v1 = iconst 42 1899 let inst = func.dfg.make_inst(InstructionData::UnaryImm { 1900 opcode: Opcode::Iconst, 1901 imm: 42.into(), 1902 }); 1903 func.dfg.append_result(inst, types::I32); 1904 func.dfg.append_result(inst, types::I32); 1905 func.layout.append_inst(inst, block0); 1906 1907 // Setup verifier. 1908 let mut errors = VerifierErrors::default(); 1909 let flags = &settings::Flags::new(settings::builder()); 1910 let verifier = Verifier::new(&func, flags.into()); 1911 1912 // Now the error message, when printed, should contain the instruction sequence causing the 1913 // error (i.e. v0, v1 = iconst.i32 42) and not only its entity value (i.e. inst0) 1914 let _ = verifier.typecheck_results(inst, types::I32, &mut errors); 1915 assert_eq!( 1916 format!("{}", errors.0[0]), 1917 "inst0 (v0, v1 = iconst.i32 42): has more result values than expected" 1918 ) 1919 } 1920 1921 #[test] 1922 fn test_empty_block() { 1923 let mut func = Function::new(); 1924 let block0 = func.dfg.make_block(); 1925 func.layout.append_block(block0); 1926 1927 let flags = &settings::Flags::new(settings::builder()); 1928 let verifier = Verifier::new(&func, flags.into()); 1929 let mut errors = VerifierErrors::default(); 1930 let _ = verifier.run(&mut errors); 1931 1932 assert_err_with_msg!(errors, "block0 cannot be empty"); 1933 } 1934 } 1935