-------------------------------------------------------------------------------- I1 cache: 65536 B, 64 B, 4-way associative D1 cache: 32768 B, 64 B, 8-way associative LL cache: 67108864 B, 64 B, 64-way associative Command: /usr/home/liquid/.rustup/toolchains/w-profiling/bin/rustc --crate-name unicode_categories src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=dad5295dfe3f63fa -C extra-filename=-dad5295dfe3f63fa --out-dir /usr/home/liquid/tmp/.tmpWhI8xY/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpWhI8xY/target/debug/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-unicode_categories-0.1.1-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 951,632,778 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 21,380,419 ( 2.25%) ./malloc/malloc.c:_int_malloc 14,881,497 ( 1.56%) ./malloc/malloc.c:_int_free 11,760,276 ( 1.24%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 10,390,794 ( 1.09%) ./malloc/malloc.c:malloc 10,308,916 ( 1.08%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 7,984,608 ( 0.84%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::scan_escape 7,107,505 ( 0.75%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 5,768,231 ( 0.61%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 5,750,225 ( 0.60%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 5,446,181 ( 0.57%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 5,409,699 ( 0.57%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::intern 4,845,200 ( 0.51%) ./elf/dl-lookup.c:do_lookup_x 4,799,711 ( 0.50%) ./malloc/malloc.c:malloc_consolidate 4,603,016 ( 0.48%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 4,397,199 ( 0.46%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 4,300,749 ( 0.45%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 4,279,101 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 4,237,390 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 4,141,271 ( 0.44%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 4,057,780 ( 0.43%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 4,004,025 ( 0.42%) ./malloc/malloc.c:free 3,848,544 ( 0.40%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 3,633,413 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 3,356,096 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 3,318,208 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 3,293,539 ( 0.35%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:<&str as core::hash::Hash>::hash:: 3,256,560 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 3,197,341 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 3,127,705 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 3,052,172 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::read_scalar:: 2,979,318 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand::::qualif_local::{closure#0}> 2,970,001 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 2,955,460 ( 0.31%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 2,932,102 ( 0.31%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 2,798,896 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 2,785,952 ( 0.29%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:::write 2,774,663 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 2,704,328 ( 0.28%) ./malloc/malloc.c:unlink_chunk.constprop.0 2,662,278 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 2,581,632 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 2,573,768 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::check_static_ptr 2,527,986 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 2,520,445 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get_global_alloc 2,490,713 ( 0.26%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 2,480,759 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 2,459,360 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::try_visit_primitive 2,396,014 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 2,378,681 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs:::as_operand 2,350,584 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 2,349,200 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_internal:: 2,338,528 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs:::visit_expr 2,332,819 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 2,303,822 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 2,296,875 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs:md5::utils::compress 2,278,376 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::aggregate_field_path_elem 2,259,210 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 2,230,827 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 2,227,370 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get 2,220,796 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::read_scalar 2,220,112 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_query_system/src/query/plumbing.rs:rustc_query_system::query::plumbing::get_query:: 2,189,143 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 2,167,898 ( 0.23%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 2,139,033 ( 0.22%) ./elf/do-rel.h:_dl_relocate_object 2,138,942 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_node_id 2,125,464 ( 0.22%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 2,125,046 ( 0.22%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 2,123,836 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 2,090,104 ( 0.22%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 2,051,090 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_relocations:: 2,034,490 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/bit.rs:::hash:: 2,009,000 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:md5::utils::compress 1,999,753 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::collect_tokens_for_expr::<::parse_dot_or_call_expr::{closure#0}>::{closure#0} 1,999,656 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 1,989,554 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::single_quoted_string 1,978,621 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_with_expectation_and_args 1,967,652 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::insert 1,965,698 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:::intern 1,964,606 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::try_read_immediate 1,932,603 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::read_scalar:: 1,930,808 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::const_val_to_op 1,927,794 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs:::to_u32 1,903,133 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::eval_operand 1,887,804 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 1,855,473 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs:::visit_constant 1,842,715 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::is_trivially_unpin 1,830,550 ( 0.19%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 1,827,830 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 1,811,144 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)>>::remove_entry::>::{closure#0}> 1,794,924 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex))>>::reserve_rehash::, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>::{closure#0}> 1,754,780 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::is_freeze 1,752,624 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:>::coerce 1,711,289 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/region.rs:::visit_expr 1,684,834 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs:::add_const 1,656,027 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/mem_categorization.rs:::cat_expr_unadjusted 1,655,879 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs:::hash:: 1,638,918 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 1,635,846 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::place_field 1,622,924 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, ())>>::reserve_rehash::, rustc_middle::ty::context::Interned, (), core::hash::BuildHasherDefault>::{closure#0}> 1,612,607 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 1,604,218 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/intrinsics.rs:::intern 1,594,826 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs:rustc_hir::intravisit::walk_expr:: 1,584,090 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::copy_op_no_validate 1,581,228 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/pointer.rs:<&mut >::mplace_array_fields::{closure#0} as core::ops::function::FnOnce<(u64,)>>::call_once 1,576,209 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:::intern 1,561,217 ( 0.16%) ???:llvm::X86TargetLowering::X86TargetLowering(llvm::X86TargetMachine const&, llvm::X86Subtarget const&) 1,554,973 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::insert 1,538,969 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs:::check_expr_pat_type 1,538,167 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::single_quoted_string 1,534,787 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (core::result::Result, rustc_middle::ty::layout::LayoutError>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 1,525,316 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs:::filter_map_expr 1,524,521 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs:>::try_read_immediate 1,522,367 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 1,519,477 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::from_key_hashed_nocheck:: 1,510,450 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs:> as rustc_trait_selection::traits::query::type_op::TypeOp>::fully_perform 1,508,844 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 1,507,225 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 1,505,072 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::next 1,494,632 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::write_immediate_to_mplace_no_validate 1,475,739 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/intrinsics.rs:>>::insert 1,459,872 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)>>::remove_entry::>::{closure#0}> 1,444,079 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs: as rustc_ast::visit::Visitor>::visit_expr 1,434,084 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/check_attr.rs:::check_attributes 1,418,436 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::node_type 1,414,656 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs: as rustc_ast::visit::Visitor>::visit_expr 1,406,304 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs:, rustc_middle::mir::interpret::allocation::Allocation), core::hash::BuildHasherDefault>>::rustc_entry 1,406,107 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/scope.rs:::as_operand 1,402,608 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::read_scalar 1,374,425 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 1,359,642 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 1,358,820 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::find_bit 1,354,882 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_dot_or_call_expr_with_ 1,350,573 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, ())>>::insert_entry::, rustc_middle::ty::context::Interned, (), core::hash::BuildHasherDefault>::{closure#0}> 1,347,814 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_constant.rs:::as_constant 1,346,450 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/visitor.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::walk_value 1,343,772 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::visit_value 1,343,618 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::walk_value 1,343,241 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex))>>::insert::, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>::{closure#0}> 1,343,186 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 1,336,839 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::push 1,335,670 ( 0.14%) ???:llvm::TargetLoweringBase::computeRegisterProperties(llvm::TargetRegisterInfo const*) 1,316,213 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/util/literal.rs:::from_lit_token 1,298,327 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:::next_token 1,292,011 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::next_token 1,278,875 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::single_quoted_string 1,270,731 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_expr 1,264,068 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_prefix_expr 1,257,438 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_opt_lit 1,244,418 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::get_global_alloc 1,240,681 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/late.rs:::resolve_expr 1,238,888 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs:>>::get:: 1,237,451 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_kind 1,233,456 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ptr.rs:>::map::<::parse_dot_or_call_expr_with::{closure#0}::{closure#0}> 1,233,425 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/late.rs:rustc_hir::intravisit::walk_expr::> 1,232,810 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sorted_map.rs:>::range_slice_indices::> 1,230,654 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs:::get_relocations:: 1,230,516 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get_mut 1,227,240 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_lit_expr 1,220,712 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ast.rs:::hash:: 1,214,400 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::from_key_hashed_nocheck:: 1,206,256 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/walk.rs:::next 1,205,018 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 1,204,906 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::check 1,198,600 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs:>::hash_stable 1,181,253 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_lowering/src/expr.rs:rustc_data_structures::stack::ensure_sufficient_stack::::lower_expr_mut::{closure#0}> 1,168,773 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::insert 1,162,044 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:rustc_ast::util::unicode::contains_text_flow_control_chars 1,154,612 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/vec.rs:::mirror_expr_inner 1,153,161 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs:::check_heap_type 1,147,492 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::check_expr 1,144,104 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/canonical.rs:::fully_perform_op::<&rustc_middle::ty::TyS, rustc_middle::ty::ParamEnvAnd>> 1,141,998 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:<&mut >::mplace_array_fields::{closure#0} as core::ops::function::FnOnce<(u64,)>>::call_once 1,128,804 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::next 1,122,578 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::inherent_atomic_method_call 1,114,502 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_mut:: 1,113,324 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_middle::mir::interpret::allocation::Allocation), core::hash::BuildHasherDefault>>::rustc_entry 1,109,942 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs:::to_char 1,099,780 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/stacker-0.1.14/src/lib.rs:stacker::remaining_stack 1,089,501 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::expect 1,085,656 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::insert 1,085,356 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::write_scalar:: 1,080,844 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/constant.rs:rustc_mir_build::thir::constant::lit_to_const 1,073,975 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 1,071,416 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs:::parse_outer_attributes 1,069,980 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::new_imported_source_file 1,067,020 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::new_imported_source_file 1,063,801 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs:::visit_expr 1,062,576 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs:::warn_if_unreachable 1,062,388 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::get:: 1,053,288 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::const_to_op 1,052,154 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::attrs 1,044,995 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::insert 1,034,285 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::check_expr 1,033,725 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/passes.rs:::check_expr 1,028,225 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::ty 1,021,335 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::try_find_coercion_lub:: 1,011,140 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/scope.rs:::pop_scope 1,007,718 ( 0.11%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 1,003,534 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 1,000,066 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:<&rustc_middle::ty::consts::Const as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 996,455 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::try_read_immediate 996,228 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 995,018 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::lifetime_or_char 994,262 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::unescape_literal::<::validate_literal_escape::{closure#0}> 993,204 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_array_or_repeat_expr 993,160 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/enumerate.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::walk_value 988,462 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::opt_local_def_id 982,384 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs:::check_rvalue 974,450 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 969,983 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:<&rustc_middle::ty::consts::Const as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 966,254 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:::next_token 964,624 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 954,305 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::advance_token -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/region.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . } . . /// Records the lifetime of a local variable as `cx.var_parent` . fn record_var_lifetime( . visitor: &mut RegionResolutionVisitor<'_>, . var_id: hir::ItemLocalId, . _sp: Span, . ) { 111 ( 0.00%) match visitor.cx.var_parent { . None => { . // this can happen in extern fn declarations like . // . // extern fn isalnum(c: c_int) -> c_int . } 148 ( 0.00%) Some((parent_scope, _)) => visitor.scope_tree.record_var_scope(var_id, parent_scope), . } . } . . fn resolve_block<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, blk: &'tcx hir::Block<'tcx>) { . debug!("resolve_block(blk.hir_id={:?})", blk.hir_id); . 216 ( 0.00%) let prev_cx = visitor.cx; . . // We treat the tail expression in the block (if any) somewhat . // differently from the statements. The issue has to do with . // temporary lifetimes. Consider the following: . // . // quux({ . // let inner = ... (&bar()) ...; . // -- line 100 ---------------------------------------- -- line 111 ---------------------------------------- . // tail expression for the block are assigned lifetimes so that . // they will be cleaned up as part of the terminating scope . // *surrounding* the block expression. Here, the terminating . // scope for the block expression is the `quux(..)` call; so . // those temporaries will only be cleaned up *after* both . // `other_argument()` has run and also the call to `quux(..)` . // itself has returned. . 108 ( 0.00%) visitor.enter_node_scope_with_dtor(blk.hir_id.local_id); 180 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . . { . // This block should be kept approximately in sync with . // `intravisit::walk_block`. (We manually walk the block, rather . // than call `walk_block`, in order to maintain precise . // index information.) . 36 ( 0.00%) for (i, statement) in blk.stmts.iter().enumerate() { . match statement.kind { . hir::StmtKind::Local(..) | hir::StmtKind::Item(..) => { . // Each declaration introduces a subscope for bindings . // introduced by the declaration; this subscope covers a . // suffix of the block. Each subscope in a block has the . // previous subscope in the block as a parent, except for . // the first such subscope, which has the block itself as a . // parent. -- line 136 ---------------------------------------- -- line 139 ---------------------------------------- . data: ScopeData::Remainder(FirstStatementIndex::new(i)), . }); . visitor.cx.var_parent = visitor.cx.parent; . } . hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {} . } . visitor.visit_stmt(statement) . } 108 ( 0.00%) walk_list!(visitor, visit_expr, &blk.expr); . } . 180 ( 0.00%) visitor.cx = prev_cx; . } . . fn resolve_arm<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, arm: &'tcx hir::Arm<'tcx>) { 52 ( 0.00%) let prev_cx = visitor.cx; . 13 ( 0.00%) visitor.enter_scope(Scope { id: arm.hir_id.local_id, data: ScopeData::Node }); 52 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . 26 ( 0.00%) visitor.terminating_scopes.insert(arm.body.hir_id.local_id); . 39 ( 0.00%) if let Some(hir::Guard::If(ref expr)) = arm.guard { . visitor.terminating_scopes.insert(expr.hir_id.local_id); . } . . intravisit::walk_arm(visitor, arm); . 52 ( 0.00%) visitor.cx = prev_cx; . } . . fn resolve_pat<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) { 50 ( 0.00%) visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node }); . . // If this is a binding then record the lifetime of that binding. 100 ( 0.00%) if let PatKind::Binding(..) = pat.kind { . record_var_lifetime(visitor, pat.hir_id.local_id, pat.span); . } . . debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); . 150 ( 0.00%) intravisit::walk_pat(visitor, pat); . 200 ( 0.00%) visitor.expr_and_pat_count += 1; . . debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); . } . . fn resolve_stmt<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) { . let stmt_id = stmt.hir_id.local_id; . debug!("resolve_stmt(stmt.id={:?})", stmt_id); . -- line 190 ---------------------------------------- -- line 201 ---------------------------------------- . intravisit::walk_stmt(visitor, stmt); . . visitor.cx.parent = prev_parent; . } . . fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx hir::Expr<'tcx>) { . debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr); . 118,140 ( 0.01%) let prev_cx = visitor.cx; 59,070 ( 0.01%) visitor.enter_node_scope_with_dtor(expr.hir_id.local_id); . . { . let terminating_scopes = &mut visitor.terminating_scopes; . let mut terminating = |id: hir::ItemLocalId| { . terminating_scopes.insert(id); . }; 118,228 ( 0.01%) match expr.kind { . // Conditional or repeating scopes are always terminating . // scopes, meaning that temporaries cannot outlive them. . // This ensures fixed size stacks. . hir::ExprKind::Binary( . source_map::Spanned { node: hir::BinOpKind::And, .. }, . _, . ref r, . ) -- line 225 ---------------------------------------- -- line 328 ---------------------------------------- . // about what types could possibly live across yield points, . // but we will never fail to detect that a type does actually . // live across a yield point. The latter part is critical - . // we're already overly conservative about what types will live . // across yield points, as the generated MIR will determine . // when things are actually live. However, for typecheck to work . // properly, we can't miss any types. . 177,210 ( 0.02%) match expr.kind { . // Manually recurse over closures and inline consts, because they are the only . // case of nested bodies that share the parent environment. . hir::ExprKind::Closure(.., body, _, _) . | hir::ExprKind::ConstBlock(hir::AnonConst { body, .. }) => { . let body = visitor.tcx.hir().body(body); . visitor.visit_body(body); . } . hir::ExprKind::AssignOp(_, ref left_expr, ref right_expr) => { -- line 344 ---------------------------------------- -- line 406 ---------------------------------------- . let expr_cx = visitor.cx; . visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen }); . visitor.cx.var_parent = visitor.cx.parent; . visitor.visit_expr(cond); . visitor.visit_expr(then); . visitor.cx = expr_cx; . } . 88,605 ( 0.01%) _ => intravisit::walk_expr(visitor, expr), . } . 118,140 ( 0.01%) visitor.expr_and_pat_count += 1; . . debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr); . 59,070 ( 0.01%) if let hir::ExprKind::Yield(_, source) = &expr.kind { . // Mark this expr's scope and all parent scopes as containing `yield`. . let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node }; . loop { . let span = match expr.kind { . hir::ExprKind::Yield(expr, hir::YieldSource::Await { .. }) => { . expr.span.shrink_to_hi().to(expr.span) . } . _ => expr.span, -- line 429 ---------------------------------------- -- line 449 ---------------------------------------- . ScopeData::CallSite => break, . _ => scope = superscope, . }, . None => break, . } . } . } . 147,675 ( 0.02%) visitor.cx = prev_cx; . } . . fn resolve_local<'tcx>( . visitor: &mut RegionResolutionVisitor<'tcx>, . pat: Option<&'tcx hir::Pat<'tcx>>, . init: Option<&'tcx hir::Expr<'tcx>>, . ) { . debug!("resolve_local(pat={:?}, init={:?})", pat, init); . 28 ( 0.00%) let blk_scope = visitor.cx.var_parent.map(|(p, _)| p); . . // As an exception to the normal rules governing temporary . // lifetimes, initializers in a let have a temporary lifetime . // of the enclosing block. This means that e.g., a program . // like the following is legal: . // . // let ref x = HashMap::new(); . // -- line 475 ---------------------------------------- -- line 518 ---------------------------------------- . // . // let ref x = [&a(), &b()]; . // . // Here, the expression `[...]` has an extended lifetime due to rule . // A, but the inner rvalues `a()` and `b()` have an extended lifetime . // due to rule C. . . if let Some(expr) = init { 84 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope); . . if let Some(pat) = pat { . if is_binding_pat(pat) { . record_rvalue_scope(visitor, &expr, blk_scope); . } . } . } . . // Make sure we visit the initializer first, so expr_and_pat_count remains correct . if let Some(expr) = init { 84 ( 0.00%) visitor.visit_expr(expr); . } . if let Some(pat) = pat { . visitor.visit_pat(pat); . } . . /// Returns `true` if `pat` match the `P&` non-terminal. . /// . /// ```text -- line 545 ---------------------------------------- -- line 614 ---------------------------------------- . /// | StructName { ..., f: E&, ... } . /// | [ ..., E&, ... ] . /// | ( ..., E&, ... ) . /// | {...; E&} . /// | box E& . /// | E& as ... . /// | ( E& ) . /// ``` 351,180 ( 0.04%) fn record_rvalue_scope_if_borrow_expr<'tcx>( . visitor: &mut RegionResolutionVisitor<'tcx>, . expr: &hir::Expr<'_>, . blk_id: Option, . ) { 117,060 ( 0.01%) match expr.kind { . hir::ExprKind::AddrOf(_, _, ref subexpr) => { 280 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . record_rvalue_scope(visitor, &subexpr, blk_id); . } . hir::ExprKind::Struct(_, fields, _) => { . for field in fields { . record_rvalue_scope_if_borrow_expr(visitor, &field.expr, blk_id); . } . } . hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => { . for subexpr in subexprs { 146,045 ( 0.02%) record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . } . } . hir::ExprKind::Cast(ref subexpr, _) => { . record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id) . } . hir::ExprKind::Block(ref block, _) => { . if let Some(ref subexpr) = block.expr { . record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . } . } . _ => {} . } 234,120 ( 0.02%) } . . /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by . /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that . /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let` . /// statement. . /// . /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching . /// `` as `blk_id`: -- line 660 ---------------------------------------- -- line 675 ---------------------------------------- . ) { . let mut expr = expr; . loop { . // Note: give all the expressions matching `ET` with the . // extended temporary lifetime, not just the innermost rvalue, . // because in codegen if we must compile e.g., `*rvalue()` . // into a temporary, we request the temporary scope of the . // outer expression. 140 ( 0.00%) visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope); . 112 ( 0.00%) match expr.kind { . hir::ExprKind::AddrOf(_, _, ref subexpr) . | hir::ExprKind::Unary(hir::UnOp::Deref, ref subexpr) . | hir::ExprKind::Field(ref subexpr, _) . | hir::ExprKind::Index(ref subexpr, _) => { . expr = &subexpr; . } . _ => { . return; -- line 693 ---------------------------------------- -- line 696 ---------------------------------------- . } . } . } . . impl<'tcx> RegionResolutionVisitor<'tcx> { . /// Records the current parent (if any) as the parent of `child_scope`. . /// Returns the depth of `child_scope`. . fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth { 59,658 ( 0.01%) let parent = self.cx.parent; 209,063 ( 0.02%) self.scope_tree.record_scope_parent(child_scope, parent); . // If `child_scope` has no parent, it must be the root node, and so has . // a depth of 1. Otherwise, its depth is one more than its parent's. 59,494 ( 0.01%) parent.map_or(1, |(_p, d)| d + 1) . } . . /// Records the current parent (if any) as the parent of `child_scope`, . /// and sets `child_scope` as the new current parent. . fn enter_scope(&mut self, child_scope: Scope) { . let child_depth = self.record_child_scope(child_scope); 89,497 ( 0.01%) self.cx.parent = Some((child_scope, child_depth)); . } . 206,997 ( 0.02%) fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) { . // If node was previously marked as a terminating scope during the . // recursive visit of its parent node in the AST, then we need to . // account for the destruction scope representing the scope of . // the destructors that run immediately after it completes. 59,142 ( 0.01%) if self.terminating_scopes.contains(&id) { 99 ( 0.00%) self.enter_scope(Scope { id, data: ScopeData::Destruction }); . } 29,571 ( 0.00%) self.enter_scope(Scope { id, data: ScopeData::Node }); 177,426 ( 0.02%) } . } . . impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { 324 ( 0.00%) fn visit_block(&mut self, b: &'tcx Block<'tcx>) { . resolve_block(self, b); 288 ( 0.00%) } . 576 ( 0.00%) fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) { 192 ( 0.00%) let body_id = body.id(); 512 ( 0.00%) let owner_id = self.tcx.hir().body_owner(body_id); . . debug!( . "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})", . owner_id, . self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span), . body_id, . self.cx.parent . ); . . // Save all state that is specific to the outer function . // body. These will be restored once down below, once we've . // visited the body. . let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0); 256 ( 0.00%) let outer_cx = self.cx; 64 ( 0.00%) let outer_ts = mem::take(&mut self.terminating_scopes); . // The 'pessimistic yield' flag is set to true when we are . // processing a `+=` statement and have to make pessimistic . // control flow assumptions. This doesn't apply to nested . // bodies within the `+=` statements. See #69307. . let outer_pessimistic_yield = mem::replace(&mut self.pessimistic_yield, false); 128 ( 0.00%) self.terminating_scopes.insert(body.value.hir_id.local_id); . 64 ( 0.00%) self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite }); 64 ( 0.00%) self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments }); . . // The arguments and `self` are parented to the fn. 128 ( 0.00%) self.cx.var_parent = self.cx.parent.take(); 448 ( 0.00%) for param in body.params { 185 ( 0.00%) self.visit_pat(¶m.pat); . } . . // The body of the every fn is a root scope. 256 ( 0.00%) self.cx.parent = self.cx.var_parent; 704 ( 0.00%) if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() { 144 ( 0.00%) self.visit_expr(&body.value) . } else { . // Only functions have an outer terminating (drop) scope, while . // temporaries in constant initializers may be 'static, but only . // according to rvalue lifetime semantics, using the same . // syntactical rules used for let initializers. . // . // e.g., in `let x = &f();`, the temporary holding the result from . // the `f()` call lives for the entirety of the surrounding block. -- line 780 ---------------------------------------- -- line 784 ---------------------------------------- . // ever get lifted) that the value *could* have a destructor, but . // it'd get leaked instead of the destructor running during the . // evaluation of `X` (if at all allowed by CTFE). . // . // However, `const Y: ... = g(&f());`, like `let y = g(&f());`, . // would *not* let the `f()` temporary escape into an outer scope . // (i.e., `'static`), which means that after `g` returns, it drops, . // and all the associated destruction scope rules apply. 28 ( 0.00%) self.cx.var_parent = None; . resolve_local(self, None, Some(&body.value)); . } . 64 ( 0.00%) if body.generator_kind.is_some() { . self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count); . } . . // Restore context we had at the start. 64 ( 0.00%) self.expr_and_pat_count = outer_ec; 256 ( 0.00%) self.cx = outer_cx; 320 ( 0.00%) self.terminating_scopes = outer_ts; 64 ( 0.00%) self.pessimistic_yield = outer_pessimistic_yield; 512 ( 0.00%) } . 117 ( 0.00%) fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) { . resolve_arm(self, a); 104 ( 0.00%) } 450 ( 0.00%) fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) { . resolve_pat(self, p); 400 ( 0.00%) } . fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) { . resolve_stmt(self, s); . } 265,815 ( 0.03%) fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { . resolve_expr(self, ex); 236,280 ( 0.02%) } . fn visit_local(&mut self, l: &'tcx Local<'tcx>) { . resolve_local(self, Some(&l.pat), l.init); . } . } . 940 ( 0.00%) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree { 282 ( 0.00%) let typeck_root_def_id = tcx.typeck_root_def_id(def_id); 282 ( 0.00%) if typeck_root_def_id != def_id { . return tcx.region_scope_tree(typeck_root_def_id); . } . . let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); 470 ( 0.00%) let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) { 1,216 ( 0.00%) let mut visitor = RegionResolutionVisitor { . tcx, . scope_tree: ScopeTree::default(), . expr_and_pat_count: 0, . cx: Context { parent: None, var_parent: None }, . terminating_scopes: Default::default(), . pessimistic_yield: false, . fixup_scopes: vec![], . }; . 256 ( 0.00%) let body = tcx.hir().body(body_id); 192 ( 0.00%) visitor.scope_tree.root_body = Some(body.value.hir_id); 128 ( 0.00%) visitor.visit_body(body); 1,920 ( 0.00%) visitor.scope_tree . } else { . ScopeTree::default() . }; . 94 ( 0.00%) tcx.arena.alloc(scope_tree) 846 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { region_scope_tree, ..*providers }; . } 441,600 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 187 ---------------------------------------- . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { . fn clone(&self) -> Self { 9 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 2 ( 0.00%) table: self.table.clone(), . } . } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); -- line 205 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 76,903 ( 0.01%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 641,629 ( 0.07%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 31,448 ( 0.00%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 2 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { . hash_builder.hash_one(val) 4 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 360,723 ( 0.04%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 61 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 527 ---------------------------------------- . /// map.insert("c", 3); . /// . /// for key in map.keys() { . /// println!("{}", key); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn keys(&self) -> Keys<'_, K, V> { 6 ( 0.00%) Keys { inner: self.iter() } . } . . /// An iterator visiting all values in arbitrary order. . /// The iterator element type is `&'a V`. . /// . /// # Examples . /// . /// ``` -- line 543 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 902 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 91,795 ( 0.01%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 8 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { . Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 10 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 10 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 903,225 ( 0.09%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 946,938 ( 0.10%) if self.table.is_empty() { . None . } else { 1 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 71,225 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 134,508 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 15 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 2 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 5 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); 8 ( 0.00%) self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. . /// . /// Returns an array of length `N` with the results of each query. For soundness, at most one . /// mutable reference will be returned to any value. `None` will be returned if any of the . /// keys are duplicates or missing. -- line 1223 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,919,872 ( 0.20%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 126 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 596,115 ( 0.06%) self.table 757,772 ( 0.08%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 39,051 ( 0.00%) None . } 1,753,837 ( 0.18%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 119,118 ( 0.01%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 408,594 ( 0.04%) match self.remove_entry(k) { 2,125 ( 0.00%) Some((_, v)) => Some(v), 89,674 ( 0.01%) None => None, . } 297,524 ( 0.03%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 132,188 ( 0.01%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 101,326 ( 0.01%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 383,415 ( 0.04%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 360,438 ( 0.04%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 11,648 ( 0.00%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 63,457 ( 0.01%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 130,747 ( 0.01%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 767,173 ( 0.08%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 420,631 ( 0.04%) self.from_hash(hash, equivalent(k)) 1,111,326 ( 0.12%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 1,112,262 ( 0.12%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 197,566 ( 0.02%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 194 ( 0.00%) fn into_iter(self) -> IntoIter { 4,681 ( 0.00%) IntoIter { 2,766 ( 0.00%) inner: self.table.into_iter(), . } 582 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 94,527 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 71 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 63 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 225 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 3,232 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 2,249 ( 0.00%) let iter = iter.into_iter(); 1,600 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 3 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 16,269 ( 0.00%) self.insert(k, v); . }); 2,128 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- -- line 4604 ---------------------------------------- . impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap . where . K: Eq + Hash + Copy, . V: Copy, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 77 ( 0.00%) fn extend>(&mut self, iter: T) { . self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); 88 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (&'a K, &'a V)) { . self.insert(*k, *v); . } . . #[inline] -- line 4622 ---------------------------------------- 679,512 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . enum OuterAttributeType { . DocComment, . DocBlockComment, . Attribute, . } . . impl<'a> Parser<'a> { . /// Parses attributes that appear before an item. 266,328 ( 0.03%) pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> { . let mut attrs: Vec = Vec::new(); . let mut just_parsed_doc_comment = false; 147,960 ( 0.02%) let start_pos = self.token_cursor.num_next_calls; . loop { 148,530 ( 0.02%) let attr = if self.check(&token::Pound) { 588 ( 0.00%) let inner_error_reason = if just_parsed_doc_comment { . "an inner attribute is not permitted following an outer doc comment" . } else if !attrs.is_empty() { . "an inner attribute is not permitted following an outer attribute" . } else { . DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG . }; . let inner_parse_policy = InnerAttrPolicy::Forbidden { . reason: inner_error_reason, . saw_doc_comment: just_parsed_doc_comment, 21 ( 0.00%) prev_attr_sp: attrs.last().map(|a| a.span), . }; . just_parsed_doc_comment = false; 336 ( 0.00%) Some(self.parse_attribute(inner_parse_policy)?) 59,400 ( 0.01%) } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind { 72 ( 0.00%) if attr_style != ast::AttrStyle::Outer { . let span = self.token.span; . let mut err = self.sess.span_diagnostic.struct_span_err_with_code( . span, . "expected outer doc comment", . error_code!(E0753), . ); . if let Some(replacement_span) = self.annotate_following_item_if_applicable( . &mut err, -- line 65 ---------------------------------------- -- line 77 ---------------------------------------- . replacement_span, . "you might have meant to write a regular comment", . String::new(), . rustc_errors::Applicability::MachineApplicable, . ); . } . err.emit(); . } 144 ( 0.00%) self.bump(); . just_parsed_doc_comment = true; . // Always make an outer attribute - this allows us to recover from a misplaced . // inner attribute. 1,728 ( 0.00%) Some(attr::mk_doc_comment( . comment_kind, . ast::AttrStyle::Outer, . data, 72 ( 0.00%) self.prev_token.span, . )) . } else { . None . }; . 228 ( 0.00%) if let Some(attr) = attr { 2,052 ( 0.00%) attrs.push(attr); . } else { . break; . } . } 207,144 ( 0.02%) Ok(AttrWrapper::new(attrs.into(), start_pos)) 236,736 ( 0.02%) } . . /// Matches `attribute = # ! [ meta_item ]`. . /// `inner_parse_policy` prescribes how to handle inner attributes. . // Public for rustfmt usage. 420 ( 0.00%) pub fn parse_attribute( . &mut self, . inner_parse_policy: InnerAttrPolicy<'_>, . ) -> PResult<'a, ast::Attribute> { . debug!( . "parse_attribute: inner_parse_policy={:?} self.token={:?}", . inner_parse_policy, self.token . ); 210 ( 0.00%) let lo = self.token.span; . // Attributes can't have attributes of their own [Editor's note: not with that attitude] . self.collect_tokens_no_attrs(|this| { . if this.eat(&token::Pound) { . let style = if this.eat(&token::Not) { . ast::AttrStyle::Inner . } else { . ast::AttrStyle::Outer . }; . 126 ( 0.00%) this.expect(&token::OpenDelim(token::Bracket))?; 168 ( 0.00%) let item = this.parse_attr_item(false)?; 126 ( 0.00%) this.expect(&token::CloseDelim(token::Bracket))?; 126 ( 0.00%) let attr_sp = lo.to(this.prev_token.span); . . // Emit error if inner attribute is encountered and forbidden. 84 ( 0.00%) if style == ast::AttrStyle::Inner { . this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy); . } . 1,386 ( 0.00%) Ok(attr::mk_attr_from_item(item, None, style, attr_sp)) . } else { . let token_str = pprust::token_to_string(&this.token); . let msg = &format!("expected `#`, found `{}`", token_str); . Err(this.struct_span_err(this.token.span, msg)) . } . }) 378 ( 0.00%) } . . fn annotate_following_item_if_applicable( . &self, . err: &mut DiagnosticBuilder<'_>, . span: Span, . attr_type: OuterAttributeType, . ) -> Option { . let mut snapshot = self.clone(); -- line 154 ---------------------------------------- -- line 248 ---------------------------------------- . /// The tokens must be either a delimited token stream, or empty token stream, . /// or the "legacy" key-value form. . /// PATH `(` TOKEN_STREAM `)` . /// PATH `[` TOKEN_STREAM `]` . /// PATH `{` TOKEN_STREAM `}` . /// PATH . /// PATH `=` UNSUFFIXED_LIT . /// The delimiters or `=` are still put into the resulting token stream. 420 ( 0.00%) pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> { 84 ( 0.00%) let item = match self.token.kind { . token::Interpolated(ref nt) => match **nt { . Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()), . _ => None, . }, . _ => None, . }; 504 ( 0.00%) Ok(if let Some(item) = item { . self.bump(); . item . } else { 252 ( 0.00%) let do_parse = |this: &mut Self| { 84 ( 0.00%) let path = this.parse_path(PathStyle::Mod)?; . let args = this.parse_attr_args()?; 378 ( 0.00%) Ok(ast::AttrItem { path, args, tokens: None }) 168 ( 0.00%) }; . // Attr items don't have attributes 168 ( 0.00%) if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }? . }) 630 ( 0.00%) } . . /// Parses attributes that appear after the opening of an item. These should . /// be preceded by an exclamation mark, but we accept and warn about one . /// terminated by a semicolon. . /// . /// Matches `inner_attrs*`. 392 ( 0.00%) crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec> { . let mut attrs: Vec = vec![]; . loop { 67 ( 0.00%) let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap(); . // Only try to parse if it is an inner attribute (has `!`). 337 ( 0.00%) let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) { . Some(self.parse_attribute(InnerAttrPolicy::Permitted)?) 134 ( 0.00%) } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind { 19 ( 0.00%) if attr_style == ast::AttrStyle::Inner { 36 ( 0.00%) self.bump(); 450 ( 0.00%) Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span)) . } else { . None . } . } else { . None . }; 378 ( 0.00%) if let Some(attr) = attr { 18 ( 0.00%) let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap(); . // If we are currently capturing tokens, mark the location of this inner attribute. . // If capturing ends up creating a `LazyTokenStream`, we will include . // this replace range with it, removing the inner attribute from the final . // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note. . // During macro expansion, they are selectively inserted back into the . // token stream (the first inner attribute is remoevd each time we invoke the . // corresponding macro). . let range = start_pos..end_pos; 54 ( 0.00%) if let Capturing::Yes = self.capture_state.capturing { . self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![])); . } 288 ( 0.00%) attrs.push(attr); . } else { . break; . } . } 294 ( 0.00%) Ok(attrs) 441 ( 0.00%) } . 7 ( 0.00%) crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> { 1 ( 0.00%) let lit = self.parse_lit()?; . debug!("checking if {:?} is unusuffixed", lit); . . if !lit.kind.is_unsuffixed() { . self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes") . .help( . "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \ . use an unsuffixed version (`1`, `1.0`, etc.)", . ) . .emit(); . } . . Ok(lit) 6 ( 0.00%) } . . /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited. . pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> { . let cfg_predicate = self.parse_meta_item()?; . self.expect(&token::Comma)?; . . // Presumably, the majority of the time there will only be one attr. . let mut expanded_attrs = Vec::with_capacity(1); -- line 343 ---------------------------------------- -- line 349 ---------------------------------------- . break; . } . } . . Ok((cfg_predicate, expanded_attrs)) . } . . /// Matches `COMMASEP(meta_item_inner)`. 9 ( 0.00%) crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec> { . // Presumably, the majority of the time there will only be one attr. . let mut nmis = Vec::with_capacity(1); 5 ( 0.00%) while self.token.kind != token::Eof { 4 ( 0.00%) nmis.push(self.parse_meta_item_inner()?); . if !self.eat(&token::Comma) { . break; . } . } 8 ( 0.00%) Ok(nmis) 8 ( 0.00%) } . . /// Matches the following grammar (per RFC 1559). . /// . /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ; . /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ; 9 ( 0.00%) pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { 2 ( 0.00%) let nt_meta = match self.token.kind { . token::Interpolated(ref nt) => match **nt { . token::NtMeta(ref e) => Some(e.clone()), . _ => None, . }, . _ => None, . }; . . if let Some(item) = nt_meta { -- line 382 ---------------------------------------- -- line 384 ---------------------------------------- . Some(meta) => { . self.bump(); . Ok(meta) . } . None => self.unexpected(), . }; . } . 2 ( 0.00%) let lo = self.token.span; 1 ( 0.00%) let path = self.parse_path(PathStyle::Mod)?; 2 ( 0.00%) let kind = self.parse_meta_item_kind()?; 2 ( 0.00%) let span = lo.to(self.prev_token.span); 28 ( 0.00%) Ok(ast::MetaItem { path, kind, span }) 9 ( 0.00%) } . . crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> { 6 ( 0.00%) Ok(if self.eat(&token::Eq) { . ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) 5 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { . // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`. . let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?; . ast::MetaItemKind::List(list) . } else { . ast::MetaItemKind::Word . }) . } . . /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`. 9 ( 0.00%) fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> { 3 ( 0.00%) match self.parse_unsuffixed_lit() { . Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)), 4 ( 0.00%) Err(ref mut err) => err.cancel(), 2 ( 0.00%) } . 4 ( 0.00%) match self.parse_meta_item() { 15 ( 0.00%) Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)), . Err(ref mut err) => err.cancel(), . } . . let found = pprust::token_to_string(&self.token); . let msg = format!("expected unsuffixed literal or identifier, found `{}`", found); . Err(self.struct_span_err(self.token.span, &msg)) 7 ( 0.00%) } . } . . pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool { . // One of the attributes may either itself be a macro, . // or expand to macro attributes (`cfg_attr`). . attrs.iter().any(|attr| { 1,682 ( 0.00%) if attr.is_doc_comment() { . return false; . } 168 ( 0.00%) attr.ident().map_or(true, |ident| { 168 ( 0.00%) ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name) . }) . }) . } 302 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/late.rs -------------------------------------------------------------------------------- Ir -- line 29 ---------------------------------------- . . use std::any::Any; . use std::cell::Cell; . use std::slice; . use tracing::debug; . . /// Extract the `LintStore` from the query context. . /// This function exists because we've erased `LintStore` as `dyn Any` in the context. 2 ( 0.00%) crate fn unerased_lint_store(tcx: TyCtxt<'_>) -> &LintStore { 7 ( 0.00%) let store: &dyn Any = &*tcx.lint_store; . store.downcast_ref().unwrap() 6 ( 0.00%) } . . macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({ . $cx.pass.$f(&$cx.context, $($args),*); . }) } . . struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> { . context: LateContext<'tcx>, . pass: T, -- line 48 ---------------------------------------- -- line 51 ---------------------------------------- . impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> { . /// Merge the lints specified by any lint attributes into the . /// current lint context, call the provided function, then reset the . /// lints in effect to their previous state. . fn with_lint_attrs(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { 445,164 ( 0.05%) let attrs = self.context.tcx.hir().attrs(id); 2,739 ( 0.00%) let prev = self.context.last_node_with_lint_attrs; 206,834 ( 0.02%) self.context.last_node_with_lint_attrs = id; . self.enter_attrs(attrs); . f(self); . self.exit_attrs(attrs); 236,483 ( 0.02%) self.context.last_node_with_lint_attrs = prev; . } . . fn with_param_env(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { 194 ( 0.00%) let old_param_env = self.context.param_env; 228 ( 0.00%) self.context.param_env = 679 ( 0.00%) self.context.tcx.param_env(self.context.tcx.hir().local_def_id(id)); . f(self); 291 ( 0.00%) self.context.param_env = old_param_env; . } . . fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { 16 ( 0.00%) lint_callback!(self, check_mod, m, s, n); . hir_visit::walk_mod(self, m, n); 21 ( 0.00%) lint_callback!(self, check_mod_post, m, s, n); . } . . fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) { . debug!("late context: enter_attrs({:?})", attrs); 149,442 ( 0.02%) lint_callback!(self, enter_lint_attrs, attrs); . } . . fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) { . debug!("late context: exit_attrs({:?})", attrs); 208,074 ( 0.02%) lint_callback!(self, exit_lint_attrs, attrs); . } . } . . impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPass<'tcx, T> { . type NestedFilter = nested_filter::All; . . /// Because lints are scoped lexically, we want to walk nested . /// items in the context of the outer item, so enable . /// deep-walking. . fn nested_visit_map(&mut self) -> Self::Map { . self.context.tcx.hir() . } . 864 ( 0.00%) fn visit_nested_body(&mut self, body_id: hir::BodyId) { . let old_enclosing_body = self.context.enclosing_body.replace(body_id); 128 ( 0.00%) let old_cached_typeck_results = self.context.cached_typeck_results.get(); . . // HACK(eddyb) avoid trashing `cached_typeck_results` when we're . // nested in `visit_fn`, which may have already resulted in them . // being queried. 300 ( 0.00%) if old_enclosing_body != Some(body_id) { . self.context.cached_typeck_results.set(None); . } . 932 ( 0.00%) let body = self.context.tcx.hir().body(body_id); . self.visit_body(body); 292 ( 0.00%) self.context.enclosing_body = old_enclosing_body; . . // See HACK comment above. 300 ( 0.00%) if old_enclosing_body != Some(body_id) { . self.context.cached_typeck_results.set(old_cached_typeck_results); . } 800 ( 0.00%) } . 333 ( 0.00%) fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 148 ( 0.00%) self.with_lint_attrs(param.hir_id, |cx| { 148 ( 0.00%) lint_callback!(cx, check_param, param); . hir_visit::walk_param(cx, param); . }); 296 ( 0.00%) } . . fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) { 320 ( 0.00%) lint_callback!(self, check_body, body); 276 ( 0.00%) hir_visit::walk_body(self, body); 320 ( 0.00%) lint_callback!(self, check_body_post, body); . } . . fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { . let generics = self.context.generics.take(); 204 ( 0.00%) self.context.generics = it.kind.generics(); . let old_cached_typeck_results = self.context.cached_typeck_results.take(); . let old_enclosing_body = self.context.enclosing_body.take(); 68 ( 0.00%) self.with_lint_attrs(it.hir_id(), |cx| { 204 ( 0.00%) cx.with_param_env(it.hir_id(), |cx| { 272 ( 0.00%) lint_callback!(cx, check_item, it); 238 ( 0.00%) hir_visit::walk_item(cx, it); 136 ( 0.00%) lint_callback!(cx, check_item_post, it); . }); . }); 170 ( 0.00%) self.context.enclosing_body = old_enclosing_body; . self.context.cached_typeck_results.set(old_cached_typeck_results); 68 ( 0.00%) self.context.generics = generics; . } . . fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { . self.with_lint_attrs(it.hir_id(), |cx| { . cx.with_param_env(it.hir_id(), |cx| { . lint_callback!(cx, check_foreign_item, it); . hir_visit::walk_foreign_item(cx, it); . lint_callback!(cx, check_foreign_item_post, it); . }); . }) . } . . fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { 263 ( 0.00%) lint_callback!(self, check_pat, p); 300 ( 0.00%) hir_visit::walk_pat(self, p); . } . . fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 117,972 ( 0.01%) self.with_lint_attrs(e.hir_id, |cx| { 235,866 ( 0.02%) lint_callback!(cx, check_expr, e); 177,131 ( 0.02%) hir_visit::walk_expr(cx, e); 117,936 ( 0.01%) lint_callback!(cx, check_expr_post, e); . }) . } . . fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) { . // See `EarlyContextAndPass::visit_stmt` for an explanation . // of why we call `walk_stmt` outside of `with_lint_attrs` . self.with_lint_attrs(s.hir_id, |cx| { . lint_callback!(cx, check_stmt, s); . }); . hir_visit::walk_stmt(self, s); . } . 396 ( 0.00%) fn visit_fn( . &mut self, . fk: hir_visit::FnKind<'tcx>, . decl: &'tcx hir::FnDecl<'tcx>, . body_id: hir::BodyId, . span: Span, . id: hir::HirId, . ) { . // Wrap in typeck results here, not just in visit_nested_body, . // in order for `check_fn` to be able to use them. . let old_enclosing_body = self.context.enclosing_body.replace(body_id); . let old_cached_typeck_results = self.context.cached_typeck_results.take(); 540 ( 0.00%) let body = self.context.tcx.hir().body(body_id); 869 ( 0.00%) lint_callback!(self, check_fn, fk, decl, body, span, id); 580 ( 0.00%) hir_visit::walk_fn(self, fk, decl, body_id, span, id); 652 ( 0.00%) lint_callback!(self, check_fn_post, fk, decl, body, span, id); 144 ( 0.00%) self.context.enclosing_body = old_enclosing_body; . self.context.cached_typeck_results.set(old_cached_typeck_results); 288 ( 0.00%) } . . fn visit_variant_data( . &mut self, . s: &'tcx hir::VariantData<'tcx>, . _: Symbol, . _: &'tcx hir::Generics<'tcx>, . _: hir::HirId, . _: Span, -- line 215 ---------------------------------------- -- line 235 ---------------------------------------- . self.with_lint_attrs(v.id, |cx| { . lint_callback!(cx, check_variant, v); . hir_visit::walk_variant(cx, v, g, item_id); . lint_callback!(cx, check_variant_post, v); . }) . } . . fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { 632 ( 0.00%) lint_callback!(self, check_ty, t); 865 ( 0.00%) hir_visit::walk_ty(self, t); . } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . lint_callback!(self, check_infer, inf); . hir_visit::walk_inf(self, inf); . } . . fn visit_name(&mut self, sp: Span, name: Symbol) { 1,976 ( 0.00%) lint_callback!(self, check_name, sp, name); . } . . fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { 6 ( 0.00%) if !self.context.only_module { . self.process_mod(m, s, n); . } . } . . fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . self.with_lint_attrs(l.hir_id, |cx| { . lint_callback!(cx, check_local, l); . hir_visit::walk_local(cx, l); -- line 265 ---------------------------------------- -- line 268 ---------------------------------------- . . fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { . lint_callback!(self, check_block, b); . hir_visit::walk_block(self, b); . lint_callback!(self, check_block_post, b); . } . . fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { 52 ( 0.00%) lint_callback!(self, check_arm, a); 104 ( 0.00%) hir_visit::walk_arm(self, a); . } . . fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { . lint_callback!(self, check_generic_param, p); . hir_visit::walk_generic_param(self, p); . } . . fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) { 329 ( 0.00%) lint_callback!(self, check_generics, g); 126 ( 0.00%) hir_visit::walk_generics(self, g); . } . . fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) { . lint_callback!(self, check_where_predicate, p); . hir_visit::walk_where_predicate(self, p); . } . . fn visit_poly_trait_ref( . &mut self, . t: &'tcx hir::PolyTraitRef<'tcx>, . m: hir::TraitBoundModifier, . ) { 12 ( 0.00%) lint_callback!(self, check_poly_trait_ref, t, m); . hir_visit::walk_poly_trait_ref(self, t, m); . } . . fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { . let generics = self.context.generics.take(); 70 ( 0.00%) self.context.generics = Some(&trait_item.generics); 70 ( 0.00%) self.with_lint_attrs(trait_item.hir_id(), |cx| { 210 ( 0.00%) cx.with_param_env(trait_item.hir_id(), |cx| { 175 ( 0.00%) lint_callback!(cx, check_trait_item, trait_item); 245 ( 0.00%) hir_visit::walk_trait_item(cx, trait_item); 175 ( 0.00%) lint_callback!(cx, check_trait_item_post, trait_item); . }); . }); 70 ( 0.00%) self.context.generics = generics; . } . . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { . let generics = self.context.generics.take(); 112 ( 0.00%) self.context.generics = Some(&impl_item.generics); 56 ( 0.00%) self.with_lint_attrs(impl_item.hir_id(), |cx| { 168 ( 0.00%) cx.with_param_env(impl_item.hir_id(), |cx| { 140 ( 0.00%) lint_callback!(cx, check_impl_item, impl_item); 196 ( 0.00%) hir_visit::walk_impl_item(cx, impl_item); 140 ( 0.00%) lint_callback!(cx, check_impl_item_post, impl_item); . }); . }); 56 ( 0.00%) self.context.generics = generics; . } . . fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) { 87 ( 0.00%) lint_callback!(self, check_lifetime, lt); . hir_visit::walk_lifetime(self, lt); . } . 36 ( 0.00%) fn visit_path(&mut self, p: &'tcx hir::Path<'tcx>, id: hir::HirId) { 1,943 ( 0.00%) lint_callback!(self, check_path, p, id); . hir_visit::walk_path(self, p); 32 ( 0.00%) } . . fn visit_attribute(&mut self, hir_id: hir::HirId, attr: &'tcx ast::Attribute) { . self.with_lint_attrs(hir_id, |cx| { 508 ( 0.00%) lint_callback!(cx, check_attribute, attr); . }) . } . } . . struct LateLintPassObjects<'a> { . lints: &'a mut [LateLintPassObject], . } . -- line 350 ---------------------------------------- -- line 389 ---------------------------------------- . param_env: ty::ParamEnv::empty(), . access_levels, . lint_store: unerased_lint_store(tcx), . last_node_with_lint_attrs: tcx.hir().local_def_id_to_hir_id(module_def_id), . generics: None, . only_module: true, . }; . 36 ( 0.00%) let mut cx = LateContextAndPass { context, pass }; . 22 ( 0.00%) let (module, span, hir_id) = tcx.hir().get_module(module_def_id); . cx.process_mod(module, span, hir_id); . . // Visit the crate attributes 6 ( 0.00%) if hir_id == hir::CRATE_HIR_ID { 5 ( 0.00%) for attr in tcx.hir().attrs(hir::CRATE_HIR_ID).iter() { . cx.visit_attribute(hir_id, attr) . } . } . } . 14 ( 0.00%) pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx>>( . tcx: TyCtxt<'tcx>, . module_def_id: LocalDefId, . builtin_lints: T, . ) { 6 ( 0.00%) if tcx.sess.opts.debugging_opts.no_interleave_lints { . // These passes runs in late_lint_crate with -Z no_interleave_lints . return; . } . . late_lint_mod_pass(tcx, module_def_id, builtin_lints); . . let mut passes: Vec<_> = . unerased_lint_store(tcx).late_module_passes.iter().map(|pass| (pass)()).collect(); . 2 ( 0.00%) if !passes.is_empty() { . late_lint_mod_pass(tcx, module_def_id, LateLintPassObjects { lints: &mut passes[..] }); . } 16 ( 0.00%) } . . fn late_lint_pass_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, pass: T) { . let access_levels = &tcx.privacy_access_levels(()); . . let context = LateContext { . tcx, . enclosing_body: None, . cached_typeck_results: Cell::new(None), . param_env: ty::ParamEnv::empty(), . access_levels, 2 ( 0.00%) lint_store: unerased_lint_store(tcx), . last_node_with_lint_attrs: hir::CRATE_HIR_ID, . generics: None, . only_module: false, . }; . 16 ( 0.00%) let mut cx = LateContextAndPass { context, pass }; . . // Visit the whole crate. . cx.with_lint_attrs(hir::CRATE_HIR_ID, |cx| { . // since the root module isn't visited as an item (because it isn't an . // item), warn for it here. 2 ( 0.00%) lint_callback!(cx, check_crate,); 1 ( 0.00%) tcx.hir().walk_toplevel_module(cx); 1 ( 0.00%) tcx.hir().walk_attributes(cx); 2 ( 0.00%) lint_callback!(cx, check_crate_post,); . }) . } . 10 ( 0.00%) fn late_lint_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, builtin_lints: T) { 1 ( 0.00%) let mut passes = unerased_lint_store(tcx).late_passes.iter().map(|p| (p)()).collect::>(); . 6 ( 0.00%) if !tcx.sess.opts.debugging_opts.no_interleave_lints { 1 ( 0.00%) if !passes.is_empty() { . late_lint_pass_crate(tcx, LateLintPassObjects { lints: &mut passes[..] }); . } . 4 ( 0.00%) late_lint_pass_crate(tcx, builtin_lints); . } else { . for pass in &mut passes { . tcx.sess.prof.extra_verbose_generic_activity("run_late_lint", pass.name()).run(|| { . late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) }); . }); . } . . let mut passes: Vec<_> = -- line 474 ---------------------------------------- -- line 477 ---------------------------------------- . for pass in &mut passes { . tcx.sess.prof.extra_verbose_generic_activity("run_late_module_lint", pass.name()).run( . || { . late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) }); . }, . ); . } . } 9 ( 0.00%) } . . /// Performs lint checking on a crate. . pub fn check_crate<'tcx, T: LateLintPass<'tcx>>( . tcx: TyCtxt<'tcx>, . builtin_lints: impl FnOnce() -> T + Send, . ) { . join( . || { 5 ( 0.00%) tcx.sess.time("crate_lints", || { . // Run whole crate non-incremental lints 4 ( 0.00%) late_lint_crate(tcx, builtin_lints()); . }); . }, . || { 5 ( 0.00%) tcx.sess.time("module_lints", || { . // Run per-module lints 1 ( 0.00%) tcx.hir().par_for_each_module(|module| tcx.ensure().lint_mod(module)); . }); . }, . ); . } 177 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/vec.rs -------------------------------------------------------------------------------- Ir -- line 13 ---------------------------------------- . /// . /// Purpose: avoid mixing indexes for different bitvector domains. . pub trait Idx: Copy + 'static + Eq + PartialEq + Debug + Hash { . fn new(idx: usize) -> Self; . . fn index(self) -> usize; . . fn increment_by(&mut self, amount: usize) { 30,197 ( 0.00%) *self = self.plus(amount); . } . . fn plus(self, amount: usize) -> Self { 30,711 ( 0.00%) Self::new(self.index() + amount) . } . } . . impl Idx for usize { . #[inline] . fn new(idx: usize) -> Self { . idx . } -- line 33 ---------------------------------------- -- line 35 ---------------------------------------- . fn index(self) -> usize { . self . } . } . . impl Idx for u32 { . #[inline] . fn new(idx: usize) -> Self { 794 ( 0.00%) assert!(idx <= u32::MAX as usize); . idx as u32 . } . #[inline] . fn index(self) -> usize { 138 ( 0.00%) self as usize . } . } . . /// Creates a struct type `S` that can be used as an index with . /// `IndexVec` and so on. . /// . /// There are two ways of interacting with these indices: . /// -- line 56 ---------------------------------------- -- line 71 ---------------------------------------- . . // Use default constants . ($(#[$attrs:meta])* $v:vis struct $name:ident { .. }) => ( . $crate::newtype_index!( . // Leave out derives marker so we can use its absence to ensure it comes first . @attrs [$(#[$attrs])*] . @type [$name] . // shave off 256 indices at the end to allow space for packing these indices into enums 71,753 ( 0.01%) @max [0xFFFF_FF00] . @vis [$v] . @debug_format ["{}"]); . ); . . // Define any constants . ($(#[$attrs:meta])* $v:vis struct $name:ident { $($tokens:tt)+ }) => ( . $crate::newtype_index!( . // Leave out derives marker so we can use its absence to ensure it comes first . @attrs [$(#[$attrs])*] . @type [$name] . // shave off 256 indices at the end to allow space for packing these indices into enums 66,790 ( 0.01%) @max [0xFFFF_FF00] . @vis [$v] . @debug_format ["{}"] . $($tokens)+); . ); . . // ---- private rules ---- . . // Base case, user-defined constants (if any) have already been defined -- line 99 ---------------------------------------- -- line 102 ---------------------------------------- . @type [$type:ident] . @max [$max:expr] . @vis [$v:vis] . @debug_format [$debug_format:tt]) => ( . $(#[$attrs])* . #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)] . #[rustc_layout_scalar_valid_range_end($max)] . $v struct $type { 2,934,979 ( 0.31%) private: u32 . } . . impl Clone for $type { . #[inline] . fn clone(&self) -> Self { . *self . } . } -- line 118 ---------------------------------------- -- line 126 ---------------------------------------- . . /// Creates a new index from a given `usize`. . /// . /// # Panics . /// . /// Will panic if `value` exceeds `MAX`. . #[inline] . $v const fn from_usize(value: usize) -> Self { 416,582 ( 0.04%) assert!(value <= ($max as usize)); . // SAFETY: We just checked that `value <= max`. . unsafe { 158 ( 0.00%) Self::from_u32_unchecked(value as u32) . } . } . . /// Creates a new index from a given `u32`. . /// . /// # Panics . /// . /// Will panic if `value` exceeds `MAX`. . #[inline] . $v const fn from_u32(value: u32) -> Self { 138,570 ( 0.01%) assert!(value <= $max); . // SAFETY: We just checked that `value <= max`. . unsafe { . Self::from_u32_unchecked(value) . } . } . . /// Creates a new index from a given `u32`. . /// -- line 156 ---------------------------------------- -- line 175 ---------------------------------------- . #[inline] . $v const fn as_u32(self) -> u32 { . self.private . } . . /// Extracts the value of this index as a `usize`. . #[inline] . $v const fn as_usize(self) -> usize { 289,153 ( 0.03%) self.as_u32() as usize . } . } . . impl std::ops::Add for $type { . type Output = Self; . . fn add(self, other: usize) -> Self { 32 ( 0.00%) Self::from_usize(self.index() + other) . } . } . . impl $crate::vec::Idx for $type { . #[inline] . fn new(value: usize) -> Self { . Self::from_usize(value) . } -- line 199 ---------------------------------------- -- line 269 ---------------------------------------- . @debug_format [custom]) => (); . . // base case for handle_debug, no debug overrides found, so use default . (@handle_debug . @derives [] . @type [$type:ident] . @debug_format [$debug_format:tt]) => ( . impl ::std::fmt::Debug for $type { 84 ( 0.00%) fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { 336 ( 0.00%) write!(fmt, $debug_format, self.as_u32()) 84 ( 0.00%) } . } . ); . . // Debug is requested for derive, don't generate any Debug implementation. . (@handle_debug . @derives [Debug, $($derives:ident,)*] . @type [$type:ident] . @debug_format [$debug_format:tt]) => (); -- line 287 ---------------------------------------- -- line 391 ---------------------------------------- . @debug_format [$debug_format] . $($tokens)*); . $crate::newtype_index!(@serializable $type); . ); . . (@serializable $type:ident) => ( . impl ::rustc_serialize::Decodable for $type { . fn decode(d: &mut D) -> Self { 2,323 ( 0.00%) Self::from_u32(d.read_u32()) . } . } . impl ::rustc_serialize::Encodable for $type { 2,275 ( 0.00%) fn encode(&self, e: &mut E) -> Result<(), E::Error> { . e.emit_u32(self.private) 2,730 ( 0.00%) } . } . ); . . // Rewrite final without comma to one that includes comma . (@derives [$($derives:ident,)*] . @attrs [$(#[$attrs:meta])*] . @type [$type:ident] . @max [$max:expr] -- line 413 ---------------------------------------- -- line 499 ---------------------------------------- . @type [$type] . @max [$max] . @vis [$v] . @debug_format [$debug_format] . $($tokens)*); . ); . } . 3,011 ( 0.00%) #[derive(Clone, PartialEq, Eq, Hash)] . pub struct IndexVec { 924 ( 0.00%) pub raw: Vec, . _marker: PhantomData, . } . . // Whether `IndexVec` is `Send` depends only on the data, . // not the phantom data. . unsafe impl Send for IndexVec where T: Send {} . . impl> Encodable for IndexVec { -- line 517 ---------------------------------------- -- line 523 ---------------------------------------- . impl> Encodable for &IndexVec { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . Encodable::encode(&self.raw, s) . } . } . . impl> Decodable for IndexVec { . fn decode(d: &mut D) -> Self { 446 ( 0.00%) IndexVec { raw: Decodable::decode(d), _marker: PhantomData } . } . } . . impl fmt::Debug for IndexVec { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&self.raw, fmt) . } . } . . impl IndexVec { . #[inline] . pub fn new() -> Self { 1,679 ( 0.00%) IndexVec { raw: Vec::new(), _marker: PhantomData } . } . . #[inline] . pub fn from_raw(raw: Vec) -> Self { 3,084 ( 0.00%) IndexVec { raw, _marker: PhantomData } . } . . #[inline] . pub fn with_capacity(capacity: usize) -> Self { 949 ( 0.00%) IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData } . } . . #[inline] . pub fn from_elem(elem: T, universe: &IndexVec) -> Self . where . T: Clone, . { 5,045 ( 0.00%) IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData } . } . . #[inline] . pub fn from_elem_n(elem: T, n: usize) -> Self . where . T: Clone, . { 9,307 ( 0.00%) IndexVec { raw: vec![elem; n], _marker: PhantomData } . } . . /// Create an `IndexVec` with `n` elements, where the value of each . /// element is the result of `func(i)`. (The underlying vector will . /// be allocated only once, with a capacity of at least `n`.) . #[inline] . pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self { . let indices = (0..n).map(I::new); . Self::from_raw(indices.map(func).collect()) . } . . #[inline] . pub fn push(&mut self, d: T) -> I { . let idx = I::new(self.len()); 906,080 ( 0.10%) self.raw.push(d); . idx . } . . #[inline] . pub fn pop(&mut self) -> Option { . self.raw.pop() . } . . #[inline] . pub fn len(&self) -> usize { 179,718 ( 0.02%) self.raw.len() . } . . /// Gives the next index that will be assigned when `push` is . /// called. . #[inline] . pub fn next_index(&self) -> I { . I::new(self.len()) . } -- line 604 ---------------------------------------- -- line 612 ---------------------------------------- . pub fn into_iter(self) -> vec::IntoIter { . self.raw.into_iter() . } . . #[inline] . pub fn into_iter_enumerated( . self, . ) -> impl DoubleEndedIterator + ExactSizeIterator { 33,150 ( 0.00%) self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t)) . } . . #[inline] . pub fn iter(&self) -> slice::Iter<'_, T> { . self.raw.iter() . } . . #[inline] -- line 628 ---------------------------------------- -- line 692 ---------------------------------------- . . #[inline] . pub fn get_mut(&mut self, index: I) -> Option<&mut T> { . self.raw.get_mut(index.index()) . } . . /// Returns mutable references to two distinct elements, a and b. Panics if a == b. . #[inline] 351 ( 0.00%) pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) { . let (ai, bi) = (a.index(), b.index()); 702 ( 0.00%) assert!(ai != bi); . 351 ( 0.00%) if ai < bi { . let (c1, c2) = self.raw.split_at_mut(bi); 1,468 ( 0.00%) (&mut c1[ai], &mut c2[0]) . } else { . let (c2, c1) = self.pick2_mut(b, a); . (c1, c2) . } 1,053 ( 0.00%) } . . /// Returns mutable references to three distinct elements or panics otherwise. . #[inline] . pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) { . let (ai, bi, ci) = (a.index(), b.index(), c.index()); . assert!(ai != bi && bi != ci && ci != ai); . let len = self.raw.len(); . assert!(ai < len && bi < len && ci < len); -- line 719 ---------------------------------------- -- line 726 ---------------------------------------- . } . . /// Grows the index vector so that it contains an entry for . /// `elem`; if that is already true, then has no . /// effect. Otherwise, inserts new values as needed by invoking . /// `fill_value`. . #[inline] . pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) { 433 ( 0.00%) let min_new_len = elem.index() + 1; 124,453 ( 0.01%) if self.len() < min_new_len { 752 ( 0.00%) self.raw.resize_with(min_new_len, fill_value); . } . } . . #[inline] . pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) { . let min_new_len = elem.index() + 1; . self.raw.resize_with(min_new_len, fill_value); . } -- line 744 ---------------------------------------- -- line 823 ---------------------------------------- . } . . impl FromIterator for IndexVec { . #[inline] . fn from_iter(iter: J) -> Self . where . J: IntoIterator, . { 5,052 ( 0.00%) IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData } . } . } . . impl IntoIterator for IndexVec { . type Item = T; . type IntoIter = vec::IntoIter; . . #[inline] -- line 839 ---------------------------------------- 119,017 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs -------------------------------------------------------------------------------- Ir -- line 448 ---------------------------------------- . } . . fn lint_literal<'tcx>( . cx: &LateContext<'tcx>, . type_limits: &TypeLimits, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . ) { 350,904 ( 0.04%) match *cx.typeck_results().node_type(e.hir_id).kind() { . ty::Int(t) => { . match lit.node { . ast::LitKind::Int(v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed) => { . lint_int_literal(cx, type_limits, e, lit, t, v) . } . _ => bug!(), . }; . } -- line 464 ---------------------------------------- -- line 487 ---------------------------------------- . }); . } . } . _ => {} . } . } . . impl<'tcx> LateLintPass<'tcx> for TypeLimits { 265,815 ( 0.03%) fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) { 206,657 ( 0.02%) match e.kind { . hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { . // propagate negation, if the negation itself isn't negated . if self.negated_expr_id != Some(e.hir_id) { . self.negated_expr_id = Some(expr.hir_id); . } . } 22 ( 0.00%) hir::ExprKind::Binary(binop, ref l, ref r) => { 22 ( 0.00%) if is_comparison(binop) && !check_limits(cx, binop, &l, &r) { . cx.struct_span_lint(UNUSED_COMPARISONS, e.span, |lint| { . lint.build("comparison is useless due to type limits").emit() . }); . } . } 58,484 ( 0.01%) hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit), . _ => {} . }; . . fn is_valid(binop: hir::BinOp, v: T, min: T, max: T) -> bool { . match binop.node { . hir::BinOpKind::Lt => v > min && v <= max, . hir::BinOpKind::Le => v >= min && v < max, . hir::BinOpKind::Gt => v >= min && v < max, -- line 518 ---------------------------------------- -- line 575 ---------------------------------------- . }; . is_valid(norm_binop, lit_val, min, max) . } . _ => true, . } . } . . fn is_comparison(binop: hir::BinOp) -> bool { 44 ( 0.00%) matches!( 22 ( 0.00%) binop.node, . hir::BinOpKind::Eq . | hir::BinOpKind::Lt . | hir::BinOpKind::Le . | hir::BinOpKind::Ne . | hir::BinOpKind::Ge . | hir::BinOpKind::Gt . ) . } 236,280 ( 0.02%) } . } . . declare_lint! { . /// The `improper_ctypes` lint detects incorrect use of types in foreign . /// modules. . /// . /// ### Example . /// -- line 601 ---------------------------------------- -- line 1268 ---------------------------------------- . . fn check_foreign_static(&mut self, id: hir::HirId, span: Span) { . let def_id = self.cx.tcx.hir().local_def_id(id); . let ty = self.cx.tcx.type_of(def_id); . self.check_type_for_ffi_and_report_errors(span, ty, true, false); . } . . fn is_internal_abi(&self, abi: SpecAbi) -> bool { 72 ( 0.00%) matches!( . abi, . SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustIntrinsic | SpecAbi::PlatformIntrinsic . ) . } . } . . impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations { . fn check_foreign_item(&mut self, cx: &LateContext<'_>, it: &hir::ForeignItem<'_>) { -- line 1284 ---------------------------------------- -- line 1306 ---------------------------------------- . kind: hir::intravisit::FnKind<'tcx>, . decl: &'tcx hir::FnDecl<'_>, . _: &'tcx hir::Body<'_>, . _: Span, . hir_id: hir::HirId, . ) { . use hir::intravisit::FnKind; . 178 ( 0.00%) let abi = match kind { . FnKind::ItemFn(_, _, header, ..) => header.abi, 35 ( 0.00%) FnKind::Method(_, sig, ..) => sig.header.abi, . _ => return, . }; . 72 ( 0.00%) let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Definition }; . if !vis.is_internal_abi(abi) { . vis.check_foreign_fn(hir_id, decl); . } . } . } . . declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]); . . impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { 238 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 68 ( 0.00%) if let hir::ItemKind::Enum(ref enum_definition, _) = it.kind { . let t = cx.tcx.type_of(it.def_id); . let ty = cx.tcx.erase_regions(t); . let layout = match cx.layout_of(ty) { . Ok(layout) => layout, . Err( . ty::layout::LayoutError::Unknown(_) . | ty::layout::LayoutError::SizeOverflow(_) . | ty::layout::LayoutError::NormalizationFailure(_, _), -- line 1339 ---------------------------------------- -- line 1385 ---------------------------------------- . larger ({} bytes) than the next largest", . largest . )) . .emit() . }, . ); . } . } 272 ( 0.00%) } . } . . declare_lint! { . /// The `invalid_atomic_ordering` lint detects passing an `Ordering` . /// to an atomic operation that does not support that ordering. . /// . /// ### Example . /// -- line 1401 ---------------------------------------- -- line 1437 ---------------------------------------- . INVALID_ATOMIC_ORDERING, . Deny, . "usage of invalid atomic ordering in atomic operations and memory fences" . } . . declare_lint_pass!(InvalidAtomicOrdering => [INVALID_ATOMIC_ORDERING]); . . impl InvalidAtomicOrdering { 472,560 ( 0.05%) fn inherent_atomic_method_call<'hir>( . cx: &LateContext<'_>, . expr: &Expr<'hir>, . recognized_names: &[Symbol], // used for fast path calculation . ) -> Option<(Symbol, &'hir [Expr<'hir>])> { . const ATOMIC_TYPES: &[Symbol] = &[ . sym::AtomicBool, . sym::AtomicPtr, . sym::AtomicUsize, -- line 1453 ---------------------------------------- -- line 1459 ---------------------------------------- . sym::AtomicIsize, . sym::AtomicI8, . sym::AtomicI16, . sym::AtomicI32, . sym::AtomicI64, . sym::AtomicI128, . ]; . if_chain! { 118,140 ( 0.01%) if let ExprKind::MethodCall(ref method_path, args, _) = &expr.kind; 124 ( 0.00%) if recognized_names.contains(&method_path.ident.name); . if let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); . if let Some(impl_did) = cx.tcx.impl_of_method(m_def_id); . if let Some(adt) = cx.tcx.type_of(impl_did).ty_adt_def(); . // skip extension traits, only lint functions from the standard library . if cx.tcx.trait_id_of_impl(impl_did).is_none(); . . if let Some(parent) = cx.tcx.parent(adt.did); . if cx.tcx.is_diagnostic_item(sym::atomic_mod, parent); . if ATOMIC_TYPES.contains(&cx.tcx.item_name(adt.did)); . then { . return Some((method_path.ident.name, args)); . } . } 59,070 ( 0.01%) None 472,560 ( 0.05%) } . . fn matches_ordering(cx: &LateContext<'_>, did: DefId, orderings: &[Symbol]) -> bool { . let tcx = cx.tcx; . let atomic_ordering = tcx.get_diagnostic_item(sym::Ordering); . orderings.iter().any(|ordering| { . tcx.item_name(did) == *ordering && { . let parent = tcx.parent(did); . parent == atomic_ordering -- line 1491 ---------------------------------------- -- line 1502 ---------------------------------------- . None . } . } . . fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) { . use rustc_hir::def::{DefKind, Res}; . use rustc_hir::QPath; . if_chain! { 206,745 ( 0.02%) if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store]); . if let Some((ordering_arg, invalid_ordering)) = match method { . sym::load => Some((&args[1], sym::Release)), . sym::store => Some((&args[2], sym::Acquire)), . _ => None, . }; . . if let ExprKind::Path(QPath::Resolved(_, path)) = ordering_arg.kind; . if let Res::Def(DefKind::Ctor(..), ctor_id) = path.res; -- line 1518 ---------------------------------------- -- line 1531 ---------------------------------------- . } . }); . } . } . } . . fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) { . if_chain! { 59,070 ( 0.01%) if let ExprKind::Call(ref func, ref args) = expr.kind; 112 ( 0.00%) if let ExprKind::Path(ref func_qpath) = func.kind; 252 ( 0.00%) if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); 168 ( 0.00%) if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::fence | sym::compiler_fence)); . if let ExprKind::Path(ref ordering_qpath) = &args[0].kind; . if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, args[0].hir_id).opt_def_id(); . if Self::matches_ordering(cx, ordering_def_id, &[sym::Relaxed]); . then { . cx.struct_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, |diag| { . diag.build("memory fences cannot have `Relaxed` ordering") . .help("consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`") . .emit(); . }); . } . } . } . . fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { . if_chain! { 265,815 ( 0.03%) if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak]); . if let Some((success_order_arg, failure_order_arg)) = match method { . sym::fetch_update => Some((&args[1], &args[2])), . sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])), . _ => None, . }; . . if let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg); . then { -- line 1566 ---------------------------------------- -- line 1613 ---------------------------------------- . } . } . } . } . } . } . . impl<'tcx> LateLintPass<'tcx> for InvalidAtomicOrdering { 265,815 ( 0.03%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { . Self::check_atomic_load_store(cx, expr); . Self::check_memory_fence(cx, expr); . Self::check_atomic_compare_exchange(cx, expr); 236,280 ( 0.02%) } . } 29,538 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs -------------------------------------------------------------------------------- Ir -- line 86 ---------------------------------------- . impl Qualif for HasMutInterior { . const ANALYSIS_NAME: &'static str = "flow_has_mut_interior"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.has_mut_interior . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 526,098 ( 0.06%) !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. -- line 102 ---------------------------------------- -- line 115 ---------------------------------------- . impl Qualif for NeedsDrop { . const ANALYSIS_NAME: &'static str = "flow_needs_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.needs_drop . } . 233,896 ( 0.02%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 58,474 ( 0.01%) ty.needs_drop(cx.tcx, cx.param_env) 263,133 ( 0.03%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_dtor(cx.tcx) . } -- line 133 ---------------------------------------- -- line 141 ---------------------------------------- . const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . const ALLOW_PROMOTED: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.needs_non_const_drop . } . 252 ( 0.00%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // Avoid selecting for simple cases, such as builtin types. 112 ( 0.00%) if ty::util::is_trivially_const_drop(ty) { . return false; . } . . let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else { . // there is no way to define a type that needs non-const drop . // without having the lang item present. . return false; . }; -- line 159 ---------------------------------------- -- line 196 ---------------------------------------- . let mut fcx = FulfillmentContext::new(); . for nested in impl_src.nested_obligations() { . fcx.register_predicate_obligation(&infcx, nested); . } . . // If we had any errors, then it's bad . !fcx.select_all_or_error(&infcx).is_empty() . }) 252 ( 0.00%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_non_const_dtor(cx.tcx) . } -- line 212 ---------------------------------------- -- line 223 ---------------------------------------- . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`, . // we know that at least some values of that type are not structural-match. I say "some" . // because that component may be part of an enum variant (e.g., . // `Option::::Some`), in which case some values of this type may be . // structural-match (`Option::None`). 84 ( 0.00%) traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some() . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . substs: SubstsRef<'tcx>, . ) -> bool { . let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); . !ty.is_structural_eq_shallow(cx.tcx) . } . } . . // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. . . /// Returns `true` if this `Rvalue` contains qualif `Q`. 1,400 ( 0.00%) pub fn in_rvalue<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . rvalue: &Rvalue<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 700 ( 0.00%) match rvalue { . Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => { . Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) . } . . Rvalue::Discriminant(place) | Rvalue::Len(place) => { . in_place::(cx, in_local, place.as_ref()) . } . -- line 264 ---------------------------------------- -- line 267 ---------------------------------------- . | Rvalue::UnaryOp(_, operand) . | Rvalue::Cast(_, operand, _) . | Rvalue::ShallowInitBox(operand, _) => in_operand::(cx, in_local, operand), . . Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { . in_operand::(cx, in_local, lhs) || in_operand::(cx, in_local, rhs) . } . 56 ( 0.00%) Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { . // Special-case reborrows to be more like a copy of the reference. . if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { . let base_ty = place_base.ty(cx.body, cx.tcx).ty; . if let ty::Ref(..) = base_ty.kind() { . return in_place::(cx, in_local, place_base); . } . } . 168 ( 0.00%) in_place::(cx, in_local, place.as_ref()) . } . . Rvalue::Aggregate(kind, operands) => { . // Return early if we know that the struct or enum being constructed is always . // qualified. 336 ( 0.00%) if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { . let def = cx.tcx.adt_def(adt_did); . if Q::in_adt_inherently(cx, def, substs) { . return true; . } . if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { . return true; . } . } . . // Otherwise, proceed structurally... 525,762 ( 0.06%) operands.iter().any(|o| in_operand::(cx, in_local, o)) . } . } 1,148 ( 0.00%) } . . /// Returns `true` if this `Place` contains qualif `Q`. 560 ( 0.00%) pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 252 ( 0.00%) let mut place = place; . while let Some((place_base, elem)) = place.last_projection() { . match elem { . ProjectionElem::Index(index) if in_local(index) => return true, . . ProjectionElem::Deref . | ProjectionElem::Field(_, _) . | ProjectionElem::ConstantIndex { .. } . | ProjectionElem::Subslice { .. } -- line 320 ---------------------------------------- -- line 327 ---------------------------------------- . if !Q::in_any_value_of_ty(cx, proj_ty) { . return false; . } . . place = place_base; . } . . assert!(place.projection.is_empty()); 140 ( 0.00%) in_local(place.local) . } . . /// Returns `true` if this `Operand` contains qualif `Q`. 1,022,315 ( 0.11%) pub fn in_operand<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . operand: &Operand<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 233,672 ( 0.02%) let constant = match operand { . Operand::Copy(place) | Operand::Move(place) => { . return in_place::(cx, in_local, place.as_ref()); . } . . Operand::Constant(c) => c, . }; . . // Check the qualifs of the value of `const` items. 584,180 ( 0.06%) if let Some(ct) = constant.literal.const_for_ty() { 233,672 ( 0.02%) if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) = ct.val { . // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible . // only for `NeedsNonConstDrop` with precise drop checking. This is the only const . // check performed after the promotion. Verify that with an assertion. . assert!(promoted.is_none() || Q::ALLOW_PROMOTED); . // Don't peek inside trait associated constants. . if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { . let qualifs = if let Some((did, param_did)) = def.as_const_arg() { . cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did)) -- line 366 ---------------------------------------- -- line 374 ---------------------------------------- . . // Just in case the type is more specific than . // the definition, e.g., impl associated const . // with type parameters, take it into account. . } . } . } . // Otherwise use the qualifs of the type. 321,299 ( 0.03%) Q::in_any_value_of_ty(cx, constant.literal.ty()) 934,688 ( 0.10%) } 196 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs -------------------------------------------------------------------------------- Ir -- line 491 ---------------------------------------- . . use crate::iter::{self, FromIterator, FusedIterator, TrustedLen}; . use crate::ops::{self, ControlFlow, Deref, DerefMut}; . use crate::{convert, fmt, hint}; . . /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]). . /// . /// See the [module documentation](self) for details. 120 ( 0.00%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[must_use = "this `Result` may be an `Err` variant, which should be handled"] . #[rustc_diagnostic_item = "Result"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Result { . /// Contains the success value . #[lang = "Ok"] . #[stable(feature = "rust1", since = "1.0.0")] . Ok(#[stable(feature = "rust1", since = "1.0.0")] T), -- line 507 ---------------------------------------- -- line 534 ---------------------------------------- . /// let x: Result = Err("Some error message"); . /// assert_eq!(x.is_ok(), false); . /// ``` . #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"] . #[rustc_const_stable(feature = "const_result", since = "1.48.0")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn is_ok(&self) -> bool { 428 ( 0.00%) matches!(*self, Ok(_)) . } . . /// Returns `true` if the result is [`Ok`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] -- line 550 ---------------------------------------- -- line 628 ---------------------------------------- . /// assert_eq!(x.ok(), Some(2)); . /// . /// let x: Result = Err("Nothing here"); . /// assert_eq!(x.ok(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ok(self) -> Option { 1,582 ( 0.00%) match self { 494 ( 0.00%) Ok(x) => Some(x), . Err(_) => None, . } 1 ( 0.00%) } . . /// Converts from `Result` to [`Option`]. . /// . /// Converts `self` into an [`Option`], consuming `self`, . /// and discarding the success value, if any. . /// . /// # Examples . /// -- line 648 ---------------------------------------- -- line 657 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn err(self) -> Option { . match self { . Ok(_) => None, . Err(x) => Some(x), . } 4 ( 0.00%) } . . ///////////////////////////////////////////////////////////////////////// . // Adapter for working with references . ///////////////////////////////////////////////////////////////////////// . . /// Converts from `&Result` to `Result<&T, &E>`. . /// . /// Produces a new `Result`, containing a reference -- line 673 ---------------------------------------- -- line 683 ---------------------------------------- . /// . /// let x: Result = Err("Error"); . /// assert_eq!(x.as_ref(), Err(&"Error")); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_result", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn as_ref(&self) -> Result<&T, &E> { 62 ( 0.00%) match *self { . Ok(ref x) => Ok(x), . Err(ref x) => Err(x), . } . } . . /// Converts from `&mut Result` to `Result<&mut T, &mut E>`. . /// . /// # Examples -- line 699 ---------------------------------------- -- line 715 ---------------------------------------- . /// let mut x: Result = Err(13); . /// mutate(&mut x); . /// assert_eq!(x.unwrap_err(), 0); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_result", issue = "82814")] . pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> { 2,435 ( 0.00%) match *self { . Ok(ref mut x) => Ok(x), . Err(ref mut x) => Err(x), . } . } . . ///////////////////////////////////////////////////////////////////////// . // Transforming contained values . ///////////////////////////////////////////////////////////////////////// -- line 731 ---------------------------------------- -- line 747 ---------------------------------------- . /// Ok(n) => println!("{}", n), . /// Err(..) => {} . /// } . /// } . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn map U>(self, op: F) -> Result { 184,446 ( 0.02%) match self { 16,340 ( 0.00%) Ok(t) => Ok(op(t)), 962 ( 0.00%) Err(e) => Err(e), . } 233,672 ( 0.02%) } . . /// Returns the provided default (if [`Err`]), or . /// applies a function to the contained value (if [`Ok`]), . /// . /// Arguments passed to `map_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`map_or_else`], . /// which is lazily evaluated. . /// -- line 767 ---------------------------------------- -- line 774 ---------------------------------------- . /// assert_eq!(x.map_or(42, |v| v.len()), 3); . /// . /// let x: Result<&str, _> = Err("bar"); . /// assert_eq!(x.map_or(42, |v| v.len()), 42); . /// ``` . #[inline] . #[stable(feature = "result_map_or", since = "1.41.0")] . pub fn map_or U>(self, default: U, f: F) -> U { 6 ( 0.00%) match self { . Ok(t) => f(t), . Err(_) => default, . } . } . . /// Maps a `Result` to `U` by applying fallback function `default` to . /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value. . /// -- line 790 ---------------------------------------- -- line 831 ---------------------------------------- . /// let x: Result = Ok(2); . /// assert_eq!(x.map_err(stringify), Ok(2)); . /// . /// let x: Result = Err(13); . /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 85 ( 0.00%) pub fn map_err F>(self, op: O) -> Result { 459,286 ( 0.05%) match self { 1,178,299 ( 0.12%) Ok(t) => Ok(t), 48 ( 0.00%) Err(e) => Err(op(e)), . } 150 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Ok`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 852 ---------------------------------------- -- line 1012 ---------------------------------------- . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "result_expect", since = "1.4.0")] . pub fn expect(self, msg: &str) -> T . where . E: fmt::Debug, . { 3,478 ( 0.00%) match self { 809 ( 0.00%) Ok(t) => t, . Err(e) => unwrap_failed(msg, &e), . } . } . . /// Returns the contained [`Ok`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`Err`] -- line 1029 ---------------------------------------- -- line 1051 ---------------------------------------- . /// . /// ```should_panic . /// let x: Result = Err("emergency failure"); . /// x.unwrap(); // panics with `emergency failure` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] 70 ( 0.00%) pub fn unwrap(self) -> T . where . E: fmt::Debug, . { 64,429 ( 0.01%) match self { 2,203 ( 0.00%) Ok(t) => t, . Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), . } 105 ( 0.00%) } . . /// Returns the contained [`Ok`] value or a default . /// . /// Consumes the `self` argument then, if [`Ok`], returns the contained . /// value, otherwise if [`Err`], returns the default value for that . /// type. . /// . /// # Examples -- line 1075 ---------------------------------------- -- line 1092 ---------------------------------------- . /// [`parse`]: str::parse . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "result_unwrap_or_default", since = "1.16.0")] . pub fn unwrap_or_default(self) -> T . where . T: Default, . { 175 ( 0.00%) match self { 125 ( 0.00%) Ok(x) => x, . Err(_) => Default::default(), . } . } . . /// Returns the contained [`Err`] value, consuming the `self` value. . /// . /// # Panics . /// -- line 1109 ---------------------------------------- -- line 1190 ---------------------------------------- . /// ``` . #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] . #[inline] . pub fn into_ok(self) -> T . where . E: Into, . { . match self { 125,791 ( 0.01%) Ok(x) => x, . Err(e) => e.into(), . } . } . . /// Returns the contained [`Err`] value, but never panics. . /// . /// Unlike [`unwrap_err`], this method is known to never panic on the . /// result types it is implemented for. Therefore, it can be used -- line 1206 ---------------------------------------- -- line 1290 ---------------------------------------- . /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16)); . /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4)); . /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2)); . /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn and_then Result>(self, op: F) -> Result { 264,567 ( 0.03%) match self { 265,953 ( 0.03%) Ok(t) => op(t), 174 ( 0.00%) Err(e) => Err(e), . } . } . . /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. -- line 1308 ---------------------------------------- -- line 1355 ---------------------------------------- . /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); . /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); . /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); . /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn or_else Result>(self, op: O) -> Result { 59,724 ( 0.01%) match self { 266,405 ( 0.03%) Ok(t) => Ok(t), . Err(e) => op(e), . } . } . . /// Returns the contained [`Ok`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 1372 ---------------------------------------- -- line 1384 ---------------------------------------- . /// assert_eq!(x.unwrap_or(default), 9); . /// . /// let x: Result = Err("error"); . /// assert_eq!(x.unwrap_or(default), default); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn unwrap_or(self, default: T) -> T { 32 ( 0.00%) match self { 6 ( 0.00%) Ok(t) => t, . Err(_) => default, . } . } . . /// Returns the contained [`Ok`] value or computes it from a closure. . /// . /// . /// # Examples -- line 1401 ---------------------------------------- -- line 1406 ---------------------------------------- . /// fn count(x: &str) -> usize { x.len() } . /// . /// assert_eq!(Ok(2).unwrap_or_else(count), 2); . /// assert_eq!(Err("foo").unwrap_or_else(count), 3); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn unwrap_or_else T>(self, op: F) -> T { 122,040 ( 0.01%) match self { 3,170 ( 0.00%) Ok(t) => t, . Err(e) => op(e), . } . } . . /// Returns the contained [`Ok`] value, consuming the `self` value, . /// without checking that the value is not an [`Err`]. . /// . /// # Safety -- line 1423 ---------------------------------------- -- line 1751 ---------------------------------------- . . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Result { . #[inline] 846 ( 0.00%) fn clone(&self) -> Self { 275,302 ( 0.03%) match self { 4,211 ( 0.00%) Ok(x) => Ok(x.clone()), 2,200 ( 0.00%) Err(x) => Err(x.clone()), . } 118,748 ( 0.01%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Ok(to), Ok(from)) => to.clone_from(from), . (Err(to), Err(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } -- line 1772 ---------------------------------------- -- line 2011 ---------------------------------------- . /// . /// Since the third element caused an underflow, no further elements were taken, . /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. . #[inline] . fn from_iter>>(iter: I) -> Result { . // FIXME(#11084): This could be replaced with Iterator::scan when this . // performance bug is closed. . 204 ( 0.00%) iter::process_results(iter.into_iter(), |i| i.collect()) . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Result { . type Output = T; . type Residual = Result; -- line 2027 ---------------------------------------- -- line 2028 ---------------------------------------- . . #[inline] . fn from_output(output: Self::Output) -> Self { . Ok(output) . } . . #[inline] . fn branch(self) -> ControlFlow { 2,120,234 ( 0.22%) match self { 4,385,495 ( 0.46%) Ok(v) => ControlFlow::Continue(v), 164 ( 0.00%) Err(e) => ControlFlow::Break(Err(e)), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl> const ops::FromResidual> . for Result . { . #[inline] . #[track_caller] . fn from_residual(residual: Result) -> Self { . match residual { 30,970 ( 0.00%) Err(e) => Err(From::from(e)), . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Result { . type TryType = Result; . } -- line 2060 ---------------------------------------- 1,729,315 ( 0.18%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 88,129 ( 0.01%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 56 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 2 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 2 ( 0.00%) pub token: Token, . /// The spacing for the current token 1 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 3 ( 0.00%) pub prev_token: Token, 1 ( 0.00%) pub capture_cfg: bool, 2 ( 0.00%) restrictions: Restrictions, 2 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 2 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 2 ( 0.00%) unmatched_angle_bracket_count: u32, 3 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 1 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 1 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 4 ( 0.00%) #[derive(Clone)] . struct CaptureState { 4 ( 0.00%) capturing: Capturing, 1 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 17 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 3,607 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 810 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 264 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 1,720 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 472 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 944 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 20 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 313 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 724,272 ( 0.08%) fn next(&mut self) -> (Token, Spacing) { . loop { 303,911 ( 0.03%) let (tree, spacing) = if !self.frame.open_delim { 305 ( 0.00%) self.frame.open_delim = true; 1,525 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 723,610 ( 0.08%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 1,228 ( 0.00%) } else if !self.frame.close_delim { 303 ( 0.00%) self.frame.close_delim = true; 1,515 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 606 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 3,939 ( 0.00%) self.frame = frame; . continue; . } else { 144 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 121,322 ( 0.01%) match tree { . TokenTree::Token(token) => { 482,848 ( 0.05%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 482,848 ( 0.05%) } . 150 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 45 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 75 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 135 ( 0.00%) } . } . 980 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 784 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 392 ---------------------------------------- . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 2 ( 0.00%) Some(match token.kind { 4 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 4 ( 0.00%) _ if token.is_used_keyword() => "keyword", 4 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 7 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 2 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 7 ( 0.00%) _ => format!("`{}`", token_str), . } 5 ( 0.00%) } . . impl<'a> Parser<'a> { 56 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 4 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 8 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 124 ( 0.00%) let mut parser = Parser { . sess, 4 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 4 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 24 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 8 ( 0.00%) parser.bump(); . . parser 36 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 361,734 ( 0.04%) let (mut next, spacing) = if self.desugar_doc_comments { 60 ( 0.00%) self.token_cursor.next_desugared() . } else { 180,822 ( 0.02%) self.token_cursor.next() . }; 241,156 ( 0.03%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 60,289 ( 0.01%) self.token_cursor.break_last_token = false; 241,156 ( 0.03%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 24 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 181,776 ( 0.02%) if matches!( 120,578 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 241,156 ( 0.03%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 265,014 ( 0.03%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 29,446 ( 0.00%) if self.expected_tokens.is_empty() { 6 ( 0.00%) if self.token == *t { 5 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 353,340 ( 0.04%) self.expect_one_of(slice::from_ref(t), &[]) . } 441,690 ( 0.05%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 353,892 ( 0.04%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 58,982 ( 0.01%) if edible.contains(&self.token.kind) { 88,368 ( 0.01%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 442,365 ( 0.05%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 1,455 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 1,122 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 2,618 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 374 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 2,244 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 1,496 ( 0.00%) self.bump(); . Ok(ident) 3,740 ( 0.00%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 1,061,179 ( 0.11%) fn check(&mut self, tok: &TokenKind) -> bool { 454,913 ( 0.05%) let is_present = self.token == *tok; 303,430 ( 0.03%) if !is_present { 753,288 ( 0.08%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 1,061,179 ( 0.11%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. . pub fn eat(&mut self, tok: &TokenKind) -> bool { 183,450 ( 0.02%) let is_present = self.check(tok); 122,370 ( 0.01%) if is_present { 1,379 ( 0.00%) self.bump() . } . is_present . } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 855 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 536 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 10,158 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 1,985 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 2,388 ( 0.00%) if self.check_keyword(kw) { 291 ( 0.00%) self.bump(); . true . } else { . false . } 1,985 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 384 ( 0.00%) if self.token.is_keyword(kw) { 96 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 20 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 16 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 1,560 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 780 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 1,755 ( 0.00%) } . 1,968 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 752 ( 0.00%) if ok { . true . } else { 580 ( 0.00%) self.expected_tokens.push(typ); . false . } 1,968 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 117 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 780 ( 0.00%) fn check_path(&mut self) -> bool { 1,824 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 975 ( 0.00%) } . . fn check_type(&mut self) -> bool { . self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { . self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 414 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 230 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 414 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 384 ( 0.00%) self.check_or_expected( 192 ( 0.00%) self.token.is_like_plus(), 192 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 3,720 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 2,170 ( 0.00%) if self.token.kind == expected { 118 ( 0.00%) self.bump(); . return true; . } 1,255 ( 0.00%) match self.token.kind.break_two_token_op() { . Some((first, second)) if first == expected => { . let first_span = self.sess.source_map().start_point(self.token.span); . let second_span = self.token.span.with_lo(first_span.hi()); . self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token -- line 682 ---------------------------------------- -- line 684 ---------------------------------------- . // and `next_tok` will set this field to `None` . self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. . self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 753 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 3,794 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 8 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 348 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { . if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 192 ( 0.00%) fn eat_lt(&mut self) -> bool { 821 ( 0.00%) let ate = self.break_and_eat(token::Lt); 500 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. . self.unmatched_angle_bracket_count += 1; . self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 192 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. -- line 733 ---------------------------------------- -- line 742 ---------------------------------------- . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 175,935 ( 0.02%) TokenExpectType::Expect => self.check(k), . TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, -- line 758 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 146,572 ( 0.02%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 58,902 ( 0.01%) if let Some(ref t) = sep.sep { 88,315 ( 0.01%) if first { . first = false; . } else { 233,443 ( 0.02%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 58,606 ( 0.01%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 29,498 ( 0.00%) let t = f(self)?; 195 ( 0.00%) v.push(t); . } . 620 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 804 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 590 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 369 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 251 ( 0.00%) if !recovered { . self.eat(ket); . } 863 ( 0.00%) Ok((val, trailing)) 472 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 247 ( 0.00%) self.expect(bra)?; 472 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 129 ( 0.00%) &token::OpenDelim(delim), 199 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 783,757 ( 0.08%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 361,734 ( 0.04%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 241,156 ( 0.03%) self.prev_token = mem::replace(&mut self.token, next_token); 60,289 ( 0.01%) self.token_spacing = next_spacing; . . // Diagnostics. 60,289 ( 0.01%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 482,312 ( 0.05%) pub fn bump(&mut self) { 241,156 ( 0.03%) let next_token = self.next_tok(self.token.span); 361,734 ( 0.04%) self.bump_with(next_token); 482,312 ( 0.05%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. . pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 224 ( 0.00%) if dist == 0 { 123 ( 0.00%) return looker(&self.token); . } . 29,800 ( 0.00%) let frame = &self.token_cursor.frame; 29,883 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 89,473 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 119,198 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 149,175 ( 0.02%) return match frame.tree_cursor.look_ahead(dist - 1) { 59,388 ( 0.01%) Some(tree) => match tree { 29,641 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 523 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 947 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 67 ( 0.00%) let mut token = Token::dummy(); . while i < dist { 469 ( 0.00%) token = cursor.next().0; 205 ( 0.00%) if matches!( 134 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } . i += 1; . } . return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 999 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 228 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 999 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 148 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 592 ( 0.00%) } . . /// Parses constness: `const` or nothing. 640 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 168 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { . Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 1,120 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 144 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { -- line 1126 ---------------------------------------- -- line 1135 ---------------------------------------- . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { . self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 24 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 126 ( 0.00%) self.parse_mac_args_common(false) . } . 486 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 432 ( 0.00%) Ok( 434 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 123 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 123 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 52 ( 0.00%) match self.parse_token_tree() { 65 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 26 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 82 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 378 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 88,092 ( 0.01%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 58,720 ( 0.01%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 120 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 45 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 326 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 178 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 30 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 30 ( 0.00%) let span = frame.span; 15 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 30 ( 0.00%) self.bump(); 75 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { . self.bump(); . TokenTree::Token(self.prev_token.clone()) . } . } 105 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 29,402 ( 0.00%) let old = self.restrictions; 29,460 ( 0.00%) self.restrictions = res; . let res = f(self); 29,408 ( 0.00%) self.restrictions = old; . res . } . 1,232 ( 0.00%) fn is_crate_vis(&self) -> bool { 770 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 1,386 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 1,080 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 216 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 108 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 432 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 79 ( 0.00%) return Ok(Visibility { 237 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 29 ( 0.00%) let lo = self.prev_token.span; . 145 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. . if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. -- line 1303 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 87 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 972 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 70 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1409 ---------------------------------------- . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, . |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) . } . . /// `::{` or `::*` 2,408 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 1,204 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 464 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 2,448 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 40 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 20 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 20 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 40 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 362,825 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . // the value lives here, at offset 0, and that allocation definitely is an `AllocKind::Memory` . // (so you can use `AllocMap::unwrap_memory`). . pub alloc_id: AllocId, . pub ty: Ty<'tcx>, . } . . /// Represents a constant value in Rust. `Scalar` and `Slice` are optimizations for . /// array length computations, enum discriminants and the pattern matching logic. 2,294,556 ( 0.24%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Hash)] . #[derive(HashStable)] . pub enum ConstValue<'tcx> { . /// Used only for types with `layout::abi::Scalar` ABI and ZSTs. . /// . /// Not using the enum `Value` to encode that this must not be `Uninit`. . Scalar(Scalar), . . /// Used only for `&[u8]` and `&str` -- line 36 ---------------------------------------- -- line 62 ---------------------------------------- . } . }) . } . } . . impl<'tcx> ConstValue<'tcx> { . #[inline] . pub fn try_to_scalar(&self) -> Option> { 1,348 ( 0.00%) match *self { . ConstValue::ByRef { .. } | ConstValue::Slice { .. } => None, 126 ( 0.00%) ConstValue::Scalar(val) => Some(val), . } . } . . pub fn try_to_scalar_int(&self) -> Option { . Some(self.try_to_scalar()?.assert_int()) . } . 86 ( 0.00%) pub fn try_to_bits(&self, size: Size) -> Option { 731 ( 0.00%) self.try_to_scalar_int()?.to_bits(size).ok() 129 ( 0.00%) } . . pub fn try_to_bool(&self) -> Option { . self.try_to_scalar_int()?.try_into().ok() . } . 166 ( 0.00%) pub fn try_to_machine_usize(&self, tcx: TyCtxt<'tcx>) -> Option { 1,245 ( 0.00%) self.try_to_scalar_int()?.try_to_machine_usize(tcx).ok() 249 ( 0.00%) } . 430 ( 0.00%) pub fn try_to_bits_for_ty( . &self, . tcx: TyCtxt<'tcx>, . param_env: ParamEnv<'tcx>, . ty: Ty<'tcx>, . ) -> Option { 129 ( 0.00%) let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size; 86 ( 0.00%) self.try_to_bits(size) 344 ( 0.00%) } . . pub fn from_bool(b: bool) -> Self { . ConstValue::Scalar(Scalar::from_bool(b)) . } . . pub fn from_u64(i: u64) -> Self { . ConstValue::Scalar(Scalar::from_u64(i)) . } -- line 108 ---------------------------------------- -- line 114 ---------------------------------------- . . /// A `Scalar` represents an immediate, primitive value existing outside of a . /// `memory::Allocation`. It is in many ways like a small chunk of an `Allocation`, up to 16 bytes in . /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes . /// of a simple value or a pointer into another `Allocation` . /// . /// These variants would be private if there was a convenient way to achieve that in Rust. . /// Do *not* match on a `Scalar`! Use the various `to_*` methods instead. 1,130,693 ( 0.12%) #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)] . #[derive(HashStable)] . pub enum Scalar { . /// The raw bytes of a simple value. 185,743 ( 0.02%) Int(ScalarInt), . . /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of . /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the . /// relocation and its associated offset together as a `Pointer` here. . /// . /// We also store the size of the pointer, such that a `Scalar` always knows how big it is. . /// The size is always the pointer size of the current target, but this is not information . /// that we always have readily available. 282 ( 0.00%) Ptr(Pointer, u8), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Scalar, 24); . . // We want the `Debug` output to be readable as it is used by `derive(Debug)` for . // all the Miri types. . impl fmt::Debug for Scalar { -- line 143 ---------------------------------------- -- line 179 ---------------------------------------- . } . } . . impl Scalar { . pub const ZST: Self = Scalar::Int(ScalarInt::ZST); . . #[inline(always)] . pub fn from_pointer(ptr: Pointer, cx: &impl HasDataLayout) -> Self { 569 ( 0.00%) Scalar::Ptr(ptr, u8::try_from(cx.pointer_size().bytes()).unwrap()) . } . . /// Create a Scalar from a pointer with an `Option<_>` tag (where `None` represents a plain integer). 178 ( 0.00%) pub fn from_maybe_pointer(ptr: Pointer>, cx: &impl HasDataLayout) -> Self { 178 ( 0.00%) match ptr.into_parts() { . (Some(tag), offset) => Scalar::from_pointer(Pointer::new(tag, offset), cx), . (None, offset) => { . Scalar::Int(ScalarInt::try_from_uint(offset.bytes(), cx.pointer_size()).unwrap()) . } . } 356 ( 0.00%) } . . #[inline] . pub fn null_ptr(cx: &impl HasDataLayout) -> Self { . Scalar::Int(ScalarInt::null(cx.pointer_size())) . } . . #[inline] . pub fn from_bool(b: bool) -> Self { -- line 206 ---------------------------------------- -- line 213 ---------------------------------------- . } . . #[inline] . pub fn try_from_uint(i: impl Into, size: Size) -> Option { . ScalarInt::try_from_uint(i, size).map(Scalar::Int) . } . . #[inline] 84 ( 0.00%) pub fn from_uint(i: impl Into, size: Size) -> Self { 117,572 ( 0.01%) let i = i.into(); . Self::try_from_uint(i, size) . .unwrap_or_else(|| bug!("Unsigned value {:#x} does not fit in {} bits", i, size.bits())) 112 ( 0.00%) } . . #[inline] . pub fn from_u8(i: u8) -> Self { . Scalar::Int(i.into()) . } . . #[inline] . pub fn from_u16(i: u16) -> Self { -- line 233 ---------------------------------------- -- line 241 ---------------------------------------- . . #[inline] . pub fn from_u64(i: u64) -> Self { . Scalar::Int(i.into()) . } . . #[inline] . pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self { 143 ( 0.00%) Self::from_uint(i, cx.data_layout().pointer_size) . } . . #[inline] . pub fn try_from_int(i: impl Into, size: Size) -> Option { . ScalarInt::try_from_int(i, size).map(Scalar::Int) . } . . #[inline] -- line 257 ---------------------------------------- -- line 288 ---------------------------------------- . . /// This is almost certainly not the method you want! You should dispatch on the type . /// and use `to_{u8,u16,...}`/`scalar_to_ptr` to perform ptr-to-int / int-to-ptr casts as needed. . /// . /// This method only exists for the benefit of low-level operations that truly need to treat the . /// scalar in whatever form it is. . #[inline] . pub fn to_bits_or_ptr_internal(self, target_size: Size) -> Result> { 88,596 ( 0.01%) assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST"); 59,064 ( 0.01%) match self { 146,340 ( 0.02%) Scalar::Int(int) => Ok(int.assert_bits(target_size)), 792 ( 0.00%) Scalar::Ptr(ptr, sz) => { 1,056 ( 0.00%) assert_eq!(target_size.bytes(), u64::from(sz)); . Err(ptr) . } . } . } . } . . impl<'tcx, Tag: Provenance> Scalar { . /// Fundamental scalar-to-int (cast) operation. Many convenience wrappers exist below, that you . /// likely want to use instead. . /// . /// Will perform ptr-to-int casts if needed and possible. . /// If that fails, we know the offset is relative, so we return an "erased" Scalar . /// (which is useful for error messages but not much else). . #[inline] . pub fn try_to_int(self) -> Result> { 118,052 ( 0.01%) match self { 4 ( 0.00%) Scalar::Int(int) => Ok(int), . Scalar::Ptr(ptr, sz) => { . if Tag::OFFSET_IS_ADDR { . Ok(ScalarInt::try_from_uint(ptr.offset.bytes(), Size::from_bytes(sz)).unwrap()) . } else { . // We know `offset` is relative, since `OFFSET_IS_ADDR == false`. . let (tag, offset) = ptr.into_parts(); . Err(Scalar::Ptr(Pointer::new(tag.get_alloc_id(), offset), sz)) . } . } . } . } . . #[inline(always)] . pub fn assert_int(self) -> ScalarInt { 610 ( 0.00%) self.try_to_int().unwrap() . } . . /// This throws UB (instead of ICEing) on a size mismatch since size mismatches can arise in . /// Miri when someone declares a function that we shim (such as `malloc`) with a wrong type. . #[inline] 364 ( 0.00%) pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> { 273 ( 0.00%) assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST"); 527,400 ( 0.06%) self.try_to_int().map_err(|_| err_unsup!(ReadPointerAsBytes))?.to_bits(target_size).map_err( . |size| { . err_ub!(ScalarSizeMismatch { . target_size: target_size.bytes(), . data_size: size.bytes(), . }) . .into() . }, . ) 455 ( 0.00%) } . . #[inline(always)] . pub fn assert_bits(self, target_size: Size) -> u128 { 28 ( 0.00%) self.to_bits(target_size).unwrap() . } . . pub fn to_bool(self) -> InterpResult<'tcx, bool> { . let val = self.to_u8()?; . match val { . 0 => Ok(false), . 1 => Ok(true), . _ => throw_ub!(InvalidBool(val)), . } . } . 58,418 ( 0.01%) pub fn to_char(self) -> InterpResult<'tcx, char> { 642,598 ( 0.07%) let val = self.to_u32()?; 116,836 ( 0.01%) match std::char::from_u32(val) { . Some(c) => Ok(c), . None => throw_ub!(InvalidChar(val)), . } 292,090 ( 0.03%) } . . #[inline] . fn to_unsigned_with_bit_width(self, bits: u64) -> InterpResult<'static, u128> { . let sz = Size::from_bits(bits); 292,090 ( 0.03%) self.to_bits(sz) . } . . /// Converts the scalar to produce a `u8`. Fails if the scalar is a pointer. . pub fn to_u8(self) -> InterpResult<'static, u8> { . self.to_unsigned_with_bit_width(8).map(|v| u8::try_from(v).unwrap()) . } . . /// Converts the scalar to produce a `u16`. Fails if the scalar is a pointer. . pub fn to_u16(self) -> InterpResult<'static, u16> { . self.to_unsigned_with_bit_width(16).map(|v| u16::try_from(v).unwrap()) . } . . /// Converts the scalar to produce a `u32`. Fails if the scalar is a pointer. 175,254 ( 0.02%) pub fn to_u32(self) -> InterpResult<'static, u32> { . self.to_unsigned_with_bit_width(32).map(|v| u32::try_from(v).unwrap()) 233,672 ( 0.02%) } . . /// Converts the scalar to produce a `u64`. Fails if the scalar is a pointer. . pub fn to_u64(self) -> InterpResult<'static, u64> { . self.to_unsigned_with_bit_width(64).map(|v| u64::try_from(v).unwrap()) . } . . /// Converts the scalar to produce a `u128`. Fails if the scalar is a pointer. . pub fn to_u128(self) -> InterpResult<'static, u128> { . self.to_unsigned_with_bit_width(128) . } . . pub fn to_machine_usize(self, cx: &impl HasDataLayout) -> InterpResult<'static, u64> { 811 ( 0.00%) let b = self.to_bits(cx.data_layout().pointer_size)?; . Ok(u64::try_from(b).unwrap()) . } . . #[inline] . fn to_signed_with_bit_width(self, bits: u64) -> InterpResult<'static, i128> { . let sz = Size::from_bits(bits); . let b = self.to_bits(sz)?; . Ok(sz.sign_extend(b) as i128) -- line 413 ---------------------------------------- -- line 502 ---------------------------------------- . . #[inline] . pub fn from_maybe_pointer(ptr: Pointer>, cx: &impl HasDataLayout) -> Self { . ScalarMaybeUninit::Scalar(Scalar::from_maybe_pointer(ptr, cx)) . } . . #[inline] . pub fn check_init(self) -> InterpResult<'static, Scalar> { 117,472 ( 0.01%) match self { 166 ( 0.00%) ScalarMaybeUninit::Scalar(scalar) => Ok(scalar), . ScalarMaybeUninit::Uninit => throw_ub!(InvalidUninitBytes(None)), . } . } . } . . impl<'tcx, Tag: Provenance> ScalarMaybeUninit { . #[inline(always)] . pub fn to_bool(self) -> InterpResult<'tcx, bool> { . self.check_init()?.to_bool() . } . . #[inline(always)] . pub fn to_char(self) -> InterpResult<'tcx, char> { 350,508 ( 0.04%) self.check_init()?.to_char() . } . . #[inline(always)] . pub fn to_f32(self) -> InterpResult<'tcx, Single> { . self.check_init()?.to_f32() . } . . #[inline(always)] -- line 533 ---------------------------------------- 789,807 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 556,826 ( 0.06%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 417,618 ( 0.04%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 22,400 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 33,600 ( 0.00%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 144,796 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 28,248 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 56,496 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_constant.rs -------------------------------------------------------------------------------- Ir -- line 3 ---------------------------------------- . use crate::build::Builder; . use rustc_middle::mir::*; . use rustc_middle::thir::*; . use rustc_middle::ty::CanonicalUserTypeAnnotation; . . impl<'a, 'tcx> Builder<'a, 'tcx> { . /// Compile `expr`, yielding a compile-time constant. Assumes that . /// `expr` is a valid compile-time constant! 205,149 ( 0.02%) crate fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> { . let this = self; 146,535 ( 0.02%) let Expr { ty, temp_lifetime: _, span, ref kind } = *expr; 87,921 ( 0.01%) match *kind { . ExprKind::Scope { region_scope: _, lint_level: _, value } => { . this.as_constant(&this.thir[value]) . } 87,837 ( 0.01%) ExprKind::Literal { literal, user_ty, const_id: _ } => { 204,953 ( 0.02%) let user_ty = user_ty.map(|user_ty| { . this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { . span, . user_ty, . inferred_ty: ty, . }) . }); 29,279 ( 0.00%) assert_eq!(literal.ty, ty); 146,395 ( 0.02%) Constant { span, user_ty, literal: literal.into() } . } 28 ( 0.00%) ExprKind::StaticRef { literal, .. } => { . Constant { span, user_ty: None, literal: literal.into() } . } . ExprKind::ConstBlock { value } => { . Constant { span: span, user_ty: None, literal: value.into() } . } . _ => span_bug!(span, "expression is not a valid constant {:?}", kind), . } 263,763 ( 0.03%) } . } 175,954 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sorted_map.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . fn default() -> SortedMap { . SortedMap { data: Vec::new() } . } . } . . impl SortedMap { . #[inline] . pub const fn new() -> SortedMap { 1 ( 0.00%) SortedMap { data: Vec::new() } . } . } . . impl SortedMap { . /// Construct a `SortedMap` from a presorted set of elements. This is faster . /// than creating an empty map and then inserting the elements individually. . /// . /// It is up to the caller to make sure that the elements are sorted by key -- line 43 ---------------------------------------- -- line 45 ---------------------------------------- . #[inline] . pub fn from_presorted_elements(elements: Vec<(K, V)>) -> SortedMap { . debug_assert!(elements.array_windows().all(|[fst, snd]| fst.0 < snd.0)); . . SortedMap { data: elements } . } . . #[inline] 1,336 ( 0.00%) pub fn insert(&mut self, key: K, mut value: V) -> Option { . match self.lookup_index_for(&key) { . Ok(index) => { . let slot = unsafe { self.data.get_unchecked_mut(index) }; . mem::swap(&mut slot.1, &mut value); . Some(value) . } . Err(index) => { . self.data.insert(index, (key, value)); . None . } . } 1,016 ( 0.00%) } . . #[inline] . pub fn remove(&mut self, key: &K) -> Option { . match self.lookup_index_for(key) { . Ok(index) => Some(self.data.remove(index).1), . Err(_) => None, . } . } -- line 73 ---------------------------------------- -- line 116 ---------------------------------------- . /// Iterate over values, sorted by key . #[inline] . pub fn values(&self) -> impl Iterator + ExactSizeIterator + DoubleEndedIterator { . self.data.iter().map(|&(_, ref v)| v) . } . . #[inline] . pub fn len(&self) -> usize { 64 ( 0.00%) self.data.len() . } . . #[inline] . pub fn is_empty(&self) -> bool { . self.len() == 0 . } . . #[inline] . pub fn range(&self, range: R) -> &[(K, V)] . where . R: RangeBounds, . { 410,442 ( 0.04%) let (start, end) = self.range_slice_indices(range); . &self.data[start..end] . } . . #[inline] . pub fn remove_range(&mut self, range: R) . where . R: RangeBounds, . { -- line 145 ---------------------------------------- -- line 201 ---------------------------------------- . . /// Looks up the key in `self.data` via `slice::binary_search()`. . #[inline(always)] . fn lookup_index_for(&self, key: &Q) -> Result . where . K: Borrow, . Q: Ord + ?Sized, . { 11,072 ( 0.00%) self.data.binary_search_by(|&(ref x, _)| x.borrow().cmp(key)) . } . . #[inline] 205,221 ( 0.02%) fn range_slice_indices(&self, range: R) -> (usize, usize) . where . R: RangeBounds, . { . let start = match range.start_bound() { . Bound::Included(ref k) => match self.lookup_index_for(k) { . Ok(index) | Err(index) => index, . }, . Bound::Excluded(ref k) => match self.lookup_index_for(k) { -- line 221 ---------------------------------------- -- line 228 ---------------------------------------- . let end = match range.end_bound() { . Bound::Included(ref k) => match self.lookup_index_for(k) { . Ok(index) => index + 1, . Err(index) => index, . }, . Bound::Excluded(ref k) => match self.lookup_index_for(k) { . Ok(index) | Err(index) => index, . }, 294 ( 0.00%) Bound::Unbounded => self.data.len(), . }; . . (start, end) 615,663 ( 0.06%) } . . #[inline] . pub fn contains_key(&self, key: &Q) -> bool . where . K: Borrow, . Q: Ord + ?Sized, . { . self.get(key).is_some() -- line 248 ---------------------------------------- -- line 276 ---------------------------------------- . Q: Ord + ?Sized, . { . fn index_mut(&mut self, key: &Q) -> &mut Self::Output { . self.get_mut(key).expect("no entry found for key") . } . } . . impl FromIterator<(K, V)> for SortedMap { 686 ( 0.00%) fn from_iter>(iter: T) -> Self { . let mut data: Vec<(K, V)> = iter.into_iter().collect(); . . data.sort_unstable_by(|&(ref k1, _), &(ref k2, _)| k1.cmp(k2)); . data.dedup_by(|&mut (ref k1, _), &mut (ref k2, _)| k1.cmp(k2) == Ordering::Equal); . 392 ( 0.00%) SortedMap { data } 784 ( 0.00%) } . } . . impl, V: HashStable, CTX> HashStable for SortedMap { . #[inline] . fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . self.data.hash_stable(ctx, hasher); . } . } -- line 299 ---------------------------------------- 409,666 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs -------------------------------------------------------------------------------- Ir -- line 114 ---------------------------------------- . . /// Lets us implement `HasDataLayout`, which is awfully convenient. . pub tcx: TyCtxt<'tcx>, . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { 203 ( 0.00%) &self.tcx.data_layout . } . } . . /// A reference to some allocation that was already bounds-checked for the given region . /// and had the on-access machine hooks run. . #[derive(Copy, Clone)] . pub struct AllocRef<'a, 'tcx, Tag, Extra> { . alloc: &'a Allocation, -- line 130 ---------------------------------------- -- line 138 ---------------------------------------- . alloc: &'a mut Allocation, . range: AllocRange, . tcx: TyCtxt<'tcx>, . alloc_id: AllocId, . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . pub fn new(tcx: TyCtxt<'tcx>, extra: M::MemoryExtra) -> Self { 1,080 ( 0.00%) Memory { . alloc_map: M::MemoryMap::default(), . extra_fn_ptr_map: FxHashMap::default(), . dead_alloc_map: FxHashMap::default(), . extra, . tcx, . } . } . -- line 154 ---------------------------------------- -- line 157 ---------------------------------------- . /// for any other pointers, nor for TLS statics. . /// . /// Using the resulting pointer represents a *direct* access to that memory . /// (e.g. by directly using a `static`), . /// as opposed to access through a pointer that was created by the program. . /// . /// This function can fail only if `ptr` points to an `extern static`. . #[inline] 1,608 ( 0.00%) pub fn global_base_pointer( . &self, . ptr: Pointer, . ) -> InterpResult<'tcx, Pointer> { . // We know `offset` is relative to the allocation, so we can use `into_parts`. . let (alloc_id, offset) = ptr.into_parts(); . // We need to handle `extern static`. 536 ( 0.00%) match self.tcx.get_global_alloc(alloc_id) { 448 ( 0.00%) Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => { . bug!("global memory cannot point to thread-local static") . } 56 ( 0.00%) Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => { . return M::extern_static_base_pointer(self, def_id); . } . _ => {} . } . // And we need to get the tag. 402 ( 0.00%) Ok(M::tag_alloc_base_pointer(self, Pointer::new(alloc_id, offset))) 1,072 ( 0.00%) } . . pub fn create_fn_alloc( . &mut self, . fn_val: FnVal<'tcx, M::ExtraFnVal>, . ) -> Pointer { . let id = match fn_val { . FnVal::Instance(instance) => self.tcx.create_fn_alloc(instance), . FnVal::Other(extra) => { -- line 191 ---------------------------------------- -- line 196 ---------------------------------------- . id . } . }; . // Functions are global allocations, so make sure we get the right base pointer. . // We know this is not an `extern static` so this cannot fail. . self.global_base_pointer(Pointer::from(id)).unwrap() . } . 1,359 ( 0.00%) pub fn allocate( . &mut self, . size: Size, . align: Align, . kind: MemoryKind, . ) -> InterpResult<'static, Pointer> { 588 ( 0.00%) let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?; 1,323 ( 0.00%) Ok(self.allocate_with(alloc, kind)) 1,065 ( 0.00%) } . 39 ( 0.00%) pub fn allocate_bytes( . &mut self, . bytes: &[u8], . align: Align, . kind: MemoryKind, . mutability: Mutability, . ) -> Pointer { . let alloc = Allocation::from_bytes(bytes, align, mutability); 24 ( 0.00%) self.allocate_with(alloc, kind) 30 ( 0.00%) } . . pub fn allocate_with( . &mut self, . alloc: Allocation, . kind: MemoryKind, . ) -> Pointer { 300 ( 0.00%) let id = self.tcx.reserve_alloc_id(); . debug_assert_ne!( . Some(kind), . M::GLOBAL_KIND.map(MemoryKind::Machine), . "dynamically allocating global memory" . ); . let alloc = M::init_allocation_extra(self, id, Cow::Owned(alloc), Some(kind)); 2,739 ( 0.00%) self.alloc_map.insert(id, (kind, alloc.into_owned())); . M::tag_alloc_base_pointer(self, Pointer::from(id)) . } . . pub fn reallocate( . &mut self, . ptr: Pointer>, . old_size_and_align: Option<(Size, Align)>, . new_size: Size, -- line 245 ---------------------------------------- -- line 361 ---------------------------------------- . let align = M::enforce_alignment(&self.extra).then_some(align); . self.check_and_deref_ptr( . ptr, . size, . align, . CheckInAllocMsg::MemoryAccessTest, . |alloc_id, offset, ptr| { . let (size, align) = 117,192 ( 0.01%) self.get_size_and_align(alloc_id, AllocCheck::Dereferenceable)?; . Ok((size, align, (alloc_id, offset, ptr))) . }, . ) . } . . /// Check if the given pointer points to live memory of given `size` and `align` . /// (ignoring `M::enforce_alignment`). The caller can control the error message for the . /// out-of-bounds case. -- line 377 ---------------------------------------- -- line 378 ---------------------------------------- . #[inline(always)] . pub fn check_ptr_access_align( . &self, . ptr: Pointer>, . size: Size, . align: Align, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { 1,220 ( 0.00%) self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| { 568 ( 0.00%) let check = match msg { . CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => { . AllocCheck::Dereferenceable . } . CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => { . AllocCheck::Live . } . }; 284 ( 0.00%) let (size, align) = self.get_size_and_align(alloc_id, check)?; . Ok((size, align, ())) . })?; . Ok(()) . } . . /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference . /// to the allocation it points to. Supports both shared and mutable references, as the actual . /// checking is offloaded to a helper closure. `align` defines whether and which alignment check . /// is done. Returns `None` for size 0, and otherwise `Some` of what `alloc_size` returned. 2,016 ( 0.00%) fn check_and_deref_ptr( . &self, . ptr: Pointer>, . size: Size, . align: Option, . msg: CheckInAllocMsg, . alloc_size: impl FnOnce( . AllocId, . Size, . Pointer, . ) -> InterpResult<'tcx, (Size, Align, T)>, . ) -> InterpResult<'tcx, Option> { 284 ( 0.00%) fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> { 710 ( 0.00%) if offset % align.bytes() == 0 { . Ok(()) . } else { . // The biggest power of two through which `offset` is divisible. . let offset_pow2 = 1 << offset.trailing_zeros(); . throw_ub!(AlignmentCheckFailed { . has: Align::from_bytes(offset_pow2).unwrap(), . required: align, . }) . } 426 ( 0.00%) } . . // Extract from the pointer an `Option` and an offset, which is relative to the . // allocation or (if that is `None`) an absolute address. 176,762 ( 0.02%) let ptr_or_addr = if size.bytes() == 0 { . // Let's see what we can do, but don't throw errors if there's nothing there. . self.ptr_try_get_alloc(ptr) . } else { . // A "real" access, we insist on getting an `AllocId`. . Ok(self.ptr_get_alloc(ptr)?) . }; . Ok(match ptr_or_addr { . Err(addr) => { -- line 440 ---------------------------------------- -- line 446 ---------------------------------------- . } . // Must be aligned. . if let Some(align) = align { . check_offset_align(addr, align)?; . } . None . } . Ok((alloc_id, offset, ptr)) => { 56 ( 0.00%) let (alloc_size, alloc_align, ret_val) = alloc_size(alloc_id, offset, ptr)?; . // Test bounds. This also ensures non-null. . // It is sufficient to check this for the end pointer. Also check for overflow! . if offset.checked_add(size, &self.tcx).map_or(true, |end| end > alloc_size) { . throw_ub!(PointerOutOfBounds { . alloc_id, . alloc_size, . ptr_offset: self.machine_usize_to_isize(offset.bytes()), . ptr_size: size, . msg, . }) . } . // Test align. Check this last; if both bounds and alignment are violated . // we want the error to be about the bounds. 284 ( 0.00%) if let Some(align) = align { . if M::force_int_for_alignment_check(&self.extra) { . let addr = Scalar::from_pointer(ptr, &self.tcx) . .to_machine_usize(&self.tcx) . .expect("ptr-to-int cast for align check should never fail"); . check_offset_align(addr, align)?; . } else { . // Check allocation alignment and offset alignment. 284 ( 0.00%) if alloc_align.bytes() < align.bytes() { . throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align }); . } 710 ( 0.00%) check_offset_align(offset.bytes(), align)?; . } . } . . // We can still be zero-sized in this branch, in which case we have to . // return `None`. 28 ( 0.00%) if size.bytes() == 0 { None } else { Some(ret_val) } . } . }) 2,130 ( 0.00%) } . . /// Test if the pointer might be null. . pub fn ptr_may_be_null(&self, ptr: Pointer>) -> bool { . match self.ptr_try_get_alloc(ptr) { . Ok((alloc_id, offset, _)) => { . let (size, _align) = self . .get_size_and_align(alloc_id, AllocCheck::MaybeDead) . .expect("alloc info with MaybeDead cannot fail"); -- line 496 ---------------------------------------- -- line 505 ---------------------------------------- . . /// Allocation accessors . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . /// Helper function to obtain a global (tcx) allocation. . /// This attempts to return a reference to an existing allocation if . /// one can be found in `tcx`. That, however, is only possible if `tcx` and . /// this machine use the same pointer tag, so it is indirected through . /// `M::tag_allocation`. 645,101 ( 0.07%) fn get_global_alloc( . &self, . id: AllocId, . is_write: bool, . ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { 527,759 ( 0.06%) let (alloc, def_id) = match self.tcx.get_global_alloc(id) { 58,615 ( 0.01%) Some(GlobalAlloc::Memory(mem)) => { . // Memory of a constant or promoted or anonymous memory referenced by a static. . (mem, None) . } . Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)), . None => throw_ub!(PointerUseAfterFree(id)), 56 ( 0.00%) Some(GlobalAlloc::Static(def_id)) => { 168 ( 0.00%) assert!(self.tcx.is_static(def_id)); 168 ( 0.00%) assert!(!self.tcx.is_thread_local_static(def_id)); . // Notice that every static has two `AllocId` that will resolve to the same . // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID, . // and the other one is maps to `GlobalAlloc::Memory`, this is returned by . // `eval_static_initializer` and it is the "resolved" ID. . // The resolved ID is never used by the interpreted program, it is hidden. . // This is relied upon for soundness of const-patterns; a pointer to the resolved . // ID would "sidestep" the checks that make sure consts do not point to statics! . // The `GlobalAlloc::Memory` branch here is still reachable though; when a static . // contains a reference to memory that was created during its evaluation (i.e., not . // to another static), those inner references only exist in "resolved" form. 28 ( 0.00%) if self.tcx.is_foreign_item(def_id) { . throw_unsup!(ReadExternStatic(def_id)); . } . 112 ( 0.00%) (self.tcx.eval_static_initializer(def_id)?, Some(def_id)) . } . }; 468,920 ( 0.05%) M::before_access_global(&self.extra, id, alloc, def_id, is_write)?; . let alloc = Cow::Borrowed(alloc); . // We got tcx memory. Let the machine initialize its "extra" stuff. . let alloc = M::init_allocation_extra( . self, . id, // always use the ID we got as input, not the "hidden" one. . alloc, . M::GLOBAL_KIND.map(MemoryKind::Machine), . ); 234,572 ( 0.02%) Ok(alloc) 469,144 ( 0.05%) } . . /// Gives raw access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! 234,544 ( 0.02%) fn get_raw( . &self, . id: AllocId, . ) -> InterpResult<'tcx, &Allocation> { . // The error type of the inner closure here is somewhat funny. We have two . // ways of "erroring": An actual error, or because we got a reference from . // `get_global_alloc` that we can actually use directly without inserting anything anywhere. . // So the error type is `InterpResult<'tcx, &Allocation>`. . let a = self.alloc_map.get_or(id, || { 234,600 ( 0.02%) let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?; 117,286 ( 0.01%) match alloc { . Cow::Borrowed(alloc) => { . // We got a ref, cheaply return that as an "error" so that the . // map does not get mutated. . Err(Ok(alloc)) . } . Cow::Owned(alloc) => { . // Need to put it into the map and return a ref to that . let kind = M::GLOBAL_KIND.expect( -- line 577 ---------------------------------------- -- line 582 ---------------------------------------- . } . } . }); . // Now unpack that funny error type . match a { . Ok(a) => Ok(&a.1), . Err(a) => a, . } 175,929 ( 0.02%) } . . /// "Safe" (bounds and align-checked) allocation access. 703,716 ( 0.07%) pub fn get<'a>( . &'a self, . ptr: Pointer>, . size: Size, . align: Align, . ) -> InterpResult<'tcx, Option>> { . let align = M::enforce_alignment(&self.extra).then_some(align); . let ptr_and_alloc = self.check_and_deref_ptr( . ptr, . size, . align, . CheckInAllocMsg::MemoryAccessTest, . |alloc_id, offset, ptr| { 234,572 ( 0.02%) let alloc = self.get_raw(alloc_id)?; . Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc))) . }, . )?; 117,230 ( 0.01%) if let Some((alloc_id, offset, ptr, alloc)) = ptr_and_alloc { . let range = alloc_range(offset, size); . M::memory_read(&self.extra, &alloc.extra, ptr.provenance, range)?; 410,501 ( 0.04%) Ok(Some(AllocRef { alloc, range, tcx: self.tcx, alloc_id })) . } else { . // Even in this branch we have to be sure that we actually access the allocation, in . // order to ensure that `static FOO: Type = FOO;` causes a cycle error instead of . // magically pulling *any* ZST value from the ether. However, the `get_raw` above is . // always called when `ptr` has an `AllocId`. . Ok(None) . } 527,787 ( 0.06%) } . . /// Return the `extra` field of the given allocation. . pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> { . Ok(&self.get_raw(id)?.extra) . } . . /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! . /// . /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the . /// allocation. 234,384 ( 0.02%) fn get_raw_mut( . &mut self, . id: AllocId, . ) -> InterpResult<'tcx, (&mut Allocation, &mut M::MemoryExtra)> . { . // We have "NLL problem case #3" here, which cannot be worked around without loss of . // efficiency even for the common case where the key is in the map. . // . // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`.) 29,298 ( 0.00%) if self.alloc_map.get_mut(id).is_none() { . // Slow path. . // Allocation not found locally, go look global. . let alloc = self.get_global_alloc(id, /*is_write*/ true)?; . let kind = M::GLOBAL_KIND.expect( . "I got a global allocation that I have to copy but the machine does \ . not expect that to happen", . ); . self.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned())); . } . 29,298 ( 0.00%) let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap(); 29,298 ( 0.00%) if alloc.mutability == Mutability::Not { . throw_ub!(WriteToReadOnly(id)) . } 117,192 ( 0.01%) Ok((alloc, &mut self.extra)) 146,490 ( 0.02%) } . . /// "Safe" (bounds and align-checked) allocation access. 351,576 ( 0.04%) pub fn get_mut<'a>( . &'a mut self, . ptr: Pointer>, . size: Size, . align: Align, . ) -> InterpResult<'tcx, Option>> { . let parts = self.get_ptr_access(ptr, size, align)?; 58,596 ( 0.01%) if let Some((alloc_id, offset, ptr)) = parts { . let tcx = self.tcx; . // FIXME: can we somehow avoid looking up the allocation twice here? . // We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`. 87,894 ( 0.01%) let (alloc, extra) = self.get_raw_mut(alloc_id)?; . let range = alloc_range(offset, size); . M::memory_written(extra, &mut alloc.extra, ptr.provenance, range)?; 175,788 ( 0.02%) Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id })) . } else { . Ok(None) . } 263,682 ( 0.03%) } . . /// Return the `extra` field of the given allocation. . pub fn get_alloc_extra_mut<'a>( . &'a mut self, . id: AllocId, . ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M::MemoryExtra)> { . let (alloc, memory_extra) = self.get_raw_mut(id)?; . Ok((&mut alloc.extra, memory_extra)) . } . . /// Obtain the size and alignment of an allocation, even if that allocation has . /// been deallocated. . /// . /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`. 323,840 ( 0.03%) pub fn get_size_and_align( . &self, . id: AllocId, . liveness: AllocCheck, . ) -> InterpResult<'static, (Size, Align)> { . // # Regular allocations . // Don't use `self.get_raw` here as that will . // a) cause cycles in case `id` refers to a static . // b) duplicate a global's allocation in miri 147,200 ( 0.02%) if let Some((_, alloc)) = self.alloc_map.get(id) { 29,298 ( 0.00%) return Ok((alloc.size(), alloc.align)); . } . . // # Function pointers . // (both global from `alloc_map` and local from `extra_fn_ptr_map`) 568 ( 0.00%) if self.get_fn_alloc(id).is_some() { . return if let AllocCheck::Dereferenceable = liveness { . // The caller requested no function pointers. . throw_ub!(DerefFunctionPointer(id)) . } else { . Ok((Size::ZERO, Align::ONE)) . }; . } . . // # Statics . // Can't do this in the match argument, we may get cycle errors since the lock would . // be held throughout the match. 1,506 ( 0.00%) match self.tcx.get_global_alloc(id) { 56 ( 0.00%) Some(GlobalAlloc::Static(did)) => { 168 ( 0.00%) assert!(!self.tcx.is_thread_local_static(did)); . // Use size and align of the type. 28 ( 0.00%) let ty = self.tcx.type_of(did); 28 ( 0.00%) let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap(); 56 ( 0.00%) Ok((layout.size, layout.align.abi)) . } 114 ( 0.00%) Some(GlobalAlloc::Memory(alloc)) => { . // Need to duplicate the logic here, because the global allocations have . // different associated types than the interpreter-local ones. 228 ( 0.00%) Ok((alloc.size(), alloc.align)) . } . Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"), . // The rest must be dead. . None => { . if let AllocCheck::MaybeDead = liveness { . // Deallocated pointers are allowed, we should be able to find . // them in the map. . Ok(*self -- line 740 ---------------------------------------- -- line 741 ---------------------------------------- . .dead_alloc_map . .get(&id) . .expect("deallocated pointers should all be recorded in `dead_alloc_map`")) . } else { . throw_ub!(PointerUseAfterFree(id)) . } . } . } 235,520 ( 0.02%) } . 568 ( 0.00%) fn get_fn_alloc(&self, id: AllocId) -> Option> { . if let Some(extra) = self.extra_fn_ptr_map.get(&id) { . Some(FnVal::Other(*extra)) . } else { 710 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)), 142 ( 0.00%) _ => None, . } . } 568 ( 0.00%) } . . pub fn get_fn( . &self, . ptr: Pointer>, . ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> { . trace!("get_fn({:?})", ptr); . let (alloc_id, offset, _ptr) = self.ptr_get_alloc(ptr)?; . if offset.bytes() != 0 { -- line 768 ---------------------------------------- -- line 903 ---------------------------------------- . writeln!(fmt)?; . } . Ok(()) . } . } . . /// Reading and writing. . impl<'tcx, 'a, Tag: Provenance, Extra> AllocRefMut<'a, 'tcx, Tag, Extra> { 263,961 ( 0.03%) pub fn write_scalar( . &mut self, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { 146,645 ( 0.02%) Ok(self . .alloc 322,619 ( 0.03%) .write_scalar(&self.tcx, self.range.subrange(range), val) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 175,974 ( 0.02%) } . . pub fn write_ptr_sized( . &mut self, . offset: Size, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { . self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val) . } . } . . impl<'tcx, 'a, Tag: Provenance, Extra> AllocRef<'a, 'tcx, Tag, Extra> { 696 ( 0.00%) pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit> { 645,769 ( 0.07%) Ok(self . .alloc 352,467 ( 0.04%) .read_scalar(&self.tcx, self.range.subrange(range)) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 696 ( 0.00%) } . . pub fn read_ptr_sized(&self, offset: Size) -> InterpResult<'tcx, ScalarMaybeUninit> { . self.read_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size)) . } . . pub fn check_bytes(&self, range: AllocRange, allow_uninit_and_ptr: bool) -> InterpResult<'tcx> { . Ok(self . .alloc -- line 945 ---------------------------------------- -- line 1136 ---------------------------------------- . dest_alloc.mark_relocation_range(relocations); . . Ok(()) . } . } . . /// Machine pointer introspection. . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { 203 ( 0.00%) pub fn scalar_to_ptr(&self, scalar: Scalar) -> Pointer> { . // We use `to_bits_or_ptr_internal` since we are just implementing the method people need to . // call to force getting out a pointer. 1,015 ( 0.00%) match scalar.to_bits_or_ptr_internal(self.pointer_size()) { . Err(ptr) => ptr.into(), . Ok(bits) => { . let addr = u64::try_from(bits).unwrap(); . let ptr = M::ptr_from_addr(&self, addr); . if addr == 0 { . assert!(ptr.provenance.is_none(), "null pointer can never have an AllocId"); . } . ptr . } . } 406 ( 0.00%) } . . /// Turning a "maybe pointer" into a proper pointer (and some information . /// about where it points), or an absolute address. . pub fn ptr_try_get_alloc( . &self, . ptr: Pointer>, . ) -> Result<(AllocId, Size, Pointer), u64> { . match ptr.into_pointer_or_addr() { -- line 1166 ---------------------------------------- 558,544 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/stacker-0.1.14/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . /// `stack_size` bytes. . /// . /// The closure `f` is guaranteed to run on a stack with at least `red_zone` bytes, and it will be . /// run on the current stack if there's space available. . #[inline(always)] . pub fn maybe_grow R>(red_zone: usize, stack_size: usize, callback: F) -> R { . // if we can't guess the remaining stack (unsupported on some platforms) we immediately grow . // the stack and then cache the new stack size (which we do know now because we allocated it. 203,728 ( 0.02%) let enough_space = match remaining_stack() { . Some(remaining) => remaining >= red_zone, . None => false, . }; 299,940 ( 0.03%) if enough_space { 2,252 ( 0.00%) callback() . } else { . grow(stack_size, callback) . } . } . . /// Always creates a new stack for the passed closure to run on. . /// The closure will still be on the same thread as the caller of `grow`. . /// This will allocate a new stack with at least `stack_size` bytes. -- line 63 ---------------------------------------- -- line 82 ---------------------------------------- . _grow(stack_size, dyn_callback); . ret.unwrap() . } . . /// Queries the amount of remaining stack as interpreted by this library. . /// . /// This function will return the amount of stack space left which will be used . /// to determine whether a stack switch should be made or not. 199,960 ( 0.02%) pub fn remaining_stack() -> Option { . let current_ptr = current_stack_ptr(); 199,960 ( 0.02%) get_stack_limit().map(|limit| current_ptr - limit) 399,920 ( 0.04%) } . . psm_stack_information! ( . yes { . fn current_stack_ptr() -> usize { 199,960 ( 0.02%) psm::stack_pointer() as usize . } . } . no { . #[inline(always)] . fn current_stack_ptr() -> usize { . unsafe { . let mut x = std::mem::MaybeUninit::::uninit(); . // Unlikely to be ever exercised. As a fallback we execute a volatile read to a -- line 106 ---------------------------------------- -- line 111 ---------------------------------------- . x.as_ptr() as usize . } . } . } . ); . . thread_local! { . static STACK_LIMIT: Cell> = Cell::new(unsafe { 1 ( 0.00%) guess_os_stack_limit() . }) . } . . #[inline(always)] . fn get_stack_limit() -> Option { . STACK_LIMIT.with(|s| s.get()) . } . -- line 127 ---------------------------------------- -- line 403 ---------------------------------------- . VirtualQuery( . psm::stack_pointer() as *const _, . mi.as_mut_ptr(), . std::mem::size_of::() as SIZE_T, . ); . Some(mi.assume_init().AllocationBase as usize + get_thread_stack_guarantee() + 0x1000) . } . } else if #[cfg(any(target_os = "linux", target_os="solaris", target_os = "netbsd"))] { 2 ( 0.00%) unsafe fn guess_os_stack_limit() -> Option { . let mut attr = std::mem::MaybeUninit::::uninit(); 4 ( 0.00%) assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); 7 ( 0.00%) assert_eq!(libc::pthread_getattr_np(libc::pthread_self(), . attr.as_mut_ptr()), 0); 1 ( 0.00%) let mut stackaddr = std::ptr::null_mut(); 4 ( 0.00%) let mut stacksize = 0; 4 ( 0.00%) assert_eq!(libc::pthread_attr_getstack( . attr.as_ptr(), &mut stackaddr, &mut stacksize . ), 0); 4 ( 0.00%) assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); 1 ( 0.00%) Some(stackaddr as usize) 3 ( 0.00%) } . } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { . unsafe fn guess_os_stack_limit() -> Option { . let mut attr = std::mem::MaybeUninit::::uninit(); . assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); . assert_eq!(libc::pthread_attr_get_np(libc::pthread_self(), attr.as_mut_ptr()), 0); . let mut stackaddr = std::ptr::null_mut(); . let mut stacksize = 0; . assert_eq!(libc::pthread_attr_getstack( -- line 431 ---------------------------------------- 189,780 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs -------------------------------------------------------------------------------- Ir . #![allow(clippy::many_single_char_names)] . use crate::consts::RC; . use core::convert::TryInto; . . #[inline(always)] . fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 655,375 ( 0.07%) ((x & y) | (!x & z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . #[inline(always)] . fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 624,750 ( 0.07%) ((x & z) | (y & !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 306,250 ( 0.03%) (x ^ y ^ z) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 392,000 ( 0.04%) (y ^ (x | !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline] 55,125 ( 0.01%) pub fn compress(state: &mut [u32; 4], input: &[u8; 64]) { 12,250 ( 0.00%) let mut a = state[0]; 6,125 ( 0.00%) let mut b = state[1]; 6,125 ( 0.00%) let mut c = state[2]; 6,125 ( 0.00%) let mut d = state[3]; . . let mut data = [0u32; 16]; . for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { 153,125 ( 0.02%) *o = u32::from_le_bytes(chunk.try_into().unwrap()); . } . . // round 1 . a = op_f(a, b, c, d, data[0], RC[0], 7); . d = op_f(d, a, b, c, data[1], RC[1], 12); . c = op_f(c, d, a, b, data[2], RC[2], 17); . b = op_f(b, c, d, a, data[3], RC[3], 22); . -- line 61 ---------------------------------------- -- line 132 ---------------------------------------- . c = op_i(c, d, a, b, data[6], RC[58], 15); . b = op_i(b, c, d, a, data[13], RC[59], 21); . . a = op_i(a, b, c, d, data[4], RC[60], 6); . d = op_i(d, a, b, c, data[11], RC[61], 10); . c = op_i(c, d, a, b, data[2], RC[62], 15); . b = op_i(b, c, d, a, data[9], RC[63], 21); . 12,250 ( 0.00%) state[0] = state[0].wrapping_add(a); 6,125 ( 0.00%) state[1] = state[1].wrapping_add(b); 6,125 ( 0.00%) state[2] = state[2].wrapping_add(c); 6,125 ( 0.00%) state[3] = state[3].wrapping_add(d); 49,000 ( 0.01%) } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs -------------------------------------------------------------------------------- Ir -- line 132 ---------------------------------------- . /// State for tracking recursive validation of references . pub struct RefTracking { . pub seen: FxHashSet, . pub todo: Vec<(T, PATH)>, . } . . impl RefTracking { . pub fn empty() -> Self { 324 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![] } . } 390 ( 0.00%) pub fn new(op: T) -> Self { . let mut ref_tracking_for_consts = 1,248 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] }; . ref_tracking_for_consts.seen.insert(op); . ref_tracking_for_consts 390 ( 0.00%) } . . pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) { 344 ( 0.00%) if self.seen.insert(op) { . trace!("Recursing below ptr {:#?}", op); . let path = path(); . // Remember to come back to this later. 638 ( 0.00%) self.todo.push((op, path)); . } . } . } . . /// Format a path . fn write_path(out: &mut String, path: &[PathElem]) { . use self::PathElem::*; . -- line 162 ---------------------------------------- -- line 208 ---------------------------------------- . path: Vec, . ref_tracking: Option<&'rt mut RefTracking, Vec>>, . /// `None` indicates this is not validating for CTFE (but for runtime). . ctfe_mode: Option, . ecx: &'rt InterpCx<'mir, 'tcx, M>, . } . . impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> { 701,040 ( 0.07%) fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem { . // First, check if we are projecting to a variant. 175,260 ( 0.02%) match layout.variants { . Variants::Multiple { tag_field, .. } => { 4 ( 0.00%) if tag_field == field { 6 ( 0.00%) return match layout.ty.kind() { 4 ( 0.00%) ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag, . ty::Generator(..) => PathElem::GeneratorTag, . _ => bug!("non-variant type {:?}", layout.ty), . }; . } . } . Variants::Single { .. } => {} . } . . // Now we know we are projecting to a field, so figure out which one. 233,672 ( 0.02%) match layout.ty.kind() { . // generators and closures. . ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => { . let mut name = None; . // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar . // https://github.com/rust-lang/project-rfc-2229/issues/46 . if let Some(local_def_id) = def_id.as_local() { . let tables = self.ecx.tcx.typeck(local_def_id); . if let Some(captured_place) = -- line 240 ---------------------------------------- -- line 280 ---------------------------------------- . ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field), . . // dyn traits . ty::Dynamic(..) => PathElem::DynDowncast, . . // nothing else has an aggregate layout . _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty), . } 759,460 ( 0.08%) } . . fn with_elem( . &mut self, . elem: PathElem, . f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>, . ) -> InterpResult<'tcx, R> { . // Remember the old state 116,848 ( 0.01%) let path_len = self.path.len(); . // Record new element . self.path.push(elem); . // Perform operation 116,848 ( 0.01%) let r = f(self)?; . // Undo changes . self.path.truncate(path_len); . // Done . Ok(r) . } . 252 ( 0.00%) fn check_wide_ptr_meta( . &mut self, . meta: MemPlaceMeta, . pointee: TyAndLayout<'tcx>, . ) -> InterpResult<'tcx> { 196 ( 0.00%) let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env); 112 ( 0.00%) match tail.kind() { . ty::Dynamic(..) => { . let vtable = self.ecx.scalar_to_ptr(meta.unwrap_meta()); . // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines. . try_validation!( . self.ecx.memory.check_ptr_access_align( . vtable, . 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align . self.ecx.tcx.data_layout.pointer_align.abi, -- line 321 ---------------------------------------- -- line 347 ---------------------------------------- . err_ub!(InvalidVtableAlignment(msg)) => . { "invalid vtable: alignment {}", msg }, . err_unsup!(ReadPointerAsBytes) => { "invalid size or align in vtable" }, . ); . // FIXME: More checks for the vtable. . } . ty::Slice(..) | ty::Str => { . let _len = try_validation!( 28 ( 0.00%) meta.unwrap_meta().to_machine_usize(self.ecx), . self.path, . err_unsup!(ReadPointerAsBytes) => { "non-integer slice length in wide pointer" }, . ); . // We do not check that `len * elem_size <= isize::MAX`: . // that is only required for references, and there it falls out of the . // "dereferenceable" check performed by Stacked Borrows. . } . ty::Foreign(..) => { . // Unsized, but not wide. . } . _ => bug!("Unexpected unsized type tail: {:?}", tail), . } . . Ok(()) 252 ( 0.00%) } . . /// Check a reference or `Box`. 638 ( 0.00%) fn check_safe_pointer( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . kind: &str, . ) -> InterpResult<'tcx> { 174 ( 0.00%) let value = try_validation!( 116 ( 0.00%) self.ecx.read_immediate(value), . self.path, . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, . ); . // Handle wide pointers. . // Check metadata early, for better diagnostics 580 ( 0.00%) let place = try_validation!( 174 ( 0.00%) self.ecx.ref_to_mplace(&value), . self.path, . err_ub!(InvalidUninitBytes(None)) => { "uninitialized {}", kind }, . ); 170 ( 0.00%) if place.layout.is_unsized() { 308 ( 0.00%) self.check_wide_ptr_meta(place.meta, place.layout)?; . } . // Make sure this is dereferenceable and all. 116 ( 0.00%) let size_and_align = try_validation!( 58 ( 0.00%) self.ecx.size_and_align_of_mplace(&place), . self.path, . err_ub!(InvalidMeta(msg)) => { "invalid {} metadata: {}", kind, msg }, . ); . let (size, align) = size_and_align . // for the purpose of validity, consider foreign types to have . // alignment and size determined by the layout (size will be 0, . // alignment should take attributes into account). . .unwrap_or_else(|| (place.layout.size, place.layout.align.abi)); . // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines. . try_validation!( 116 ( 0.00%) self.ecx.memory.check_ptr_access_align( 174 ( 0.00%) place.ptr, . size, . align, . CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message . ), . self.path, . err_ub!(AlignmentCheckFailed { required, has }) => . { . "an unaligned {} (required {} byte alignment but found {})", -- line 415 ---------------------------------------- -- line 424 ---------------------------------------- . err_ub!(PointerOutOfBounds { .. }) => . { "a dangling {} (going beyond the bounds of its allocation)", kind }, . // This cannot happen during const-eval (because interning already detects . // dangling pointers), but it can happen in Miri. . err_ub!(PointerUseAfterFree(..)) => . { "a dangling {} (use-after-free)", kind }, . ); . // Recursive checking 174 ( 0.00%) if let Some(ref mut ref_tracking) = self.ref_tracking { . // Proceed recursively even for ZST, no reason to skip them! . // `!` is a ZST and we want to validate it. . // Skip validation entirely for some external statics 116 ( 0.00%) if let Ok((alloc_id, _offset, _ptr)) = self.ecx.memory.ptr_try_get_alloc(place.ptr) { . // not a ZST 174 ( 0.00%) let alloc_kind = self.ecx.tcx.get_global_alloc(alloc_id); 116 ( 0.00%) if let Some(GlobalAlloc::Static(did)) = alloc_kind { . assert!(!self.ecx.tcx.is_thread_local_static(did)); . assert!(self.ecx.tcx.is_static(did)); . if matches!( . self.ctfe_mode, . Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. }) . ) { . // See const_eval::machine::MemoryExtra::can_access_statics for why . // this check is so important. -- line 447 ---------------------------------------- -- line 460 ---------------------------------------- . // and that static refers back to us. . // We might miss const-invalid data, . // but things are still sound otherwise (in particular re: consts . // referring to statics). . return Ok(()); . } . } . let path = &self.path; 522 ( 0.00%) ref_tracking.track(place, || { . // We need to clone the path anyway, make sure it gets created . // with enough space for the additional `Deref`. 232 ( 0.00%) let mut new_path = Vec::with_capacity(path.len() + 1); . new_path.clone_from(path); . new_path.push(PathElem::Deref); . new_path . }); . } . Ok(()) 522 ( 0.00%) } . 409,094 ( 0.04%) fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 467,536 ( 0.05%) Ok(try_validation!( 175,326 ( 0.02%) self.ecx.read_scalar(op), . self.path, . err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" }, . )) 350,652 ( 0.04%) } . . /// Check if this is a value of primitive type, and if yes check the validity of the value . /// at that type. Return `true` if the type is indeed primitive. 527,022 ( 0.06%) fn try_visit_primitive( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, bool> { . // Go over all the primitive types 175,674 ( 0.02%) let ty = value.layout.ty; 351,348 ( 0.04%) match ty.kind() { . ty::Bool => { . let value = self.read_scalar(value)?; . try_validation!( . value.to_bool(), . self.path, . err_ub!(InvalidBool(..)) | err_ub!(InvalidUninitBytes(None)) => . { "{}", value } expected { "a boolean" }, . ); . Ok(true) . } . ty::Char => { 233,672 ( 0.02%) let value = self.read_scalar(value)?; 116,836 ( 0.01%) try_validation!( . value.to_char(), . self.path, . err_ub!(InvalidChar(..)) | err_ub!(InvalidUninitBytes(None)) => . { "{}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" }, . ); . Ok(true) . } . ty::Float(_) | ty::Int(_) | ty::Uint(_) => { 88 ( 0.00%) let value = self.read_scalar(value)?; . // NOTE: Keep this in sync with the array optimization for int/float . // types below! . if M::enforce_number_validity(self.ecx) { . // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous . let is_bits = value.check_init().map_or(false, |v| v.try_to_int().is_ok()); . if !is_bits { . throw_validation_failure!(self.path, . { "{}", value } expected { "initialized plain (non-pointer) bytes" } -- line 529 ---------------------------------------- -- line 543 ---------------------------------------- . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, . ); . if place.layout.is_unsized() { . self.check_wide_ptr_meta(place.meta, place.layout)?; . } . Ok(true) . } . ty::Ref(_, ty, mutbl) => { 146 ( 0.00%) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) . && *mutbl == hir::Mutability::Mut . { . // A mutable reference inside a const? That does not seem right (except if it is . // a ZST). . let layout = self.ecx.layout_of(ty)?; . if !layout.is_zst() { . throw_validation_failure!(self.path, { "mutable reference in a `const`" }); . } . } 174 ( 0.00%) self.check_safe_pointer(value, "reference")?; . Ok(true) . } 8 ( 0.00%) ty::Adt(def, ..) if def.is_box() => { . self.check_safe_pointer(value, "box")?; . Ok(true) . } . ty::FnPtr(_sig) => { . let value = try_validation!( . self.ecx.read_immediate(value), . self.path, . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, -- line 572 ---------------------------------------- -- line 606 ---------------------------------------- . | ty::Infer(..) . | ty::Placeholder(..) . | ty::Bound(..) . | ty::Param(..) . | ty::Opaque(..) . | ty::Projection(..) . | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty), . } 878,370 ( 0.09%) } . 16 ( 0.00%) fn visit_scalar( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . scalar_layout: ScalarAbi, . ) -> InterpResult<'tcx> { 6 ( 0.00%) if scalar_layout.valid_range.is_full_for(op.layout.size) { . // Nothing to check . return Ok(()); . } . // At least one value is excluded. . let valid_range = scalar_layout.valid_range; . let WrappingRange { start, end } = valid_range; . let max_value = op.layout.size.unsigned_int_max(); 8 ( 0.00%) assert!(end <= max_value); . // Determine the allowed range 6 ( 0.00%) let value = self.read_scalar(op)?; . let value = try_validation!( . value.check_init(), . self.path, . err_ub!(InvalidUninitBytes(None)) => { "{}", value } . expected { "something {}", wrapping_range_format(valid_range, max_value) }, . ); 4 ( 0.00%) let bits = match value.try_to_int() { . Err(_) => { . // So this is a pointer then, and casting to an int failed. . // Can only happen during CTFE. . let ptr = self.ecx.scalar_to_ptr(value); . if start == 1 && end == max_value { . // Only null is the niche. So make sure the ptr is NOT null. . if self.ecx.memory.ptr_may_be_null(ptr) { . throw_validation_failure!(self.path, -- line 646 ---------------------------------------- -- line 659 ---------------------------------------- . { "a pointer" } . expected { . "something that cannot possibly fail to be {}", . wrapping_range_format(valid_range, max_value) . } . ) . } . } 32 ( 0.00%) Ok(int) => int.assert_bits(op.layout.size), . }; . // Now compare. This is slightly subtle because this is a special "wrap-around" range. 7 ( 0.00%) if valid_range.contains(bits) { . Ok(()) . } else { . throw_validation_failure!(self.path, . { "{}", bits } . expected { "something {}", wrapping_range_format(valid_range, max_value) } . ) . } 18 ( 0.00%) } . } . . impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> . for ValidityVisitor<'rt, 'mir, 'tcx, M> . { . type V = OpTy<'tcx, M::PointerTag>; . . #[inline(always)] -- line 686 ---------------------------------------- -- line 688 ---------------------------------------- . &self.ecx . } . . fn read_discriminant( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, VariantIdx> { . self.with_elem(PathElem::EnumTag, move |this| { 6 ( 0.00%) Ok(try_validation!( 8 ( 0.00%) this.ecx.read_discriminant(op), . this.path, . err_ub!(InvalidTag(val)) => . { "{}", val } expected { "a valid enum tag" }, . err_ub!(InvalidUninitBytes(None)) => . { "uninitialized bytes" } expected { "a valid enum tag" }, . err_unsup!(ReadPointerAsBytes) => . { "a pointer" } expected { "a valid enum tag" }, . ) -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . . #[inline] . fn visit_field( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . field: usize, . new_op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 408,934 ( 0.04%) let elem = self.aggregate_field_path_elem(old_op.layout, field); 175,260 ( 0.02%) self.with_elem(elem, move |this| this.visit_value(new_op)) . } . . #[inline] . fn visit_variant( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . variant_id: VariantIdx, . new_op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 8 ( 0.00%) let name = match old_op.layout.ty.kind() { 8 ( 0.00%) ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].name), . // Generators also have variants . ty::Generator(..) => PathElem::GeneratorState(variant_id), . _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty), . }; 14 ( 0.00%) self.with_elem(name, move |this| this.visit_value(new_op)) . } . . #[inline(always)] . fn visit_union( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . _fields: NonZeroUsize, . ) -> InterpResult<'tcx> { -- line 742 ---------------------------------------- -- line 745 ---------------------------------------- . if !op.layout.ty.is_freeze(self.ecx.tcx.at(DUMMY_SP), self.ecx.param_env) { . throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); . } . } . Ok(()) . } . . #[inline] 525,798 ( 0.06%) fn visit_value(&mut self, op: &OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { . trace!("visit_value: {:?}, {:?}", *op, op.layout); . . // Check primitive types -- the leafs of our recursive descend. 234,096 ( 0.02%) if self.try_visit_primitive(op)? { . return Ok(()); . } . // Sanity check: `builtin_deref` does not know any pointers that are not primitive. 240 ( 0.00%) assert!(op.layout.ty.builtin_deref(true).is_none()); . . // Special check preventing `UnsafeCell` in the inner part of constants 128 ( 0.00%) if let Some(def) = op.layout.ty.ty_adt_def() { 20 ( 0.00%) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) 28 ( 0.00%) && Some(def.did) == self.ecx.tcx.lang_items().unsafe_cell_type() . { . throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); . } . } . . // Recursively walk the value at its type. 300 ( 0.00%) self.walk_value(op)?; . . // *After* all of this, check the ABI. We need to check the ABI to handle . // types like `NonNull` where the `Scalar` info is more restrictive than what . // the fields say (`rustc_layout_scalar_valid_range_start`). . // But in most cases, this will just propagate what the fields say, . // and then we want the error to point at the field -- so, first recurse, . // then check ABI. . // . // FIXME: We could avoid some redundant checks here. For newtypes wrapping . // scalars, we do the same check on every "level" (e.g., first we check . // MyNewtype and then the scalar in there). 304 ( 0.00%) match op.layout.abi { . Abi::Uninhabited => { . throw_validation_failure!(self.path, . { "a value of uninhabited type {:?}", op.layout.ty } . ); . } . Abi::Scalar(scalar_layout) => { 28 ( 0.00%) self.visit_scalar(op, scalar_layout)?; . } . Abi::ScalarPair { .. } | Abi::Vector { .. } => { . // These have fields that we already visited above, so we already checked . // all their scalar-level restrictions. . // There is also no equivalent to `rustc_layout_scalar_valid_range_start` . // that would make skipping them here an issue. . } . Abi::Aggregate { .. } => { . // Nothing to do. . } . } . . Ok(()) 467,376 ( 0.05%) } . . fn visit_aggregate( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . fields: impl Iterator>, . ) -> InterpResult<'tcx> { 540 ( 0.00%) match op.layout.ty.kind() { . ty::Str => { . let mplace = op.assert_mem_place(); // strings are never immediate . let len = mplace.len(self.ecx)?; . try_validation!( . self.ecx.memory.read_bytes(mplace.ptr, Size::from_bytes(len)), . self.path, . err_ub!(InvalidUninitBytes(..)) => { "uninitialized data in `str`" }, . err_unsup!(ReadPointerAsBytes) => { "a pointer in `str`" }, -- line 821 ---------------------------------------- -- line 822 ---------------------------------------- . ); . } . ty::Array(tys, ..) | ty::Slice(tys) . // This optimization applies for types that can hold arbitrary bytes (such as . // integer and floating point types) or for structs or tuples with no fields. . // FIXME(wesleywiser) This logic could be extended further to arbitrary structs . // or tuples made up of integer/floating point types or inhabited ZSTs with no . // padding. 280 ( 0.00%) if matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..)) . => . { . // Optimized handling for arrays of integer/float type. . . // Arrays cannot be immediate, slices are never immediate. . let mplace = op.assert_mem_place(); . // This is the length of the array/slice. . let len = mplace.len(self.ecx)?; -- line 838 ---------------------------------------- -- line 891 ---------------------------------------- . _ => return Err(err), . } . } . } . } . // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element . // of an array and not all of them, because there's only a single value of a specific . // ZST type, so either validation fails for all elements or none. 504 ( 0.00%) ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => { . // Validate just the first element (if any). . self.walk_aggregate(op, fields.take(1))? . } . _ => { . self.walk_aggregate(op, fields)? // default handler . } . } . Ok(()) . } . } . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { 816 ( 0.00%) fn validate_operand_internal( . &self, . op: &OpTy<'tcx, M::PointerTag>, . path: Vec, . ref_tracking: Option<&mut RefTracking, Vec>>, . ctfe_mode: Option, . ) -> InterpResult<'tcx> { . trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty); . . // Construct a visitor 1,224 ( 0.00%) let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self }; . . // Run it. 408 ( 0.00%) match visitor.visit_value(&op) { . Ok(()) => Ok(()), . // Pass through validation failures. . Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err), . // Also pass through InvalidProgram, those just indicate that we could not . // validate and each caller will know best what to do with them. . Err(err) if matches!(err.kind(), InterpError::InvalidProgram(_)) => Err(err), . // Avoid other errors as those do not show *where* in the value the issue lies. . Err(err) => { . err.print_backtrace(); . bug!("Unexpected error during validation: {}", err); . } . } 952 ( 0.00%) } . . /// This function checks the data at `op` to be const-valid. . /// `op` is assumed to cover valid memory if it is an indirect operand. . /// It will error if the bits at the destination do not match the ones described by the layout. . /// . /// `ref_tracking` is used to record references that we encounter so that they . /// can be checked recursively by an outside driving loop. . /// -- line 946 ---------------------------------------- -- line 950 ---------------------------------------- . #[inline(always)] . pub fn const_validate_operand( . &self, . op: &OpTy<'tcx, M::PointerTag>, . path: Vec, . ref_tracking: &mut RefTracking, Vec>, . ctfe_mode: CtfeValidationMode, . ) -> InterpResult<'tcx> { 1,360 ( 0.00%) self.validate_operand_internal(op, path, Some(ref_tracking), Some(ctfe_mode)) . } . . /// This function checks the data at `op` to be runtime-valid. . /// `op` is assumed to cover valid memory if it is an indirect operand. . /// It will error if the bits at the destination do not match the ones described by the layout. . #[inline(always)] . pub fn validate_operand(&self, op: &OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { . self.validate_operand_internal(op, vec![], None, None) -- line 966 ---------------------------------------- 702,427 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs -------------------------------------------------------------------------------- Ir -- line 83 ---------------------------------------- . if $self.is_proc_macro { . return Lazy::empty(); . } . }; . } . . macro_rules! encoder_methods { . ($($name:ident($ty:ty);)*) => { 1,560 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 1,872 ( 0.00%) })* . } . } . . impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { . type Error = ::Error; . . #[inline] . fn emit_unit(&mut self) -> Result<(), Self::Error> { -- line 101 ---------------------------------------- -- line 125 ---------------------------------------- . emit_raw_bytes(&[u8]); . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 457 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 10 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 160 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 303 ( 0.00%) e.emit_lazy_distance(*self) 6 ( 0.00%) } . } . . impl<'a, 'tcx, I: Idx, T: Encodable>> Encodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 144 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx> Encodable> for CrateNum { 728 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 1,130 ( 0.00%) if *self != LOCAL_CRATE && s.is_proc_macro { . panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); . } . s.emit_u32(self.as_u32()) 624 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 485 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 582 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for ExpnIndex { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) . } . } . . impl<'a, 'tcx> Encodable> for SyntaxContext { 157,225 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 94,335 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 188,670 ( 0.02%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 101 ( 0.00%) if self.krate == LOCAL_CRATE { . // We will only write details for local expansions. Non-local expansions will fetch . // data from the corresponding crate's metadata. . // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external . // metadata from proc-macro crates. 310 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 208 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 251,512 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 188,634 ( 0.02%) let span = self.data(); . . // Don't serialize any `SyntaxContext`s from a proc-macro crate, . // since we don't load proc-macro dependencies during serialization. . // This means that any hygiene information from macros used *within* . // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro . // definition) will be lost. . // . // This can show up in two ways: -- line 211 ---------------------------------------- -- line 228 ---------------------------------------- . // None of these user-visible effects should result in any . // cross-crate inconsistencies (getting one behavior in the same . // crate, and a different behavior in another crate) due to the . // limited surface that proc-macros can expose. . // . // IMPORTANT: If this is ever changed, be sure to update . // `rustc_span::hygiene::raw_encode_expn_id` to handle . // encoding `ExpnData` for proc-macro crates. 62,878 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 31,439 ( 0.00%) span.ctxt.encode(s)?; . } . 31,439 ( 0.00%) if self.is_dummy() { . return TAG_PARTIAL_SPAN.encode(s); . } . . // The Span infrastructure should make sure that this invariant holds: . debug_assert!(span.lo <= span.hi); . 157,114 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { 12 ( 0.00%) let source_map = s.tcx.sess.source_map(); 24 ( 0.00%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 12 ( 0.00%) s.source_file_cache = 24 ( 0.00%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 94,296 ( 0.01%) if !s.source_file_cache.0.contains(span.hi) { . // Unfortunately, macro expansion still sometimes generates Spans . // that malformed in this way. . return TAG_PARTIAL_SPAN.encode(s); . } . . let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); . // Record the fact that we need to encode the data for this `SourceFile` 31,424 ( 0.00%) source_files.insert(s.source_file_cache.1); . . // There are two possible cases here: . // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the . // crate we are writing metadata for. When the metadata for *this* crate gets . // deserialized, the deserializer will need to know which crate it originally came . // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should . // be deserialized after the rest of the span data, which tells the deserializer . // which crate contains the source map information. -- line 272 ---------------------------------------- -- line 274 ---------------------------------------- . // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use . // our own source map information. . // . // If we're a proc-macro crate, we always treat this as a local `Span`. . // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata . // if we're a proc-macro crate. . // This allows us to avoid loading the dependencies of proc-macro crates: all of . // the information we need to decode `Span`s is stored in the proc-macro crate. 188,544 ( 0.02%) let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { . // To simplify deserialization, we 'rebase' this span onto the crate it originally came from . // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values . // are relative to the source map information for the 'foreign' crate whose CrateNum . // we write into the metadata. This allows `imported_source_files` to binary . // search through the 'foreign' crate's source map information, using the . // deserialized 'lo' and 'hi' values directly. . // . // All of this logic ensures that the final result of deserialization is a 'normal' -- line 290 ---------------------------------------- -- line 296 ---------------------------------------- . src => panic!("Unexpected external source {:?}", src), . } . }; . let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; . let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 94,272 ( 0.01%) (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) . }; . . tag.encode(s)?; . lo.encode(s)?; . . // Encode length which is usually less than span.hi and profits more . // from the variable-length integer encoding that we use. . let len = hi - lo; . len.encode(s)?; . 62,848 ( 0.01%) if tag == TAG_VALID_SPAN_FOREIGN { . // This needs to be two lines to avoid holding the `s.source_file_cache` . // while calling `cnum.encode(s)` . let cnum = s.source_file_cache.0.cnum; . cnum.encode(s)?; . } . . Ok(()) 251,512 ( 0.03%) } . } . . impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { . const CLEAR_CROSS_CRATE: bool = true; . . fn position(&self) -> usize { . self.opaque.position() . } -- line 331 ---------------------------------------- -- line 333 ---------------------------------------- . fn type_shorthands(&mut self) -> &mut FxHashMap, usize> { . &mut self.type_shorthands . } . . fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize> { . &mut self.predicate_shorthands . } . 140 ( 0.00%) fn encode_alloc_id( . &mut self, . alloc_id: &rustc_middle::mir::interpret::AllocId, . ) -> Result<(), Self::Error> { 84 ( 0.00%) let (index, _) = self.interpret_allocs.insert_full(*alloc_id); . . index.encode(self) 140 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . (**self).encode(s) . } . } . -- line 356 ---------------------------------------- -- line 361 ---------------------------------------- . } . . /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. . trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { . fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for &T { 848 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 483 ( 0.00%) self.encode(ecx).unwrap() . } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 2,441 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 1,253 ( 0.00%) self.encode(ecx).unwrap() 1,416 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 21 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 842 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 27 ( 0.00%) } . } . . // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would . // normally need extra variables to avoid errors about multiple mutable borrows. . macro_rules! record { . ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ . { . let value = $value; . let lazy = $self.lazy(value); . $self.$tables.$table.set($def_id.index, lazy); . } . }}; . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 865 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 599 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 133 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 266 ( 0.00%) assert!(pos <= start); . start - pos . } 40 ( 0.00%) LazyState::Previous(last_pos) => { 40 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 120 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 346 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 865 ( 0.00%) } . 1,069 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 1,411 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 4,133 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 2,988 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 1,819 ( 0.00%) self.lazy_state = LazyState::NoNode; . 3,217 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 1,556 ( 0.00%) } . . fn encode_info_for_items(&mut self) { 9 ( 0.00%) self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module()); . . // Proc-macro crates only export proc-macro items, which are looked . // up using `proc_macro_data` 2 ( 0.00%) if self.is_proc_macro { . return; . } . 6 ( 0.00%) self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor()); . } . . fn encode_def_path_table(&mut self) { 4 ( 0.00%) let table = self.tcx.resolutions(()).definitions.def_path_table(); 2 ( 0.00%) if self.is_proc_macro { . for def_index in std::iter::once(CRATE_DEF_INDEX) . .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) . { . let def_key = self.lazy(table.def_key(def_index)); . let def_path_hash = self.lazy(table.def_path_hash(def_index)); . self.tables.def_keys.set(def_index, def_key); . self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } else { 5 ( 0.00%) for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { . let def_key = self.lazy(def_key); . let def_path_hash = self.lazy(def_path_hash); 392 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 392 ( 0.00%) self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } . } . . fn encode_def_path_hash_map(&mut self) -> Lazy> { . self.lazy(DefPathHashMapRef::BorrowedFromTcx( 2 ( 0.00%) self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), . )) . } . . fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { 2 ( 0.00%) let source_map = self.tcx.sess.source_map(); 3 ( 0.00%) let all_source_files = source_map.files(); . . // By replacing the `Option` with `None`, we ensure that we can't . // accidentally serialize any more `Span`s after the source map encoding . // is done. . let required_source_files = self.required_source_files.take().unwrap(); . . let adapted = all_source_files . .iter() . .enumerate() . .filter(|(idx, source_file)| { . // Only serialize `SourceFile`s that were used . // during the encoding of a `Span` 1,055 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 9 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 6 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 4 ( 0.00%) let mut adapted = (**source_file).clone(); 32 ( 0.00%) adapted.name = FileName::Real(match realname { . RealFileName::LocalPath(path_to_file) => { . // Prepend path of working directory onto potentially . // relative paths, because they could become relative . // to a wrong directory. . // We include `working_dir` as part of the crate hash, . // so it's okay for us to use it as part of the encoded . // metadata. 4 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 4 ( 0.00%) match working_dir { . RealFileName::LocalPath(absolute) => { . // Although neither working_dir or the file name were subject . // to path remapping, the concatenation between the two may . // be. Hence we need to do a remapping here. . let joined = Path::new(absolute).join(path_to_file); 14 ( 0.00%) let (joined, remapped) = 22 ( 0.00%) source_map.path_mapping().map_prefix(joined); 4 ( 0.00%) if remapped { . RealFileName::Remapped { . local_path: None, . virtual_name: joined, . } . } else { . RealFileName::LocalPath(joined) . } . } -- line 532 ---------------------------------------- -- line 544 ---------------------------------------- . RealFileName::Remapped { local_path: _, virtual_name } => { . RealFileName::Remapped { . // We do not want any local path to be exported into metadata . local_path: None, . virtual_name: virtual_name.clone(), . } . } . }); 4 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 2 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 2 ( 0.00%) Lrc::new(adapted) . } . . // expanded code, not from a file . _ => source_file.clone(), . }; . . // We're serializing this `SourceFile` into our crate metadata, . // so mark it as coming from this crate. . // This also ensures that we don't try to deserialize the . // `CrateNum` for a proc-macro dependency - since proc macro . // dependencies aren't loaded when we deserialize a proc-macro, . // trying to remap the `CrateNum` would fail. 4 ( 0.00%) if self.is_proc_macro { . Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; . } . adapted . }) . .collect::>(); . . self.lazy(adapted.iter().map(|rc| &**rc)) . } . 8 ( 0.00%) fn encode_crate_root(&mut self) -> Lazy> { . let mut i = self.position(); . . // Encode the crate deps . let crate_deps = self.encode_crate_deps(); . let dylib_dependency_formats = self.encode_dylib_dependency_formats(); 5 ( 0.00%) let dep_bytes = self.position() - i; . . // Encode the lib features. . i = self.position(); . let lib_features = self.encode_lib_features(); 7 ( 0.00%) let lib_feature_bytes = self.position() - i; . . // Encode the language items. . i = self.position(); . let lang_items = self.encode_lang_items(); . let lang_items_missing = self.encode_lang_items_missing(); 5 ( 0.00%) let lang_item_bytes = self.position() - i; . . // Encode the diagnostic items. . i = self.position(); . let diagnostic_items = self.encode_diagnostic_items(); 5 ( 0.00%) let diagnostic_item_bytes = self.position() - i; . . // Encode the native libraries used . i = self.position(); . let native_libraries = self.encode_native_libraries(); 4 ( 0.00%) let native_lib_bytes = self.position() - i; . . let foreign_modules = self.encode_foreign_modules(); . . // Encode DefPathTable . i = self.position(); . self.encode_def_path_table(); 5 ( 0.00%) let def_path_table_bytes = self.position() - i; . . // Encode the def IDs of traits, for rustdoc and diagnostics. . i = self.position(); . let traits = self.encode_traits(); 5 ( 0.00%) let traits_bytes = self.position() - i; . . // Encode the def IDs of impls, for coherence checking. . i = self.position(); . let impls = self.encode_impls(); 5 ( 0.00%) let impls_bytes = self.position() - i; . 3 ( 0.00%) let tcx = self.tcx; . . // Encode MIR. . i = self.position(); . self.encode_mir(); 5 ( 0.00%) let mir_bytes = self.position() - i; . . // Encode the items. . i = self.position(); . self.encode_def_ids(); . self.encode_info_for_items(); 4 ( 0.00%) let item_bytes = self.position() - i; . . // Encode the allocation index . let interpret_alloc_index = { . let mut interpret_alloc_index = Vec::new(); . let mut n = 0; . trace!("beginning to encode alloc ids"); . loop { . let new_n = self.interpret_allocs.len(); . // if we have found new ids, serialize those, too 4 ( 0.00%) if n == new_n { . // otherwise, abort . break; . } . trace!("encoding {} further alloc ids", new_n - n); . for idx in n..new_n { 28 ( 0.00%) let id = self.interpret_allocs[idx]; . let pos = self.position() as u32; . interpret_alloc_index.push(pos); 84 ( 0.00%) interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); . } . n = new_n; . } 6 ( 0.00%) self.lazy(interpret_alloc_index) . }; . . // Encode the proc macro data. This affects 'tables', . // so we need to do this before we encode the tables . i = self.position(); . let proc_macro_data = self.encode_proc_macros(); 4 ( 0.00%) let proc_macro_data_bytes = self.position() - i; . . i = self.position(); 4 ( 0.00%) let tables = self.tables.encode(&mut self.opaque); 4 ( 0.00%) let tables_bytes = self.position() - i; . . // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode . // this as late as possible to give the prefetching as much time as possible to complete. . i = self.position(); . let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); . let exported_symbols = self.encode_exported_symbols(&exported_symbols); 4 ( 0.00%) let exported_symbols_bytes = self.position() - i; . . // Encode the hygiene data, . // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process . // of encoding other items (e.g. `optimized_mir`) may cause us to load . // data from the incremental cache. If this causes us to deserialize a `Span`, . // then we may load additional `SyntaxContext`s into the global `HygieneData`. . // Therefore, we need to encode the hygiene data last to ensure that we encode . // any `SyntaxContext`s that might be used. . i = self.position(); . let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene(); 5 ( 0.00%) let hygiene_bytes = self.position() - i; . . i = self.position(); . let def_path_hash_map = self.encode_def_path_hash_map(); 1 ( 0.00%) let def_path_hash_map_bytes = self.position() - i; . . // Encode source_map. This needs to be done last, . // since encoding `Span`s tells us which `SourceFiles` we actually . // need to encode. . i = self.position(); . let source_map = self.encode_source_map(); 4 ( 0.00%) let source_map_bytes = self.position() - i; . 3 ( 0.00%) let attrs = tcx.hir().krate_attrs(); 7 ( 0.00%) let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); . 118 ( 0.00%) let root = self.lazy(CrateRoot { . name: tcx.crate_name(LOCAL_CRATE), 3 ( 0.00%) extra_filename: tcx.sess.opts.cg.extra_filename.clone(), 1 ( 0.00%) triple: tcx.sess.opts.target_triple.clone(), . hash: tcx.crate_hash(LOCAL_CRATE), . stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), 3 ( 0.00%) panic_strategy: tcx.sess.panic_strategy(), 3 ( 0.00%) panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop, 2 ( 0.00%) edition: tcx.sess.edition(), . has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), . has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), . has_default_lib_allocator, . proc_macro_data, 6 ( 0.00%) compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), 6 ( 0.00%) needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), 6 ( 0.00%) needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), 6 ( 0.00%) no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), 5 ( 0.00%) panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), 5 ( 0.00%) profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), 2 ( 0.00%) symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), . . crate_deps, . dylib_dependency_formats, . lib_features, . lang_items, . diagnostic_items, . lang_items_missing, . native_libraries, . foreign_modules, . source_map, . traits, . impls, . exported_symbols, . interpret_alloc_index, 2 ( 0.00%) tables, . syntax_contexts, . expn_data, . expn_hashes, . def_path_hash_map, . }); . 1 ( 0.00%) let total_bytes = self.position(); . 4 ( 0.00%) if tcx.sess.meta_stats() { . let mut zero_bytes = 0; . for e in self.opaque.data.iter() { . if *e == 0 { . zero_bytes += 1; . } . } . . eprintln!("metadata stats:"); -- line 756 ---------------------------------------- -- line 770 ---------------------------------------- . eprintln!(" item bytes: {}", item_bytes); . eprintln!(" table bytes: {}", tables_bytes); . eprintln!(" hygiene bytes: {}", hygiene_bytes); . eprintln!(" zero bytes: {}", zero_bytes); . eprintln!(" total bytes: {}", total_bytes); . } . . root 9 ( 0.00%) } . } . . fn should_encode_visibility(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Mod . | DefKind::Struct . | DefKind::Union . | DefKind::Enum -- line 786 ---------------------------------------- -- line 853 ---------------------------------------- . /// Whether we should encode MIR. . /// . /// Computing, optimizing and encoding the MIR is a relatively expensive operation. . /// We want to avoid this work when not required. Therefore: . /// - we only compute `mir_for_ctfe` on items with const-eval semantics; . /// - we skip `optimized_mir` for check runs. . /// . /// Return a pair, resp. for CTFE and for LLVM. 576 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 320 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { . let mir_opt_base = tcx.sess.opts.output_types.should_codegen() . || tcx.sess.opts.debugging_opts.always_encode_mir; . (true, mir_opt_base) . } . // Constants . DefKind::AnonConst . | DefKind::InlineConst . | DefKind::AssocConst . | DefKind::Static . | DefKind::Const => (true, false), . // Full-fledged functions . DefKind::AssocFn | DefKind::Fn => { . let generics = tcx.generics_of(def_id); 202 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 58 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 105 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 36 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 180 ( 0.00%) || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 72 ( 0.00%) (is_const_fn, needs_inline || always_encode_mir) . } . // Closures can't be const fn. . DefKind::Closure => { . let generics = tcx.generics_of(def_id); . let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) . && tcx.sess.opts.output_types.should_codegen(); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; . (false, needs_inline || always_encode_mir) . } . // Generators require optimized MIR to compute layout. . DefKind::Generator => (false, true), . // The others don't have MIR. . _ => (false, false), . } 576 ( 0.00%) } . . fn should_encode_variances(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Variant . | DefKind::Fn -- line 909 ---------------------------------------- -- line 969 ---------------------------------------- . | DefKind::LifetimeParam . | DefKind::GlobalAsm . | DefKind::ExternCrate => false, . } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_def_ids(&mut self) { 2 ( 0.00%) if self.is_proc_macro { . return; . } 1 ( 0.00%) let tcx = self.tcx; 3 ( 0.00%) let hir = tcx.hir(); 45 ( 0.00%) for local_id in hir.iter_local_def_id() { . let def_id = local_id.to_def_id(); . let def_kind = tcx.opt_def_kind(local_id); 588 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 1,568 ( 0.00%) record!(self.tables.def_kind[def_id] <- match def_kind { . // Replace Ctor by the enclosing object to avoid leaking details in children crates. . DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, . DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, . def_kind => def_kind, . }); 294 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 1,176 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 784 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 582 ( 0.00%) record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); . } . if should_encode_stability(def_kind) { . self.encode_stability(def_id); . self.encode_const_stability(def_id); 576 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 128 ( 0.00%) let v = self.tcx.variances_of(def_id); 448 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 376 ( 0.00%) record!(self.tables.generics[def_id] <- g); 1,128 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 94 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 94 ( 0.00%) if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 686 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { 14 ( 0.00%) record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); . } . } . let inherent_impls = tcx.crate_inherent_impls(()); . for (def_id, implementations) in inherent_impls.inherent_impls.iter() { . if implementations.is_empty() { . continue; . } . record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { . assert!(def_id.is_local()); . def_id.index . })); . } . } . 651 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 558 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 744 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; . let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . . let data = VariantData { -- line 1043 ---------------------------------------- -- line 1078 ---------------------------------------- . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . self.encode_item_type(def_id); . if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 20 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 4 ( 0.00%) let tcx = self.tcx; . let def_id = local_def_id.to_def_id(); . debug!("EncodeContext::encode_info_for_mod({:?})", def_id); . . // If we are encoding a proc-macro crates, `encode_info_for_mod` will . // only ever get called for the crate root. We still want to encode . // the crate root for consistency with other crates (some of the resolver . // code uses it). However, we skip encoding anything relating to child . // items - we encode information about proc-macros later on. 6 ( 0.00%) let reexports = if !self.is_proc_macro { 4 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 8 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 4 ( 0.00%) if self.is_proc_macro { . // Encode this here because we don't do it in encode_def_ids. . record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); . } else { . let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index); . // Foreign items are planted into their parent modules from name resolution point of view. 4 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 170 ( 0.00%) .filter_map(|item_id| match tcx.hir().item(*item_id).kind { . hir::ItemKind::ForeignMod { items, .. } => { . Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index)) . } . _ => None, . }) . .flatten(); . 14 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 16 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; -- line 1134 ---------------------------------------- -- line 1166 ---------------------------------------- . let bounds = self.tcx.explicit_item_bounds(def_id); . if !bounds.is_empty() { . record!(self.tables.explicit_item_bounds[def_id] <- bounds); . } . } . . fn encode_info_for_trait_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id); 35 ( 0.00%) let tcx = self.tcx; . 245 ( 0.00%) let ast_item = tcx.hir().expect_trait_item(def_id.expect_local()); . let trait_item = tcx.associated_item(def_id); . 175 ( 0.00%) let container = match trait_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, . hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, . hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), . }; . 210 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const => { . let rendered = rustc_hir_pretty::to_string( . &(&self.tcx.hir() as &dyn intravisit::Map<'_>), . |s| s.print_trait_item(ast_item), . ); . let rendered_const = self.lazy(RenderedConst(rendered)); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . Default::default(), . rendered_const, . )); . } . ty::AssocKind::Fn => { 70 ( 0.00%) let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { 70 ( 0.00%) let param_names = match *m { . hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names), 14 ( 0.00%) hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body), . }; . FnData { . asyncness: m_sig.header.asyncness, . constness: hir::Constness::NotConst, . param_names, . } . } else { . bug!() -- line 1211 ---------------------------------------- -- line 1217 ---------------------------------------- . }))); . } . ty::AssocKind::Type => { . self.encode_explicit_item_bounds(def_id); . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } . self.encode_ident_span(def_id, ast_item.ident); 105 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const | ty::AssocKind::Fn => { . self.encode_item_type(def_id); . } . ty::AssocKind::Type => { . if trait_item.defaultness.has_value() { . self.encode_item_type(def_id); . } . } . } 35 ( 0.00%) if trait_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_info_for_impl_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); 56 ( 0.00%) let tcx = self.tcx; . 168 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 28 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 112 ( 0.00%) let container = match impl_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, . hir::Defaultness::Final => AssocContainer::ImplFinal, . hir::Defaultness::Default { has_value: false } => { . span_bug!(ast_item.span, "impl items always have values (currently)") . } . }; . 168 ( 0.00%) match impl_item.kind { . ty::AssocKind::Const => { . if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { . let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . qualifs, . self.encode_rendered_const_for_body(body_id)) . ); . } else { . bug!() . } . } . ty::AssocKind::Fn => { 56 ( 0.00%) let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { . FnData { . asyncness: sig.header.asyncness, . // Can be inside `impl const Trait`, so using sig.header.constness is not reliable 28 ( 0.00%) constness: if self.tcx.is_const_fn_raw(def_id) { . hir::Constness::Const . } else { . hir::Constness::NotConst . }, . param_names: self.encode_fn_param_names_for_body(body), . } . } else { . bug!() -- line 1282 ---------------------------------------- -- line 1286 ---------------------------------------- . container, . has_self: impl_item.fn_has_self_parameter, . }))); . } . ty::AssocKind::Type => { . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } 84 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 140 ( 0.00%) self.encode_item_type(def_id); 112 ( 0.00%) if let Some(trait_item_def_id) = impl_item.trait_item_def_id { . record!(self.tables.trait_item_def_id[def_id] <- trait_item_def_id); . } 28 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 8 ( 0.00%) fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 236 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) 8 ( 0.00%) } . . fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { . self.lazy(param_names.iter()) . } . . fn encode_mir(&mut self) { 3 ( 0.00%) if self.is_proc_macro { . return; . } . . let keys_and_jobs = self . .tcx . .mir_keys(()) . .iter() . .filter_map(|&def_id| { 320 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 381 ( 0.00%) if encode_const || encode_opt { 126 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 128 ( 0.00%) }) . .collect::>(); 320 ( 0.00%) for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { . debug_assert!(encode_const || encode_opt); . . debug!("EntryBuilder::encode_mir({:?})", def_id); 63 ( 0.00%) if encode_opt { 140 ( 0.00%) record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 63 ( 0.00%) if encode_const { 112 ( 0.00%) record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); . . // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir` 28 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 112 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 252 ( 0.00%) record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); . . let instance = . ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); 63 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 63 ( 0.00%) if !unused.is_empty() { . record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); . } . } . } . . fn encode_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 768 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_stability(def_id) { . record!(self.tables.stability[def_id] <- stab) . } . } . } . . fn encode_const_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_const_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 672 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_const_stability(def_id) { . record!(self.tables.const_stability[def_id] <- stab) . } . } . } . 576 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 480 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 480 ( 0.00%) } . . fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { . let hir = self.tcx.hir(); . let body = hir.body(body_id); . let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { . s.print_expr(&body.value) . }); . let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) . } . 288 ( 0.00%) fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { . let tcx = self.tcx; . . debug!("EncodeContext::encode_info_for_item({:?})", def_id); . . self.encode_ident_span(def_id, item.ident); . 248 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, . hir::ItemKind::Const(_, body_id) => { . let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); . EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } 2 ( 0.00%) hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { 1 ( 0.00%) asyncness: sig.header.asyncness, 1 ( 0.00%) constness: sig.header.constness, 2 ( 0.00%) param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } . hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 12 ( 0.00%) return self.encode_info_for_mod(item.def_id, m); . } . hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, . hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, . hir::ItemKind::TyAlias(..) => EntryKind::Type, . hir::ItemKind::OpaqueTy(..) => { . self.encode_explicit_item_bounds(def_id); . EntryKind::OpaqueTy . } -- line 1433 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 4 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 4 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 2 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 2 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 1 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 6 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 6 ( 0.00%) an.nth(1).and_then(|node| match node { . specialization_graph::Node::Impl(parent) => Some(parent), . _ => None, . }) . }) . } else { . None . }; . . // if this is an impl of `CoerceUnsized`, create its . // "unsized info", else just store None . let coerce_unsized_info = trait_ref.and_then(|t| { 6 ( 0.00%) if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { . Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) . } else { . None . } . }); . . let data = ImplData { . polarity, -- line 1496 ---------------------------------------- -- line 1498 ---------------------------------------- . constness, . parent_impl: parent, . coerce_unsized_info, . }; . . EntryKind::Impl(self.lazy(data)) . } . hir::ItemKind::Trait(..) => { 2 ( 0.00%) let trait_def = self.tcx.trait_def(def_id); . let data = TraitData { 1 ( 0.00%) unsafety: trait_def.unsafety, 2 ( 0.00%) paren_sugar: trait_def.paren_sugar, 5 ( 0.00%) has_auto_impl: self.tcx.trait_is_auto(def_id), 1 ( 0.00%) is_marker: trait_def.is_marker, 1 ( 0.00%) skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, 1 ( 0.00%) specialization_kind: trait_def.specialization_kind, . must_implement_one_of: trait_def.must_implement_one_of.clone(), . }; . . EntryKind::Trait(self.lazy(data)) . } . hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { . bug!("cannot encode info for item {:?}", item) . } . }; . record!(self.tables.kind[def_id] <- entry_kind); . // FIXME(eddyb) there should be a nicer way to do this. 155 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).variants.iter().map(|v| { . assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { . assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 4 ( 0.00%) let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); . record!(self.tables.children[def_id] <- . associated_item_def_ids.iter().map(|&def_id| { 63 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 64 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) 120 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 92 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { 4 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 63 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 5 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 5 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 248 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { . record!(self.tables.kind[def_id] <- kind); . if encode_type { . self.encode_item_type(def_id); . } . } . -- line 1580 ---------------------------------------- -- line 1611 ---------------------------------------- . let const_data = self.encode_rendered_const_for_body(body_id); . let qualifs = self.tcx.mir_const_qualif(def_id); . . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); . self.encode_item_type(def_id.to_def_id()); . } . . fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); . self.lazy(used_libraries.iter()) . } . . fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { 5 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); . self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) . } . . fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) { . let mut syntax_contexts: TableBuilder<_, _> = Default::default(); . let mut expn_data_table: TableBuilder<_, _> = Default::default(); . let mut expn_hash_table: TableBuilder<_, _> = Default::default(); . 2 ( 0.00%) let _: Result<(), !> = self.hygiene_ctxt.encode( 8 ( 0.00%) &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table), . |(this, syntax_contexts, _, _), index, ctxt_data| { . syntax_contexts.set(index, this.lazy(ctxt_data)); . Ok(()) . }, . |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| { . if let Some(index) = index.as_local() { 4 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 4 ( 0.00%) expn_hash_table.set(index.as_raw(), this.lazy(hash)); . } . Ok(()) . }, . ); . . ( . syntax_contexts.encode(&mut self.opaque), . expn_data_table.encode(&mut self.opaque), . expn_hash_table.encode(&mut self.opaque), . ) . } . . fn encode_proc_macros(&mut self) -> Option { 6 ( 0.00%) let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); . if is_proc_macro { . let tcx = self.tcx; . let hir = tcx.hir(); . . let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; . let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); . let macros = . self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); -- line 1666 ---------------------------------------- -- line 1725 ---------------------------------------- . . Some(ProcMacroData { proc_macro_decls_static, stability, macros }) . } else { . None . } . } . . fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { 7 ( 0.00%) empty_proc_macro!(self); . 1 ( 0.00%) let deps = self . .tcx . .crates(()) . .iter() . .map(|&cnum| { . let dep = CrateDep { 19 ( 0.00%) name: self.tcx.crate_name(cnum), 19 ( 0.00%) hash: self.tcx.crate_hash(cnum), 19 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 19 ( 0.00%) kind: self.tcx.dep_kind(cnum), 19 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 95 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 38 ( 0.00%) for &(n, _) in &deps { 48 ( 0.00%) assert_eq!(n, CrateNum::new(expected_cnum)); . expected_cnum += 1; . } . } . . // We're just going to write a list of crate 'name-hash-version's, with . // the assumption that they are numbered 1 to n. . // FIXME (#2166): This is not nearly enough to support correct versioning . // but is enough to get transitive crate dependencies working. . self.lazy(deps.iter().map(|&(_, ref dep)| dep)) . } . . fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option)]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let lib_features = tcx.lib_features(()); 2 ( 0.00%) self.lazy(lib_features.to_vec()) . } . . fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id; . self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) . } . . fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { 4 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) let lang_items = tcx.lang_items(); 2 ( 0.00%) let lang_items = lang_items.items().iter(); . self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { 568 ( 0.00%) if let Some(def_id) = opt_def_id { . if def_id.is_local() { . return Some((def_id.index, i)); . } . } . None . })) . } . . fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) self.lazy(&tcx.lang_items().missing) . } . . fn encode_traits(&mut self) -> Lazy<[DefIndex]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index)) . } . . /// Encodes an index, mapping each trait to its (local) implementations. . fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { . debug!("EncodeContext::encode_traits_and_impls()"); 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let tcx = self.tcx; 5 ( 0.00%) let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() }; 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . . let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); . . // Bring everything into deterministic order for hashing . all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() 15 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing . impls.sort_by_cached_key(|&(index, _)| { . tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 4 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 3 ( 0.00%) impls: self.lazy(&impls), . } 8 ( 0.00%) }) . .collect(); . . self.lazy(&all_impls) . } . . // Encodes all symbols exported from this crate into the metadata. . // . // This pass is seeded off the reachability list calculated in the . // middle::reachable module but filters out items that either don't have a . // symbol associated with them (they weren't translated) or if they're an FFI . // definition (as that's not defined in this crate). . fn encode_exported_symbols( . &mut self, . exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], . ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { 2 ( 0.00%) empty_proc_macro!(self); . // The metadata symbol name is special. It should not show up in . // downstream crates. 9 ( 0.00%) let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); . . self.lazy( . exported_symbols . .iter() 74 ( 0.00%) .filter(|&&(ref exported_symbol, _)| match *exported_symbol { . ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, . _ => true, . }) . .cloned(), . ) . } . . fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let formats = self.tcx.dependency_formats(()); 4 ( 0.00%) for (ty, arr) in formats.iter() { 2 ( 0.00%) if *ty != CrateType::Dylib { . continue; . } . return self.lazy(arr.iter().map(|slot| match *slot { . Linkage::NotLinked | Linkage::IncludedFromDylib => None, . . Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), . Linkage::Static => Some(LinkagePreference::RequireStatic), . })); -- line 1876 ---------------------------------------- -- line 1914 ---------------------------------------- . } . } . . // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. . impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 64 ( 0.00%) self.tcx.hir() . } 265,815 ( 0.03%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 29,535 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 236,280 ( 0.02%) } . fn visit_anon_const(&mut self, c: &'tcx AnonConst) { . intravisit::walk_anon_const(self, c); . self.encode_info_for_anon_const(c.hir_id); . } . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 102 ( 0.00%) intravisit::walk_item(self, item); 68 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 128 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 136 ( 0.00%) self.encode_addl_info_for_item(item); . } . fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { . intravisit::walk_foreign_item(self, ni); . self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); . } 594 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 528 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_fields(&mut self, adt_def: &ty::AdtDef) { . for (variant_index, variant) in adt_def.variants.iter_enumerated() { . for (field_index, _field) in variant.fields.iter().enumerate() { . self.encode_field(adt_def, variant_index, field_index); . } -- line 1955 ---------------------------------------- -- line 1975 ---------------------------------------- . record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) . } . } . } . } . } . . fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { 59,070 ( 0.01%) if let hir::ExprKind::Closure(..) = expr.kind { . self.encode_info_for_closure(expr.hir_id); . } . } . . fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { . record!(self.tables.ident_span[def_id] <- ident.span); . } . . /// In some cases, along with the item itself, we also . /// encode some sub-items. Usually we want some info from the item . /// so it's easier to do that here then to wait until we would encounter . /// normally in the visitor walk. 306 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 170 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::Macro(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::ForeignMod { .. } . | hir::ItemKind::GlobalAsm(..) . | hir::ItemKind::ExternCrate(..) -- line 2005 ---------------------------------------- -- line 2031 ---------------------------------------- . self.encode_struct_ctor(def, ctor_def_id.to_def_id()); . } . } . hir::ItemKind::Union(..) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . } . hir::ItemKind::Impl { .. } => { 112 ( 0.00%) for &trait_item_def_id in 1 ( 0.00%) self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_impl_item(trait_item_def_id); . } . } . hir::ItemKind::Trait(..) => { 106 ( 0.00%) for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_trait_item(item_def_id); . } . } . } 272 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 238 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 68 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 4 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 6 ( 0.00%) let simplified_self_ty = fast_reject::simplify_type( . self.tcx, . trait_ref.self_ty(), . SimplifyParams::No, . StripReferences::No, . ); . . self.impls . .entry(trait_ref.def_id) . .or_default() . .push((item.def_id.local_def_index, simplified_self_ty)); . } . } . _ => {} . } 272 ( 0.00%) } . . fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} . . fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { . // handled in `visit_item` above . } . . fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} -- line 2088 ---------------------------------------- -- line 2146 ---------------------------------------- . } . . #[inline] . pub fn raw_data(&self) -> &[u8] { . &self.raw_data . } . } . 10 ( 0.00%) pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { 5 ( 0.00%) let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata"); . . // Since encoding metadata is not in a query, and nothing is cached, . // there's no need to do dep-graph tracking for any of it. . tcx.dep_graph.assert_ignored(); . 7 ( 0.00%) join( 3 ( 0.00%) || encode_metadata_impl(tcx), . || { 5 ( 0.00%) if tcx.sess.threads() == 1 { . return; . } . // Prefetch some queries used by metadata encoding. . // This is not necessary for correctness, but is only done for performance reasons. . // It can be removed if it turns out to cause trouble or be detrimental to performance. . join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); . }, . ) . .0 9 ( 0.00%) } . 9 ( 0.00%) fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { 1 ( 0.00%) let mut encoder = opaque::Encoder::new(vec![]); . encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); . . // Will be filled with the root position after encoding everything. . encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); . 2 ( 0.00%) let source_map_files = tcx.sess.source_map().files(); 3 ( 0.00%) let source_file_cache = (source_map_files[0].clone(), 0); 2 ( 0.00%) let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); . drop(source_map_files); . . let hygiene_ctxt = HygieneEncodeContext::default(); . 35 ( 0.00%) let mut ecx = EncodeContext { 4 ( 0.00%) opaque: encoder, . tcx, 2 ( 0.00%) feat: tcx.features(), . tables: Default::default(), . lazy_state: LazyState::NoNode, . type_shorthands: Default::default(), . predicate_shorthands: Default::default(), 4 ( 0.00%) source_file_cache, . interpret_allocs: Default::default(), 4 ( 0.00%) required_source_files, 2 ( 0.00%) is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), . hygiene_ctxt: &hygiene_ctxt, . }; . . // Encode the rustc version string in a predictable location. . rustc_version().encode(&mut ecx).unwrap(); . . // Encode all the entries and extra information in the crate, . // culminating in the `CrateRoot` which points to all of it. 1 ( 0.00%) let root = ecx.encode_crate_root(); . 7 ( 0.00%) let mut result = ecx.opaque.into_inner(); . . // Encode the root position. . let header = METADATA_HEADER.len(); . let pos = root.position.get(); 3 ( 0.00%) result[header + 0] = (pos >> 24) as u8; 3 ( 0.00%) result[header + 1] = (pos >> 16) as u8; 1 ( 0.00%) result[header + 2] = (pos >> 8) as u8; 5 ( 0.00%) result[header + 3] = (pos >> 0) as u8; . . // Record metadata size for self-profiling . tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64); . 5 ( 0.00%) EncodedMetadata { raw_data: result } 12 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { . traits_in_crate: |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . 1 ( 0.00%) #[derive(Default)] . struct TraitsVisitor { . traits: Vec, . } . impl ItemLikeVisitor<'_> for TraitsVisitor { . fn visit_item(&mut self, item: &hir::Item<'_>) { 136 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { 1 ( 0.00%) self.traits.push(item.def_id.to_def_id()); . } . } . fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {} . fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {} . fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {} . } . . let mut visitor = TraitsVisitor::default(); 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . // Bring everything into deterministic order. . visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } -- line 2257 ---------------------------------------- 69,118 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_query_system/src/query/plumbing.rs -------------------------------------------------------------------------------- Ir -- line 43 ---------------------------------------- . pub(super) key_hash: u64, . shard: usize, . } . . // We compute the key's hash once and then use it for both the . // shard lookup and the hashmap lookup. This relies on the fact . // that both of them use `FxHasher`. . fn hash_for_shard(key: &K) -> u64 { 88,959 ( 0.01%) let mut hasher = FxHasher::default(); 289 ( 0.00%) key.hash(&mut hasher); 34 ( 0.00%) hasher.finish() . } . . impl QueryCacheStore { 126 ( 0.00%) pub(super) fn get_lookup<'tcx>( . &'tcx self, . key: &C::Key, . ) -> (QueryLookup, LockGuard<'tcx, C::Sharded>) { . let key_hash = hash_for_shard(key); . let shard = get_shard_index_by_hash(key_hash); . let lock = self.shards.get_shard_by_index(shard).lock(); 468 ( 0.00%) (QueryLookup { key_hash, shard }, lock) 355 ( 0.00%) } . . pub fn iter_results(&self, f: &mut dyn FnMut(&C::Key, &C::Value, DepNodeIndex)) { . self.cache.iter(&self.shards, f) . } . } . . struct QueryStateShard { . active: FxHashMap>, -- line 73 ---------------------------------------- -- line 190 ---------------------------------------- . ) -> TryGetJob<'b, CTX::DepKind, K> . where . CTX: QueryContext, . { . let shard = lookup.shard; . let mut state_lock = state.shards.get_shard_by_index(shard).lock(); . let lock = &mut *state_lock; . 76,578 ( 0.01%) match lock.active.entry(key) { . Entry::Vacant(entry) => { . // Generate an id unique within this shard. 37,536 ( 0.00%) let id = lock.jobs.checked_add(1).unwrap(); 37,536 ( 0.00%) lock.jobs = id; . let id = QueryShardJobId(NonZeroU32::new(id).unwrap()); . . let job = tcx.current_query_job(); . let job = QueryJob::new(id, span, job); . . let key = entry.key().clone(); . entry.insert(QueryResult::Started(job)); . . let global_id = QueryJobId::new(id, shard, dep_kind); . let owner = JobOwner { state, id: global_id, key }; 89,398 ( 0.01%) return TryGetJob::NotYetStarted(owner); . } . Entry::Occupied(mut entry) => { . match entry.get_mut() { . #[cfg(not(parallel_compiler))] . QueryResult::Started(job) => { . let id = QueryJobId::new(job.id, shard, dep_kind); . . drop(state_lock); -- line 221 ---------------------------------------- -- line 262 ---------------------------------------- . cache: &QueryCacheStore, . result: C::Value, . dep_node_index: DepNodeIndex, . ) -> C::Stored . where . C: QueryCache, . { . // We can move out of `self` here because we `mem::forget` it below 9,524 ( 0.00%) let key = unsafe { ptr::read(&self.key) }; . let state = self.state; . . // Forget ourself so our destructor won't poison the query . mem::forget(self); . 451 ( 0.00%) let (job, result) = { . let key_hash = hash_for_shard(&key); . let shard = get_shard_index_by_hash(key_hash); . let job = { . let mut lock = state.shards.get_shard_by_index(shard).lock(); 3 ( 0.00%) match lock.active.remove(&key).unwrap() { . QueryResult::Started(job) => job, . QueryResult::Poisoned => panic!(), . } . }; . let result = { . let mut lock = cache.shards.get_shard_by_index(shard).lock(); 15,685 ( 0.00%) cache.cache.complete(&mut lock, key, result, dep_node_index) . }; 258 ( 0.00%) (job, result) . }; . . job.signal_complete(); . result . } . } . . impl<'tcx, D, K> Drop for JobOwner<'tcx, D, K> -- line 298 ---------------------------------------- -- line 347 ---------------------------------------- . Cycle(CycleError), . } . . /// Checks if the query is already computed and in the cache. . /// It returns the shard index and a lock guard to the shard, . /// which will be used if the query is not in the cache and we need . /// to compute it. . #[inline] 43,839 ( 0.00%) pub fn try_get_cached<'a, CTX, C, R, OnHit>( . tcx: CTX, . cache: &'a QueryCacheStore, . key: &C::Key, . // `on_hit` can be called while holding a lock to the query cache . on_hit: OnHit, . ) -> Result . where . C: QueryCache, . CTX: DepContext, . OnHit: FnOnce(&C::Stored) -> R, . { . cache.cache.lookup(cache, &key, |value, index| { 433,615 ( 0.05%) if unlikely!(tcx.profiler().enabled()) { . tcx.profiler().query_cache_hit(index.into()); . } . tcx.dep_graph().read_index(index); 344,494 ( 0.04%) on_hit(value) . }) 49,096 ( 0.01%) } . 68,853 ( 0.01%) fn try_execute_query( . tcx: CTX, . state: &QueryState, . cache: &QueryCacheStore, . span: Span, . key: C::Key, . lookup: QueryLookup, . dep_node: Option>, . query: &QueryVtable, -- line 384 ---------------------------------------- -- line 391 ---------------------------------------- . match JobOwner::<'_, CTX::DepKind, C::Key>::try_start( . &tcx, . state, . span, . key.clone(), . lookup, . query.dep_kind, . ) { 182,506 ( 0.02%) TryGetJob::NotYetStarted(job) => { 420,563 ( 0.04%) let (result, dep_node_index) = execute_job(tcx, key, dep_node, query, job.id); 7,403 ( 0.00%) let result = job.complete(cache, result, dep_node_index); 99,815 ( 0.01%) (result, Some(dep_node_index)) . } . TryGetJob::Cycle(error) => { . let result = mk_cycle(tcx, error, query.handle_cycle_error, &cache.cache); . (result, None) . } . #[cfg(parallel_compiler)] . TryGetJob::JobCompleted(query_blocked_prof_timer) => { . let (v, index) = cache -- line 410 ---------------------------------------- -- line 415 ---------------------------------------- . if unlikely!(tcx.dep_context().profiler().enabled()) { . tcx.dep_context().profiler().query_cache_hit(index.into()); . } . query_blocked_prof_timer.finish_with_query_invocation_id(index.into()); . . (v, Some(index)) . } . } 72,075 ( 0.01%) } . . fn execute_job( . tcx: CTX, . key: K, . mut dep_node_opt: Option>, . query: &QueryVtable, . job_id: QueryJobId, . ) -> (V, DepNodeIndex) -- line 431 ---------------------------------------- -- line 432 ---------------------------------------- . where . K: Clone + DepNodeParams, . V: Debug, . CTX: QueryContext, . { . let dep_graph = tcx.dep_context().dep_graph(); . . // Fast path for when incr. comp. is off. 37,536 ( 0.00%) if !dep_graph.is_fully_enabled() { . let prof_timer = tcx.dep_context().profiler().query_provider(); 39,150 ( 0.00%) let result = tcx.start_query(job_id, None, || query.compute(*tcx.dep_context(), key)); . let dep_node_index = dep_graph.next_virtual_depnode_index(); . prof_timer.finish_with_query_invocation_id(dep_node_index.into()); 15,793 ( 0.00%) return (result, dep_node_index); . } . . if !query.anon && !query.eval_always { . // `to_dep_node` is expensive for some `DepKind`s. . let dep_node = . dep_node_opt.get_or_insert_with(|| query.to_dep_node(*tcx.dep_context(), &key)); . . // The diagnostics for this query will be promoted to the current session during -- line 453 ---------------------------------------- -- line 691 ---------------------------------------- . /// Executing `query::ensure(D)` is considered a read of the dep-node `D`. . /// Returns true if the query should still run. . /// . /// This function is particularly useful when executing passes for their . /// side-effects -- e.g., in order to report errors for erroneous programs. . /// . /// Note: The optimization is only available during incr. comp. . #[inline(never)] 7,128 ( 0.00%) fn ensure_must_run( . tcx: CTX, . key: &K, . query: &QueryVtable, . ) -> (bool, Option>) . where . K: crate::dep_graph::DepNodeParams, . CTX: QueryContext, . { 1,782 ( 0.00%) if query.eval_always { 4 ( 0.00%) return (true, None); . } . . // Ensuring an anonymous query makes no sense 1,778 ( 0.00%) assert!(!query.anon); . . let dep_node = query.to_dep_node(*tcx.dep_context(), key); . . let dep_graph = tcx.dep_context().dep_graph(); 4,975 ( 0.00%) match dep_graph.try_mark_green(tcx, &dep_node) { . None => { . // A None return from `try_mark_green` means that this is either . // a new dep node or that the dep node has already been marked red. . // Either way, we can't call `dep_graph.read()` as we don't have the . // DepNodeIndex. We must invoke the query itself. The performance cost . // this introduces should be negligible as we'll immediately hit the . // in-memory cache, or another query down the line will. 5,334 ( 0.00%) (true, Some(dep_node)) . } . Some((_, dep_node_index)) => { . dep_graph.read_index(dep_node_index); . tcx.dep_context().profiler().query_cache_hit(dep_node_index.into()); . (false, None) . } . } 7,128 ( 0.00%) } . . pub enum QueryMode { . Get, . Ensure, . } . 444,253 ( 0.05%) pub fn get_query( . tcx: CTX, . span: Span, . key: Q::Key, . lookup: QueryLookup, . mode: QueryMode, . ) -> Option . where . Q: QueryDescription, . Q::Key: DepNodeParams, . CTX: QueryContext, . { . let query = Q::make_vtable(tcx, &key); 104,711 ( 0.01%) let dep_node = if let QueryMode::Ensure = mode { 8,325 ( 0.00%) let (must_run, dep_node) = ensure_must_run(tcx, &key, &query); 891 ( 0.00%) if !must_run { . return None; . } 1,846 ( 0.00%) dep_node . } else { . None . }; . . debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span); 104,145 ( 0.01%) let (result, dep_node_index) = try_execute_query( . tcx, . Q::query_state(tcx), . Q::query_cache(tcx), . span, 119,421 ( 0.01%) key, . lookup, 30,826 ( 0.00%) dep_node, . &query, . ); 75,072 ( 0.01%) if let Some(dep_node_index) = dep_node_index { . tcx.dep_context().dep_graph().read_index(dep_node_index) . } 8,734 ( 0.00%) Some(result) 455,492 ( 0.05%) } . . pub fn force_query(tcx: CTX, key: Q::Key, dep_node: DepNode) . where . Q: QueryDescription, . Q::Key: DepNodeParams, . CTX: QueryContext, . { . // We may be concurrently trying both execute and force a query. -- line 787 ---------------------------------------- 454,824 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs -------------------------------------------------------------------------------- Ir -- line 4 ---------------------------------------- . . use super::Utf8Error; . . /// Returns the initial codepoint accumulator for the first byte. . /// The first byte is special, only want bottom 5 bits for width 2, 4 bits . /// for width 3, and 3 bits for width 4. . #[inline] . const fn utf8_first_byte(byte: u8, width: u32) -> u32 { 18 ( 0.00%) (byte & (0x7F >> width)) as u32 . } . . /// Returns the value of `ch` updated with continuation byte `byte`. . #[inline] . const fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { 30 ( 0.00%) (ch << 6) | (byte & CONT_MASK) as u32 . } . . /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the . /// bits `10`). . #[inline] . pub(super) const fn utf8_is_cont_byte(byte: u8) -> bool { 438 ( 0.00%) (byte as i8) < -64 . } . . /// Reads the next code point out of a byte iterator (assuming a . /// UTF-8-like encoding). . /// . /// # Safety . /// . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[unstable(feature = "str_internals", issue = "none")] . #[inline] . pub unsafe fn next_code_point<'a, I: Iterator>(bytes: &mut I) -> Option { . // Decode UTF-8 1,597,260 ( 0.17%) let x = *bytes.next()?; 2,816,532 ( 0.30%) if x < 128 { 58,526 ( 0.01%) return Some(x as u32); . } . . // Multibyte case follows . // Decode from a byte combination out of: [[[x y] z] w] . // NOTE: Performance is sensitive to the exact formulation here . let init = utf8_first_byte(x, 2); . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let y = unsafe { *bytes.next().unwrap_unchecked() }; . let mut ch = utf8_acc_cont_byte(init, y); 36 ( 0.00%) if x >= 0xE0 { . // [[x y z] w] case . // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let z = unsafe { *bytes.next().unwrap_unchecked() }; . let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z); . ch = init << 12 | y_z; 16 ( 0.00%) if x >= 0xF0 { . // [x y z w] case . // use only the lower 3 bits of `init` . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let w = unsafe { *bytes.next().unwrap_unchecked() }; . ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w); . } . } -- line 67 ---------------------------------------- -- line 77 ---------------------------------------- . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[inline] . pub(super) unsafe fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option . where . I: DoubleEndedIterator, . { . // Decode UTF-8 . let w = match *bytes.next_back()? { 645 ( 0.00%) next_byte if next_byte < 128 => return Some(next_byte as u32), . back_byte => back_byte, . }; . . // Multibyte case follows . // Decode from a byte combination out of: [x [y [z w]]] . let mut ch; . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. -- line 93 ---------------------------------------- -- line 113 ---------------------------------------- . } . . // use truncation to fit u64 into usize . const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize; . . /// Returns `true` if any byte in the word `x` is nonascii (>= 128). . #[inline] . const fn contains_nonascii(x: usize) -> bool { 25,413 ( 0.00%) (x & NONASCII_MASK) != 0 . } . . /// Walks through `v` checking that it's a valid UTF-8 sequence, . /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`. . #[inline(always)] . #[rustc_const_unstable(feature = "str_internals", issue = "none")] . pub(super) const fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { . let mut index = 0; . let len = v.len(); . . let usize_bytes = mem::size_of::(); . let ascii_block_size = 2 * usize_bytes; 711 ( 0.00%) let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 }; . let align = v.as_ptr().align_offset(usize_bytes); . 926 ( 0.00%) while index < len { . let old_offset = index; . macro_rules! err { . ($error_len: expr) => { . return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len }) . }; . } . . macro_rules! next { -- line 145 ---------------------------------------- -- line 148 ---------------------------------------- . // we needed data, but there was none: error! . if index >= len { . err!(None) . } . v[index] . }}; . } . 423 ( 0.00%) let first = v[index]; 846 ( 0.00%) if first >= 128 { . let w = utf8_char_width(first); . // 2-byte encoding is for codepoints \u{0080} to \u{07ff} . // first C2 80 last DF BF . // 3-byte encoding is for codepoints \u{0800} to \u{ffff} . // first E0 A0 80 last EF BF BF . // excluding surrogates codepoints \u{d800} to \u{dfff} . // ED A0 80 to ED BF BF . // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff -- line 165 ---------------------------------------- -- line 169 ---------------------------------------- . // . // https://tools.ietf.org/html/rfc3629 . // UTF8-1 = %x00-7F . // UTF8-2 = %xC2-DF UTF8-tail . // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / . // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) . // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / . // %xF4 %x80-8F 2( UTF8-tail ) 16 ( 0.00%) match w { . 2 => { 10 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(1)) . } . } . 3 => { 8 ( 0.00%) match (first, next!()) { . (0xE0, 0xA0..=0xBF) 7 ( 0.00%) | (0xE1..=0xEC, 0x80..=0xBF) . | (0xED, 0x80..=0x9F) . | (0xEE..=0xEF, 0x80..=0xBF) => {} . _ => err!(Some(1)), . } 5 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(2)) . } . } . 4 => { . match (first, next!()) { . (0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {} . _ => err!(Some(1)), . } -- line 199 ---------------------------------------- -- line 201 ---------------------------------------- . err!(Some(2)) . } . if next!() as i8 >= -64 { . err!(Some(3)) . } . } . _ => err!(Some(1)), . } 9 ( 0.00%) index += 1; . } else { . // Ascii case, try to skip forward quickly. . // When the pointer is aligned, read 2 words of data per iteration . // until we find a word containing a non-ascii byte. 1,472 ( 0.00%) if align != usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 { . let ptr = v.as_ptr(); 51,244 ( 0.01%) while index < blocks_end { . // SAFETY: since `align - index` and `ascii_block_size` are . // multiples of `usize_bytes`, `block = ptr.add(index)` is . // always aligned with a `usize` so it's safe to dereference . // both `block` and `block.offset(1)`. . unsafe { . let block = ptr.add(index) as *const usize; . // break if there is a nonascii byte 25,413 ( 0.00%) let zu = contains_nonascii(*block); . let zv = contains_nonascii(*block.offset(1)); 50,826 ( 0.01%) if zu || zv { . break; . } . } 50,820 ( 0.01%) index += ascii_block_size; . } . // step from the point where the wordwise loop stopped 7,991 ( 0.00%) while index < len && v[index] < 128 { 1,741 ( 0.00%) index += 1; . } . } else { 208 ( 0.00%) index += 1; . } . } . } . . Ok(()) . } . . // https://tools.ietf.org/html/rfc3629 -- line 245 ---------------------------------------- -- line 263 ---------------------------------------- . 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F . ]; . . /// Given a first byte, determines how many bytes are in this UTF-8 character. . #[unstable(feature = "str_internals", issue = "none")] . #[must_use] . #[inline] . pub const fn utf8_char_width(b: u8) -> usize { 6 ( 0.00%) UTF8_CHAR_WIDTH[b as usize] as usize . } . . /// Mask of the value bits of a continuation byte. . const CONT_MASK: u8 = 0b0011_1111; . . // truncate `&str` to length at most equal to `max` . // return `true` if it were truncated, and the new str. . pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) { -- line 279 ---------------------------------------- 106,092 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . #[derive(Debug)] . pub struct Token { . pub kind: TokenKind, . pub len: usize, . } . . impl Token { . fn new(kind: TokenKind, len: usize) -> Token { 814,959 ( 0.09%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 6,570 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] . pub enum TokenKind { . // Multi-char tokens: . /// "// comment" . LineComment { doc_style: Option }, . /// `/* block comment */` . /// . /// Block comments can be recursive, so the sequence like `/* /* */` . /// will not be considered terminated and will result in a parsing error. -- line 60 ---------------------------------------- -- line 192 ---------------------------------------- . /// Literal starts with "0x". . Hexadecimal, . /// Literal doesn't contain a prefix. . Decimal, . } . . /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", . /// but shebang isn't a part of rust syntax. 14 ( 0.00%) pub fn strip_shebang(input: &str) -> Option { . // Shebang must start with `#!` literally, without any preceding whitespace. . // For simplicity we consider any line starting with `#!` a shebang, . // regardless of restrictions put on shebangs by specific platforms. . if let Some(input_tail) = input.strip_prefix("#!") { . // Ok, this is a shebang but if the next non-whitespace token is `[`, . // then it may be valid Rust code, so consider it Rust code. . let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { . !matches!( -- line 208 ---------------------------------------- -- line 213 ---------------------------------------- . ) . }); . if next_non_whitespace_token != Some(TokenKind::OpenBracket) { . // No other choice than to consider this a shebang. . return Some(2 + input_tail.lines().next().unwrap_or_default().len()); . } . } . None 16 ( 0.00%) } . . /// Parses the first token from the provided input string. 271,653 ( 0.03%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 90,551 ( 0.01%) Cursor::new(input).advance_token() 362,204 ( 0.04%) } . . /// Creates an iterator that produces tokens from the input string. . pub fn tokenize(input: &str) -> impl Iterator + '_ { . let mut cursor = Cursor::new(input); . std::iter::from_fn(move || { . if cursor.is_eof() { . None . } else { -- line 235 ---------------------------------------- -- line 243 ---------------------------------------- . /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) . /// for definitions of these classes. . pub fn is_whitespace(c: char) -> bool { . // This is Pattern_White_Space. . // . // Note that this set is stable (ie, it doesn't change with different . // Unicode versions), so it's ok to just hard-code the values. . 153,680 ( 0.02%) matches!( . c, . // Usual ASCII suspects . '\u{0009}' // \t . | '\u{000A}' // \n . | '\u{000B}' // vertical tab . | '\u{000C}' // form feed . | '\u{000D}' // \r . | '\u{0020}' // space -- line 259 ---------------------------------------- -- line 271 ---------------------------------------- . ) . } . . /// True if `c` is valid as a first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_start(c: char) -> bool { . // This is XID_Start OR '_' (which formally is not a XID_Start). 117,012 ( 0.01%) c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) . } . . /// True if `c` is valid as a non-first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_continue(c: char) -> bool { . unicode_xid::UnicodeXID::is_xid_continue(c) . } -- line 287 ---------------------------------------- -- line 293 ---------------------------------------- . is_id_start(start) && chars.all(is_id_continue) . } else { . false . } . } . . impl Cursor<'_> { . /// Parses a token from the input string. 724,408 ( 0.08%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 361,603 ( 0.04%) let token_kind = match first_char { . // Slash, comment or block comment. 408 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), . _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . -- line 313 ---------------------------------------- -- line 322 ---------------------------------------- . } . let kind = RawStr { n_hashes, err }; . Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 585 ( 0.00%) 'b' => match (self.first(), self.second()) { . ('\'', _) => { . self.bump(); . let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } . let kind = Byte { terminated }; -- line 338 ---------------------------------------- -- line 361 ---------------------------------------- . _ => self.ident_or_unknown_prefix(), . }, . . // Identifier (this should be checked after other variant that can . // start as identifier). . c if is_id_start(c) => self.ident_or_unknown_prefix(), . . // Numeric literal. 179,013 ( 0.02%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); . TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 138 ( 0.00%) ';' => Semi, 58,442 ( 0.01%) ',' => Comma, 152 ( 0.00%) '.' => Dot, 308 ( 0.00%) '(' => OpenParen, 308 ( 0.00%) ')' => CloseParen, 94 ( 0.00%) '{' => OpenBrace, 94 ( 0.00%) '}' => CloseBrace, 198 ( 0.00%) '[' => OpenBracket, 198 ( 0.00%) ']' => CloseBracket, . '@' => At, 84 ( 0.00%) '#' => Pound, . '~' => Tilde, . '?' => Question, 178 ( 0.00%) ':' => Colon, . '$' => Dollar, 82 ( 0.00%) '=' => Eq, 34 ( 0.00%) '!' => Bang, . '<' => Lt, 154 ( 0.00%) '>' => Gt, 128 ( 0.00%) '-' => Minus, 116 ( 0.00%) '&' => And, 88 ( 0.00%) '|' => Or, 2 ( 0.00%) '+' => Plus, . '*' => Star, . '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. 87,816 ( 0.01%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { . let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } -- line 413 ---------------------------------------- -- line 416 ---------------------------------------- . } . // Identifier starting with an emoji. Only lexed for graceful error recovery. . c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } . _ => Unknown, . }; . Token::new(token_kind, self.len_consumed()) 814,959 ( 0.09%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 264 ( 0.00%) let doc_style = match self.first() { . // `//!` is an inner line doc comment. . '!' => Some(DocStyle::Inner), . // `////` (more than 3 slashes) is not considered a doc comment. 216 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 3,991 ( 0.00%) self.eat_while(|c| c != '\n'); 306 ( 0.00%) LineComment { doc_style } . } . . fn block_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '*'); . self.bump(); . . let doc_style = match self.first() { . // `/*!` is an inner block doc comment. -- line 447 ---------------------------------------- -- line 474 ---------------------------------------- . } . . BlockComment { doc_style, terminated: depth == 0 } . } . . fn whitespace(&mut self) -> TokenKind { . debug_assert!(is_whitespace(self.prev())); . self.eat_while(is_whitespace); 30,121 ( 0.00%) Whitespace . } . . fn raw_ident(&mut self) -> TokenKind { . debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); . // Eat "#" symbol. . self.bump(); . // Eat the identifier part of RawIdent. . self.eat_identifier(); . RawIdent . } . 3,285 ( 0.00%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 1,314 ( 0.00%) self.eat_while(is_id_continue); . // Known prefixes must have been handled earlier. So if . // we see a prefix here, it is definitely an unknown prefix. 1,314 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 657 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 657 ( 0.00%) _ => Ident, . } 2,628 ( 0.00%) } . . fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { . // Start is already eaten, eat the rest of identifier. . self.eat_while(|c| { . unicode_xid::UnicodeXID::is_xid_continue(c) . || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) . || c == '\u{200d}' . }); -- line 515 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 204,904 ( 0.02%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 58,544 ( 0.01%) let can_be_a_lifetime = if self.second() == '\'' { . // It's surely not a lifetime. . false . } else { . // If the first symbol is valid for identifier, it can be a lifetime. . // Also check if it's a number for a better error reporting (so '0 will . // be reported as invalid lifetime and not as unterminated char literal). . is_id_start(self.first()) || self.first().is_digit(10) . }; . 29,234 ( 0.00%) if !can_be_a_lifetime { 87,729 ( 0.01%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 58,486 ( 0.01%) if terminated { . self.eat_literal_suffix(); . } . let kind = Char { terminated }; 116,972 ( 0.01%) return Literal { kind, suffix_start }; . } . . // Either a lifetime or a character literal with . // length greater than 1. . . let starts_with_number = self.first().is_digit(10); . . // Skip the literal contents. . // First symbol can be a number (which isn't a valid identifier start), . // so skip it without any checks. . self.bump(); 58 ( 0.00%) self.eat_while(is_id_continue); . . // Check if after skipping literal contents we've met a closing . // single quote (which means that user attempted to create a . // string with single quotes). 58 ( 0.00%) if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { 58 ( 0.00%) Lifetime { starts_with_number } . } 175,632 ( 0.02%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. 58,504 ( 0.01%) if self.second() == '\'' && self.first() != '\\' { . self.bump(); . self.bump(); . return true; . } . . // Literal has more than one symbol. . . // Parse until either quotes are terminated or error is detected. . loop { 1,450,414 ( 0.15%) match self.first() { . // Quotes are terminated, finish parsing. . '\'' => { . self.bump(); . return true; . } . // Probably beginning of the comment, which we don't want to include . // to the error report. . '/' => break, -- line 660 ---------------------------------------- -- line 670 ---------------------------------------- . // Skip the character. . _ => { . self.bump(); . } . } . } . // String was not terminated. . false 29,243 ( 0.00%) } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { . match c { . '"' => { -- line 686 ---------------------------------------- -- line 816 ---------------------------------------- . if self.first() == '-' || self.first() == '+' { . self.bump(); . } . self.eat_decimal_digits() . } . . // Eats the suffix of the literal, e.g. "_u8". . fn eat_literal_suffix(&mut self) { 58,486 ( 0.01%) self.eat_identifier(); . } . . // Eats the identifier. 87,729 ( 0.01%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 116,972 ( 0.01%) } . } 1,194,511 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . /// - `promoted` -- map of promoted constants within `body` . /// - `universal_regions` -- the universal regions from `body`s function signature . /// - `location_table` -- MIR location map of `body` . /// - `borrow_set` -- information about borrows occurring in `body` . /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts . /// - `flow_inits` -- results of a maybe-init dataflow analysis . /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis . /// - `elements` -- MIR region map 768 ( 0.00%) pub(crate) fn type_check<'mir, 'tcx>( . infcx: &InferCtxt<'_, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . body: &Body<'tcx>, . promoted: &IndexVec>, . universal_regions: &Rc>, . location_table: &LocationTable, . borrow_set: &BorrowSet<'tcx>, . all_facts: &mut Option, . flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>, . move_data: &MoveData<'tcx>, . elements: &Rc, . upvars: &[Upvar<'tcx>], . ) -> MirTypeckResults<'tcx> { 576 ( 0.00%) let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body)); . let mut universe_causes = FxHashMap::default(); . universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other()); 1,408 ( 0.00%) let mut constraints = MirTypeckRegionConstraints { . placeholder_indices: PlaceholderIndices::default(), . placeholder_index_to_region: IndexVec::default(), 64 ( 0.00%) liveness_constraints: LivenessValues::new(elements.clone()), . outlives_constraints: OutlivesConstraintSet::default(), . member_constraints: MemberConstraintSet::default(), . closure_bounds_mapping: Default::default(), . type_tests: Vec::default(), 256 ( 0.00%) universe_causes, . }; . . let CreateResult { 128 ( 0.00%) universal_region_relations, 256 ( 0.00%) region_bound_pairs, 256 ( 0.00%) normalized_inputs_and_output, 320 ( 0.00%) } = free_region_relations::create( . infcx, . param_env, . Some(implicit_region_bound), . universal_regions, . &mut constraints, . ); . 128 ( 0.00%) for u in ty::UniverseIndex::ROOT..infcx.universe() { . let info = UniverseInfo::other(); . constraints.universe_causes.insert(u, info); . } . 576 ( 0.00%) let mut borrowck_context = BorrowCheckContext { 64 ( 0.00%) universal_regions, . location_table, . borrow_set, . all_facts, . constraints: &mut constraints, . upvars, . }; . . let opaque_type_values = type_check_internal( -- line 180 ---------------------------------------- -- line 243 ---------------------------------------- . } else { . Some((opaque_type_key, decl)) . } . }) . .collect() . }, . ); . 768 ( 0.00%) MirTypeckResults { constraints, universal_region_relations, opaque_type_values } 512 ( 0.00%) } . . #[instrument( . skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra), . level = "debug" . )] . fn type_check_internal<'a, 'tcx, R>( . infcx: &'a InferCtxt<'a, 'tcx>, . param_env: ty::ParamEnv<'tcx>, -- line 260 ---------------------------------------- -- line 270 ---------------------------------------- . body, . param_env, . region_bound_pairs, . implicit_region_bound, . borrowck_context, . ); . let errors_reported = { . let mut verifier = TypeVerifier::new(&mut checker, body, promoted); 64 ( 0.00%) verifier.visit_body(&body); 64 ( 0.00%) verifier.errors_reported . }; . 64 ( 0.00%) if !errors_reported { . // if verifier failed, don't do further checks to avoid ICEs 64 ( 0.00%) checker.typeck_mir(body); . } . 832 ( 0.00%) extra(checker) . } . . fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) { . let cx = &mut typeck.borrowck_context; 256 ( 0.00%) if let Some(facts) = cx.all_facts { . let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation"); . let location_table = cx.location_table; . facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map( . |constraint: &OutlivesConstraint<'_>| { . if let Some(from_location) = constraint.locations.from_location() { . Either::Left(iter::once(( . constraint.sup, . constraint.sub, -- line 300 ---------------------------------------- -- line 334 ---------------------------------------- . body: &'b Body<'tcx>, . promoted: &'b IndexVec>, . last_span: Span, . errors_reported: bool, . } . . impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { . fn visit_span(&mut self, span: &Span) { 124,608 ( 0.01%) if !span.is_dummy() { 31,152 ( 0.00%) self.last_span = *span; . } . } . 9,207 ( 0.00%) fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) { . self.sanitize_place(place, location, context); 6,696 ( 0.00%) } . 352,548 ( 0.04%) fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) { . self.super_constant(constant, location); 235,032 ( 0.02%) let ty = self.sanitize_type(constant, constant.literal.ty()); . 264,411 ( 0.03%) self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| { . let live_region_vid = . self.cx.borrowck_context.universal_regions.to_region_vid(live_region); 168 ( 0.00%) self.cx . .borrowck_context . .constraints . .liveness_constraints 168 ( 0.00%) .add_element(live_region_vid, location); . }); . 117,516 ( 0.01%) if let Some(annotation_index) = constant.user_ty { . if let Err(terr) = self.cx.relate_type_and_user_type( . constant.literal.ty(), . ty::Variance::Invariant, . &UserTypeProjection { base: annotation_index, projs: vec![] }, . location.to_locations(), . ConstraintCategory::Boring, . ) { . let annotation = &self.cx.user_type_annotations[annotation_index]; -- line 373 ---------------------------------------- -- line 377 ---------------------------------------- . "bad constant user type {:?} vs {:?}: {:?}", . annotation, . constant.literal.ty(), . terr, . ); . } . } else { . let tcx = self.tcx(); 88,137 ( 0.01%) let maybe_uneval = match constant.literal { 88,137 ( 0.01%) ConstantKind::Ty(ct) => match ct.val { 28 ( 0.00%) ty::ConstKind::Unevaluated(uv) => Some(uv), . _ => None, . }, . _ => None, . }; 56 ( 0.00%) if let Some(uv) = maybe_uneval { 56 ( 0.00%) if let Some(promoted) = uv.promoted { . let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>, . promoted: &Body<'tcx>, . ty, . san_ty| { 84 ( 0.00%) if let Err(terr) = verifier.cx.eq_types( . ty, . san_ty, 56 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . verifier, . promoted, . "bad promoted type ({:?}: {:?}): {:?}", . ty, . san_ty, . terr . ); . }; . }; . 56 ( 0.00%) if !self.errors_reported { 28 ( 0.00%) let promoted_body = &self.promoted[promoted]; 112 ( 0.00%) self.sanitize_promoted(promoted_body, location); . . let promoted_ty = promoted_body.return_ty(); . check_err(self, promoted_body, ty, promoted_ty); . } . } else { . if let Err(terr) = self.cx.fully_perform_op( . location.to_locations(), . ConstraintCategory::Boring, -- line 425 ---------------------------------------- -- line 433 ---------------------------------------- . self, . constant, . "bad constant type {:?} ({:?})", . constant, . terr . ); . } . } 117,404 ( 0.01%) } else if let Some(static_def_id) = constant.check_static_ptr(tcx) { . let unnormalized_ty = tcx.type_of(static_def_id); 56 ( 0.00%) let locations = location.to_locations(); 196 ( 0.00%) let normalized_ty = self.cx.normalize(unnormalized_ty, locations); 140 ( 0.00%) let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty; . 84 ( 0.00%) if let Err(terr) = self.cx.eq_types( . literal_ty, . normalized_ty, . locations, . ConstraintCategory::Boring, . ) { . span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr); . } . } . 117,693 ( 0.01%) if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() { 118 ( 0.00%) let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs); 118 ( 0.00%) self.cx.normalize_and_prove_instantiated_predicates( . def_id, 354 ( 0.00%) instantiated_predicates, 118 ( 0.00%) location.to_locations(), . ); . } . } 235,032 ( 0.02%) } . 3,982 ( 0.00%) fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { . self.super_rvalue(rvalue, location); 1,086 ( 0.00%) let rval_ty = rvalue.ty(self.body, self.tcx()); 4,344 ( 0.00%) self.sanitize_type(rvalue, rval_ty); . } . 4,530 ( 0.00%) fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) { . self.super_local_decl(local, local_decl); 2,265 ( 0.00%) self.sanitize_type(local_decl, local_decl.ty); . 1,359 ( 0.00%) if let Some(user_ty) = &local_decl.user_ty { . for (user_ty, span) in user_ty.projections_and_spans() { . let ty = if !local_decl.is_nonref_binding() { . // If we have a binding of the form `let ref x: T = ..` . // then remove the outermost reference so we can check the . // type annotation for the remaining type. . if let ty::Ref(_, rty, _) = local_decl.ty.kind() { . rty . } else { -- line 486 ---------------------------------------- -- line 504 ---------------------------------------- . local, . local_decl.ty, . local_decl.user_ty, . terr, . ); . } . } . } 3,624 ( 0.00%) } . 644 ( 0.00%) fn visit_body(&mut self, body: &Body<'tcx>) { 276 ( 0.00%) self.sanitize_type(&"return type", body.return_ty()); . for local_decl in &body.local_decls { 2,265 ( 0.00%) self.sanitize_type(local_decl, local_decl.ty); . } 184 ( 0.00%) if self.errors_reported { . return; . } . self.super_body(body); 736 ( 0.00%) } . } . . impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { . fn new( . cx: &'a mut TypeChecker<'b, 'tcx>, . body: &'b Body<'tcx>, . promoted: &'b IndexVec>, . ) -> Self { 576 ( 0.00%) TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 89,888 ( 0.01%) self.cx.infcx.tcx . } . 307,390 ( 0.03%) fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> { 61,478 ( 0.01%) if ty.has_escaping_bound_vars() || ty.references_error() { . span_mirbug_and_err!(self, parent, "bad type {:?}", ty) . } else { . ty . } 215,173 ( 0.02%) } . . /// Checks that the types internal to the `place` match up with . /// what would be expected. . fn sanitize_place( . &mut self, . place: &Place<'tcx>, . location: Location, . context: PlaceContext, . ) -> PlaceTy<'tcx> { . debug!("sanitize_place: {:?}", place); . 3,348 ( 0.00%) let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty); . 1,009 ( 0.00%) for elem in place.projection.iter() { 86 ( 0.00%) if place_ty.variant_index.is_none() { 86 ( 0.00%) if place_ty.ty.references_error() { . assert!(self.errors_reported); . return PlaceTy::from_ty(self.tcx().ty_error()); . } . } . place_ty = self.sanitize_projection(place_ty, elem, place, location); . } . 2,432 ( 0.00%) if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context { . let tcx = self.tcx(); . let trait_ref = ty::TraitRef { 1,070 ( 0.00%) def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)), 535 ( 0.00%) substs: tcx.mk_substs_trait(place_ty.ty, &[]), . }; . . // To have a `Copy` operand, the type `T` of the . // value must be `Copy`. Note that we prove that `T: Copy`, . // rather than using the `is_copy_modulo_regions` . // test. This is important because . // `is_copy_modulo_regions` ignores the resulting region . // obligations and assumes they pass. This can result in . // bounds from `Copy` impls being unsoundly ignored (e.g., . // #29149). Note that we decide to use `Copy` before knowing . // whether the bounds fully apply: in effect, the rule is . // that if a value of some type could implement `Copy`, then . // it must. 321 ( 0.00%) self.cx.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::CopyBound, . ); . } . . place_ty . } -- line 595 ---------------------------------------- -- line 598 ---------------------------------------- . // Determine the constraints from the promoted MIR by running the type . // checker on the promoted MIR, then transfer the constraints back to . // the main MIR, changing the locations to the provided location. . . let parent_body = mem::replace(&mut self.body, promoted_body); . . // Use new sets of constraints and closure bounds so that we can . // modify their locations. 28 ( 0.00%) let all_facts = &mut None; . let mut constraints = Default::default(); . let mut closure_bounds = Default::default(); . let mut liveness_constraints = 56 ( 0.00%) LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body))); . // Don't try to add borrow_region facts for the promoted MIR . . let mut swap_constraints = |this: &mut Self| { 112 ( 0.00%) mem::swap(this.cx.borrowck_context.all_facts, all_facts); . mem::swap( 112 ( 0.00%) &mut this.cx.borrowck_context.constraints.outlives_constraints, . &mut constraints, . ); . mem::swap( 112 ( 0.00%) &mut this.cx.borrowck_context.constraints.closure_bounds_mapping, . &mut closure_bounds, . ); . mem::swap( 112 ( 0.00%) &mut this.cx.borrowck_context.constraints.liveness_constraints, . &mut liveness_constraints, . ); . }; . 28 ( 0.00%) swap_constraints(self); . 84 ( 0.00%) self.visit_body(&promoted_body); . 56 ( 0.00%) if !self.errors_reported { . // if verifier failed, don't do further checks to avoid ICEs 84 ( 0.00%) self.cx.typeck_mir(promoted_body); . } . 28 ( 0.00%) self.body = parent_body; . // Merge the outlives constraints back in, at the given location. 28 ( 0.00%) swap_constraints(self); . . let locations = location.to_locations(); . for constraint in constraints.outlives().iter() { . let mut constraint = constraint.clone(); . constraint.locations = locations; 224 ( 0.00%) if let ConstraintCategory::Return(_) . | ConstraintCategory::UseAsConst . | ConstraintCategory::UseAsStatic = constraint.category . { . // "Returning" from a promoted is an assignment to a . // temporary from the user's point of view. . constraint.category = ConstraintCategory::Boring; . } . self.cx.borrowck_context.constraints.outlives_constraints.push(constraint) -- line 654 ---------------------------------------- -- line 661 ---------------------------------------- . self.cx . .borrowck_context . .constraints . .liveness_constraints . .add_element(region, location); . } . } . 28 ( 0.00%) if !closure_bounds.is_empty() { . let combined_bounds_mapping = . closure_bounds.into_iter().flat_map(|(_, value)| value).collect(); . let existing = self . .cx . .borrowck_context . .constraints . .closure_bounds_mapping . .insert(location, combined_bounds_mapping); . assert!(existing.is_none(), "Multiple promoteds/closures at the same location."); . } 112 ( 0.00%) } . . fn sanitize_projection( . &mut self, . base: PlaceTy<'tcx>, . pi: PlaceElem<'tcx>, . place: &Place<'tcx>, . location: Location, . ) -> PlaceTy<'tcx> { . debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place); . let tcx = self.tcx(); 86 ( 0.00%) let base_ty = base.ty; 430 ( 0.00%) match pi { . ProjectionElem::Deref => { 258 ( 0.00%) let deref_ty = base_ty.builtin_deref(true); . PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty) . })) . } . ProjectionElem::Index(i) => { . let index_ty = Place::from(i).ty(self.body, tcx).ty; . if index_ty != tcx.types.usize { . PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)) -- line 702 ---------------------------------------- -- line 965 ---------------------------------------- . } . } . } . . /// The `Locations` type summarizes *where* region constraints are . /// required to hold. Normally, this is at a particular point which . /// created the obligation, but for constraints that the user gave, we . /// want the constraint to hold at all points. 1,414 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] . pub enum Locations { . /// Indicates that a type constraint should always be true. This . /// is particularly important in the new borrowck analysis for . /// things like the type of the return slot. Consider this . /// example: . /// . /// ``` . /// fn foo<'a>(x: &'a u32) -> &'a u32 { -- line 981 ---------------------------------------- -- line 1036 ---------------------------------------- . fn new( . infcx: &'a InferCtxt<'a, 'tcx>, . body: &'a Body<'tcx>, . param_env: ty::ParamEnv<'tcx>, . region_bound_pairs: &'a RegionBoundPairs<'tcx>, . implicit_region_bound: ty::Region<'tcx>, . borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>, . ) -> Self { 832 ( 0.00%) let mut checker = Self { . infcx, . last_span: DUMMY_SP, . body, 64 ( 0.00%) user_type_annotations: &body.user_type_annotations, . param_env, . region_bound_pairs, . implicit_region_bound, . borrowck_context, . reported_errors: Default::default(), . }; . checker.check_user_type_annotations(); . checker . } . . fn unsized_feature_enabled(&self) -> bool { 745 ( 0.00%) let features = self.tcx().features(); 1,490 ( 0.00%) features.unsized_locals || features.unsized_fn_params . } . . /// Equate the inferred type and the annotated type for user type annotations . fn check_user_type_annotations(&mut self) { . debug!( . "check_user_type_annotations: user_type_annotations={:?}", . self.user_type_annotations . ); -- line 1069 ---------------------------------------- -- line 1128 ---------------------------------------- . fn push_region_constraints( . &mut self, . locations: Locations, . category: ConstraintCategory, . data: &QueryRegionConstraints<'tcx>, . ) { . debug!("constraints generated: {:#?}", data); . 59 ( 0.00%) constraint_conversion::ConstraintConversion::new( . self.infcx, 118 ( 0.00%) self.borrowck_context.universal_regions, 59 ( 0.00%) self.region_bound_pairs, . Some(self.implicit_region_bound), . self.param_env, . locations, . category, 59 ( 0.00%) &mut self.borrowck_context.constraints, . ) . .convert_all(data); . } . . /// Try to relate `sub <: sup` . fn sub_types( . &mut self, . sub: Ty<'tcx>, . sup: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { . // Use this order of parameters because the sup type is usually the . // "expected" type in diagnostics. 299,088 ( 0.03%) self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category) . } . . #[instrument(skip(self, category), level = "debug")] . fn eq_types( . &mut self, . expected: Ty<'tcx>, . found: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { 1,680 ( 0.00%) self.relate_types(expected, ty::Variance::Invariant, found, locations, category) . } . . #[instrument(skip(self), level = "debug")] . fn relate_type_and_user_type( . &mut self, . a: Ty<'tcx>, . v: ty::Variance, . user_ty: &UserTypeProjection, -- line 1178 ---------------------------------------- -- line 1231 ---------------------------------------- . /// . /// In terms of our function parameters: . /// . /// * `anon_ty` would be `Box>` where `Foo` is an opaque type . /// scoped to this function (note that it is parameterized by the . /// generics of `foo`). Note that `anon_ty` is not just the opaque type, . /// but the entire return type (which may contain opaque types within it). . /// * `revealed_ty` would be `Box<(T, u32)>` 1,216 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn eq_opaque_type_and_type( . &mut self, . revealed_ty: Ty<'tcx>, . anon_ty: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { . // Fast path for the common case. 64 ( 0.00%) if !anon_ty.has_opaque_types() { 128 ( 0.00%) if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) { . span_mirbug!( . self, . locations, . "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`", . revealed_ty, . anon_ty, . terr . ); -- line 1257 ---------------------------------------- -- line 1328 ---------------------------------------- . || "opaque_type_map".to_string(), . ), . )?; . } . Ok(()) . } . . fn tcx(&self) -> TyCtxt<'tcx> { 6,290 ( 0.00%) self.infcx.tcx . } . . #[instrument(skip(self, body, location), level = "debug")] . fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) { . let tcx = self.tcx(); 3,200 ( 0.00%) match stmt.kind { 362 ( 0.00%) StatementKind::Assign(box (ref place, ref rv)) => { . // Assignments to temporaries are not "interesting"; . // they are not caused by the user, but rather artifacts . // of lowering. Assignments to other sorts of places *are* interesting . // though. 1,448 ( 0.00%) let category = match place.as_local() { . Some(RETURN_PLACE) => { 162 ( 0.00%) let defining_ty = &self.borrowck_context.universal_regions.defining_ty; 81 ( 0.00%) if defining_ty.is_const() { 224 ( 0.00%) if tcx.is_static(defining_ty.def_id()) { . ConstraintCategory::UseAsStatic . } else { . ConstraintCategory::UseAsConst . } . } else { . ConstraintCategory::Return(ReturnConstraint::Normal) . } . } . Some(l) 393 ( 0.00%) if matches!( 590 ( 0.00%) body.local_decls[l].local_info, . Some(box LocalInfo::AggregateTemp) . ) => . { . ConstraintCategory::Usage . } . Some(l) if !body.local_decls[l].is_user_variable() => { . ConstraintCategory::Boring . } -- line 1371 ---------------------------------------- -- line 1373 ---------------------------------------- . }; . debug!( . "assignment category: {:?} {:?}", . category, . place.as_local().map(|l| &body.local_decls[l]) . ); . . let place_ty = place.ty(body, tcx).ty; 4,344 ( 0.00%) let place_ty = self.normalize(place_ty, location); 362 ( 0.00%) let rv_ty = rv.ty(body, tcx); 2,172 ( 0.00%) let rv_ty = self.normalize(rv_ty, location); 724 ( 0.00%) if let Err(terr) = . self.sub_types(rv_ty, place_ty, location.to_locations(), category) . { . span_mirbug!( . self, . stmt, . "bad assignment ({:?} = {:?}): {:?}", . place_ty, . rv_ty, -- line 1392 ---------------------------------------- -- line 1409 ---------------------------------------- . "bad user type on rvalue ({:?} = {:?}): {:?}", . annotation, . rv_ty, . terr . ); . } . } . 2,534 ( 0.00%) self.check_rvalue(body, rv, location); 362 ( 0.00%) if !self.unsized_feature_enabled() { . let trait_ref = ty::TraitRef { 3,982 ( 0.00%) def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)), 1,810 ( 0.00%) substs: tcx.mk_substs_trait(place_ty, &[]), . }; 1,086 ( 0.00%) self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::SizedBound, . ); . } . } . StatementKind::SetDiscriminant { ref place, variant_index } => { . let place_type = place.ty(body, tcx).ty; -- line 1431 ---------------------------------------- -- line 1488 ---------------------------------------- . #[instrument(skip(self, body, term_location), level = "debug")] . fn check_terminator( . &mut self, . body: &Body<'tcx>, . term: &Terminator<'tcx>, . term_location: Location, . ) { . let tcx = self.tcx(); 1,495 ( 0.00%) match term.kind { . TerminatorKind::Goto { .. } . | TerminatorKind::Resume . | TerminatorKind::Abort . | TerminatorKind::Return . | TerminatorKind::GeneratorDrop . | TerminatorKind::Unreachable . | TerminatorKind::Drop { .. } . | TerminatorKind::FalseEdge { .. } -- line 1504 ---------------------------------------- -- line 1520 ---------------------------------------- . term, . "bad DropAndReplace ({:?} = {:?}): {:?}", . place_ty, . rv_ty, . terr . ); . } . } 176 ( 0.00%) TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => { 132 ( 0.00%) self.check_operand(discr, term_location); . 44 ( 0.00%) let discr_ty = discr.ty(body, tcx); 88 ( 0.00%) if let Err(terr) = self.sub_types( . discr_ty, . switch_ty, . term_location.to_locations(), . ConstraintCategory::Assignment, . ) { . span_mirbug!( . self, . term, . "bad SwitchInt ({:?} on {:?}): {:?}", . switch_ty, . discr_ty, . terr . ); . } 88 ( 0.00%) if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() { . span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty); . } . // FIXME: check the values . } 354 ( 0.00%) TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => { 295 ( 0.00%) self.check_operand(func, term_location); . for arg in args { 440 ( 0.00%) self.check_operand(arg, term_location); . } . 59 ( 0.00%) let func_ty = func.ty(body, tcx); . debug!("check_terminator: call, func_ty={:?}", func_ty); 236 ( 0.00%) let sig = match func_ty.kind() { 236 ( 0.00%) ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx), . _ => { . span_mirbug!(self, term, "call to non-function {:?}", func_ty); . return; . } . }; 590 ( 0.00%) let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars( 177 ( 0.00%) term.source_info.span, . LateBoundRegionConversionTime::FnCall, . sig, . ); 118 ( 0.00%) let sig = self.normalize(sig, term_location); 236 ( 0.00%) self.check_call_dest(body, term, &sig, destination, term_location); . . self.prove_predicates( 59 ( 0.00%) sig.inputs_and_output . .iter() 294 ( 0.00%) .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))), . term_location.to_locations(), . ConstraintCategory::Boring, . ); . . // The ordinary liveness rules will ensure that all . // regions in the type of the callee are live here. We . // then further constrain the late-bound regions that . // were instantiated at the call site to be live as . // well. The resulting is that all the input (and . // output) types in the signature must be live, since . // all the inputs that fed into it were live. 360 ( 0.00%) for &late_bound_region in map.values() { . let region_vid = 6 ( 0.00%) self.borrowck_context.universal_regions.to_region_vid(late_bound_region); 6 ( 0.00%) self.borrowck_context . .constraints . .liveness_constraints . .add_element(region_vid, term_location); . } . 118 ( 0.00%) self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call); . } . TerminatorKind::Assert { ref cond, ref msg, .. } => { . self.check_operand(cond, term_location); . . let cond_ty = cond.ty(body, tcx); . if cond_ty != tcx.types.bool { . span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty); . } -- line 1607 ---------------------------------------- -- line 1647 ---------------------------------------- . &mut self, . body: &Body<'tcx>, . term: &Terminator<'tcx>, . sig: &ty::FnSig<'tcx>, . destination: &Option<(Place<'tcx>, BasicBlock)>, . term_location: Location, . ) { . let tcx = self.tcx(); 236 ( 0.00%) match *destination { . Some((ref dest, _target_block)) => { . let dest_ty = dest.ty(body, tcx).ty; 354 ( 0.00%) let dest_ty = self.normalize(dest_ty, term_location); 295 ( 0.00%) let category = match dest.as_local() { . Some(RETURN_PLACE) => { 203 ( 0.00%) if let BorrowCheckContext { . universal_regions: . UniversalRegions { . defining_ty: . DefiningTy::Const(def_id, _) . | DefiningTy::InlineConst(def_id, _), . .. . }, . .. -- line 1669 ---------------------------------------- -- line 1681 ---------------------------------------- . Some(l) if !body.local_decls[l].is_user_variable() => { . ConstraintCategory::Boring . } . _ => ConstraintCategory::Assignment, . }; . . let locations = term_location.to_locations(); . 413 ( 0.00%) if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) { . span_mirbug!( . self, . term, . "call dest mismatch ({:?} <- {:?}): {:?}", . dest_ty, . sig.output(), . terr . ); . } . . // When `unsized_fn_params` and `unsized_locals` are both not enabled, . // this check is done at `check_local`. 59 ( 0.00%) if self.unsized_feature_enabled() { . let span = term.source_info.span; . self.ensure_place_sized(dest_ty, span); . } . } . None => { . if !self . .tcx() . .conservative_is_privately_uninhabited(self.param_env.and(sig.output())) -- line 1710 ---------------------------------------- -- line 1720 ---------------------------------------- . body: &Body<'tcx>, . term: &Terminator<'tcx>, . sig: &ty::FnSig<'tcx>, . args: &[Operand<'tcx>], . term_location: Location, . from_hir_call: bool, . ) { . debug!("check_call_inputs({:?}, {:?})", sig, args); 413 ( 0.00%) if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) { . span_mirbug!(self, term, "call to {:?} with wrong # of args", sig); . } 294 ( 0.00%) for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() { . let op_arg_ty = op_arg.ty(body, self.tcx()); 352 ( 0.00%) let op_arg_ty = self.normalize(op_arg_ty, term_location); . let category = if from_hir_call { . ConstraintCategory::CallArgument . } else { . ConstraintCategory::Boring . }; 176 ( 0.00%) if let Err(terr) = 176 ( 0.00%) self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category) . { . span_mirbug!( . self, . term, . "bad arg #{:?} ({:?} <- {:?}): {:?}", . n, . fn_arg, . op_arg_ty, . terr . ); . } . } . } . . fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) { 187 ( 0.00%) let is_cleanup = block_data.is_cleanup; 897 ( 0.00%) self.last_span = block_data.terminator().source_info.span; 1,794 ( 0.00%) match block_data.terminator().kind { 57 ( 0.00%) TerminatorKind::Goto { target } => { 228 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup) . } 44 ( 0.00%) TerminatorKind::SwitchInt { ref targets, .. } => { 44 ( 0.00%) for target in targets.all_targets() { 528 ( 0.00%) self.assert_iscleanup(body, block_data, *target, is_cleanup); . } . } . TerminatorKind::Resume => { 36 ( 0.00%) if !is_cleanup { . span_mirbug!(self, block_data, "resume on non-cleanup block!") . } . } . TerminatorKind::Abort => { . if !is_cleanup { . span_mirbug!(self, block_data, "abort on non-cleanup block!") . } . } . TerminatorKind::Return => { 92 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "return on cleanup block") . } . } . TerminatorKind::GeneratorDrop { .. } => { . if is_cleanup { . span_mirbug!(self, block_data, "generator_drop in cleanup block") . } . } -- line 1786 ---------------------------------------- -- line 1800 ---------------------------------------- . self.assert_iscleanup(body, block_data, target, is_cleanup); . if let Some(unwind) = unwind { . if is_cleanup { . span_mirbug!(self, block_data, "unwind on cleanup block") . } . self.assert_iscleanup(body, block_data, unwind, true); . } . } 59 ( 0.00%) TerminatorKind::Call { ref destination, cleanup, .. } => { 295 ( 0.00%) if let &Some((_, target)) = destination { 118 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup); . } 177 ( 0.00%) if let Some(cleanup) = cleanup { 59 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "cleanup on cleanup block") . } . self.assert_iscleanup(body, block_data, cleanup, true); . } . } 22 ( 0.00%) TerminatorKind::FalseEdge { real_target, imaginary_target } => { 66 ( 0.00%) self.assert_iscleanup(body, block_data, real_target, is_cleanup); 55 ( 0.00%) self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup); . } . TerminatorKind::FalseUnwind { real_target, unwind } => { . self.assert_iscleanup(body, block_data, real_target, is_cleanup); . if let Some(unwind) = unwind { . if is_cleanup { . span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind"); . } . self.assert_iscleanup(body, block_data, unwind, true); -- line 1829 ---------------------------------------- -- line 1838 ---------------------------------------- . span_mirbug!(self, block_data, "cleanup on cleanup block") . } . self.assert_iscleanup(body, block_data, cleanup, true); . } . } . } . } . 2,565 ( 0.00%) fn assert_iscleanup( . &mut self, . body: &Body<'tcx>, . ctxt: &dyn fmt::Debug, . bb: BasicBlock, . iscleanuppad: bool, . ) { 1,710 ( 0.00%) if body[bb].is_cleanup != iscleanuppad { . span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad); . } 1,425 ( 0.00%) } . . fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) { . match body.local_kind(local) { . LocalKind::ReturnPointer | LocalKind::Arg => { . // return values of normal functions are required to be . // sized by typeck, but return values of ADT constructors are . // not because we don't include a `Self: Sized` bounds on them. . // -- line 1864 ---------------------------------------- -- line 1866 ---------------------------------------- . // - maybe we should make that a warning. . return; . } . LocalKind::Var | LocalKind::Temp => {} . } . . // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls . // and nullary ops are checked in `check_call_dest`. 324 ( 0.00%) if !self.unsized_feature_enabled() { 648 ( 0.00%) let span = local_decl.source_info.span; 324 ( 0.00%) let ty = local_decl.ty; 648 ( 0.00%) self.ensure_place_sized(ty, span); . } . } . 2,916 ( 0.00%) fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) { . let tcx = self.tcx(); . . // Erase the regions from `ty` to get a global type. The . // `Sized` bound in no way depends on precise regions, so this . // shouldn't affect `is_sized`. . let erased_ty = tcx.erase_regions(ty); 1,944 ( 0.00%) if !erased_ty.is_sized(tcx.at(span), self.param_env) { . // in current MIR construction, all non-control-flow rvalue . // expressions evaluate through `as_temp` or `into` a return . // slot or local, so to find all unsized rvalues it is enough . // to check all temps, return slots and locals. . if self.reported_errors.replace((ty, span)).is_none() { . let mut diag = struct_span_err!( . self.tcx().sess, . span, -- line 1896 ---------------------------------------- -- line 1901 ---------------------------------------- . ); . . // While this is located in `nll::typeck` this error is not . // an NLL error, it's a required check to prevent creation . // of unsized rvalues in a call expression. . diag.emit(); . } . } 1,944 ( 0.00%) } . . fn aggregate_field_ty( . &mut self, . ak: &AggregateKind<'tcx>, . field_index: usize, . location: Location, . ) -> Result, FieldAccessError> { . let tcx = self.tcx(); . 146,045 ( 0.02%) match *ak { . AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => { . let def = tcx.adt_def(adt_did); . let variant = &def.variants[variant_index]; . let adj_field_index = active_field_index.unwrap_or(field_index); . if let Some(field) = variant.fields.get(adj_field_index) { . Ok(self.normalize(field.ty(tcx, substs), location)) . } else { . Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) -- line 1927 ---------------------------------------- -- line 1941 ---------------------------------------- . // aggregate rvalues. . match substs.as_generator().prefix_tys().nth(field_index) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_generator().prefix_tys().count(), . }), . } . } 29,209 ( 0.00%) AggregateKind::Array(ty) => Ok(ty), . AggregateKind::Tuple => { . unreachable!("This should have been covered in check_rvalues"); . } . } . } . 207,676 ( 0.02%) fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) { 59,336 ( 0.01%) if let Operand::Constant(constant) = op { 88,137 ( 0.01%) let maybe_uneval = match constant.literal { 88,137 ( 0.01%) ConstantKind::Ty(ct) => match ct.val { 28 ( 0.00%) ty::ConstKind::Unevaluated(uv) => Some(uv), . _ => None, . }, . _ => None, . }; 56 ( 0.00%) if let Some(uv) = maybe_uneval { 28 ( 0.00%) if uv.promoted.is_none() { . let tcx = self.tcx(); . let def_id = uv.def.def_id_for_type_of(); . if tcx.def_kind(def_id) == DefKind::InlineConst { . let predicates = self.prove_closure_bounds( . tcx, . def_id.expect_local(), . uv.substs, . location, -- line 1974 ---------------------------------------- -- line 1977 ---------------------------------------- . def_id, . predicates, . location.to_locations(), . ); . } . } . } . } 237,344 ( 0.02%) } . 4,706 ( 0.00%) fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) { . let tcx = self.tcx(); . 1,898 ( 0.00%) match rvalue { . Rvalue::Aggregate(ak, ops) => { . for op in ops { 146,045 ( 0.02%) self.check_operand(op, location); . } 56 ( 0.00%) self.check_aggregate_rvalue(&body, rvalue, ak, ops, location) . } . . Rvalue::Repeat(operand, len) => { . self.check_operand(operand, location); . . // If the length cannot be evaluated we must assume that the length can be larger . // than 1. . // If the length is larger than 1, the repeat expression will need to copy the -- line 2003 ---------------------------------------- -- line 2071 ---------------------------------------- . . self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::SizedBound, . ); . } . 112 ( 0.00%) Rvalue::Cast(cast_kind, op, ty) => { 112 ( 0.00%) self.check_operand(op, location); . 364 ( 0.00%) match cast_kind { . CastKind::Pointer(PointerCast::ReifyFnPointer) => { . let fn_sig = op.ty(body, tcx).fn_sig(tcx); . . // The type that we see in the fcx is like . // `foo::<'a, 'b>`, where `foo` is the path to a . // function definition. When we extract the . // signature, it comes from the `fn_sig` query, . // and hence may contain unnormalized results. -- line 2090 ---------------------------------------- -- line 2158 ---------------------------------------- . ty_fn_ptr_from, . ty, . terr . ); . } . } . . CastKind::Pointer(PointerCast::Unsize) => { 84 ( 0.00%) let &ty = ty; . let trait_ref = ty::TraitRef { 308 ( 0.00%) def_id: tcx 28 ( 0.00%) .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)), 336 ( 0.00%) substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]), . }; . 252 ( 0.00%) self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::Cast, . ); . } . . CastKind::Pointer(PointerCast::MutToConstPointer) => { . let ty_from = match op.ty(body, tcx).kind() { -- line 2181 ---------------------------------------- -- line 2312 ---------------------------------------- . | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float)) . | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_))) . | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (), . } . } . } . } . 88 ( 0.00%) Rvalue::Ref(region, _borrow_kind, borrowed_place) => { 528 ( 0.00%) self.add_reborrow_constraint(&body, location, region, borrowed_place); . } . . Rvalue::BinaryOp( . BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge, 66 ( 0.00%) box (left, right), . ) => { 110 ( 0.00%) self.check_operand(left, location); 110 ( 0.00%) self.check_operand(right, location); . 22 ( 0.00%) let ty_left = left.ty(body, tcx); 66 ( 0.00%) match ty_left.kind() { . // Types with regions are comparable if they have a common super-type. . ty::RawPtr(_) | ty::FnPtr(_) => { . let ty_right = right.ty(body, tcx); . let common_ty = self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span: body.source_info(location).span, . }); . self.sub_types( -- line 2340 ---------------------------------------- -- line 2360 ---------------------------------------- . ty_right, . terr . ) . } . } . // For types with no regions we can just check that the . // both operands have the same type. . ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) 110 ( 0.00%) if ty_left == right.ty(body, tcx) => {} . // Other types are compared by trait methods, not by . // `Rvalue::BinaryOp`. . _ => span_mirbug!( . self, . rvalue, . "unexpected comparison types {:?} and {:?}", . ty_left, . right.ty(body, tcx) . ), . } . } . . Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => { 392 ( 0.00%) self.check_operand(operand, location); . } . . Rvalue::BinaryOp(_, box (left, right)) . | Rvalue::CheckedBinaryOp(_, box (left, right)) => { . self.check_operand(left, location); . self.check_operand(right, location); . } . . Rvalue::AddressOf(..) . | Rvalue::ThreadLocalRef(..) . | Rvalue::Len(..) . | Rvalue::Discriminant(..) => {} . } 1,328 ( 0.00%) } . . /// If this rvalue supports a user-given type annotation, then . /// extract and return it. This represents the final type of the . /// rvalue and will be unified with the inferred type. . fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option { 1,448 ( 0.00%) match rvalue { . Rvalue::Use(_) . | Rvalue::ThreadLocalRef(_) . | Rvalue::Repeat(..) . | Rvalue::Ref(..) . | Rvalue::AddressOf(..) . | Rvalue::Len(..) . | Rvalue::Cast(..) . | Rvalue::ShallowInitBox(..) . | Rvalue::BinaryOp(..) . | Rvalue::CheckedBinaryOp(..) . | Rvalue::NullaryOp(..) . | Rvalue::UnaryOp(..) . | Rvalue::Discriminant(..) => None, . 84 ( 0.00%) Rvalue::Aggregate(aggregate, _) => match **aggregate { . AggregateKind::Adt(_, _, _, user_ty, _) => user_ty, . AggregateKind::Array(_) => None, . AggregateKind::Tuple => None, . AggregateKind::Closure(_, _) => None, . AggregateKind::Generator(_, _, _) => None, . }, . } . } -- line 2425 ---------------------------------------- -- line 2431 ---------------------------------------- . aggregate_kind: &AggregateKind<'tcx>, . operands: &[Operand<'tcx>], . location: Location, . ) { . let tcx = self.tcx(); . . self.prove_aggregate_predicates(aggregate_kind, location); . 28 ( 0.00%) if *aggregate_kind == AggregateKind::Tuple { . // tuple rvalue field type is always the type of the op. Nothing to check here. . return; . } . 29,209 ( 0.00%) for (i, operand) in operands.iter().enumerate() { . let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) { 58,418 ( 0.01%) Ok(field_ty) => field_ty, . Err(FieldAccessError::OutOfRange { field_count }) => { . span_mirbug!( . self, . rvalue, . "accessed field #{} but variant only has {}", . i, . field_count . ); . continue; . } . }; . let operand_ty = operand.ty(body, tcx); 175,254 ( 0.02%) let operand_ty = self.normalize(operand_ty, location); . 58,418 ( 0.01%) if let Err(terr) = self.sub_types( . operand_ty, 29,209 ( 0.00%) field_ty, . location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . self, . rvalue, . "{:?} is not a subtype of {:?}: {:?}", . operand_ty, -- line 2471 ---------------------------------------- -- line 2486 ---------------------------------------- . fn add_reborrow_constraint( . &mut self, . body: &Body<'tcx>, . location: Location, . borrow_region: ty::Region<'tcx>, . borrowed_place: &Place<'tcx>, . ) { . // These constraints are only meaningful during borrowck: 88 ( 0.00%) let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } = . self.borrowck_context; . . // In Polonius mode, we also push a `loan_issued_at` fact . // linking the loan to the region (in some cases, though, . // there is no loan associated with this borrow expression -- . // that occurs when we are borrowing an unsafe place, for . // example). 528 ( 0.00%) if let Some(all_facts) = all_facts { . let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation"); . if let Some(borrow_index) = borrow_set.get_index_of(&location) { . let region_vid = borrow_region.to_region_vid(); . all_facts.loan_issued_at.push(( . region_vid, . borrow_index, . location_table.mid_index(location), . )); -- line 2510 ---------------------------------------- -- line 2516 ---------------------------------------- . // *p`, where the `p` has type `&'b mut Foo`, for example, we . // need to ensure that `'b: 'a`. . . debug!( . "add_reborrow_constraint({:?}, {:?}, {:?})", . location, borrow_region, borrowed_place . ); . 88 ( 0.00%) let mut cursor = borrowed_place.projection.as_ref(); 88 ( 0.00%) let tcx = self.infcx.tcx; 176 ( 0.00%) let field = path_utils::is_upvar_field_projection( . tcx, 176 ( 0.00%) &self.borrowck_context.upvars, . borrowed_place.as_ref(), . body, . ); 176 ( 0.00%) let category = if let Some(field) = field { . let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable(); . // FIXME(project-rfc-2229#8): Use Place for better diagnostics . ConstraintCategory::ClosureUpvar(var_hir_id) . } else { . ConstraintCategory::Boring . }; . 380 ( 0.00%) while let [proj_base @ .., elem] = cursor { . cursor = proj_base; . . debug!("add_reborrow_constraint - iteration {:?}", elem); . 406 ( 0.00%) match elem { . ProjectionElem::Deref => { 116 ( 0.00%) let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty; . . debug!("add_reborrow_constraint - base_ty = {:?}", base_ty); 290 ( 0.00%) match base_ty.kind() { . ty::Ref(ref_region, _, mutbl) => { 58 ( 0.00%) constraints.outlives_constraints.push(OutlivesConstraint { 116 ( 0.00%) sup: ref_region.to_region_vid(), . sub: borrow_region.to_region_vid(), . locations: location.to_locations(), . category, . variance_info: ty::VarianceDiagInfo::default(), . }); . 174 ( 0.00%) match mutbl { . hir::Mutability::Not => { . // Immutable reference. We don't need the base . // to be valid for the entire lifetime of . // the borrow. . break; . } . hir::Mutability::Mut => { . // Mutable reference. We *do* need the base -- line 2568 ---------------------------------------- -- line 2617 ---------------------------------------- . ) { . let tcx = self.tcx(); . . debug!( . "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})", . aggregate_kind, location . ); . 308 ( 0.00%) let (def_id, instantiated_predicates) = match aggregate_kind { . AggregateKind::Adt(adt_did, _, substs, _, _) => { . (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs)) . } . . // For closures, we have some **extra requirements** we . // . // have to check. In particular, in their upvars and . // signatures, closures often reference various regions -- line 2633 ---------------------------------------- -- line 2648 ---------------------------------------- . // these extra requirements are basically like where . // clauses on the struct. . AggregateKind::Closure(def_id, substs) . | AggregateKind::Generator(def_id, substs, _) => { . (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)) . } . . AggregateKind::Array(_) | AggregateKind::Tuple => { 56 ( 0.00%) (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty()) . } . }; . 28 ( 0.00%) self.normalize_and_prove_instantiated_predicates( . def_id, 84 ( 0.00%) instantiated_predicates, . location.to_locations(), . ); . } . . fn prove_closure_bounds( . &mut self, . tcx: TyCtxt<'tcx>, . def_id: LocalDefId, -- line 2670 ---------------------------------------- -- line 2728 ---------------------------------------- . ConstraintCategory::ClosureBounds, . &closure_constraints, . ); . } . . tcx.predicates_of(def_id).instantiate(tcx, substs) . } . 1,380 ( 0.00%) #[instrument(skip(self, body), level = "debug")] . fn typeck_mir(&mut self, body: &Body<'tcx>) { 368 ( 0.00%) self.last_span = body.span; . debug!(?body.span); . . for (local, local_decl) in body.local_decls.iter_enumerated() { . self.check_local(&body, local, local_decl); . } . . for (block, block_data) in body.basic_blocks().iter_enumerated() { . let mut location = Location { block, statement_index: 0 }; . for stmt in &block_data.statements { 3,200 ( 0.00%) if !stmt.source_info.span.is_dummy() { 3,200 ( 0.00%) self.last_span = stmt.source_info.span; . } . self.check_stmt(body, stmt, location); 500 ( 0.00%) location.statement_index += 1; . } . . self.check_terminator(&body, block_data.terminator(), location); . self.check_iscleanup(&body, block_data); . } . } . } . -- line 2760 ---------------------------------------- -- line 2765 ---------------------------------------- . impl NormalizeLocation for Locations { . fn to_locations(self) -> Locations { . self . } . } . . impl NormalizeLocation for Location { . fn to_locations(self) -> Locations { 90,787 ( 0.01%) Locations::Single(self) . } . } . . #[derive(Debug, Default)] . struct ObligationAccumulator<'tcx> { . obligations: PredicateObligations<'tcx>, . } . -- line 2781 ---------------------------------------- 68,550 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . /// See #47489 and #48598 . /// See docs on the "AllowTwoPhase" type for a more detailed discussion . allow_two_phase: AllowTwoPhase, . } . . impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 2,688 ( 0.00%) &self.fcx . } . } . . type CoerceResult<'tcx> = InferResult<'tcx, (Vec>, Ty<'tcx>)>; . . /// Coercing a mutable reference to an immutable works, while . /// coercing `&T` to `&mut T` should be forbidden. . fn coerce_mutbls<'tcx>( . from_mutbl: hir::Mutability, . to_mutbl: hir::Mutability, . ) -> RelateResult<'tcx, ()> { 258 ( 0.00%) match (from_mutbl, to_mutbl) { . (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not) . | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()), . (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability), . } . } . . /// Do not require any adjustments, i.e. coerce `x -> x`. . fn identity(_: Ty<'_>) -> Vec> { -- line 101 ---------------------------------------- -- line 107 ---------------------------------------- . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 637 ( 0.00%) Ok(InferOk { value: (adj, target), obligations }) . } . . impl<'f, 'tcx> Coerce<'f, 'tcx> { . fn new( . fcx: &'f FnCtxt<'f, 'tcx>, . cause: ObligationCause<'tcx>, . allow_two_phase: AllowTwoPhase, . ) -> Self { 1,848 ( 0.00%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 4,774 ( 0.00%) fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { . debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub); . self.commit_if_ok(|_| { 868 ( 0.00%) if self.use_lub { . self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 868 ( 0.00%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 3,472 ( 0.00%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 696 ( 0.00%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 1,098 ( 0.00%) self.unify(&a, &b) 924 ( 0.00%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 522 ( 0.00%) } . 4,851 ( 0.00%) #[instrument(skip(self))] . fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . // First, remove any resolved type variables (at the top level, at least): 231 ( 0.00%) let a = self.shallow_resolve(a); 231 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 462 ( 0.00%) if a.references_error() || b.references_error() { . return success(vec![], self.fcx.tcx.ty_error(), vec![]); . } . . // Coercing from `!` to any type is allowed: 231 ( 0.00%) if a.is_never() { . return success(simple(Adjust::NeverToAny)(b), b, vec![]); . } . . // Coercing *from* an unresolved inference variable means that . // we have no information about the source type. This will always . // ultimately fall back to some form of subtyping. 231 ( 0.00%) if a.is_ty_var() { . return self.coerce_from_inference_variable(a, b, identity); . } . . // Consider coercing the subtype to a DST . // . // NOTE: this is wrapped in a `commit_if_ok` because it creates . // a "spurious" type variable, and we don't want to have that . // type variable in memory if the coercion fails. . let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b)); 868 ( 0.00%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 420 ( 0.00%) return unsize; . } . Err(TypeError::ObjectUnsafeCoercion(did)) => { . debug!("coerce: unsize not object safe"); . return Err(TypeError::ObjectUnsafeCoercion(did)); . } . Err(error) => { . debug!(?error, "coerce: unsize failed"); . } . } . . // Examine the supertype and consider auto-borrowing. 957 ( 0.00%) match *b.kind() { . ty::RawPtr(mt_b) => { . return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 58 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 174 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 1,218 ( 0.00%) match *a.kind() { . ty::FnDef(..) => { . // Function items are coercible to any closure . // type; function pointers are not (that would . // require double indirection). . // Additionally, we permit coercion of function . // items to drop the unsafe qualifier. . self.coerce_from_fn_item(a, b) . } -- line 212 ---------------------------------------- -- line 218 ---------------------------------------- . ty::Closure(closure_def_id_a, substs_a) => { . // Non-capturing closures are coercible to . // function pointers or unsafe function pointers. . // It cannot convert closures that require unsafe. . self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 870 ( 0.00%) self.unify_and(a, b, identity) . } . } 462 ( 0.00%) } . . /// Coercing *from* an inference variable. In this case, we have no information . /// about the source type, so we can't really do a true coercion and we always . /// fall back to subtyping (`unify_and`). . fn coerce_from_inference_variable( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, -- line 237 ---------------------------------------- -- line 278 ---------------------------------------- . // to do something useful. . self.unify_and(a, b, make_adjustments) . } . } . . /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. . /// To match `A` with `B`, autoderef will be performed, . /// calling `deref`/`deref_mut` where necessary. 290 ( 0.00%) fn coerce_borrowed_pointer( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . r_b: ty::Region<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); . . // If we have a parameter of type `&M T_a` and the value . // provided is `expr`, we will be adding an implicit borrow, . // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, . // to type check, we will construct the type that `&M*expr` would . // yield. . 58 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 87 ( 0.00%) ty::Ref(r_a, ty, mutbl) => { . let mt_a = ty::TypeAndMut { ty, mutbl }; . coerce_mutbls(mt_a.mutbl, mutbl_b)?; . (r_a, mt_a) . } . _ => return self.unify_and(a, b, identity), . }; . 58 ( 0.00%) let span = self.cause.span; . . let mut first_error = None; . let mut r_borrow_var = None; . let mut autoderef = self.autoderef(span, a); . let mut found = None; . 116 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 116 ( 0.00%) if autoderefs == 0 { . // Don't let this pass, otherwise it would cause . // &T to autoref to &&T. . continue; . } . . // At this point, we have deref'd `a` to `referent_ty`. So . // imagine we are coercing from `&'a mut Vec` to `&'b mut [T]`. . // In the autoderef loop for `&'a mut Vec`, we would get -- line 326 ---------------------------------------- -- line 386 ---------------------------------------- . // this extra edge causes the region `'a` to be inferred to something . // too big, which then results in borrowck errors.) . // - We could track the innermost shared reference, but there is already . // code in regionck that has the job of creating links between . // the region of a borrow and the regions in the thing being . // borrowed (here, `'a` and `'x`), and it knows how to handle . // all the various cases. So instead we just make a region variable . // and let regionck figure it out. 58 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above . } else if autoderefs == 1 { . r_a // [3] above . } else { . if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); . let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 29 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 203 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 116 ( 0.00%) found = Some(ok); . break; . } . Err(err) => { . if first_error.is_none() { . first_error = Some(err); . } . } . } . } . . // Extract type or return an error. We return the first error . // we got, which should be from relating the "base" type . // (e.g., in example above, the failure from relating `Vec` . // to the target type), since that should be the least . // confusing. 232 ( 0.00%) let InferOk { value: ty, mut obligations } = match found { . Some(d) => d, . None => { . let err = first_error.expect("coerce_borrowed_pointer had no error"); . debug!("coerce_borrowed_pointer: failed with err = {:?}", err); . return Err(err); . } . }; . 169 ( 0.00%) if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 { . // As a special case, if we would produce `&'a *x`, that's . // a total no-op. We end up with the type `&'a T` just as . // we started with. In that case, just skip it . // altogether. This is just an optimization. . // . // Note that for `&mut`, we DO want to reborrow -- . // otherwise, this would be a move, which might be an . // error. For example `foo(self.x)` where `self` and . // `self.x` both have `&mut `type would be a move of . // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`, . // which is a borrow. 56 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 112 ( 0.00%) return success(vec![], ty, obligations); . } . 7 ( 0.00%) let InferOk { value: mut adjustments, obligations: o } = 1 ( 0.00%) self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); 19 ( 0.00%) obligations.extend(autoderef.into_obligations()); . . // Now apply the autoref. We have to extract the region out of . // the final ref type we got. 2 ( 0.00%) let r_borrow = match ty.kind() { . ty::Ref(r_borrow, _, _) => r_borrow, . _ => span_bug!(span, "expected a ref type, got {:?}", ty), . }; 4 ( 0.00%) let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => { . AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase } . } . }; . adjustments.push(Adjustment { 1 ( 0.00%) kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . 8 ( 0.00%) success(adjustments, ty, obligations) 232 ( 0.00%) } . . // &[T; n] or &mut [T; n] -> &[T] . // or &mut [T; n] -> &mut [T] . // or &Concrete -> &Trait, etc. . #[instrument(skip(self), level = "debug")] . fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> { . source = self.shallow_resolve(source); . target = self.shallow_resolve(target); -- line 490 ---------------------------------------- -- line 506 ---------------------------------------- . // would need to be generic over the self-type (`impl CoerceUnsized for T`) . // or generic over the `CoerceUnsized` type parameter (`impl CoerceUnsized for . // SomeType`). . // . // However, these are exactly the kinds of impls which are forbidden by . // the compiler! Therefore, we can be sure that coercion will always fail . // when either the source or target type is a type variable. This allows us . // to skip performing any trait selection, and immediately bail out. 231 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 231 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 2,772 ( 0.00%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 924 ( 0.00%) let (Some(unsize_did), Some(coerce_unsized_did)) = traits else { . debug!("missing Unsize or CoerceUnsized traits"); . return Err(TypeError::Mismatch); . }; . . // Note, we want to avoid unnecessary unsizing. We don't want to coerce to . // a DST unless we have to. This currently comes out in the wash since . // we can't unify [T] with U. But to properly support DST, we need to allow . // that, at which point we will need extra checks on the target here. . . // Handle reborrows before selecting `Source: CoerceUnsized`. 633 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 171 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 57 ( 0.00%) let coercion = Coercion(self.cause.span); 285 ( 0.00%) let r_borrow = self.next_region_var(coercion); . let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => AutoBorrowMutability::Mut { . // We don't allow two-phase borrows here, at least for initial . // implementation. If it happens that this coercion is a function argument, . // the reborrow in coerce_borrowed_ptr will pick it up. . allow_two_phase_borrow: AllowTwoPhase::No, . }, . }; . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), 57 ( 0.00%) target: self . .tcx . .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }), . }, . )) . } . (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => { . coerce_mutbls(mt_a, mt_b)?; . -- line 563 ---------------------------------------- -- line 574 ---------------------------------------- . let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target); . . // Setup either a subtyping or a LUB relationship between . // the `CoerceUnsized` target type and the expected type. . // We only have the latter, so we use an inference variable . // for the former and let type inference do the rest. . let origin = TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, 231 ( 0.00%) span: self.cause.span, . }; 1,155 ( 0.00%) let coerce_target = self.next_ty_var(origin); 924 ( 0.00%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 462 ( 0.00%) match reborrow { 870 ( 0.00%) None => vec![unsize], 798 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 231 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 462 ( 0.00%) self.cause.span, 462 ( 0.00%) self.body_id, . ObligationCauseCode::Coercion { source, target }, . ); . . // Use a FIFO queue for this custom fulfillment procedure. . // . // A Vec (or SmallVec) is not a natural choice for a queue. However, . // this code path is hot, and this queue usually has a max length of 1 . // and almost never more than 3. By using a SmallVec we avoid an . // allocation, at the (very small) cost of (occasionally) having to . // shift subsequent elements down when removing the front element. 3,234 ( 0.00%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 462 ( 0.00%) self.tcx, 231 ( 0.00%) self.fcx.param_env, 1,155 ( 0.00%) cause, . coerce_unsized_did, . 0, . coerce_source, 1,155 ( 0.00%) &[coerce_target.into()] . )]; . . let mut has_unsized_tuple_coercion = false; . let mut has_trait_upcasting_coercion = false; . . // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid . // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where . // inference might unify those two inner type variables later. . let traits = [coerce_unsized_did, unsize_did]; 746 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 345 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 1,725 ( 0.00%) let trait_pred = match bound_predicate.skip_binder() { 1,728 ( 0.00%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 2,592 ( 0.00%) if unsize_did == trait_pred.def_id() { 342 ( 0.00%) let self_ty = trait_pred.self_ty(); 228 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 285 ( 0.00%) if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) = . (self_ty.kind(), unsize_ty.kind()) . { . if data_a.principal_def_id() != data_b.principal_def_id() { . debug!("coerce_unsized: found trait upcasting coercion"); . has_trait_upcasting_coercion = true; . } . } 342 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 576 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 342 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 3,168 ( 0.00%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { . if trait_pred.def_id() == unsize_did { . let trait_pred = self.resolve_vars_if_possible(trait_pred); . let self_ty = trait_pred.skip_binder().self_ty(); . let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); . match (&self_ty.kind(), &unsize_ty.kind()) { -- line 663 ---------------------------------------- -- line 679 ---------------------------------------- . } . } else { . debug!("coerce_unsized: early return - ambiguous"); . return Err(TypeError::Mismatch); . } . } . Err(traits::Unimplemented) => { . debug!("coerce_unsized: early return - can't prove obligation"); 1,218 ( 0.00%) return Err(TypeError::Mismatch); . } . . // Object safety violations or miscellaneous. . Err(err) => { . self.report_selection_error(obligation.clone(), &obligation, &err, false); . // Treat this like an obligation and follow through . // with the unsizing - the lack of a coercion should . // be silent, as it causes a type mismatch later. . } . 1,615 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 406 ( 0.00%) } . 56 ( 0.00%) if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { . feature_err( . &self.tcx.sess.parse_sess, . sym::unsized_tuple_coercion, . self.cause.span, . "unsized tuple coercion is not stable enough for use and is subject to change", . ) . .emit(); . } . 56 ( 0.00%) if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { . feature_err( . &self.tcx.sess.parse_sess, . sym::trait_upcasting, . self.cause.span, . "trait upcasting coercion is experimental", . ) . .emit(); . } . 308 ( 0.00%) Ok(coercion) . } . . fn coerce_from_safe_fn( . &self, . a: Ty<'tcx>, . fn_ty_a: ty::PolyFnSig<'tcx>, . b: Ty<'tcx>, . to_unsafe: F, -- line 730 ---------------------------------------- -- line 906 ---------------------------------------- . } . } . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { . /// Attempt to coerce an expression to a type, and return the . /// adjusted type of the expression, if successful. . /// Adjustments are only recorded if the coercion succeeded. . /// The expressions *must not* have any pre-existing adjustments. 3,234 ( 0.00%) pub fn try_coerce( . &self, . expr: &hir::Expr<'_>, . expr_ty: Ty<'tcx>, . target: Ty<'tcx>, . allow_two_phase: AllowTwoPhase, . cause: Option>, . ) -> RelateResult<'tcx, Ty<'tcx>> { 693 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 231 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 2,772 ( 0.00%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 924 ( 0.00%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 2,310 ( 0.00%) self.apply_adjustments(expr, adjustments); 693 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 2,079 ( 0.00%) } . . /// Same as `try_coerce()`, but without side-effects. . /// . /// Returns false if the coercion creates any obligations that result in . /// errors. . pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { . let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::can_with_predicates({:?} -> {:?})", source, target); -- line 941 ---------------------------------------- -- line 967 ---------------------------------------- . } . . /// Given some expressions, their known unified type and another expression, . /// tries to unify the types, potentially inserting coercions on any of the . /// provided expressions and returns their LUB (aka "common supertype"). . /// . /// This is really an internal helper. From outside the coercion . /// module, you should instantiate a `CoerceMany` instance. 379,496 ( 0.04%) fn try_find_coercion_lub( . &self, . cause: &ObligationCause<'tcx>, . exprs: &[E], . prev_ty: Ty<'tcx>, . new: &hir::Expr<'_>, . new_ty: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> . where . E: AsCoercionSite, . { 175,152 ( 0.02%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 87,576 ( 0.01%) let new_ty = self.resolve_vars_with_obligations(new_ty); . debug!( . "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)", . prev_ty, . new_ty, . exprs.len() . ); . . // The following check fixes #88097, where the compiler erroneously . // attempted to coerce a closure type to itself via a function pointer. 29,192 ( 0.00%) if prev_ty == new_ty { 29,192 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. . let (a_sig, b_sig) = { . let is_capturing_closure = |ty| { . if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() -- line 1006 ---------------------------------------- -- line 1100 ---------------------------------------- . // at that time. . let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No); . coerce.use_lub = true; . . // First try to coerce the new expression to the type of the previous ones, . // but only if the new expression has no coercion already applied to it. . let mut first_error = None; . if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 231 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); . match result { . Ok(ok) => { . let (adjustments, target) = self.register_infer_ok_obligations(ok); . self.apply_adjustments(new, adjustments); . debug!( . "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}", . prev_ty, new_ty, . ); -- line 1116 ---------------------------------------- -- line 1175 ---------------------------------------- . let (adjustments, target) = self.register_infer_ok_obligations(ok); . for expr in exprs { . let expr = expr.as_coercion_site(); . self.apply_adjustments(expr, adjustments.clone()); . } . Ok(target) . } . } 262,728 ( 0.03%) } . } . . /// CoerceMany encapsulates the pattern you should use when you have . /// many expressions that are all getting coerced to a common . /// type. This arises, for example, when you have a match (the result . /// of each arm is coerced to a common type). It also arises in less . /// obvious places, such as when you have many `break foo` expressions . /// that target the same loop, or the various `return` expressions in -- line 1191 ---------------------------------------- -- line 1253 ---------------------------------------- . /// expected to pass each element in the slice to `coerce(...)` in . /// order. This is used with arrays in particular to avoid . /// needlessly cloning the slice. . pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { . Self::make(expected_ty, Expressions::UpFront(coercion_sites)) . } . . fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self { 184 ( 0.00%) CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 } . } . . /// Returns the "expected type" with which this coercion was . /// constructed. This represents the "downward propagated" type . /// that was given to us at the start of typing whatever construct . /// we are typing (e.g., the match expression). . /// . /// Typically, this is used as the expected type when -- line 1269 ---------------------------------------- -- line 1281 ---------------------------------------- . self.final_ty.unwrap_or(self.expected_ty) . } . . /// Indicates that the value generated by `expression`, which is . /// of type `expression_ty`, is one of the possibilities that we . /// could coerce from. This will record `expression`, and later . /// calls to `coerce` may come back and add adjustments and things . /// if necessary. 350,508 ( 0.04%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 504 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 233,672 ( 0.02%) } . . /// Indicates that one of the inputs is a "forced unit". This . /// occurs in a case like `if foo { ... };`, where the missing else . /// generates a "forced unit". Another example is a `loop { break; . /// }`, where the `break` has no argument expression. We treat . /// these cases slightly differently for error-reporting . /// purposes. Note that these tend to correspond to cases where . /// the `()` expression is implicit in the source, and hence we do -- line 1305 ---------------------------------------- -- line 1323 ---------------------------------------- . Some(augment_error), . label_unit_as_expected, . ) . } . . /// The inner coercion "engine". If `expression` is `None`, this . /// is a forced-unit case, and hence `expression_ty` must be . /// `Nil`. 1,785 ( 0.00%) #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")] . crate fn coerce_inner<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: Option<&'tcx hir::Expr<'tcx>>, . mut expression_ty: Ty<'tcx>, . augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>, . label_expression_as_expected: bool, . ) { . // Incorporate whatever type inference information we have . // until now; in principle we might also want to process . // pending obligations, but doing so should only improve . // compatibility (hopefully that is true) by helping us . // uncover never types better. 29,294 ( 0.00%) if expression_ty.is_ty_var() { . expression_ty = fcx.infcx.shallow_resolve(expression_ty); . } . . // If we see any error types, just propagate that error . // upwards. 117,176 ( 0.01%) if expression_ty.references_error() || self.merged_ty().references_error() { . self.final_ty = Some(fcx.tcx.ty_error()); . return; . } . . // Handle the actual type unification etc. 255 ( 0.00%) let result = if let Some(expression) = expression { 87,882 ( 0.01%) if self.pushed == 0 { . // Special-case the first expression we are coercing. . // To be honest, I'm not entirely sure why we do this. . // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why 918 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 408 ( 0.00%) Some(cause.clone()), . ) . } else { 58,384 ( 0.01%) match self.expressions { . Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 175,163 ( 0.02%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 87,576 ( 0.01%) &coercion_sites[0..self.pushed], . self.merged_ty(), . expression, . expression_ty, . ), . } . } . } else { . // this is a hack for cases where we default to `()` because -- line 1389 ---------------------------------------- -- line 1403 ---------------------------------------- . fcx.at(cause, fcx.param_env) . .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty()) . .map(|infer_ok| { . fcx.register_infer_ok_obligations(infer_ok); . expression_ty . }) . }; . 58,599 ( 0.01%) match result { 29,294 ( 0.00%) Ok(v) => { 29,294 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 58,588 ( 0.01%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 58,516 ( 0.01%) Expressions::UpFront(coercion_sites) => { . // if the user gave us an array to validate, check that we got . // the next expression in the list, as expected 116,983 ( 0.01%) assert_eq!( 87,774 ( 0.01%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 117,212 ( 0.01%) self.pushed += 1; . } . } . Err(coercion_error) => { . let (expected, found) = if label_expression_as_expected { . // In the case where this is a "forced unit", like . // `break`, we want to call the `()` "expected" . // since it is implied by the syntax. . // (Note: not all force-units work this way.)" -- line 1434 ---------------------------------------- -- line 1707 ---------------------------------------- . if let ty::Dynamic(..) = ty.kind() { . return true; . } . } . } . false . } . 120 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 306 ( 0.00%) if let Some(final_ty) = self.final_ty { . final_ty . } else { . // If we only had inputs that were of type `!` (or no . // inputs at all), then the final type is `!`. . assert_eq!(self.pushed, 0); . fcx.tcx.types.never . } 150 ( 0.00%) } . } . . /// Something that can be converted into an expression to which we can . /// apply a coercion. . pub trait AsCoercionSite { . fn as_coercion_site(&self) -> &hir::Expr<'_>; . } . -- line 1732 ---------------------------------------- -- line 1736 ---------------------------------------- . } . } . . impl<'a, T> AsCoercionSite for &'a T . where . T: AsCoercionSite, . { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 36 ( 0.00%) (**self).as_coercion_site() . } . } . . impl AsCoercionSite for ! { . fn as_coercion_site(&self) -> &hir::Expr<'_> { . unreachable!() . } . } . . impl AsCoercionSite for hir::Arm<'_> { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 26 ( 0.00%) &self.body . } . } 124,965 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . AstFragmentKind::OptExpr => . result.make_expr().map(Some).map(AstFragment::OptExpr), . $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)* . } . } . } . . impl AstFragment { 1 ( 0.00%) pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { 1 ( 0.00%) if placeholders.is_empty() { . return; . } . match self { . $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| { . // We are repeating through arguments with `many`, to do that we have to . // mention some macro variable from those arguments even if it's not used. . macro _repeating($flat_map_ast_elt) {} . placeholder(AstFragmentKind::$Kind, *id, None).$make_ast() . })),)?)* . _ => panic!("unexpected AST fragment kind") . } 2 ( 0.00%) } . . pub fn make_opt_expr(self) -> Option> { . match self { . AstFragment::OptExpr(expr) => expr, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . } . . $(pub fn $make_ast(self) -> $AstTy { 2 ( 0.00%) match self { 9 ( 0.00%) AstFragment::$Kind(ast) => ast, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . })* . . fn make_ast(self) -> T::OutputTy { . T::fragment_to_output(self) . } . 2 ( 0.00%) pub fn mut_visit_with(&mut self, vis: &mut F) { 11 ( 0.00%) match self { . AstFragment::OptExpr(opt_expr) => { . visit_clobber(opt_expr, |opt_expr| { . if let Some(expr) = opt_expr { . vis.filter_map_expr(expr) . } else { . None . } . }); . } 9 ( 0.00%) $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)* . $($(AstFragment::$Kind(ast) => . ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)* . } . } . 18 ( 0.00%) pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { 10 ( 0.00%) match *self { . AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr), . AstFragment::OptExpr(None) => {} 11 ( 0.00%) $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)* . $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] { . visitor.$visit_ast_elt(ast_elt, $($args)*); . })?)* . } . } . } . . impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> { -- line 142 ---------------------------------------- -- line 358 ---------------------------------------- . monotonic: bool, // cf. `cx.monotonic_expander()` . } . . impl<'a, 'b> MacroExpander<'a, 'b> { . pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { . MacroExpander { cx, monotonic } . } . 10 ( 0.00%) pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate { 6 ( 0.00%) let file_path = match self.cx.source_map().span_to_filename(krate.span) { 11 ( 0.00%) FileName::Real(name) => name . .into_local_path() . .expect("attempting to resolve a file path in an external file"), . other => PathBuf::from(other.prefer_local().to_string()), . }; 4 ( 0.00%) let dir_path = file_path.parent().unwrap_or(&file_path).to_owned(); 3 ( 0.00%) self.cx.root_path = dir_path.clone(); 1 ( 0.00%) self.cx.current_expansion.module = Rc::new(ModuleData { 3 ( 0.00%) mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)], 4 ( 0.00%) file_path_stack: vec![file_path], . dir_path, . }); 13 ( 0.00%) let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate(); 1 ( 0.00%) assert_eq!(krate.id, ast::CRATE_NODE_ID); 2 ( 0.00%) self.cx.trace_macros_diag(); . krate 9 ( 0.00%) } . . // Recursively expand all macro invocations in this AST fragment. 9 ( 0.00%) pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment { 1 ( 0.00%) let orig_expansion_data = self.cx.current_expansion.clone(); 3 ( 0.00%) let orig_force_mode = self.cx.force_mode; . . // Collect all macro invocations and replace them with placeholders. 8 ( 0.00%) let (mut fragment_with_placeholders, mut invocations) = 10 ( 0.00%) self.collect_invocations(input_fragment, &[]); . . // Optimization: if we resolve all imports now, . // we'll be able to immediately resolve most of imported macros. . self.resolve_imports(); . . // Resolve paths in all invocations and produce output expanded fragments for them, but . // do not insert them into our input AST fragment yet, only store in `expanded_fragments`. . // The output fragments also go through expansion recursively until no invocations are left. . // Unresolved macros produce dummy outputs as a recovery measure. . invocations.reverse(); . let mut expanded_fragments = Vec::new(); . let mut undetermined_invocations = Vec::new(); 6 ( 0.00%) let (mut progress, mut force) = (false, !self.monotonic); . loop { . let Some((invoc, ext)) = invocations.pop() else { . self.resolve_imports(); 1 ( 0.00%) if undetermined_invocations.is_empty() { . break; . } . invocations = mem::take(&mut undetermined_invocations); . force = !mem::replace(&mut progress, false); . if force && self.monotonic { . self.cx.sess.delay_span_bug( . invocations.last().unwrap().0.span(), . "expansion entered force mode without producing any errors", -- line 418 ---------------------------------------- -- line 506 ---------------------------------------- . progress = true; . if expanded_fragments.len() < depth { . expanded_fragments.push(Vec::new()); . } . expanded_fragments[depth - 1].push((expn_id, expanded_fragment)); . invocations.extend(new_invocations.into_iter().rev()); . } . 23 ( 0.00%) self.cx.current_expansion = orig_expansion_data; 1 ( 0.00%) self.cx.force_mode = orig_force_mode; . . // Finally incorporate all the expanded macros into the input AST fragment. . let mut placeholder_expander = PlaceholderExpander::default(); . while let Some(expanded_fragments) = expanded_fragments.pop() { . for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() { . placeholder_expander . .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment); . } . } 1 ( 0.00%) fragment_with_placeholders.mut_visit_with(&mut placeholder_expander); . fragment_with_placeholders 8 ( 0.00%) } . . fn resolve_imports(&mut self) { 7 ( 0.00%) if self.monotonic { 8 ( 0.00%) self.cx.resolver.resolve_imports(); . } . } . . /// Collects all macro invocations reachable at this time in this AST fragment, and replace . /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s. . /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and . /// prepares data for resolving paths of macro invocations. 12 ( 0.00%) fn collect_invocations( . &mut self, . mut fragment: AstFragment, . extra_placeholders: &[NodeId], . ) -> (AstFragment, Vec<(Invocation, Option>)>) { . // Resolve `$crate`s in the fragment for pretty-printing. 4 ( 0.00%) self.cx.resolver.resolve_dollar_crates(); . . let mut invocations = { 6 ( 0.00%) let mut collector = InvocationCollector { . // Non-derive macro invocations cannot see the results of cfg expansion - they . // will either be removed along with the item, or invoked before the cfg/cfg_attr . // attribute is expanded. Therefore, we don't need to configure the tokens . // Derive macros *can* see the results of cfg-expansion - they are handled . // specially in `fully_expand_fragment` . cfg: StripUnconfigured { 1 ( 0.00%) sess: &self.cx.sess, 1 ( 0.00%) features: self.cx.ecfg.features, . config_tokens: false, . }, . cx: self.cx, . invocations: Vec::new(), 1 ( 0.00%) monotonic: self.monotonic, . }; . fragment.mut_visit_with(&mut collector); 4 ( 0.00%) fragment.add_placeholders(extra_placeholders); 4 ( 0.00%) collector.invocations . }; . 2 ( 0.00%) if self.monotonic { 3 ( 0.00%) self.cx . .resolver 2 ( 0.00%) .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment); . 3 ( 0.00%) if self.cx.sess.opts.debugging_opts.incremental_relative_spans { . for (invoc, _) in invocations.iter_mut() { . let expn_id = invoc.expansion_data.id; . let parent_def = self.cx.resolver.invocation_parent(expn_id); . let span = match &mut invoc.kind { . InvocationKind::Bang { ref mut span, .. } => span, . InvocationKind::Attr { attr, .. } => &mut attr.span, . InvocationKind::Derive { path, .. } => &mut path.span, . }; . *span = span.with_parent(Some(parent_def)); . } . } . } . 9 ( 0.00%) (fragment, invocations) 8 ( 0.00%) } . . fn error_recursion_limit_reached(&mut self) { . let expn_data = self.cx.current_expansion.id.expn_data(); . let suggested_limit = match self.cx.ecfg.recursion_limit { . Limit(0) => Limit(2), . limit => limit * 2, . }; . self.cx -- line 596 ---------------------------------------- -- line 1031 ---------------------------------------- . fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {} . fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) { . } . fn wrap_flat_map_node_noop_flat_map( . node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 876 ( 0.00%) Ok(noop_flat_map(node, collector)) . } . } . . impl InvocationCollectorNode for P { . const KIND: AstFragmentKind = AstFragmentKind::Items; . fn to_annotatable(self) -> Annotatable { . Annotatable::Item(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 102 ( 0.00%) noop_flat_map_item(self, visitor) . } . fn is_mac_call(&self) -> bool { 34 ( 0.00%) matches!(self.kind, ItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } 374 ( 0.00%) fn wrap_flat_map_node_noop_flat_map( . mut node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 68 ( 0.00%) if !matches!(node.kind, ItemKind::Mod(..)) { 198 ( 0.00%) return Ok(noop_flat_map(node, collector)); . } . . // Work around borrow checker not seeing through `P`'s deref. 11 ( 0.00%) let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs)); . let ItemKind::Mod(_, mod_kind) = &mut node.kind else { . unreachable!() . }; . . let ecx = &mut collector.cx; 2 ( 0.00%) let (file_path, dir_path, dir_ownership) = match mod_kind { . ModKind::Loaded(_, inline, _) => { . // Inline `mod foo { ... }`, but we still need to push directories. . let (dir_path, dir_ownership) = mod_dir_path( . &ecx.sess, . ident, . &attrs, . &ecx.current_expansion.module, . ecx.current_expansion.dir_ownership, . *inline, . ); . node.attrs = attrs; . (None, dir_path, dir_ownership) . } . ModKind::Unloaded => { . // We have an outline `mod foo;` so we need to parse the file. 2 ( 0.00%) let old_attrs_len = attrs.len(); 19 ( 0.00%) let ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership } = 8 ( 0.00%) parse_external_mod( 2 ( 0.00%) &ecx.sess, 2 ( 0.00%) ident, . span, 1 ( 0.00%) &ecx.current_expansion.module, 1 ( 0.00%) ecx.current_expansion.dir_ownership, . &mut attrs, . ); . 5 ( 0.00%) if let Some(lint_store) = ecx.lint_store { 13 ( 0.00%) lint_store.pre_expansion_lint( 2 ( 0.00%) ecx.sess, 4 ( 0.00%) ecx.resolver.registered_tools(), 2 ( 0.00%) ecx.current_expansion.lint_node_id, . &attrs, . &items, 1 ( 0.00%) ident.name.as_str(), . ); . } . 12 ( 0.00%) *mod_kind = ModKind::Loaded(items, Inline::No, inner_span); 9 ( 0.00%) node.attrs = attrs; 2 ( 0.00%) if node.attrs.len() > old_attrs_len { . // If we loaded an out-of-line module and added some inner attributes, . // then we need to re-configure it and re-collect attributes for . // resolution and expansion. . return Err(node); . } . (Some(file_path), dir_path, dir_ownership) . } . }; . . // Set the module info before we flat map. 7 ( 0.00%) let mut module = ecx.current_expansion.module.with_dir_path(dir_path); 2 ( 0.00%) module.mod_path.push(ident); 2 ( 0.00%) if let Some(file_path) = file_path { . module.file_path_stack.push(file_path); . } . 2 ( 0.00%) let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module)); . let orig_dir_ownership = 1 ( 0.00%) mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership); . 5 ( 0.00%) let res = Ok(noop_flat_map(node, collector)); . 3 ( 0.00%) collector.cx.current_expansion.dir_ownership = orig_dir_ownership; 4 ( 0.00%) collector.cx.current_expansion.module = orig_module; 4 ( 0.00%) res 306 ( 0.00%) } . } . . struct TraitItemTag; . impl InvocationCollectorNode for AstLikeWrapper, TraitItemTag> { . type OutputTy = SmallVec<[P; 1]>; . const KIND: AstFragmentKind = AstFragmentKind::TraitItems; . fn to_annotatable(self) -> Annotatable { . Annotatable::TraitItem(self.wrapped) -- line 1157 ---------------------------------------- -- line 1158 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_trait_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 70 ( 0.00%) noop_flat_map_assoc_item(self.wrapped, visitor) . } . fn is_mac_call(&self) -> bool { 35 ( 0.00%) matches!(self.wrapped.kind, AssocItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let item = self.wrapped.into_inner(); . match item.kind { . AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1177 ---------------------------------------- -- line 1186 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_impl_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 56 ( 0.00%) noop_flat_map_assoc_item(self.wrapped, visitor) . } . fn is_mac_call(&self) -> bool { 28 ( 0.00%) matches!(self.wrapped.kind, AssocItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let item = self.wrapped.into_inner(); . match item.kind { . AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1205 ---------------------------------------- -- line 1302 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_params() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 975 ( 0.00%) noop_flat_map_param(self, visitor) . } . } . . impl InvocationCollectorNode for ast::GenericParam { . const KIND: AstFragmentKind = AstFragmentKind::GenericParams; . fn to_annotatable(self) -> Annotatable { . Annotatable::GenericParam(self) . } -- line 1318 ---------------------------------------- -- line 1334 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_arms() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 195 ( 0.00%) noop_flat_map_arm(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Stmt { . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::Stmts; . fn to_annotatable(self) -> Annotatable { . Annotatable::Stmt(P(self)) -- line 1350 ---------------------------------------- -- line 1410 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_crate() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 3 ( 0.00%) noop_visit_crate(self, visitor) . } . } . . impl InvocationCollectorNode for P { . type OutputTy = P; . const KIND: AstFragmentKind = AstFragmentKind::Ty; . fn to_annotatable(self) -> Annotatable { . unreachable!() -- line 1426 ---------------------------------------- -- line 1427 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_ty() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 432 ( 0.00%) noop_visit_ty(self, visitor) . } . fn is_mac_call(&self) -> bool { 216 ( 0.00%) matches!(self.kind, ast::TyKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . TyKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1446 ---------------------------------------- -- line 1454 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_pat() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 156 ( 0.00%) noop_visit_pat(self, visitor) . } . fn is_mac_call(&self) -> bool { 78 ( 0.00%) matches!(self.kind, PatKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . PatKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1473 ---------------------------------------- -- line 1485 ---------------------------------------- . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn descr() -> &'static str { . "an expression" . } . fn noop_visit(&mut self, visitor: &mut V) { 498 ( 0.00%) noop_visit_expr(self, visitor) . } . fn is_mac_call(&self) -> bool { 166 ( 0.00%) matches!(self.kind, ExprKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1504 ---------------------------------------- -- line 1514 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_opt_expr() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(mut self, visitor: &mut V) -> Self::OutputTy { 58,666 ( 0.01%) noop_visit_expr(&mut self.wrapped, visitor); . Some(self.wrapped) . } . fn is_mac_call(&self) -> bool { 58,666 ( 0.01%) matches!(self.wrapped.kind, ast::ExprKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.wrapped.into_inner(); . match node.kind { . ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1534 ---------------------------------------- -- line 1581 ---------------------------------------- . . /// If `item` is an attribute invocation, remove the attribute and return it together with . /// its position and derives following it. We have to collect the derives in order to resolve . /// legacy derive helpers (helpers written before derives that introduce them). . fn take_first_attr( . &self, . item: &mut impl AstLike, . ) -> Option<(ast::Attribute, usize, Vec)> { 29,676 ( 0.00%) let mut attr = None; . 29,676 ( 0.00%) let mut cfg_pos = None; 59,273 ( 0.01%) let mut attr_pos = None; 158 ( 0.00%) for (pos, attr) in item.attrs().iter().enumerate() { 702 ( 0.00%) if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) { 76 ( 0.00%) let name = attr.ident().map(|ident| ident.name); 152 ( 0.00%) if name == Some(sym::cfg) || name == Some(sym::cfg_attr) { 2 ( 0.00%) cfg_pos = Some(pos); // a cfg attr found, no need to search anymore . break; 111 ( 0.00%) } else if attr_pos.is_none() . && !name.map_or(false, rustc_feature::is_builtin_attr_name) . { . attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr . } . } . } . . item.visit_attrs(|attrs| { 118,743 ( 0.01%) attr = Some(match (cfg_pos, attr_pos) { 17 ( 0.00%) (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()), . (_, Some(pos)) => { . let attr = attrs.remove(pos); . let following_derives = attrs[pos..] . .iter() . .filter(|a| a.has_name(sym::derive)) . .flat_map(|a| a.meta_item_list().unwrap_or_default()) . .filter_map(|nested_meta| match nested_meta { . NestedMetaItem::MetaItem(ast::MetaItem { -- line 1617 ---------------------------------------- -- line 1679 ---------------------------------------- . } . . fn expand_cfg_true( . &mut self, . node: &mut impl AstLike, . attr: ast::Attribute, . pos: usize, . ) -> bool { 2 ( 0.00%) let res = self.cfg.cfg_true(&attr); 2 ( 0.00%) if res { . // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion, . // and some tools like rustdoc and clippy rely on that. Find a way to remove them . // while keeping the tools working. . self.cx.expanded_inert_attrs.mark(&attr); . node.visit_attrs(|attrs| attrs.insert(pos, attr)); . } . res . } -- line 1696 ---------------------------------------- -- line 1701 ---------------------------------------- . }); . } . . fn flat_map_node>( . &mut self, . mut node: Node, . ) -> Node::OutputTy { . loop { 88,605 ( 0.01%) return match self.take_first_attr(&mut node) { 28 ( 0.00%) Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { 17 ( 0.00%) if self.expand_cfg_true(&mut node, attr, pos) { . continue; . } . Default::default() . } . sym::cfg_attr => { . self.expand_cfg_attr(&mut node, attr, pos); . continue; . } . _ => { . Node::pre_flat_map_node_collect_attr(&self.cfg, &attr); . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . } . }, 29,430 ( 0.00%) None if node.is_mac_call() => { . let (mac, attrs, add_semicolon) = node.take_mac_call(); . self.check_attributes(&attrs, &mac); . let mut res = self.collect_bang(mac, Node::KIND).make_ast::(); . Node::post_flat_map_node_collect_bang(&mut res, add_semicolon); . res . } . None => { 204 ( 0.00%) match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| { 383,332 ( 0.04%) assign_id!(this, node.id(), || node.noop_flat_map(this)) . }) { 634 ( 0.00%) Ok(output) => output, . Err(returned_node) => { 69 ( 0.00%) node = returned_node; . continue; . } . } . } . }; . } 1 ( 0.00%) } . . fn visit_node + DummyAstNode>( . &mut self, . node: &mut Node, . ) { . loop { 667 ( 0.00%) return match self.take_first_attr(node) { . Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { . let span = attr.span; . if self.expand_cfg_true(node, attr, pos) { . continue; . } . let msg = . format!("removing {} is not supported in this position", Node::descr()); -- line 1762 ---------------------------------------- -- line 1767 ---------------------------------------- . self.expand_cfg_attr(node, attr, pos); . continue; . } . _ => visit_clobber(node, |node| { . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . }), . }, 460 ( 0.00%) None if node.is_mac_call() => { . visit_clobber(node, |node| { . // Do not clobber unless it's actually a macro (uncommon case). . let (mac, attrs, _) = node.take_mac_call(); . self.check_attributes(&attrs, &mac); . self.collect_bang(mac, Node::KIND).make_ast::() . }) . } . None => { 5,699 ( 0.00%) assign_id!(self, node.id(), || node.noop_visit(self)) . } . }; . } . } . } . . impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { 490 ( 0.00%) fn flat_map_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(node) 315 ( 0.00%) } . 560 ( 0.00%) fn flat_map_trait_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, TraitItemTag)) 315 ( 0.00%) } . 448 ( 0.00%) fn flat_map_impl_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, ImplItemTag)) 252 ( 0.00%) } . . fn flat_map_foreign_item( . &mut self, . node: P, . ) -> SmallVec<[P; 1]> { . self.flat_map_node(node) . } . -- line 1810 ---------------------------------------- -- line 1819 ---------------------------------------- . fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> { . self.flat_map_node(node) . } . . fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> { . self.flat_map_node(node) . } . 520 ( 0.00%) fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> { 780 ( 0.00%) self.flat_map_node(node) 585 ( 0.00%) } . . fn flat_map_generic_param( . &mut self, . node: ast::GenericParam, . ) -> SmallVec<[ast::GenericParam; 1]> { . self.flat_map_node(node) . } . 104 ( 0.00%) fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> { 156 ( 0.00%) self.flat_map_node(node) 117 ( 0.00%) } . 360 ( 0.00%) fn flat_map_stmt(&mut self, mut node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> { . // FIXME: invocations in semicolon-less expressions positions are expanded as expressions, . // changing that requires some compatibility measures. 144 ( 0.00%) if node.is_expr() { . // The only way that we can end up with a `MacCall` expression statement, . // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the . // traiing expression in a block (e.g. `fn foo() { my_macro!() }`). . // Record this information, so that we can report a more specific . // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed. . // See #78991 for an investigation of treating macros in this position . // as statements, rather than expressions, during parsing. 72 ( 0.00%) return match &node.kind { . StmtKind::Expr(expr) 72 ( 0.00%) if matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) => . { . self.cx.current_expansion.is_trailing_mac = true; . // Don't use `assign_id` for this statement - it may get removed . // entirely due to a `#[cfg]` on the contained expression . let res = noop_flat_map_stmt(node, self); . self.cx.current_expansion.is_trailing_mac = false; . res . } 864 ( 0.00%) _ => assign_id!(self, &mut node.id, || noop_flat_map_stmt(node, self)), . }; . } . . self.flat_map_node(node) 288 ( 0.00%) } . 13 ( 0.00%) fn visit_crate(&mut self, node: &mut ast::Crate) { . self.visit_node(node) 8 ( 0.00%) } . 1,728 ( 0.00%) fn visit_ty(&mut self, node: &mut P) { . self.visit_node(node) 1,728 ( 0.00%) } . 624 ( 0.00%) fn visit_pat(&mut self, node: &mut P) { . self.visit_node(node) 624 ( 0.00%) } . 1,494 ( 0.00%) fn visit_expr(&mut self, node: &mut P) { . // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`. . if let Some(attr) = node.attrs.first() { . self.cfg.maybe_emit_expr_attr_err(attr); . } . self.visit_node(node) 1,328 ( 0.00%) } . 498,661 ( 0.05%) fn filter_map_expr(&mut self, node: P) -> Option> { . self.flat_map_node(AstLikeWrapper::new(node, OptExprTag)) 234,664 ( 0.02%) } . . fn visit_block(&mut self, node: &mut P) { . let orig_dir_ownership = mem::replace( 36 ( 0.00%) &mut self.cx.current_expansion.dir_ownership, . DirOwnership::UnownedViaBlock, . ); . noop_visit_block(node, self); 144 ( 0.00%) self.cx.current_expansion.dir_ownership = orig_dir_ownership; . } . . fn visit_id(&mut self, id: &mut NodeId) { . // We may have already assigned a `NodeId` . // by calling `assign_id` 122,518 ( 0.01%) if self.monotonic && *id == ast::DUMMY_NODE_ID { 1,879 ( 0.00%) *id = self.cx.resolver.next_node_id(); . } . } . } . . pub struct ExpansionConfig<'feat> { . pub crate_name: String, . pub features: Option<&'feat Features>, . pub recursion_limit: Limit, . pub trace_mac: bool, . pub should_test: bool, // If false, strip `#[test]` nodes . pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span` . pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics . } . . impl<'feat> ExpansionConfig<'feat> { 12 ( 0.00%) pub fn default(crate_name: String) -> ExpansionConfig<'static> { 18 ( 0.00%) ExpansionConfig { 9 ( 0.00%) crate_name, . features: None, 6 ( 0.00%) recursion_limit: Limit::new(1024), . trace_mac: false, . should_test: false, . span_debug: false, . proc_macro_backtrace: false, . } 15 ( 0.00%) } . . fn proc_macro_hygiene(&self) -> bool { . self.features.map_or(false, |features| features.proc_macro_hygiene) . } . } 61,857 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . use rustc_target::abi::{HasDataLayout, Size, VariantIdx, Variants}; . . use super::{ . alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg, . ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, . Operand, Pointer, PointerArithmetic, Provenance, Scalar, ScalarMaybeUninit, . }; . 1,812 ( 0.00%) #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . /// Information required for the sound usage of a `MemPlace`. . pub enum MemPlaceMeta { . /// The unsized payload (e.g. length for slices or vtable pointer for trait objects). . Meta(Scalar), . /// `Sized` types or unsized `extern type` . None, . /// The address of this place may not be taken. This protects the `MemPlace` from coming from . /// a ZST Operand without a backing allocation and being converted to an integer address. This -- line 30 ---------------------------------------- -- line 33 ---------------------------------------- . Poison, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlaceMeta, 24); . . impl MemPlaceMeta { . pub fn unwrap_meta(self) -> Scalar { 174 ( 0.00%) match self { . Self::Meta(s) => s, . Self::None | Self::Poison => { . bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)") . } . } . } . fn has_meta(self) -> bool { 87,945 ( 0.01%) match self { . Self::Meta(_) => true, . Self::None | Self::Poison => false, . } . } . } . . #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . pub struct MemPlace { . /// The pointer can be a pure integer, with the `None` tag. 2 ( 0.00%) pub ptr: Pointer>, 4 ( 0.00%) pub align: Align, . /// Metadata for unsized places. Interpretation is up to the type. . /// Must not be present for sized types, but can be missing for unsized types . /// (e.g., `extern type`). . pub meta: MemPlaceMeta, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlace, 48); -- line 68 ---------------------------------------- -- line 93 ---------------------------------------- . type Target = Place; . #[inline(always)] . fn deref(&self) -> &Place { . &self.place . } . } . . /// A MemPlace with its layout. Constructing it is only possible in this module. 14 ( 0.00%) #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] . pub struct MPlaceTy<'tcx, Tag: Provenance = AllocId> { . mplace: MemPlace, . pub layout: TyAndLayout<'tcx>, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MPlaceTy<'_>, 64); . -- line 109 ---------------------------------------- -- line 113 ---------------------------------------- . fn deref(&self) -> &MemPlace { . &self.mplace . } . } . . impl<'tcx, Tag: Provenance> From> for PlaceTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 3,270 ( 0.00%) PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout } . } . } . . impl MemPlace { . #[inline(always)] . pub fn from_ptr(ptr: Pointer>, align: Align) -> Self { . MemPlace { ptr, align, meta: MemPlaceMeta::None } . } -- line 129 ---------------------------------------- -- line 132 ---------------------------------------- . pub fn map_provenance(self, f: impl FnOnce(Option) -> Option) -> Self { . MemPlace { ptr: self.ptr.map_provenance(f), ..self } . } . . /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space. . /// This is the inverse of `ref_to_mplace`. . #[inline(always)] . pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate { 887 ( 0.00%) match self.meta { 602 ( 0.00%) MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)), . MemPlaceMeta::Meta(meta) => { 21 ( 0.00%) Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into()) . } . MemPlaceMeta::Poison => bug!( . "MPlaceTy::dangling may never be used to produce a \ . place that will have the address of its pointee taken" . ), . } . } . -- line 151 ---------------------------------------- -- line 177 ---------------------------------------- . #[inline] . pub fn offset( . &self, . offset: Size, . meta: MemPlaceMeta, . layout: TyAndLayout<'tcx>, . cx: &impl HasDataLayout, . ) -> InterpResult<'tcx, Self> { 731,881 ( 0.08%) Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout }) . } . . #[inline] . pub fn from_aligned_ptr(ptr: Pointer>, layout: TyAndLayout<'tcx>) -> Self { 100 ( 0.00%) MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout } . } . . #[inline] 87 ( 0.00%) pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> { 348 ( 0.00%) if self.layout.is_unsized() { . // We need to consult `meta` metadata 186 ( 0.00%) match self.layout.ty.kind() { 31 ( 0.00%) ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx), . _ => bug!("len not supported on unsized type {:?}", self.layout.ty), . } . } else { . // Go through the layout. There are lots of types that support a length, . // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!) 112 ( 0.00%) match self.layout.fields { 112 ( 0.00%) FieldsShape::Array { count, .. } => Ok(count), . _ => bug!("len not supported on sized type {:?}", self.layout.ty), . } . } 174 ( 0.00%) } . . #[inline] . pub(super) fn vtable(&self) -> Scalar { . match self.layout.ty.kind() { . ty::Dynamic(..) => self.mplace.meta.unwrap_meta(), . _ => bug!("vtable not supported on type {:?}", self.layout.ty), . } . } -- line 217 ---------------------------------------- -- line 218 ---------------------------------------- . } . . // These are defined here because they produce a place. . impl<'tcx, Tag: Provenance> OpTy<'tcx, Tag> { . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn try_as_mplace(&self) -> Result, ImmTy<'tcx, Tag>> { 176,674 ( 0.02%) match **self { 821,772 ( 0.09%) Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }), . Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)), 207,410 ( 0.02%) Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)), . } . } . . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Tag> { . self.try_as_mplace().unwrap() -- line 237 ---------------------------------------- -- line 263 ---------------------------------------- . M: Machine<'mir, 'tcx, PointerTag = Tag>, . { . /// Take a value, which represents a (thin or wide) reference, and make it a place. . /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`. . /// . /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not . /// want to ever use the place for memory access! . /// Generally prefer `deref_operand`. 2,030 ( 0.00%) pub fn ref_to_mplace( . &self, . val: &ImmTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . let pointee_type = 609 ( 0.00%) val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty; 609 ( 0.00%) let layout = self.layout_of(pointee_type)?; 1,015 ( 0.00%) let (ptr, meta) = match **val { 288 ( 0.00%) Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None), 413 ( 0.00%) Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta.check_init()?)), . }; . . let mplace = MemPlace { . ptr: self.scalar_to_ptr(ptr.check_init()?), . // We could use the run-time alignment here. For now, we do not, because . // the point of tracking the alignment here is to make sure that the *static* . // alignment information emitted with the loads is correct. The run-time . // alignment can only be more restrictive. 203 ( 0.00%) align: layout.align.abi, . meta, . }; 3,451 ( 0.00%) Ok(MPlaceTy { mplace, layout }) 1,827 ( 0.00%) } . . /// Take an operand, representing a pointer, and dereference it to a place -- that . /// will always be a MemPlace. Lives in `place.rs` because it creates a place. 924 ( 0.00%) pub fn deref_operand( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 252 ( 0.00%) let val = self.read_immediate(src)?; . trace!("deref to {} on {:?}", val.layout.ty, *val); 168 ( 0.00%) let mplace = self.ref_to_mplace(&val)?; 420 ( 0.00%) self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?; 924 ( 0.00%) Ok(mplace) 728 ( 0.00%) } . . #[inline] . pub(super) fn get_alloc( . &self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { . assert!(!place.layout.is_unsized()); 58,643 ( 0.01%) assert!(!place.meta.has_meta()); 58,643 ( 0.01%) let size = place.layout.size; 527,787 ( 0.06%) self.memory.get(place.ptr, size, place.align) . } . . #[inline] . pub(super) fn get_alloc_mut( . &mut self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 29,298 ( 0.00%) assert!(!place.layout.is_unsized()); 29,298 ( 0.00%) assert!(!place.meta.has_meta()); 29,298 ( 0.00%) let size = place.layout.size; 175,788 ( 0.02%) self.memory.get_mut(place.ptr, size, place.align) . } . . /// Check if this mplace is dereferenceable and sufficiently aligned. . fn check_mplace_access( . &self, . mplace: MPlaceTy<'tcx, M::PointerTag>, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { . let (size, align) = self . .size_and_align_of_mplace(&mplace)? 84 ( 0.00%) .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); 84 ( 0.00%) assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?"); 84 ( 0.00%) let align = M::enforce_alignment(&self.memory.extra).then_some(align); 252 ( 0.00%) self.memory.check_ptr_access_align(mplace.ptr, size, align.unwrap_or(Align::ONE), msg)?; . Ok(()) . } . . /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is . /// always possible without allocating, so it can take `&self`. Also return the field's layout. . /// This supports both struct and array fields. . /// . /// This also works for arrays, but then the `usize` index type is restricting. . /// For indexing into arrays, use `mplace_index`. . #[inline(always)] . pub fn mplace_field( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 116,929 ( 0.01%) let offset = base.layout.fields.offset(field); 87,696 ( 0.01%) let field_layout = base.layout.field(self, field); . . // Offset may need adjustment for unsized fields. 146,185 ( 0.02%) let (meta, offset) = if field_layout.is_unsized() { . // Re-use parent metadata to determine dynamic field layout. . // With custom DSTS, this *will* execute user-defined code, but the same . // happens at run-time so that's okay. . match self.size_and_align_of(&base.meta, &field_layout)? { . Some((_, align)) => (base.meta, offset.align_to(align)), . None => { . // For unsized types with an extern type tail we perform no adjustments. . // NOTE: keep this in sync with `PlaceRef::project_field` in the codegen backend. -- line 369 ---------------------------------------- -- line 374 ---------------------------------------- . } else { . // base.meta could be present; we might be accessing a sized field of an unsized . // struct. . (MemPlaceMeta::None, offset) . }; . . // We do not look at `base.layout.align` nor `field_layout.align`, unlike . // codegen -- mostly to see if we can get away with that 44 ( 0.00%) base.offset(offset, meta, field_layout, self) . } . . /// Index into an array. . #[inline(always)] . pub fn mplace_index( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . index: u64, -- line 390 ---------------------------------------- -- line 409 ---------------------------------------- . "`mplace_index` called on non-array type {:?}", . base.layout.ty . ), . } . } . . // Iterates over all fields of an array. Much more efficient than doing the . // same by repeatedly calling `mplace_array`. 870 ( 0.00%) pub(super) fn mplace_array_fields<'a>( . &self, . base: &'a MPlaceTy<'tcx, Tag>, . ) -> InterpResult<'tcx, impl Iterator>> + 'a> . { 348 ( 0.00%) let len = base.len(self)?; // also asserts that we have a type where this makes sense 261 ( 0.00%) let stride = match base.layout.fields { 87 ( 0.00%) FieldsShape::Array { stride, .. } => stride, . _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), . }; 174 ( 0.00%) let layout = base.layout.field(self, 0); 87 ( 0.00%) let dl = &self.tcx.data_layout; . // `Size` multiplication 527,685 ( 0.06%) Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl))) 783 ( 0.00%) } . . fn mplace_subslice( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . from: u64, . to: u64, . from_end: bool, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 439 ---------------------------------------- -- line 476 ---------------------------------------- . } . . pub(crate) fn mplace_downcast( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 4 ( 0.00%) assert!(!base.meta.has_meta()); 18 ( 0.00%) Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..*base }) . } . . /// Project into an mplace . pub(super) fn mplace_projection( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 493 ---------------------------------------- -- line 542 ---------------------------------------- . assert_eq!(layout.size, base.layout.size); . Ok((MPlaceTy { layout, ..*base }, len)) . } . . /// Gets the place of a field inside the place, and also the field's type. . /// Just a convenience function, but used quite a bit. . /// This is the only projection that might have a side-effect: We cannot project . /// into the field of a local `ScalarPair`, we have to first allocate it. 292,110 ( 0.03%) pub fn place_field( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // FIXME: We could try to be smarter and avoid allocation for fields that span the . // entire place. 29,211 ( 0.00%) let mplace = self.force_allocation(base)?; 350,532 ( 0.04%) Ok(self.mplace_field(&mplace, field)?.into()) 233,688 ( 0.02%) } . . pub fn place_index( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . let mplace = self.force_allocation(base)?; . Ok(self.mplace_index(&mplace, index)?.into()) -- line 567 ---------------------------------------- -- line 586 ---------------------------------------- . . /// Projects into a place. . pub fn place_projection( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . &proj_elem: &mir::ProjectionElem>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 840 ( 0.00%) Ok(match proj_elem { . Field(field, _) => self.place_field(base, field.index())?, . Downcast(_, variant) => self.place_downcast(base, variant)?, 448 ( 0.00%) Deref => self.deref_operand(&self.place_to_op(base)?)?.into(), . // For the other variants, we have to force an allocation. . // This matches `operand_projection`. . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . let mplace = self.force_allocation(base)?; . self.mplace_projection(&mplace, proj_elem)?.into() . } . }) . } -- line 605 ---------------------------------------- -- line 611 ---------------------------------------- . base: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . let mplace = self.force_allocation(base)?; . self.mplace_to_simd(&mplace) . } . . /// Computes a place. You should only use this if you intend to write into this . /// place; for reading, a more efficient alternative is `eval_place_for_read`. 3,760 ( 0.00%) pub fn eval_place( . &mut self, . place: mir::Place<'tcx>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { 2,205 ( 0.00%) let mut place_ty = PlaceTy { . // This works even for dead/uninitialized locals; we check further when writing . place: Place::Local { frame: self.frame_idx(), local: place.local }, . layout: self.layout_of_local(self.frame(), place.local, None)?, . }; . 112 ( 0.00%) for elem in place.projection.iter() { 56 ( 0.00%) place_ty = self.place_projection(&place_ty, &elem)? . } . . trace!("{:?}", self.dump_place(place_ty.place)); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . place_ty.layout, . )); 7,938 ( 0.00%) Ok(place_ty) 3,760 ( 0.00%) } . . /// Write an immediate to a place . #[inline(always)] . pub fn write_immediate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 1,379 ( 0.00%) self.write_immediate_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } -- line 661 ---------------------------------------- -- line 678 ---------------------------------------- . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest) . } . . /// Write an immediate to a place. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 29,460 ( 0.00%) fn write_immediate_no_validate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . if cfg!(debug_assertions) { . // This is a very common path, avoid some checks in release mode . assert!(!dest.layout.is_unsized(), "Cannot write unsized data"); . match src { -- line 694 ---------------------------------------- -- line 705 ---------------------------------------- . // FIXME: Can we check anything here? . } . } . } . trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`, . // but not factored as a separate function. 59,098 ( 0.01%) let mplace = match dest.place { 591 ( 0.00%) Place::Local { frame, local } => { 356 ( 0.00%) match M::access_local_mut(self, frame, local)? { . Ok(local) => { . // Local can be updated in-place. 2,421 ( 0.00%) *local = LocalValue::Live(Operand::Immediate(src)); . return Ok(()); . } . Err(mplace) => { . // The local is in memory, go on below. . mplace . } . } . } 175,788 ( 0.02%) Place::Ptr(mplace) => mplace, // already referring to memory . }; 263,682 ( 0.03%) let dest = MPlaceTy { mplace, layout: dest.layout }; . . // This is already in memory, write there. 322,278 ( 0.03%) self.write_immediate_to_mplace_no_validate(src, &dest) 58,920 ( 0.01%) } . . /// Write an immediate to memory. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 292,980 ( 0.03%) fn write_immediate_to_mplace_no_validate( . &mut self, . value: Immediate, . dest: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // Note that it is really important that the type here is the right one, and matches the . // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here . // to handle padding properly, which is only correct if we never look at this data with the . // wrong type. . . // Invalid places are a thing: the return place of a diverging function 29,298 ( 0.00%) let tcx = *self.tcx; 58,596 ( 0.01%) let mut alloc = match self.get_alloc_mut(dest)? { 146,490 ( 0.02%) Some(a) => a, . None => return Ok(()), // zero-sized access . }; . . // FIXME: We should check that there are dest.layout.size many bytes available in . // memory. The code below is not sufficient, with enough padding it might not . // cover all the bytes! 58,596 ( 0.01%) match value { . Immediate::Scalar(scalar) => { 58,534 ( 0.01%) match dest.layout.abi { . Abi::Scalar(_) => {} // fine . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid Scalar layout: {:#?}", . dest.layout . ), . } 263,403 ( 0.03%) alloc.write_scalar(alloc_range(Size::ZERO, dest.layout.size), scalar) . } . Immediate::ScalarPair(a_val, b_val) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. 62 ( 0.00%) let (a, b) = match dest.layout.abi { 93 ( 0.00%) Abi::ScalarPair(a, b) => (a.value, b.value), . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", . dest.layout . ), . }; . let (a_size, b_size) = (a.size(&tcx), b.size(&tcx)); . let b_offset = a_size.align_to(b.align(&tcx).abi); . . // It is tempting to verify `b_offset` against `layout.fields.offset(1)`, . // but that does not work: We could be a newtype around a pair, then the . // fields do not match the `ScalarPair` components. . 310 ( 0.00%) alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?; 248 ( 0.00%) alloc.write_scalar(alloc_range(b_offset, b_size), b_val) . } . } 234,384 ( 0.02%) } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . #[inline(always)] . pub fn copy_op( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 176,196 ( 0.02%) self.copy_op_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . /// Also, if you use this you are responsible for validating that things get copied at the . /// right type. 234,680 ( 0.02%) fn copy_op_no_validate( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // We do NOT compare the types for equality, because well-typed code can . // actually "transmute" `&mut T` to `&T` in an assignment without a cast. 529,098 ( 0.06%) if !mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . span_bug!( . self.cur_span(), . "type mismatch when copying!\nsrc: {:?},\ndest: {:?}", . src.layout.ty, . dest.layout.ty, . ); . } . . // Let us see if the layout is simple so we take a shortcut, avoid force_allocation. 147,031 ( 0.02%) let src = match self.try_read_immediate(src)? { . Ok(src_val) => { 29,424 ( 0.00%) assert!(!src.layout.is_unsized(), "cannot have unsized immediates"); . // Yay, we got a value that we can write directly. . // FIXME: Add a check to make sure that if `src` is indirect, . // it does not overlap with `dest`. 381,355 ( 0.04%) return self.write_immediate_no_validate(*src_val, dest); . } . Err(mplace) => mplace, . }; . // Slow path, this does not fit into an immediate. Just memcpy. . trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // This interprets `src.meta` with the `dest` local's layout, if an unsized local . // is being initialized! -- line 848 ---------------------------------------- -- line 853 ---------------------------------------- . "Cannot copy into already initialized unsized place" . ); . dest.layout.size . }); . assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances"); . . self.memory . .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true) 234,680 ( 0.02%) } . . /// Copies the data from an operand to a place. The layouts may disagree, but they must . /// have the same size. 624 ( 0.00%) pub fn copy_op_transmute( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 1,404 ( 0.00%) if mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . // Fast path: Just use normal `copy_op` . return self.copy_op(src, dest); . } . // We still require the sizes to match. . if src.layout.size != dest.layout.size { . // FIXME: This should be an assert instead of an error, but if we transmute within an . // array length computation, `typeck` may not have yet been run and errored out. In fact . // most likey we *are* running `typeck` right now. Investigate whether we can bail out -- line 878 ---------------------------------------- -- line 916 ---------------------------------------- . /// Ensures that a place is in memory, and returns where it is. . /// If the place currently refers to a local that doesn't yet have a matching allocation, . /// create such an allocation. . /// This is essentially `force_to_memplace`. . /// . /// This supports unsized types and returns the computed size to avoid some . /// redundant computation when copying; use `force_allocation` for a simpler, sized-only . /// version. 263,673 ( 0.03%) pub fn force_allocation_maybe_sized( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . meta: MemPlaceMeta, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option)> { 292,970 ( 0.03%) let (mplace, size) = match place.place { 29,241 ( 0.00%) Place::Local { frame, local } => { 58,482 ( 0.01%) match M::access_local_mut(self, frame, local)? { 270 ( 0.00%) Ok(&mut local_val) => { . // We need to make an allocation. . . // We need the layout of the local. We can NOT use the layout we got, . // that might e.g., be an inner field of a struct with `Scalar` layout, . // that has different alignment than the outer field. . let local_layout = 150 ( 0.00%) self.layout_of_local(&self.stack()[frame], local, None)?; . // We also need to support unsized types, and hence cannot use `allocate`. 120 ( 0.00%) let (size, align) = self . .size_and_align_of(&meta, &local_layout)? . .expect("Cannot allocate for non-dyn-sized type"); 210 ( 0.00%) let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?; . let mplace = MemPlace { ptr: ptr.into(), align, meta }; 150 ( 0.00%) if let LocalValue::Live(Operand::Immediate(value)) = local_val { . // Preserve old value. . // We don't have to validate as we can assume the local . // was already valid for its type. . let mplace = MPlaceTy { mplace, layout: local_layout }; . self.write_immediate_to_mplace_no_validate(value, &mplace)?; . } . // Now we can call `access_mut` again, asserting it goes well, . // and actually overwrite things. 570 ( 0.00%) *M::access_local_mut(self, frame, local).unwrap().unwrap() = . LocalValue::Live(Operand::Indirect(mplace)); 210 ( 0.00%) (mplace, Some(size)) . } 292,110 ( 0.03%) Err(mplace) => (mplace, None), // this already was an indirect local . } . } 728 ( 0.00%) Place::Ptr(mplace) => (mplace, None), . }; . // Return with the original layout, so that the caller can go on 351,564 ( 0.04%) Ok((MPlaceTy { mplace, layout: place.layout }, size)) 234,376 ( 0.02%) } . . #[inline(always)] . pub fn force_allocation( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 263,415 ( 0.03%) Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0) . } . 288 ( 0.00%) pub fn allocate( . &mut self, . layout: TyAndLayout<'tcx>, . kind: MemoryKind, . ) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> { 786 ( 0.00%) let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?; 216 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 252 ( 0.00%) } . . /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation. 30 ( 0.00%) pub fn allocate_str( . &mut self, . str: &str, . kind: MemoryKind, . mutbl: Mutability, . ) -> MPlaceTy<'tcx, M::PointerTag> { 27 ( 0.00%) let ptr = self.memory.allocate_bytes(str.as_bytes(), Align::ONE, kind, mutbl); . let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self); . let mplace = . MemPlace { ptr: ptr.into(), align: Align::ONE, meta: MemPlaceMeta::Meta(meta) }; . . let ty = self.tcx.mk_ref( 3 ( 0.00%) self.tcx.lifetimes.re_static, 3 ( 0.00%) ty::TypeAndMut { ty: self.tcx.types.str_, mutbl }, . ); 9 ( 0.00%) let layout = self.layout_of(ty).unwrap(); 30 ( 0.00%) MPlaceTy { mplace, layout } 24 ( 0.00%) } . . /// Writes the discriminant of the given variant. 22 ( 0.00%) pub fn write_discriminant( . &mut self, . variant_index: VariantIdx, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // This must be an enum or generator. 8 ( 0.00%) match dest.layout.ty.kind() { 4 ( 0.00%) ty::Adt(adt, _) => assert!(adt.is_enum()), . ty::Generator(..) => {} . _ => span_bug!( . self.cur_span(), . "write_discriminant called on non-variant-type (neither enum nor generator)" . ), . } . // Layout computation excludes uninhabited variants from consideration . // therefore there's no way to represent those variants in the given layout. . // Essentially, uninhabited variants do not have a tag that corresponds to their . // discriminant, so we cannot do anything here. . // When evaluating we will always error before even getting here, but ConstProp 'executes' . // dead code, so we cannot ICE here. 4 ( 0.00%) if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { . throw_ub!(UninhabitedEnumVariantWritten) . } . 10 ( 0.00%) match dest.layout.variants { . Variants::Single { index } => { . assert_eq!(index, variant_index); . } . Variants::Multiple { . tag_encoding: TagEncoding::Direct, 6 ( 0.00%) tag: tag_layout, 4 ( 0.00%) tag_field, . .. . } => { . // No need to validate that the discriminant here because the . // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. . . let discr_val = 8 ( 0.00%) dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; . . // raw discriminants for enums are isize or bigger during . // their computation, but the in-memory tag is the smallest possible . // representation . let size = tag_layout.value.size(self); . let tag_val = size.truncate(discr_val); . 10 ( 0.00%) let tag_dest = self.place_field(dest, tag_field)?; . self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?; . } . Variants::Multiple { . tag_encoding: . TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start }, . tag: tag_layout, . tag_field, . .. -- line 1060 ---------------------------------------- -- line 1082 ---------------------------------------- . // Write result. . let niche_dest = self.place_field(dest, tag_field)?; . self.write_immediate(*tag_val, &niche_dest)?; . } . } . } . . Ok(()) 16 ( 0.00%) } . 450 ( 0.00%) pub fn raw_const_to_mplace( . &self, . raw: ConstAlloc<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // This must be an allocation in `tcx` 150 ( 0.00%) let _ = self.tcx.global_alloc(raw.alloc_id); . let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?; 150 ( 0.00%) let layout = self.layout_of(raw.ty)?; 300 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 350 ( 0.00%) } . . /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type. . /// Also return some more information so drop doesn't have to run the same code twice. . pub(super) fn unpack_dyn_trait( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> { . let vtable = self.scalar_to_ptr(mplace.vtable()); // also sanity checks the type -- line 1109 ---------------------------------------- 354,536 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/late.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// parameters. . ConstParamTyRibKind, . } . . impl RibKind<'_> { . /// Whether this rib kind contains generic parameters, as opposed to local . /// variables. . crate fn contains_params(&self) -> bool { 13,882 ( 0.00%) match self { . NormalRibKind . | ClosureOrAsyncRibKind . | FnItemRibKind . | ConstantItemRibKind(..) . | ModuleRibKind(_) . | MacroDefinition(_) . | ConstParamTyRibKind => false, . AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true, -- line 157 ---------------------------------------- -- line 174 ---------------------------------------- . #[derive(Debug)] . crate struct Rib<'a, R = Res> { . pub bindings: IdentMap, . pub kind: RibKind<'a>, . } . . impl<'a, R> Rib<'a, R> { . fn new(kind: RibKind<'a>) -> Rib<'a, R> { 511 ( 0.00%) Rib { bindings: Default::default(), kind } . } . } . . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . crate enum AliasPossibility { . No, . Maybe, . } -- line 190 ---------------------------------------- -- line 212 ---------------------------------------- . match self { . PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS, . PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS, . PathSource::TraitItem(ns) => ns, . } . } . . fn defer_to_typeck(self) -> bool { 642 ( 0.00%) match self { . PathSource::Type . | PathSource::Expr(..) . | PathSource::Pat . | PathSource::Struct . | PathSource::TupleStruct(..) => true, . PathSource::Trait(_) | PathSource::TraitItem(..) => false, . } . } -- line 228 ---------------------------------------- -- line 268 ---------------------------------------- . } . } . . fn is_call(self) -> bool { . matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. }))) . } . . crate fn is_expected(self, res: Res) -> bool { 2,026 ( 0.00%) match self { 1,322 ( 0.00%) PathSource::Type => matches!( 378 ( 0.00%) res, . Res::Def( . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Trait . | DefKind::TraitAlias . | DefKind::TyAlias . | DefKind::AssocTy . | DefKind::TyParam . | DefKind::OpaqueTy . | DefKind::ForeignTy, . _, . ) | Res::PrimTy(..) . | Res::SelfTy(..) . ), 3 ( 0.00%) PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)), . PathSource::Trait(AliasPossibility::Maybe) => { 14 ( 0.00%) matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) . } 519 ( 0.00%) PathSource::Expr(..) => matches!( 285 ( 0.00%) res, . Res::Def( . DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) . | DefKind::Const . | DefKind::Static . | DefKind::Fn . | DefKind::AssocFn . | DefKind::AssocConst . | DefKind::ConstParam, -- line 307 ---------------------------------------- -- line 329 ---------------------------------------- . ) | Res::SelfTy(..) . ), . PathSource::TraitItem(ns) => match res { . Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true, . Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, . _ => false, . }, . } 404 ( 0.00%) } . . fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId { . use rustc_errors::error_code; . match (self, has_unexpected_resolution) { . (PathSource::Trait(_), true) => error_code!(E0404), . (PathSource::Trait(_), false) => error_code!(E0405), . (PathSource::Type, true) => error_code!(E0573), . (PathSource::Type, false) => error_code!(E0412), -- line 345 ---------------------------------------- -- line 350 ---------------------------------------- . (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532), . (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531), . (PathSource::TraitItem(..), true) => error_code!(E0575), . (PathSource::TraitItem(..), false) => error_code!(E0576), . } . } . } . 2 ( 0.00%) #[derive(Default)] . struct DiagnosticMetadata<'ast> { . /// The current trait's associated items' ident, used for diagnostic suggestions. . current_trait_assoc_items: Option<&'ast [P]>, . . /// The current self type if inside an impl (used for better errors). . current_self_type: Option, . . /// The current self item if inside an ADT (used for better errors). -- line 366 ---------------------------------------- -- line 434 ---------------------------------------- . fn visit_attribute(&mut self, _: &'ast Attribute) { . // We do not want to resolve expressions that appear in attributes, . // as they do not correspond to actual code. . } . fn visit_item(&mut self, item: &'ast Item) { . let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item)); . // Always report errors in items we just entered. . let old_ignore = replace(&mut self.in_func_body, false); 68 ( 0.00%) self.resolve_item(item); 34 ( 0.00%) self.in_func_body = old_ignore; 34 ( 0.00%) self.diagnostic_metadata.current_item = prev; . } 91 ( 0.00%) fn visit_arm(&mut self, arm: &'ast Arm) { . self.resolve_arm(arm); 78 ( 0.00%) } 324 ( 0.00%) fn visit_block(&mut self, block: &'ast Block) { . self.resolve_block(block); 288 ( 0.00%) } . fn visit_anon_const(&mut self, constant: &'ast AnonConst) { . // We deal with repeat expressions explicitly in `resolve_expr`. . self.resolve_anon_const(constant, IsRepeatExpr::No); . } . fn visit_expr(&mut self, expr: &'ast Expr) { 88,077 ( 0.01%) self.resolve_expr(expr, None); . } . fn visit_local(&mut self, local: &'ast Local) { . let local_spans = match local.pat.kind { . // We check for this to avoid tuple struct fields. . PatKind::Wild => None, . _ => Some(( . local.pat.span, . local.ty.as_ref().map(|ty| ty.span), . local.kind.init().map(|init| init.span), . )), . }; . let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans); . self.resolve_local(local); . self.diagnostic_metadata.current_let_binding = original; . } 1,728 ( 0.00%) fn visit_ty(&mut self, ty: &'ast Ty) { 432 ( 0.00%) let prev = self.diagnostic_metadata.current_trait_object; 1,132 ( 0.00%) match ty.kind { 190 ( 0.00%) TyKind::Path(ref qself, ref path) => { 570 ( 0.00%) self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type); . } . TyKind::ImplicitSelf => { . let self_ty = Ident::with_dummy_span(kw::SelfUpper); . let res = self 63 ( 0.00%) .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span) 378 ( 0.00%) .map_or(Res::Err, |d| d.res()); 693 ( 0.00%) self.r.record_partial_res(ty.id, PartialRes::new(res)); . } . TyKind::TraitObject(ref bounds, ..) => { . self.diagnostic_metadata.current_trait_object = Some(&bounds[..]); . } . _ => (), . } 648 ( 0.00%) visit::walk_ty(self, ty); 432 ( 0.00%) self.diagnostic_metadata.current_trait_object = prev; 1,512 ( 0.00%) } . fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { 6 ( 0.00%) self.smart_resolve_path( 2 ( 0.00%) tref.trait_ref.ref_id, . None, 2 ( 0.00%) &tref.trait_ref.path, 4 ( 0.00%) PathSource::Trait(AliasPossibility::Maybe), . ); . visit::walk_poly_trait_ref(self, tref, m); . } . fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) { . match foreign_item.kind { . ForeignItemKind::Fn(box Fn { ref generics, .. }) . | ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => { . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { -- line 507 ---------------------------------------- -- line 513 ---------------------------------------- . visit::walk_foreign_item(this, foreign_item); . }); . } . ForeignItemKind::MacCall(..) => { . visit::walk_foreign_item(self, foreign_item); . } . } . } 576 ( 0.00%) fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) { 1,040 ( 0.00%) let rib_kind = match fn_kind { . // Bail if the function is foreign, and thus cannot validly have . // a body, or if there's no body for some other reason. . FnKind::Fn(FnCtxt::Foreign, _, sig, ..) | FnKind::Fn(_, _, sig, .., None) => { . // We don't need to deal with patterns in parameters, because . // they are not possible for foreign or bodiless functions. . self.visit_fn_header(&sig.header); . visit::walk_fn_decl(self, &sig.decl); . return; . } . FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind, . FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind, . FnKind::Closure(..) => ClosureOrAsyncRibKind, . }; 252 ( 0.00%) let previous_value = self.diagnostic_metadata.current_function; 72 ( 0.00%) if matches!(fn_kind, FnKind::Fn(..)) { 252 ( 0.00%) self.diagnostic_metadata.current_function = Some((fn_kind, sp)); . } . debug!("(resolving function) entering function"); 108 ( 0.00%) let declaration = fn_kind.decl(); . . // Create a value rib for the function. . self.with_rib(ValueNS, rib_kind, |this| { . // Create a label rib for the function. . this.with_label_rib(rib_kind, |this| { . // Add each argument to the rib. 72 ( 0.00%) this.resolve_params(&declaration.inputs); . . visit::walk_fn_ret_ty(this, &declaration.output); . . // Ignore errors in function bodies if this is rustdoc . // Be sure not to set this until the function signature has been resolved. . let previous_state = replace(&mut this.in_func_body, true); . // Resolve the function body, potentially inside the body of an async closure 72 ( 0.00%) match fn_kind { 180 ( 0.00%) FnKind::Fn(.., body) => walk_list!(this, visit_block, body), . FnKind::Closure(_, body) => this.visit_expr(body), . }; . . debug!("(resolving function) leaving function"); 36 ( 0.00%) this.in_func_body = previous_state; . }) . }); 216 ( 0.00%) self.diagnostic_metadata.current_function = previous_value; 288 ( 0.00%) } . 528 ( 0.00%) fn visit_generics(&mut self, generics: &'ast Generics) { . // For type parameter defaults, we have to ban access . // to following type parameters, as the InternalSubsts can only . // provide previous type parameters as they're built. We . // put all the parameters on the ban list and then remove . // them one by one as they are processed and become available. . let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind); . let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind); . for param in generics.params.iter() { -- line 576 ---------------------------------------- -- line 593 ---------------------------------------- . // another type parameter. For ADTs, we consider it . // well-defined only after all of the ADT type parameters have . // been provided. Therefore, we do not allow use of `Self` . // anywhere in ADT type parameter defaults. . // . // (We however cannot ban `Self` for defaults on *all* generic . // lists; e.g. trait generics can usefully refer to `Self`, . // such as in the case of `trait Add`.) 66 ( 0.00%) if self.diagnostic_metadata.current_self_item.is_some() { . // (`Some` if + only if we are in ADT's generics.) . forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err); . } . . for param in &generics.params { . match param.kind { . GenericParamKind::Lifetime => self.visit_generic_param(param), . GenericParamKind::Type { ref default } => { -- line 609 ---------------------------------------- -- line 645 ---------------------------------------- . .bindings . .remove(&Ident::with_dummy_span(param.ident.name)); . } . } . } . for p in &generics.where_clause.predicates { . self.visit_where_predicate(p); . } 528 ( 0.00%) } . . fn visit_generic_arg(&mut self, arg: &'ast GenericArg) { . debug!("visit_generic_arg({:?})", arg); . let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true); . match arg { . GenericArg::Type(ref ty) => { . // We parse const arguments as path types as we cannot distinguish them during . // parsing. We try to resolve that ambiguity by attempting resolution the type -- line 661 ---------------------------------------- -- line 715 ---------------------------------------- . let previous_value = . replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p)); . visit::walk_where_predicate(self, p); . self.diagnostic_metadata.current_where_predicate = previous_value; . } . } . . impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { 9 ( 0.00%) fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> { . // During late resolution we only track the module component of the parent scope, . // although it may be useful to track other components as well for diagnostics. 1 ( 0.00%) let graph_root = resolver.graph_root; . let parent_scope = ParentScope::module(graph_root, resolver); . let start_rib_kind = ModuleRibKind(graph_root); 30 ( 0.00%) LateResolutionVisitor { . r: resolver, . parent_scope, . ribs: PerNS { 2 ( 0.00%) value_ns: vec![Rib::new(start_rib_kind)], 2 ( 0.00%) type_ns: vec![Rib::new(start_rib_kind)], 2 ( 0.00%) macro_ns: vec![Rib::new(start_rib_kind)], . }, . label_ribs: Vec::new(), . current_trait_ref: None, . diagnostic_metadata: DiagnosticMetadata::default(), . // errors at module scope should always be reported . in_func_body: false, . } 9 ( 0.00%) } . . fn resolve_ident_in_lexical_scope( . &mut self, . ident: Ident, . ns: Namespace, . record_used_id: Option, . path_span: Span, . ) -> Option> { 1,063 ( 0.00%) self.r.resolve_ident_in_lexical_scope( . ident, . ns, 100 ( 0.00%) &self.parent_scope, . record_used_id, . path_span, . &self.ribs[ns], . ) . } . . fn resolve_path( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ) -> PathResult<'a> { 3,686 ( 0.00%) self.r.resolve_path_with_ribs( . path, . opt_ns, 1 ( 0.00%) &self.parent_scope, . record_used, . path_span, . crate_lint, 1 ( 0.00%) Some(&self.ribs), . ) . } . . // AST resolution . // . // We maintain a list of value ribs and type ribs. . // . // Simultaneously, we keep track of the current position in the module -- line 785 ---------------------------------------- -- line 798 ---------------------------------------- . . /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`). . fn with_rib( . &mut self, . ns: Namespace, . kind: RibKind<'a>, . work: impl FnOnce(&mut Self) -> T, . ) -> T { 292 ( 0.00%) self.ribs[ns].push(Rib::new(kind)); . let ret = work(self); . self.ribs[ns].pop(); . ret . } . . fn with_scope(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { 8 ( 0.00%) if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) { . // Move down in the graph. . let orig_module = replace(&mut self.parent_scope.module, module); . self.with_rib(ValueNS, ModuleRibKind(module), |this| { . this.with_rib(TypeNS, ModuleRibKind(module), |this| { . let ret = f(this); 1 ( 0.00%) this.parent_scope.module = orig_module; . ret . }) . }) . } else { . f(self) . } . } . -- line 827 ---------------------------------------- -- line 908 ---------------------------------------- . let item_def_id = this.r.local_def_id(item.id).to_def_id(); . this.with_self_rib(Res::SelfTy(None, Some((item_def_id, false))), |this| { . visit::walk_item(this, item); . }); . }); . }); . } . 9 ( 0.00%) fn future_proof_import(&mut self, use_tree: &UseTree) { . let segments = &use_tree.prefix.segments; 1 ( 0.00%) if !segments.is_empty() { 2 ( 0.00%) let ident = segments[0].ident; 10 ( 0.00%) if ident.is_path_segment_keyword() || ident.span.rust_2015() { . return; . } . . let nss = match use_tree.kind { . UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..], . _ => &[TypeNS], . }; . let report_error = |this: &Self, ns| { -- line 928 ---------------------------------------- -- line 952 ---------------------------------------- . None => {} . } . } . } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind { . for (use_tree, _) in use_trees { . self.future_proof_import(use_tree); . } . } 8 ( 0.00%) } . 272 ( 0.00%) fn resolve_item(&mut self, item: &'ast Item) { . let name = item.ident.name; . debug!("(resolving item) resolving {} ({:?})", name, item.kind); . 204 ( 0.00%) match item.kind { . ItemKind::TyAlias(box TyAlias { ref generics, .. }) . | ItemKind::Fn(box Fn { ref generics, .. }) => { 4 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { 3 ( 0.00%) visit::walk_item(this, item) . }); . } . . ItemKind::Enum(_, ref generics) . | ItemKind::Struct(_, ref generics) . | ItemKind::Union(_, ref generics) => { . self.compute_num_lifetime_params(item.id, generics); . self.resolve_adt(item, generics); . } . . ItemKind::Impl(box Impl { 1 ( 0.00%) ref generics, . ref of_trait, . ref self_ty, . items: ref impl_items, . .. . }) => { 4 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); 1 ( 0.00%) self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items); . } . 1 ( 0.00%) ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => { 4 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); . // Create a new rib for the trait-wide type parameters. . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { 2 ( 0.00%) let local_def_id = this.r.local_def_id(item.id).to_def_id(); . this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| { 2 ( 0.00%) this.visit_generics(generics); . walk_list!(this, visit_param_bound, bounds); . 315 ( 0.00%) let walk_assoc_item = |this: &mut Self, generics, item| { . this.with_generic_param_rib(generics, AssocItemRibKind, |this| { 140 ( 0.00%) visit::walk_assoc_item(this, item, AssocCtxt::Trait) . }); 280 ( 0.00%) }; . . this.with_trait_items(items, |this| { . for item in items { 144 ( 0.00%) match &item.kind { . AssocItemKind::Const(_, ty, default) => { . this.visit_ty(ty); . // Only impose the restrictions of `ConstRibKind` for an . // actual constant expression in a provided default. . if let Some(expr) = default { . // We allow arbitrary const expressions inside of associated consts, . // even if they are potentially not const evaluatable. . // -- line 1018 ---------------------------------------- -- line 1021 ---------------------------------------- . this.with_constant_rib( . IsRepeatExpr::No, . true, . None, . |this| this.visit_expr(expr), . ); . } . } 70 ( 0.00%) AssocItemKind::Fn(box Fn { generics, .. }) => { 105 ( 0.00%) walk_assoc_item(this, generics, item); . } . AssocItemKind::TyAlias(box TyAlias { generics, .. }) => { . walk_assoc_item(this, generics, item); . } . AssocItemKind::MacCall(_) => { . panic!("unexpanded macro in resolve!") . } . }; -- line 1038 ---------------------------------------- -- line 1050 ---------------------------------------- . this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| { . this.visit_generics(generics); . walk_list!(this, visit_param_bound, bounds); . }); . }); . } . . ItemKind::Mod(..) | ItemKind::ForeignMod(_) => { 1 ( 0.00%) self.with_scope(item.id, |this| { 3 ( 0.00%) visit::walk_item(this, item); . }); . } . 84 ( 0.00%) ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => { . self.with_item_rib(HasGenericParams::No, |this| { 28 ( 0.00%) this.visit_ty(ty); 56 ( 0.00%) if let Some(expr) = expr { 112 ( 0.00%) let constant_item_kind = match item.kind { . ItemKind::Const(..) => ConstantItemKind::Const, . ItemKind::Static(..) => ConstantItemKind::Static, . _ => unreachable!(), . }; . // We already forbid generic params because of the above item rib, . // so it doesn't matter whether this is a trivial constant. . this.with_constant_rib( . IsRepeatExpr::No, . true, 140 ( 0.00%) Some((item.ident, constant_item_kind)), . |this| this.visit_expr(expr), . ); . } . }); . } . 1 ( 0.00%) ItemKind::Use(ref use_tree) => { 9 ( 0.00%) self.future_proof_import(use_tree); . } . . ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => { . // do nothing, these are just around to be encoded . } . . ItemKind::GlobalAsm(_) => { . visit::walk_item(self, item); . } . . ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"), . } 264 ( 0.00%) } . . fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F) . where . F: FnOnce(&mut Self), . { . debug!("with_generic_param_rib"); 66 ( 0.00%) let mut function_type_rib = Rib::new(kind); . let mut function_value_rib = Rib::new(kind); . let mut seen_bindings = FxHashMap::default(); . . // We also can't shadow bindings from the parent item . if let AssocItemRibKind = kind { 35 ( 0.00%) let mut add_bindings_for_ns = |ns| { . let parent_rib = self.ribs[ns] . .iter() 245 ( 0.00%) .rfind(|r| matches!(r.kind, ItemRibKind(_))) . .expect("associated item outside of an item"); . seen_bindings . .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span))); . }; . add_bindings_for_ns(ValueNS); . add_bindings_for_ns(TypeNS); . } . -- line 1122 ---------------------------------------- -- line 1145 ---------------------------------------- . GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam), . _ => unreachable!(), . }; . let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id()); . self.r.record_partial_res(param.id, PartialRes::new(res)); . rib.bindings.insert(ident, res); . } . 618 ( 0.00%) self.ribs[ValueNS].push(function_value_rib); 528 ( 0.00%) self.ribs[TypeNS].push(function_type_rib); . . f(self); . . self.ribs[TypeNS].pop(); . self.ribs[ValueNS].pop(); . } . . fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) { 120 ( 0.00%) self.label_ribs.push(Rib::new(kind)); . f(self); . self.label_ribs.pop(); . } . . fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) { . let kind = ItemRibKind(has_generic_params); . self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f)) . } -- line 1171 ---------------------------------------- -- line 1195 ---------------------------------------- . }, . ) . }); . } . . fn with_current_self_type(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T { . // Handle nested impls (inside fn bodies) . let previous_value = 1 ( 0.00%) replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone())); . let result = f(self); 27 ( 0.00%) self.diagnostic_metadata.current_self_type = previous_value; . result . } . . fn with_current_self_item(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T { . let previous_value = . replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id)); . let result = f(self); . self.diagnostic_metadata.current_self_item = previous_value; -- line 1213 ---------------------------------------- -- line 1218 ---------------------------------------- . fn with_trait_items( . &mut self, . trait_items: &'ast [P], . f: impl FnOnce(&mut Self) -> T, . ) -> T { . let trait_assoc_items = . replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items)); . let result = f(self); 3 ( 0.00%) self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items; . result . } . . /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`). 9 ( 0.00%) fn with_optional_trait_ref( . &mut self, . opt_trait_ref: Option<&TraitRef>, . f: impl FnOnce(&mut Self, Option) -> T, . ) -> T { 1 ( 0.00%) let mut new_val = None; . let mut new_id = None; 2 ( 0.00%) if let Some(trait_ref) = opt_trait_ref { . let path: Vec<_> = Segment::from_path(&trait_ref.path); 15 ( 0.00%) let res = self.smart_resolve_path_fragment( 1 ( 0.00%) trait_ref.ref_id, . None, . &path, 1 ( 0.00%) trait_ref.path.span, 1 ( 0.00%) PathSource::Trait(AliasPossibility::No), . CrateLint::SimplePath(trait_ref.ref_id), . ); . let res = res.base_res(); 1 ( 0.00%) if res != Res::Err { 13 ( 0.00%) if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path( . &path, . Some(TypeNS), . true, . trait_ref.path.span, 1 ( 0.00%) CrateLint::SimplePath(trait_ref.ref_id), . ) { . new_id = Some(res.def_id()); 10 ( 0.00%) new_val = Some((module, trait_ref.clone())); . } . } . } . let original_trait_ref = replace(&mut self.current_trait_ref, new_val); 7 ( 0.00%) let result = f(self, new_id); 18 ( 0.00%) self.current_trait_ref = original_trait_ref; . result 8 ( 0.00%) } . . fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) { . let mut self_type_rib = Rib::new(NormalRibKind); . . // Plain insert (no renaming, since types are not currently hygienic) . self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res); 33 ( 0.00%) self.ribs[ns].push(self_type_rib); . f(self); . self.ribs[ns].pop(); . } . . fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) { . self.with_self_rib_ns(TypeNS, self_res, f) . } . -- line 1281 ---------------------------------------- -- line 1288 ---------------------------------------- . impl_items: &'ast [P], . ) { . debug!("resolve_implementation"); . // If applicable, create a rib for the type parameters. . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { . // Dummy self type for better errors if `Self` is used in the trait path. . this.with_self_rib(Res::SelfTy(None, None), |this| { . // Resolve the trait reference, if necessary. 10 ( 0.00%) this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| { 2 ( 0.00%) let item_def_id = this.r.local_def_id(item_id); . . // Register the trait definitions from here. 2 ( 0.00%) if let Some(trait_id) = trait_id { 4 ( 0.00%) this.r.trait_impls.entry(trait_id).or_default().push(item_def_id); . } . . let item_def_id = item_def_id.to_def_id(); 1 ( 0.00%) this.with_self_rib(Res::SelfTy(trait_id, Some((item_def_id, false))), |this| { 1 ( 0.00%) if let Some(trait_ref) = opt_trait_reference.as_ref() { . // Resolve type arguments in the trait path. . visit::walk_trait_ref(this, trait_ref); . } . // Resolve the self type. 3 ( 0.00%) this.visit_ty(self_type); . // Resolve the generic parameters. 1 ( 0.00%) this.visit_generics(generics); . // Resolve the items within the impl. . this.with_current_self_type(self_type, |this| { . this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| { . debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)"); 1 ( 0.00%) for item in impl_items { . use crate::ResolutionError::*; 168 ( 0.00%) match &item.kind { . AssocItemKind::Const(_default, _ty, _expr) => { . debug!("resolve_implementation AssocItemKind::Const"); . // If this is a trait impl, ensure the const . // exists in trait . this.check_trait_item( . item.id, . item.ident, . &item.kind, -- line 1328 ---------------------------------------- -- line 1344 ---------------------------------------- . visit::walk_assoc_item( . this, . item, . AssocCtxt::Impl, . ) . }, . ); . } 28 ( 0.00%) AssocItemKind::Fn(box Fn { generics, .. }) => { . debug!("resolve_implementation AssocItemKind::Fn"); . // We also need a new scope for the impl item type parameters. . this.with_generic_param_rib( . generics, . AssocItemRibKind, . |this| { . // If this is a trait impl, ensure the method . // exists in trait . this.check_trait_item( 28 ( 0.00%) item.id, 56 ( 0.00%) item.ident, . &item.kind, . ValueNS, 84 ( 0.00%) item.span, . |i, s, c| MethodNotMemberOfTrait(i, s, c), . ); . 56 ( 0.00%) visit::walk_assoc_item( . this, . item, . AssocCtxt::Impl, . ) . }, . ); . } . AssocItemKind::TyAlias(box TyAlias { -- line 1378 ---------------------------------------- -- line 1423 ---------------------------------------- . kind: &AssocItemKind, . ns: Namespace, . span: Span, . err: F, . ) where . F: FnOnce(Ident, &str, Option) -> ResolutionError<'_>, . { . // If there is a TraitRef in scope for an impl, then the method must be in the trait. 56 ( 0.00%) let Some((module, _)) = &self.current_trait_ref else { return; }; 168 ( 0.00%) ident.span.normalize_to_macros_2_0_and_adjust(module.expansion); 140 ( 0.00%) let key = self.r.new_key(ident, ns); 280 ( 0.00%) let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); . debug!(?binding); 28 ( 0.00%) if binding.is_none() { . // We could not find the trait item in the correct namespace. . // Check the other namespace to report an error. . let ns = match ns { . ValueNS => TypeNS, . TypeNS => ValueNS, . _ => ns, . }; . let key = self.r.new_key(ident, ns); -- line 1444 ---------------------------------------- -- line 1449 ---------------------------------------- . // We could not find the method: report an error. . let candidate = self.find_similarly_named_assoc_item(ident.name, kind); . let path = &self.current_trait_ref.as_ref().unwrap().1.path; . self.report_error(span, err(ident, &path_names_to_string(path), candidate)); . return; . }; . . let res = binding.res(); 56 ( 0.00%) let Res::Def(def_kind, _) = res else { bug!() }; 196 ( 0.00%) match (def_kind, kind) { . (DefKind::AssocTy, AssocItemKind::TyAlias(..)) . | (DefKind::AssocFn, AssocItemKind::Fn(..)) . | (DefKind::AssocConst, AssocItemKind::Const(..)) => { 392 ( 0.00%) self.r.record_partial_res(id, PartialRes::new(res)); . return; . } . _ => {} . } . . // The method kind does not correspond to what appeared in the trait, report. . let path = &self.current_trait_ref.as_ref().unwrap().1.path; . let (code, kind) = match kind { -- line 1470 ---------------------------------------- -- line 1480 ---------------------------------------- . kind, . code, . trait_path: path_names_to_string(path), . trait_item_span: binding.span, . }, . ); . } . 324 ( 0.00%) fn resolve_params(&mut self, params: &'ast [Param]) { 180 ( 0.00%) let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; 216 ( 0.00%) for Param { pat, ty, .. } in params { . self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); 148 ( 0.00%) self.visit_ty(ty); . debug!("(resolving function / closure) recorded parameter"); . } 288 ( 0.00%) } . . fn resolve_local(&mut self, local: &'ast Local) { . debug!("resolving local ({:?})", local); . // Resolve the type. . walk_list!(self, visit_ty, &local.ty); . . // Resolve the initializer. . if let Some((init, els)) = local.kind.init_else_opt() { -- line 1503 ---------------------------------------- -- line 1615 ---------------------------------------- . } . . // 5) Finally bubble up all the binding maps. . maps . } . . /// Check the consistency of the outermost or-patterns. . fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) { 350 ( 0.00%) pat.walk(&mut |pat| match pat.kind { . PatKind::Or(ref ps) => { . self.check_consistent_bindings(ps); . false . } . _ => true, . }) . } . . fn resolve_arm(&mut self, arm: &'ast Arm) { . self.with_rib(ValueNS, NormalRibKind, |this| { . this.resolve_pattern_top(&arm.pat, PatternSource::Match); 13 ( 0.00%) walk_list!(this, visit_expr, &arm.guard); . this.visit_expr(&arm.body); . }); . } . . /// Arising from `source`, resolve a top level pattern. . fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) { 52 ( 0.00%) let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; . self.resolve_pattern(pat, pat_src, &mut bindings); . } . . fn resolve_pattern( . &mut self, . pat: &'ast Pat, . pat_src: PatternSource, . bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, . ) { . // We walk the pattern before declaring the pattern's inner bindings, . // so that we avoid resolving a literal expression to a binding defined . // by the pattern. 150 ( 0.00%) visit::walk_pat(self, pat); . self.resolve_pattern_inner(pat, pat_src, bindings); . // This has to happen *after* we determine which pat_idents are variants: . self.check_consistent_bindings_top(pat); . } . . /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`. . /// . /// ### `bindings` -- line 1663 ---------------------------------------- -- line 1679 ---------------------------------------- . /// See the implementation and `fresh_binding` for more details. . fn resolve_pattern_inner( . &mut self, . pat: &Pat, . pat_src: PatternSource, . bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, . ) { . // Visit all direct subpatterns of this pattern. 400 ( 0.00%) pat.walk(&mut |pat| { . debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind); 237 ( 0.00%) match pat.kind { 148 ( 0.00%) PatKind::Ident(bmode, ident, ref sub) => { . // First try to resolve the identifier as some existing entity, . // then fall back to a fresh binding. . let has_sub = sub.is_some(); 407 ( 0.00%) let res = self . .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub) 407 ( 0.00%) .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings)); 259 ( 0.00%) self.r.record_partial_res(pat.id, PartialRes::new(res)); 111 ( 0.00%) self.r.record_pat_span(pat.id, pat.span); . } . PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => { . self.smart_resolve_path( . pat.id, . qself.as_ref(), . path, . PathSource::TupleStruct( . pat.span, -- line 1706 ---------------------------------------- -- line 1740 ---------------------------------------- . return false; . } . _ => {} . } . true . }); . } . 444 ( 0.00%) fn fresh_binding( . &mut self, . ident: Ident, . pat_id: NodeId, . pat_src: PatternSource, . bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, . ) -> Res { . // Add the binding to the local ribs, if it doesn't already exist in the bindings map. . // (We must not add it if it's in the bindings map because that breaks the assumptions . // later passes make about or-patterns.) 185 ( 0.00%) let ident = ident.normalize_to_macro_rules(); . . let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident)); . // Already bound in a product pattern? e.g. `(a, a)` which is not allowed. . let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product); . // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`. . // This is *required* for consistency which is checked later. . let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or); . 37 ( 0.00%) if already_bound_and { . // Overlap in a product pattern somewhere; report an error. . use ResolutionError::*; . let error = match pat_src { . // `fn f(a: u8, a: u8)`: . PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList, . // `Variant(a, a)`: . _ => IdentifierBoundMoreThanOnceInSamePattern, . }; . self.report_error(ident.span, error(ident.name)); . } . . // Record as bound if it's valid: . let ident_valid = ident.name != kw::Empty; 37 ( 0.00%) if ident_valid { 74 ( 0.00%) bindings.last_mut().unwrap().1.insert(ident); . } . 37 ( 0.00%) if already_bound_or { . // `Variant1(a) | Variant2(a)`, ok . // Reuse definition from the first `a`. . self.innermost_rib_bindings(ValueNS)[&ident] . } else { . let res = Res::Local(pat_id); . if ident_valid { . // A completely fresh binding add to the set if it's valid. 74 ( 0.00%) self.innermost_rib_bindings(ValueNS).insert(ident, res); . } 296 ( 0.00%) res . } 333 ( 0.00%) } . . fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap { . &mut self.ribs[ns].last_mut().unwrap().bindings . } . 481 ( 0.00%) fn try_resolve_as_non_binding( . &mut self, . pat_src: PatternSource, . pat: &Pat, . bm: BindingMode, . ident: Ident, . has_sub: bool, . ) -> Option { . // An immutable (no `mut`) by-value (no `ref`) binding pattern without . // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could . // also be interpreted as a path to e.g. a constant, variant, etc. 74 ( 0.00%) let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not); . . let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?; . let (res, binding) = match ls_binding { . LexicalScopeBinding::Item(binding) . if is_syntactic_ambiguity && binding.is_ambiguity() => . { . // For ambiguous bindings we don't know all their definitions and cannot check . // whether they can be shadowed by fresh bindings or not, so force an error. -- line 1822 ---------------------------------------- -- line 1882 ---------------------------------------- . None . } . _ => span_bug!( . ident.span, . "unexpected resolution for an identifier in pattern: {:?}", . res, . ), . } 333 ( 0.00%) } . . // High-level and context dependent path resolution routine. . // Resolves the path and records the resolution into definition map. . // If resolution fails tries several techniques to find likely . // resolution candidates, suggest imports or other help, and report . // errors in user friendly way. 2,568 ( 0.00%) fn smart_resolve_path( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &Path, . source: PathSource<'ast>, . ) { 3,210 ( 0.00%) self.smart_resolve_path_fragment( . id, . qself, . &Segment::from_path(path), 214 ( 0.00%) path.span, 856 ( 0.00%) source, . CrateLint::SimplePath(id), . ); . } . 3,010 ( 0.00%) fn smart_resolve_path_fragment( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &[Segment], . span: Span, . source: PathSource<'ast>, . crate_lint: CrateLint, . ) -> PartialRes { . tracing::debug!( . "smart_resolve_path_fragment(id={:?}, qself={:?}, path={:?})", . id, . qself, . path . ); 1,720 ( 0.00%) let ns = source.namespace(); . 1,290 ( 0.00%) let report_errors = |this: &mut Self, res: Option| { . if this.should_report_errs() { . let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res); . . let def_id = this.parent_scope.module.nearest_parent_mod(); . let instead = res.is_some(); . let suggestion = . if res.is_none() { this.report_missing_type_error(path) } else { None }; . // get_from_node_id -- line 1939 ---------------------------------------- -- line 2014 ---------------------------------------- . err.cancel(); . } . . // We don't return `Some(parent_err)` here, because the error will . // be already printed as part of the `use` injections . None . }; . 4,730 ( 0.00%) let partial_res = match self.resolve_qpath_anywhere( . id, . qself, . path, . ns, . span, . source.defer_to_typeck(), . crate_lint, . ) { 1,290 ( 0.00%) Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => { 1,505 ( 0.00%) if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err . { 1,290 ( 0.00%) partial_res . } else { . report_errors(self, Some(partial_res.base_res())) . } . } . . Ok(Some(partial_res)) if source.defer_to_typeck() => { . // Not fully resolved associated item `T::A::B` or `::A::B` . // or `::A::B`. If `B` should be resolved in value namespace then -- line 2042 ---------------------------------------- -- line 2073 ---------------------------------------- . } . . PartialRes::new(Res::Err) . } . . _ => report_errors(self, None), . }; . 430 ( 0.00%) if !matches!(source, PathSource::TraitItem(..)) { . // Avoid recording definition of `A::B` in `::B::C`. 860 ( 0.00%) self.r.record_partial_res(id, partial_res); . } . . partial_res 1,720 ( 0.00%) } . . fn self_type_is_available(&mut self, span: Span) -> bool { . let binding = self.resolve_ident_in_lexical_scope( . Ident::with_dummy_span(kw::SelfUpper), . TypeNS, . None, . span, . ); -- line 2095 ---------------------------------------- -- line 2113 ---------------------------------------- . . #[inline] . /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items. . fn should_report_errs(&self) -> bool { . !(self.r.session.opts.actually_rustdoc && self.in_func_body) . } . . // Resolve in alternative namespaces if resolution in the primary namespace fails. 2,795 ( 0.00%) fn resolve_qpath_anywhere( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &[Segment], . primary_ns: Namespace, . span: Span, . defer_to_typeck: bool, . crate_lint: CrateLint, . ) -> Result, Spanned>> { . let mut fin_res = None; . 1,505 ( 0.00%) for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() { 430 ( 0.00%) if i == 0 || ns != primary_ns { 860 ( 0.00%) match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? { . Some(partial_res) 1,290 ( 0.00%) if partial_res.unresolved_segments() == 0 || defer_to_typeck => . { 2,580 ( 0.00%) return Ok(Some(partial_res)); . } . partial_res => { . if fin_res.is_none() { . fin_res = partial_res; . } . } . } . } -- line 2147 ---------------------------------------- -- line 2155 ---------------------------------------- . if let Ok((_, res)) = . self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false) . { . return Ok(Some(PartialRes::new(res))); . } . } . . Ok(fin_res) 1,720 ( 0.00%) } . . /// Handles paths that may refer to associated items. . fn resolve_qpath( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &[Segment], . ns: Namespace, -- line 2171 ---------------------------------------- -- line 2172 ---------------------------------------- . span: Span, . crate_lint: CrateLint, . ) -> Result, Spanned>> { . debug!( . "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})", . id, qself, path, ns, span, . ); . 215 ( 0.00%) if let Some(qself) = qself { . if qself.position == 0 { . // This is a case like `::B`, where there is no . // trait to resolve. In that case, we leave the `B` . // segment to be resolved by type-check. . return Ok(Some(PartialRes::with_unresolved_segments( . Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), . path.len(), . ))); -- line 2188 ---------------------------------------- -- line 2216 ---------------------------------------- . // have to be resolved by type-check, since that requires doing . // trait resolution. . return Ok(Some(PartialRes::with_unresolved_segments( . partial_res.base_res(), . partial_res.unresolved_segments() + path.len() - qself.position - 1, . ))); . } . 1,296 ( 0.00%) let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) { 2,756 ( 0.00%) PathResult::NonModule(path_res) => path_res, 12 ( 0.00%) PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => { . PartialRes::new(module.res().unwrap()) . } . // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we . // don't report an error right away, but try to fallback to a primitive type. . // So, we are still able to successfully resolve something like . // . // use std::u8; // bring module u8 in scope . // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8 -- line 2234 ---------------------------------------- -- line 2248 ---------------------------------------- . PathResult::Module(ModuleOrUniformRoot::Module(module)) => { . PartialRes::new(module.res().unwrap()) . } . PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { . return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion })); . } . PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None), . PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"), 1,075 ( 0.00%) }; . 355 ( 0.00%) if path.len() > 1 . && result.base_res() != Res::Err 28 ( 0.00%) && path[0].ident.name != kw::PathRoot . && path[0].ident.name != kw::DollarCrate . { . let unqualified_result = { 140 ( 0.00%) match self.resolve_path( 140 ( 0.00%) &[*path.last().unwrap()], . Some(ns), . false, . span, . CrateLint::No, . ) { . PathResult::NonModule(path_res) => path_res.base_res(), . PathResult::Module(ModuleOrUniformRoot::Module(module)) => { . module.res().unwrap() . } 112 ( 0.00%) _ => return Ok(Some(result)), . } . }; . if result.base_res() == unqualified_result { . let lint = lint::builtin::UNUSED_QUALIFICATIONS; . self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification") . } . } . 748 ( 0.00%) Ok(Some(result)) . } . . fn with_resolved_label(&mut self, label: Option