diff --git a/Makefile b/Makefile index 7f1c1d96f..cd70d3bfc 100644 --- a/Makefile +++ b/Makefile @@ -314,6 +314,7 @@ HARNESS_TESTS = \ scripts/tests/test_wasm_checker.py \ scripts/tests/test_wasm_module.py \ scripts/tests/test_wasm_quality.py \ + scripts/tests/test_native_source_lto.py \ scripts/tests/test_wasi_inception.py \ scripts/tests/test_wasm_generators.py \ scripts/tests/test_machine_boundary.py \ diff --git a/README.md b/README.md index 5f6f5591d..ef427f4e7 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,13 @@ Methods: [public programs](benchmarks/public/README.md) ([O0 and per-host result - The [required C++11/14/17 profile](LANGUAGE_PROFILE.md) covers selected features. It is not full conformance to each edition. - C++20 and C have partial support. The profile lists the selected C++20 features. The optional [PA38](pa38/README.md) compiles C sources in the `c17` and `gnu17` modes. - The targets are Linux x86-64, Intel macOS and wasm32 (`wasm32-unknown-unknown` and `wasm32-wasip1`, [PA37](pa37/README.md)). +- `-Oz` and the LTO flags are experimental. `-Oz` optimizes for size. + `-flto` shares identical function bodies when linking Wasm. + `-flto=full` optimizes consecutive source inputs together on Wasm and + Linux x86-64. On Linux x86-64, use `-flto=full -c -o combined.o` to + produce one object for the host linker. Full LTO needs the source files + in the same command and can use more memory. Keep competing weak and + strong definitions in separate objects so the linker can select one. - [Integrated assembly](pa29/README.md) is complete for its documented x86-64 profile. It is not a general assembler. - The compiler has no C++ standard library of its own. Use the library that is installed on the host. - The compiler can contain bugs. diff --git a/dev/cppgm.cpp b/dev/cppgm.cpp index 4658e5e42..7be8b8144 100644 --- a/dev/cppgm.cpp +++ b/dev/cppgm.cpp @@ -433,6 +433,7 @@ SourceOutputInvocation parse_source_output_invocation(const vector& args { invocation.optimizer.level = optimization_level(args[i]); invocation.optimize_size = args[i] == "-Os" || args[i] == "-Oz"; + invocation.optimizer.minimize_size = args[i] == "-Oz"; invocation.debug_optimization = args[i] == "-Og"; continue; } @@ -674,6 +675,7 @@ DriverInvocation parse_driver_invocation(const vector& args) bool compile_only = false; bool preprocess_only = false; bool explicit_outfile = false; + bool whole_source_lto = false; vector inputs; for (size_t i = 0; i < args.size(); ++i) @@ -708,6 +710,11 @@ DriverInvocation parse_driver_invocation(const vector& args) explicit_outfile = true; continue; } + if (args[i] == "-flto=full" || args[i] == "-flto" || args[i] == "-fno-lto") + { + whole_source_lto = args[i] == "-flto=full"; + continue; + } if (consume_preprocess_option(args, i) || consume_search_option(args, i) || consume_dependency_option(args, i) || consume_toolchain_option(args, i) || is_benign_driver_flag(args[i])) { @@ -728,7 +735,7 @@ DriverInvocation parse_driver_invocation(const vector& args) { throw InvocationError("invalid usage"); } - if ((compile_only || preprocess_only) && explicit_outfile && inputs.size() != 1) + if ((preprocess_only || (compile_only && !whole_source_lto)) && explicit_outfile && inputs.size() != 1) { throw InvocationError("cannot specify -o when generating multiple output files"); } @@ -1314,7 +1321,11 @@ int run_cppgm(const vector& raw_args) << "this compiler's flags:\n" " -S -emit-lowir write the LowIR that -c compiles, after the LowIR optimizer\n" " (default output: .lowir)\n" - " -fno-lowir-passes compile without the LowIR optimizer; the back end runs at the -O level\n"; + " -fno-lowir-passes compile without the LowIR optimizer; the back end runs at the -O level\n" + " -Oz optimize for smaller code\n" + " -flto fold identical function bodies when linking Wasm objects\n" + " -flto=full optimize consecutive source inputs together when linking Wasm or x86-64 ELF\n" + " on x86-64 ELF, -c with -o writes one combined object\n"; return EXIT_SUCCESS; } diff --git a/dev/frontend_source_sets.mk b/dev/frontend_source_sets.mk index 2475c09ea..887cdee8d 100644 --- a/dev/frontend_source_sets.mk +++ b/dev/frontend_source_sets.mk @@ -77,7 +77,7 @@ FRONTEND_OBJ_BASENAMES_cppgm += lowir/text_lexer lowir/text_parser lowir/text_pa FRONTEND_OBJ_BASENAMES_cppgm += asm/registers # Shared target dispatch and the wasm32 backend (PA37). -FRONTEND_PHASE_BASENAMES_wasm := wasm/bytes wasm/abi wasm/encoder wasm/mir_facts wasm/mir_writer wasm/local_cleanup wasm/local_lifetimes wasm/validation wasm/module wasm/exception_runtime wasm/exception_payload wasm/exception_plan wasm/select_exceptions wasm/selector wasm/object_places wasm/frame wasm/select_objects wasm/select_calls wasm/nonlocal_jumps wasm/select_varargs wasm/select_builtins wasm/control wasm/control_regions wasm/control_emission wasm/select_instructions wasm/select_atomics wasm/select_switch wasm/select_arithmetic wasm/select_vectors wasm/vector_permute wasm/vector_float wasm/vector_shift wasm/vector_compare wasm/vector_convert wasm/vector_horizontal wasm/vector_integer_math wasm/vector_reciprocal wasm/vector_reductions wasm/vector_carryless wasm/wide_helpers wasm/select_wide wasm/wide_locals wasm/select_wide_arithmetic wasm/select_wide_shift wasm/object_lowering wasm/object_aliases wasm/object_startup wasm/finalization wasm/runtime_inputs wasm/object_writer wasm/object_reader wasm/object_constants wasm/object_customs wasm/object_elements wasm/object_expression_validation wasm/object_features wasm/archive wasm/object_metadata wasm/object_validation wasm/object_code wasm/linker wasm/link_relocations wasm/link_globals wasm/link_data_exports wasm/link_output wasm/backend wasm/assembly_tokens wasm/assembly_parser wasm/assembly_instructions wasm/assembly_object +FRONTEND_PHASE_BASENAMES_wasm := wasm/bytes wasm/abi wasm/encoder wasm/mir_facts wasm/mir_writer wasm/local_cleanup wasm/local_lifetimes wasm/validation wasm/module wasm/exception_runtime wasm/exception_payload wasm/exception_plan wasm/select_exceptions wasm/selector wasm/object_places wasm/frame wasm/select_objects wasm/select_calls wasm/nonlocal_jumps wasm/select_varargs wasm/select_builtins wasm/control wasm/control_regions wasm/control_emission wasm/select_instructions wasm/select_atomics wasm/select_switch wasm/select_arithmetic wasm/select_vectors wasm/vector_permute wasm/vector_float wasm/vector_shift wasm/vector_compare wasm/vector_convert wasm/vector_horizontal wasm/vector_integer_math wasm/vector_reciprocal wasm/vector_reductions wasm/vector_carryless wasm/wide_helpers wasm/select_wide wasm/wide_locals wasm/select_wide_arithmetic wasm/select_wide_shift wasm/object_lowering wasm/object_aliases wasm/object_startup wasm/finalization wasm/runtime_inputs wasm/object_writer wasm/object_reader wasm/object_constants wasm/object_customs wasm/object_elements wasm/object_expression_validation wasm/object_features wasm/archive wasm/object_metadata wasm/object_validation wasm/object_code wasm/linker wasm/link_folding wasm/link_relocations wasm/link_globals wasm/link_data_exports wasm/link_output wasm/backend wasm/assembly_tokens wasm/assembly_parser wasm/assembly_instructions wasm/assembly_object FRONTEND_OBJ_BASENAMES_lowir2native += lowir/text_writer lowir/assembly_writer lowir/local_names backend/compile $(FRONTEND_PHASE_BASENAMES_wasm) $(FRONTEND_PHASE_BASENAMES_opt) # Object names use the shared UTF-8 decoder without the source lexer. FRONTEND_OBJ_BASENAMES_lowir2native += support/unicode/utf8 diff --git a/dev/src/backend/options.h b/dev/src/backend/options.h index e13193683..1e893577e 100644 --- a/dev/src/backend/options.h +++ b/dev/src/backend/options.h @@ -18,7 +18,10 @@ struct WasmLinkOptions std::set imports; bool export_table = false; bool export_constructors = false; - bool requested() const { return export_table || export_constructors || !imports.empty(); } + // Link-time identical code folding over resolved Wasm objects. + bool fold_functions = false; + bool compact_relocations = false; + bool requested() const { return export_table || export_constructors || fold_functions || !imports.empty(); } }; struct Options diff --git a/dev/src/driver/toolchain.cpp b/dev/src/driver/toolchain.cpp index bc33fb070..d8a7a9a87 100644 --- a/dev/src/driver/toolchain.cpp +++ b/dev/src/driver/toolchain.cpp @@ -155,6 +155,7 @@ struct Invocation bool wasm_atomics = true; bool wasm_atomics_explicit = false; backend::WasmLinkOptions wasm_link; + bool whole_source_lto = false; std::vector inputs; std::vector library_paths; std::vector exports; @@ -273,6 +274,10 @@ bool accepted_flag(const std::string& arg) void configure_target_runtime(Invocation& invocation, bool nostdinc) { configure_target_environment(invocation.preprocessor, invocation.target); + invocation.optimizer.has_gnu_sincos = target_model::has_gnu_sincos(invocation.target); + // Darwin objects are position independent even without an explicit -fPIC. + if (invocation.target == native::Target::MacOS) + invocation.position_independent = true; if (target_model::is_wasm(invocation.target)) { if (invocation.wasm_atomics) @@ -462,8 +467,14 @@ Invocation parse(const std::vector& args, const PreprocessorOptions { invocation.optimizer.level = optimization_level(arg); optimize_size = arg == "-Os" || arg == "-Oz"; + invocation.optimizer.minimize_size = arg == "-Oz"; invocation.debug_optimization = arg == "-Og"; } + else if (arg == "-flto" || arg == "-flto=full" || arg == "-fno-lto") + { + invocation.wasm_link.fold_functions = arg == "-flto"; + invocation.whole_source_lto = arg == "-flto=full"; + } else if (arg == "-fno-inline" || arg == "-finline") invocation.optimizer.optional_inlining = arg == "-finline"; else if (arg == "--inline-limit") @@ -569,16 +580,31 @@ Invocation parse(const std::vector& args, const PreprocessorOptions gcc_install_dir, host_error)) throw InvocationError(host_error); configure_target_runtime(invocation, nostdinc); - invocation.optimizer.has_gnu_sincos = target_model::has_gnu_sincos(invocation.target); - // Darwin objects are position independent even without an explicit -fPIC. - if (invocation.target == native::Target::MacOS) - invocation.position_independent = true; prune_include_paths(invocation.preprocessor); if (invocation.preprocess_only) invocation.preprocessor.builtin_declarations.clear(); return invocation; } +struct SourceInputs +{ + const Input* begin; + const Input* end; +}; + +SourceInputs source_lto_inputs(const Invocation& invocation) +{ + const Input* end = invocation.inputs.data() + invocation.inputs.size(); + if (!invocation.whole_source_lto) + return { end, end }; + const auto is_source = [](const Input& input) { return input.kind == Input::Kind::Source; }; + const Input* first = std::find_if(invocation.inputs.data(), end, is_source); + const Input* after = std::find_if_not(first, end, is_source); + if (first == after || std::find_if(after, end, is_source) != end) + throw InvocationError("-flto=full needs consecutive source inputs"); + return { first, after }; +} + // The semantic graph's template and evaluation work for a unit's stats // line (hosted compilations have no --emit-lowir view of it). struct UnitWork @@ -674,17 +700,17 @@ bool lower_source(const std::string& path, const Invocation& invocation, lower:: try { analyzer.analyze(unit.tree()); - front_ms = milliseconds_since(start); + front_ms += milliseconds_since(start); if (invocation.syntax_only) return true; lowering.lower_unit(unit.tree(), graph, analyzer); - work.specializations = graph.specializations; - work.instantiated_classes = graph.instantiated_classes; - work.instantiated_functions = graph.instantiated_functions; - work.instantiated_variables = graph.instantiated_variables; - work.constant_evaluations = graph.constant_evaluations; - work.resolutions = graph.resolutions; - work.candidates = graph.candidates; + work.specializations += graph.specializations; + work.instantiated_classes += graph.instantiated_classes; + work.instantiated_functions += graph.instantiated_functions; + work.instantiated_variables += graph.instantiated_variables; + work.constant_evaluations += graph.constant_evaluations; + work.resolutions += graph.resolutions; + work.candidates += graph.candidates; } catch (const sema::SemanticError& e) { @@ -717,8 +743,8 @@ bool write_unit_lowir(const lowir::Program& program, lowir::DefinitionStream* de } // With `lowir_output`, -S -emit-lowir: the program is written there as text -// instead of compiled. -bool compile_unit(const std::string& path, const Invocation& invocation, native::EhModel eh_model, +// instead of compiled. A source LTO group shares the program and the lowering. +bool compile_native_sources(SourceInputs sources, const Invocation& invocation, native::EhModel eh_model, native::object::ObjectFile& object, const std::string* lowir_output = nullptr) { const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); @@ -746,19 +772,29 @@ bool compile_unit(const std::string& path, const Invocation& invocation, native: lowering.set_strict_aliasing(invocation.strict_aliasing); lowering.set_popcnt(invocation.preprocessor.popcnt); lowering.set_exceptions(invocation.preprocessor.modes.exceptions); + if (invocation.whole_source_lto) + lowering.merge_inline_variables(); double front_ms = 0; UnitWork work; + const Input* input = sources.begin; try { - if (!lower_source(path, invocation, lowering, work, front_ms, start)) - return false; + auto unit_start = start; + for (const Input* source = sources.begin; source != sources.end; ++source) + { + input = source; + if (!lower_source(input->name, invocation, lowering, work, front_ms, unit_start)) + return false; + if (source + 1 != sources.end) + unit_start = std::chrono::steady_clock::now(); + } if (invocation.syntax_only) return true; lowering.finish(); optimize_unit(program, invocation, eh_model); if (lowir_output != nullptr) return write_unit_lowir(program, streaming ? &definitions : nullptr, *lowir_output); - object.path = path; + object.path = sources.begin->name; builder.finish(object); } // The unit's errors without a source position. An InternalError (a @@ -766,31 +802,31 @@ bool compile_unit(const std::string& path, const Invocation& invocation, native: // report. catch (const PreprocessError& e) { - std::cerr << "ERROR: " << path << ": " << e.what() << std::endl; + std::cerr << "ERROR: " << input->name << ": " << e.what() << std::endl; return false; } catch (const lower::LoweringError& e) { - std::cerr << "ERROR: " << path << ": " << e.what() << std::endl; + std::cerr << "ERROR: " << input->name << ": " << e.what() << std::endl; return false; } catch (const native::BackendError& e) { - std::cerr << "ERROR: " << path << ": " << e.what() << std::endl; + std::cerr << "ERROR: " << input->name << ": " << e.what() << std::endl; return false; } catch (const abi_mangle::EncodingError& e) { - std::cerr << "ERROR: " << path << ": " << e.what() << std::endl; + std::cerr << "ERROR: " << input->name << ": " << e.what() << std::endl; return false; } catch (const LimitError& e) { - std::cerr << "ERROR: " << path << ": " << e.what() << std::endl; + std::cerr << "ERROR: " << input->name << ": " << e.what() << std::endl; return false; } if (invocation.stats) - report_unit(path, front_ms, milliseconds_since(start) - front_ms, stats, work, object); + report_unit(object.path, front_ms, milliseconds_since(start) - front_ms, stats, work, object); report_census(stats); return true; } @@ -831,8 +867,9 @@ bool compile_input(const Input& input, const Invocation& invocation, native::EhM { if (input.kind == Input::Kind::Assembly) return compile_native_assembly(input.name, invocation.preprocessor, invocation.target, object); - return input.kind == Input::Kind::LowIR ? compile_lowir_unit(input.name, invocation, eh_model, object, lowir_output) - : compile_unit(input.name, invocation, eh_model, object, lowir_output); + return input.kind == Input::Kind::LowIR + ? compile_lowir_unit(input.name, invocation, eh_model, object, lowir_output) + : compile_native_sources({ &input, &input + 1 }, invocation, eh_model, object, lowir_output); } bool regular_file(const std::string& path) @@ -882,9 +919,29 @@ native::EhModel object_eh_model(const std::string& output) return ends_with(output, ".obj") ? native::EhModel::Course : native::EhModel::Host; } +int compile_lto_object(const Invocation& invocation) +{ + const SourceInputs sources = source_lto_inputs(invocation); + const std::string& output = invocation.output; + if (output.empty() || sources.begin != invocation.inputs.data() || + sources.end != invocation.inputs.data() + invocation.inputs.size()) + throw InvocationError("-flto=full -c requires source inputs and an explicit -o"); + check_output(invocation, output); + native::object::ObjectFile object; + if (!compile_native_sources(sources, invocation, object_eh_model(output), object)) + return EXIT_FAILURE; + std::string error; + if (native::object::write_elf_object(object, output, error)) + return EXIT_SUCCESS; + std::cerr << "ERROR: " << error << std::endl; + return EXIT_FAILURE; +} + // Libraries are link inputs: -c compiles the sources and ignores them. int compile_mode(const Invocation& invocation) { + if (invocation.whole_source_lto) + return compile_lto_object(invocation); size_t sources = 0; for (const Input& input : invocation.inputs) sources += input.kind != Input::Kind::Library ? 1 : 0; @@ -942,10 +999,20 @@ int link_mode(const Invocation& invocation) check_output(invocation, output); std::vector objects; objects.reserve(invocation.inputs.size() + 2); - for (const Input& input : invocation.inputs) + const SourceInputs sources = source_lto_inputs(invocation); + const Input* end = invocation.inputs.data() + invocation.inputs.size(); + for (const Input* next = invocation.inputs.data(); next != end;) { - objects.push_back(native::object::ObjectFile()); + objects.emplace_back(); native::object::ObjectFile& object = objects.back(); + if (next == sources.begin) + { + if (!compile_native_sources(sources, invocation, native::EhModel::Course, object)) + return EXIT_FAILURE; + next = sources.end; + continue; + } + const Input& input = *next++; if (input.kind == Input::Kind::Source || input.kind == Input::Kind::LowIR || input.kind == Input::Kind::Assembly) { @@ -1026,6 +1093,45 @@ bool wasm_assembly(const Input& input, const Invocation& invocation, wasm::LinkI return false; } +void configure_wasm_lowering(lower::ProgramLowering& lowering, const Invocation& invocation) +{ + // An object's LowIR before optimization is the same at every level. + lowering.set_optimizing(true); + lowering.set_exceptions(invocation.preprocessor.modes.exceptions); + lowering.set_strict_aliasing(invocation.strict_aliasing); +} + +bool lower_wasm_source( + const Input& input, const Invocation& invocation, lower::ProgramLowering& lowering, bool final_source) +{ + UnitWork work; + double front_ms = 0; + const auto start = std::chrono::steady_clock::now(); + if (!lower_source(input.name, invocation, lowering, work, front_ms, start)) + return false; + if (final_source) + lowering.finish(); +#if CPPGM_TELEMETRY_ENABLED + if (invocation.stats) + std::cerr << "cppgm wasm frontend stats " << input.name << ": front_ms=" << front_ms + << " lower_ms=" << milliseconds_since(start) - front_ms << " specializations=" << work.specializations + << " instantiated_functions=" << work.instantiated_functions << " resolutions=" << work.resolutions + << " candidates=" << work.candidates << std::endl; +#endif + return true; +} + +bool add_wasm_object( + lowir::Program& program, const backend::Options& options, wasm::LinkInputs& inputs, std::string& error) +{ + std::string dump = "machine_ir wasm32 1\n"; + wasm::Object object; + if (!wasm::compile_object(program, options, object, dump, error)) + return false; + inputs.objects.push_back(std::move(object)); + return true; +} + // One translation unit's posttoken records (`sof`, the PA2 tokens, `eof`); // false after an error. // With `lowir_output`, -S -emit-lowir: the program is written there as text @@ -1062,25 +1168,9 @@ bool wasm_input(const Input& input, const Invocation& invocation, const backend: program.target = invocation.target; program.explicit_target = true; lower::ProgramLowering lowering(program); - // An object's LowIR is the same at every level, so the LowIR that - // --emit-lowir writes for it compiles to this object at any level. - lowering.set_optimizing(true); - lowering.set_exceptions(invocation.preprocessor.modes.exceptions); - lowering.set_strict_aliasing(invocation.strict_aliasing); - UnitWork work; - double front_ms = 0; - const auto start = std::chrono::steady_clock::now(); - if (!lower_source(input.name, invocation, lowering, work, front_ms, start)) + configure_wasm_lowering(lowering, invocation); + if (!lower_wasm_source(input, invocation, lowering, true)) return false; - lowering.finish(); -#if CPPGM_TELEMETRY_ENABLED - if (invocation.stats) - std::cerr << "cppgm wasm frontend stats " << input.name << ": front_ms=" << front_ms - << " lower_ms=" << milliseconds_since(start) - front_ms - << " specializations=" << work.specializations - << " instantiated_functions=" << work.instantiated_functions - << " resolutions=" << work.resolutions << " candidates=" << work.candidates << std::endl; -#endif } if (lowir_output != nullptr) { @@ -1090,12 +1180,22 @@ bool wasm_input(const Input& input, const Invocation& invocation, const backend: error = "cannot write " + *lowir_output; return false; } - std::string dump = "machine_ir wasm32 1\n"; - wasm::Object object; - if (!wasm::compile_object(program, options, object, dump, error)) - return false; - inputs.objects.push_back(std::move(object)); - return true; + return add_wasm_object(program, options, inputs, error); +} + +bool compile_wasm_sources(SourceInputs sources, const Invocation& invocation, const backend::Options& options, + wasm::LinkInputs& inputs, std::string& error) +{ + lowir::Program program; + program.target = invocation.target; + program.explicit_target = true; + lower::ProgramLowering lowering(program); + configure_wasm_lowering(lowering, invocation); + lowering.merge_inline_variables(); + for (const Input* input = sources.begin; input != sources.end; ++input) + if (!lower_wasm_source(*input, invocation, lowering, input + 1 == sources.end)) + return false; + return add_wasm_object(program, options, inputs, error); } int wasm_mode(const Invocation& invocation) @@ -1116,14 +1216,30 @@ int wasm_mode(const Invocation& invocation) options.no_startfiles = invocation.no_startfiles; options.wasm_atomics = invocation.wasm_atomics; options.wasm_link = invocation.wasm_link; + options.wasm_link.fold_functions |= invocation.whole_source_lto; + options.wasm_link.compact_relocations = invocation.optimizer.minimize_size; if (invocation.wasm_stack_size != 0) options.wasm_stack_size = invocation.wasm_stack_size; options.optimizer = &invocation.optimizer; options.lowir_passes = invocation.lowir_passes; std::string error; wasm::LinkInputs objects; - for (const Input& input : invocation.inputs) + const SourceInputs sources = source_lto_inputs(invocation); + const Input* end = invocation.inputs.data() + invocation.inputs.size(); + for (const Input* next = invocation.inputs.data(); next != end;) { + if (next == sources.begin) + { + if (!compile_wasm_sources(sources, invocation, options, objects, error)) + { + if (!error.empty()) + std::cerr << "ERROR: " << error << std::endl; + return EXIT_FAILURE; + } + next = sources.end; + continue; + } + const Input& input = *next++; const std::string lowir_output = invocation.emit_lowir ? default_output_name(invocation, input) : ""; if (invocation.emit_lowir) check_output(invocation, lowir_output); @@ -1256,12 +1372,21 @@ int debug_type_request(const std::string& arg) int run_toolchain(const std::vector& args, const PreprocessorOptions& base) { const Invocation invocation = parse(args, base); + const bool wasm_target = target_model::is_wasm(invocation.target); + if (invocation.whole_source_lto) + { + if (!wasm_target && invocation.target != native::Target::Linux) + throw InvocationError("-flto=full requires x86-64 ELF or a Wasm target"); + if (invocation.preprocess_only || invocation.syntax_only || invocation.emit_lowir || + (wasm_target && invocation.compile_only)) + throw InvocationError("-flto=full requires a link command or an x86-64 ELF object build"); + } for (const Input& input : invocation.inputs) if (input.kind == Input::Kind::Assembly && (invocation.preprocess_only || invocation.syntax_only || invocation.emit_lowir)) throw InvocationError("assembly input requires a compile or link invocation"); - if (!target_model::is_wasm(invocation.target) && !invocation.exports.empty()) + if (!wasm_target && !invocation.exports.empty()) throw InvocationError("explicit function exports require a Wasm target"); if (invocation.preprocess_only) return preprocess_mode(invocation); @@ -1271,12 +1396,12 @@ int run_toolchain(const std::vector& args, const PreprocessorOption { native::object::ObjectFile object; if (input.kind == Input::Kind::Source && - !compile_unit(input.name, invocation, native::EhModel::Host, object)) + !compile_native_sources({ &input, &input + 1 }, invocation, native::EhModel::Host, object)) return EXIT_FAILURE; } return EXIT_SUCCESS; } - if (target_model::is_wasm(invocation.target)) + if (wasm_target) return wasm_mode(invocation); return invocation.compile_only ? compile_mode(invocation) : link_mode(invocation); } diff --git a/dev/src/lower/program_lowering.cpp b/dev/src/lower/program_lowering.cpp index a3484f3ee..ec8918952 100644 --- a/dev/src/lower/program_lowering.cpp +++ b/dev/src/lower/program_lowering.cpp @@ -73,6 +73,8 @@ ProgramLowering::~ProgramLowering() void ProgramLowering::lower_unit( const syntax::TranslationUnit& unit, sema::SemanticGraph& graph, sema::Analyzer& analyzer) { + // TLS initialization is tied to the translation unit that defined it. + define_unit_thread_local_init(); // Entity identities are addresses in this unit's arena: the maps keyed // by them start empty for each unit. char marker; @@ -96,6 +98,8 @@ void ProgramLowering::lower_unit( debug_file_.clear(); debug_file_name_ = 0; symbols_.clear(); + inline_copies_.clear(); + predefined_symbols_.clear(); source_object_aliases_.clear(); compound_globals_.clear(); identities_.clear(); @@ -748,7 +752,12 @@ void ProgramLowering::define_variable( { const lowir::SymbolId symbol = variable_symbol(variable); if (program_.symbols[symbol].kind != lowir::SymbolKind::Unresolved) + { + if (merge_inline_variables_ && variable->is_inline && + program_.symbols[symbol].metadata.binding == ir_model::SBM_WEAK) + return; throw LoweringError(location, "redefinition of a variable across translation units"); + } define_global(symbol, variable, initializer, location); ++counters_.globals; } diff --git a/dev/src/lower/program_lowering.h b/dev/src/lower/program_lowering.h index 1f9778e07..9727c0e10 100644 --- a/dev/src/lower/program_lowering.h +++ b/dev/src/lower/program_lowering.h @@ -426,6 +426,8 @@ class ProgramLowering // Declares what was referenced but never defined and ends the // initialization function; the program is complete afterwards. void finish(); + // Whole-source LTO keeps one definition of an inline variable. + void merge_inline_variables() { merge_inline_variables_ = true; } const LoweringCounters& counters() const { return counters_; } @@ -2057,6 +2059,7 @@ class ProgramLowering const SourcePositions* positions_ = nullptr; std::string debug_file_; lowir::NameId debug_file_name_ = 0; + bool merge_inline_variables_ = false; bool object_mode_ = false; bool host_objects_ = false; bool macho_objects_ = false; diff --git a/dev/src/opt/eh_regions.cpp b/dev/src/opt/eh_regions.cpp index 3f0b89e6c..346310814 100644 --- a/dev/src/opt/eh_regions.cpp +++ b/dev/src/opt/eh_regions.cpp @@ -218,7 +218,7 @@ bool strip_dead_regions(FunctionContext& context) return changed; } -bool proves_nounwind(const FunctionContext& context) +bool proves_nounwind(const FunctionContext& context, bool exclude_assembly) { const SymbolMetadata& m = context.program.symbols[context.symbol].metadata; if ((m.flags & SF_REPLACEABLE) != 0) @@ -228,10 +228,40 @@ bool proves_nounwind(const FunctionContext& context) for (InstId i = body.blocks[b].first; i != kNoId; i = body.instructions[i].next) { const Instruction& inst = body.instructions[i]; - if (is_eh_instruction(inst.op) || can_unwind(context, inst)) + if (is_eh_instruction(inst.op) || (exclude_assembly && inst.op == Opcode::Asm) || can_unwind(context, inst)) return false; } return true; } +void record_nounwind_calls( + Program& program, const std::vector& functions, const std::vector& nounwind) +{ + // Keep the ABI and all other facts of the existing boundary. + std::vector clean(program.signatures.size(), kNoId); + for (SymbolId id : functions) + { + FunctionBody& body = *program.functions[program.symbols[id].detail].body; + for (BlockId block : body.layout) + for (InstId i = body.blocks[block].first; i != kNoId; i = body.instructions[i].next) + { + Instruction& call = body.instructions[i]; + if (call.op != Opcode::Call || !call.ops[0].is(ValueKind::Symbol) || !nounwind[call.ops[0].index]) + continue; + const Signature* boundary = program.call_boundary(call); + if (boundary == nullptr || boundary->boundary.unwind == ir_model::CUM_NO) + continue; + SignatureId& signature = clean[boundary - program.signatures.data()]; + if (signature == kNoId) + { + Signature copy = *boundary; + copy.boundary.unwind = ir_model::CUM_NO; + signature = program.add_signature(copy); + } + call.flags |= IF_SIGNATURE; + call.immediate = signature; + } + } +} + } // namespace opt diff --git a/dev/src/opt/inliner.cpp b/dev/src/opt/inliner.cpp index e9396c58d..8ecee5327 100644 --- a/dev/src/opt/inliner.cpp +++ b/dev/src/opt/inliner.cpp @@ -1882,7 +1882,7 @@ bool InlineWaveRunner::admit( if (!source_required_ && shape.size > kTrivialLeaf && ((m.flags | program_.symbols[graph_.functions[caller_]].metadata.flags) & SF_COLD) != 0) return false; - if (wave_ != InlineWave::Once) + if (wave_ != InlineWave::Once && !options_.minimize_size) { const bool hint = (m.flags & SF_INLINE_HINT) != 0; // (-O3 admits a quarter more, as LLVM's -O3 threshold is to its -O2 one.) @@ -1925,7 +1925,8 @@ bool InlineWaveRunner::admit( : requested_once_cap; const bool sole = options_.level >= 2 && m.binding == ir_model::SBM_INTERNAL && graph_.callers_in[g] == 1 && !graph_.observed[g] && discardable(program_, callee) && size * graph_.calls_in[g] <= once_cap; - if (!(single || sole) || size > once_cap || size > once_budget_ || size > budgets_.once_unit) + if (!(single || (sole && !options_.minimize_size)) || size > once_cap || size > once_budget_ || + size > budgets_.once_unit) return false; charge = size; once = true; @@ -1950,8 +1951,8 @@ bool InlineWaveRunner::admit_partial(uint32_t g, const Instruction& call, bool h const SymbolMetadata& m = program_.symbols[callee].metadata; const Shape& shape = shapes_[g]; const bool cycle = graph_.recursive[g] && g != caller_; - if (options_.level < 2 || (m.flags & (SF_NO_INLINE | SF_REPLACEABLE)) != 0 || shape.unsafe || shape.eh || - (handler_code && shape.unwinds) || (call.result != kNoId && !phi_type(call.type))) + if (options_.level < 2 || options_.minimize_size || (m.flags & (SF_NO_INLINE | SF_REPLACEABLE)) != 0 || + shape.unsafe || shape.eh || (handler_code && shape.unwinds) || (call.result != kNoId && !phi_type(call.type))) return false; const Function& function = program_.functions[program_.symbols[callee].detail]; const Signature& sig = program_.signatures[function.signature]; @@ -2248,8 +2249,8 @@ bool InlineWaveRunner::process(SymbolId caller) // multiplies them). original_.reset(); original_count_ = recursive_budget_ = recursive_depth_ = 0; - if (wave_ == InlineWave::Late && options_.level >= 2 && graph_.recursive[caller_] && !shapes_[caller_].eh && - !shapes_[caller_].unsafe && shapes_[caller_].size <= kRecursiveCap) + if (wave_ == InlineWave::Late && options_.level >= 2 && !options_.minimize_size && graph_.recursive[caller_] && + !shapes_[caller_].eh && !shapes_[caller_].unsafe && shapes_[caller_].size <= kRecursiveCap) { const uint64_t self_calls = shapes_[caller_].self_calls; // (A loop's one self call, what is left of a tail-recursive function, diff --git a/dev/src/opt/optimizer.cpp b/dev/src/opt/optimizer.cpp index fbd1acd9e..76759e742 100644 --- a/dev/src/opt/optimizer.cpp +++ b/dev/src/opt/optimizer.cpp @@ -9,6 +9,7 @@ #include "lowir/text_writer.h" #include "lowir/validator.h" +#include "opt/call_graph.h" #include "opt/inliner.h" #include "opt/bit_recurrences.h" #include "opt/interprocedural.h" @@ -371,7 +372,8 @@ void simplify_function(Program& program, SymbolId symbol, OptimizerStats& stats, // Each run unrolls one level of a nest; the copies fold before the next. const uint64_t rolled = instruction_count(context.body); bool unrolling = false; - for (unsigned nest = 0; nest < kUnrollNest && copies_code(context) && RUN_PASS(unroll_loops); ++nest) + for (unsigned nest = 0; + nest < kUnrollNest && !options.minimize_size && copies_code(context) && RUN_PASS(unroll_loops); ++nest) { again = unrolling = true; if (nest + 1 == kUnrollNest) @@ -503,12 +505,13 @@ bool hoist_loops(FunctionContext& context) return changed; } -bool finish_loops(FunctionContext& context, int level) +bool finish_loops(FunctionContext& context, const OptimizerOptions& options) { + const int level = options.level; bool changed = false; changed = RUN_PASS(hoist_loop_loads) || changed; changed = hoist_loops(context) || changed; - const bool copies = copies_code(context); + const bool copies = !options.minimize_size && copies_code(context); changed = (copies && RUN_PASS(version_fill_loops)) || changed; if (level >= 3 && RUN_PASS(merge_loop_latches)) { @@ -664,7 +667,7 @@ void finish_function(Program& program, SymbolId symbol, OptimizerStats& stats, c if (changed) RUN_PASS(remove_dead_code); changed = (options.has_gnu_sincos && RUN_PASS(combine_sin_cos)) || changed; - changed = (options.level >= 2 && RUN_PASS(guard_sqrt_calls)) || changed; + changed = (options.level >= 2 && !options.minimize_size && RUN_PASS(guard_sqrt_calls)) || changed; // i128 values as halves once the inliner has sized its callees whole // (a variable shift is a dozen i64 instructions): the halves' slots // promoted and a round over what that exposes. @@ -697,7 +700,7 @@ void finish_function(Program& program, SymbolId symbol, OptimizerStats& stats, c changed = true; } const bool had_loops = has_loop(context); - if (had_loops && finish_loops(context, options.level)) + if (had_loops && finish_loops(context, options)) { // A load the loop passes took out of an arm leaves the arm to compute // only: the branch to it may now be a choice of values. @@ -942,6 +945,36 @@ bool parse_inline_limit(const std::string& text, InlineLimits& limits) return true; } +// Keep the late proof in the call's typed signature so lowering and the +// LowIR text round trip can use it. A callee-first walk propagates facts +// through direct acyclic edges without iterating over the whole program. +static void finish_exception_effects(Program& program, OptimizerStats& stats, const OptimizerOptions& options) +{ + CallGraph graph; + build_call_graph(program, graph); + std::vector nounwind(program.symbols.size(), 0); + for (uint32_t f : graph.bottom_up) + { + const SymbolId id = graph.functions[f]; + const Symbol& symbol = program.symbols[id]; + if (symbol.metadata.binding == ir_model::SBM_WEAK || + !program.functions[symbol.detail].body->code_labels.empty()) + continue; + FunctionContext context(program, id, stats, options.level); + const PooledContext pooled(context, context_pool()); + context.nounwind = &nounwind; + enable_verify(context, options); + if (RUN_PASS(strip_dead_regions)) + { + RUN_PASS(cleanup_cfg); + RUN_PASS(remove_dead_code); + compact_body(program, context.body); + } + nounwind[id] = proves_nounwind(context, true); + } + record_nounwind_calls(program, graph.functions, nounwind); +} + void optimize_program(Program& program, const OptimizerOptions& options, OptimizerStats* stats_out) { for (const FunctionBinding& binding : program.function_bindings) @@ -993,9 +1026,9 @@ void optimize_program(Program& program, const OptimizerOptions& options, Optimiz budgets.once_unit = 2 * budgets.force_unit; run_inline_wave(program, options, stats, InlineWave::Ordinary, budgets, original, unrolled, nounwind, simplify); prune_unreachable(program, stats); - if (level >= 2) + if (level >= 2 && !options.minimize_size) speculate_virtual_calls(program, stats); - if (level >= 2 && copy_for_callees(program, stats)) + if (level >= 2 && !options.minimize_size && copy_for_callees(program, stats)) { original.resize(program.symbols.size(), 0); nounwind.resize(program.symbols.size(), 0); @@ -1028,6 +1061,10 @@ void optimize_program(Program& program, const OptimizerOptions& options, Optimiz program.functions[program.symbols[s].detail].body != nullptr) finish_function( program, s, stats, options, nounwind, unwritten, sealed, moved_late ? &moved : nullptr, bit_tables); + // Strong Wasm definitions in this link cannot be interposed. Keep + // the late pass in the size profile since it scans every live body. + if (options.minimize_size && target_model::is_wasm(program.target)) + finish_exception_effects(program, stats, options); } if (options.level == 1) diff --git a/dev/src/opt/optimizer.h b/dev/src/opt/optimizer.h index 36ab16b72..176e0c66b 100644 --- a/dev/src/opt/optimizer.h +++ b/dev/src/opt/optimizer.h @@ -30,6 +30,7 @@ struct InlineLimits struct OptimizerOptions { int level = 0; + bool minimize_size = false; InlineLimits limits; // -fno-inline suppresses optional copies; always_inline still applies. bool optional_inlining = true; diff --git a/dev/src/opt/passes.h b/dev/src/opt/passes.h index 4c5d11005..d46f774c6 100644 --- a/dev/src/opt/passes.h +++ b/dev/src/opt/passes.h @@ -457,7 +457,9 @@ bool can_unwind(const FunctionContext& context, const lowir::Instruction& inst); bool strip_dead_regions(FunctionContext& context); // Whether the body has no EH instruction and nothing that can unwind. -bool proves_nounwind(const FunctionContext& context); +bool proves_nounwind(const FunctionContext& context, bool exclude_assembly = false); +void record_nounwind_calls( + lowir::Program& program, const std::vector& functions, const std::vector& nounwind); // Reorders blocks into reverse postorder when an ordinary use precedes its // definition in layout (after reuse across blocks); whether it did. diff --git a/dev/src/wasm/link_folding.cpp b/dev/src/wasm/link_folding.cpp new file mode 100644 index 000000000..2bcbdcb0e --- /dev/null +++ b/dev/src/wasm/link_folding.cpp @@ -0,0 +1,59 @@ +#include "wasm/linker.h" + +#include + +namespace wasm { + +Bytes Linker::forwarding_body(uint32_t target) const +{ + const ObjectRef ref = ordered_functions_[target]; + const Object& object = objects_[ref.first]; + const auto& type = object.types[object.functions[ref.second].type]; + Bytes body; + body.byte(0); // No additional locals. + for (uint32_t i = 0; i < type.parameters.size(); ++i) + { + body.byte(0x20); // local.get + body.unsigned_leb(i); + } + body.byte(0x10); // call + body.unsigned_leb(target); + body.byte(0x0b); // end + return body; +} + +// Compare whole bodies and their signatures after archive/COMDAT selection +// and relocation. Keep each table index and exported/ref.func identity. +// Direct calls can use the shared body without going through the forwarding +// entry. One scan and one candidate per hash bound the extra linker work. +void Linker::fold_functions() +{ + std::unordered_map bodies; + std::vector targets(ordered_functions_.size()); + for (uint32_t i = 0; i < targets.size(); ++i) + { + targets[i] = i; + const ObjectRef ref = ordered_functions_[i]; + if (i < imported_ || weak_functions_.count(ref)) + continue; + const ObjectFunction& function = objects_[ref.first].functions[ref.second]; + const uint32_t type = type_indices_[ref.first][function.type]; + const Bytes body = relocated(ref.first, function.code, false, true); + uint64_t hash = 14695981039346656037ull ^ type; + for (uint8_t byte : body.data) + hash = (hash ^ byte) * 1099511628211ull; + const auto found = bodies.emplace(hash, i); + if (found.second) + continue; + const uint32_t target = found.first->second; + const ObjectRef other = ordered_functions_[target]; + const ObjectFunction& definition = objects_[other.first].functions[other.second]; + if (type_indices_[other.first][definition.type] == type && + body.data.size() > forwarding_body(target).data.size() && + body.data == relocated(other.first, definition.code, false, true).data) + targets[i] = target; + } + folded_functions_.swap(targets); +} + +} // namespace wasm diff --git a/dev/src/wasm/link_output.cpp b/dev/src/wasm/link_output.cpp index 391b7ab62..866522b07 100644 --- a/dev/src/wasm/link_output.cpp +++ b/dev/src/wasm/link_output.cpp @@ -213,8 +213,10 @@ void Linker::emit(Bytes& output) body.byte(0x00); body.byte(0x0b); } + else if (!folded_functions_.empty() && folded_functions_[i] != i) + body = forwarding_body(folded_functions_[i]); else - body = relocated(ref.first, objects_[ref.first].functions[ref.second].code); + body = relocated(ref.first, objects_[ref.first].functions[ref.second].code, false, true); code.unsigned_leb(body.data.size()); code.append(body); } diff --git a/dev/src/wasm/link_relocations.cpp b/dev/src/wasm/link_relocations.cpp index 15a3ddb4c..89ccb80da 100644 --- a/dev/src/wasm/link_relocations.cpp +++ b/dev/src/wasm/link_relocations.cpp @@ -1,5 +1,7 @@ #include "wasm/linker.h" +#include + namespace wasm { bool Linker::synthetic_data(const std::string& name, uint32_t& value) const @@ -99,24 +101,58 @@ void Linker::prepare_address_globals() collect(data.first, objects_[data.first].data[data.second].contents); } -Bytes Linker::relocated(uint32_t object, const ObjectChunk& chunk, bool constant) const +uint32_t Linker::relocation_value(uint32_t object, const Relocation& relocation, bool constant) const { - Bytes result = chunk.bytes; - for (const Relocation& relocation : chunk.relocations) + const ObjectRef ref{ object, relocation.index }; + switch (relocation.kind) { - uint32_t value; - if (relocation.kind == RelocationKind::TypeIndex) - value = type_indices_[object][relocation.index]; - else if ((relocation.kind == RelocationKind::GlobalIndex || - relocation.kind == RelocationKind::GlobalIndexI32) && - objects_[object].symbols[relocation.index].kind <= 1) - value = constant ? symbol_value({ object, relocation.index }) - : address_globals_.at(selected({ object, relocation.index })); - else if (relocation.kind == RelocationKind::FunctionIndex || - relocation.kind == RelocationKind::FunctionIndexI32) - value = function_index({ object, relocation.index }); - else - value = symbol_value({ object, relocation.index }); + case RelocationKind::TypeIndex: + return type_indices_[object][relocation.index]; + case RelocationKind::GlobalIndex: + case RelocationKind::GlobalIndexI32: + if (symbol(ref).kind <= 1 && !constant) + return address_globals_.at(selected(ref)); + break; + case RelocationKind::FunctionIndex: + case RelocationKind::FunctionIndexI32: + return function_index(ref); + default: + break; + } + return symbol_value(ref); +} + +Bytes Linker::relocated(uint32_t object, const ObjectChunk& chunk, bool constant, bool code) const +{ + const bool compact = code && options_.wasm_link.compact_relocations; + const auto& source = chunk.bytes.data; + const auto by_offset = [](const Relocation& a, const Relocation& b) { return a.offset < b.offset; }; + const auto* relocations = &chunk.relocations; + std::vector sorted; + if (compact && !std::is_sorted(relocations->begin(), relocations->end(), by_offset)) + { + sorted = *relocations; + std::sort(sorted.begin(), sorted.end(), by_offset); + relocations = &sorted; + } + if (relocations->empty()) + return chunk.bytes; + + Bytes result; + if (compact) + result.data.reserve(source.size()); + else + result = chunk.bytes; + uint32_t cursor = 0; + for (const Relocation& relocation : *relocations) + { + uint32_t value = relocation_value(object, relocation, constant); + // A validated function-index relocation immediately after call is + // a direct call. Keep ref.func and other address uses on their + // original entry, even when its body shares another entry's code. + if (code && !folded_functions_.empty() && relocation.kind == RelocationKind::FunctionIndex && + relocation.offset != 0 && source[relocation.offset - 1] == 0x10 && value < folded_functions_.size()) + value = folded_functions_[value]; bool constant_address = false; if (constant && relocation.kind == RelocationKind::GlobalIndex) { @@ -135,23 +171,42 @@ Bytes Linker::relocated(uint32_t object, const ObjectChunk& chunk, bool constant if (sum < INT32_MIN || sum > UINT32_MAX) throw WasmError("Wasm relocation value overflows 32 bits"); value = static_cast(sum); - if (relocation.kind == RelocationKind::TableIndexI32 || relocation.kind == RelocationKind::MemoryAddressI32 || - relocation.kind == RelocationKind::GlobalIndexI32 || relocation.kind == RelocationKind::FunctionIndexI32) + const bool fixed = relocation.kind == RelocationKind::TableIndexI32 || + relocation.kind == RelocationKind::MemoryAddressI32 || relocation.kind == RelocationKind::GlobalIndexI32 || + relocation.kind == RelocationKind::FunctionIndexI32; + const bool signed_value = constant_address || relocation.kind == RelocationKind::TableIndex || + relocation.kind == RelocationKind::MemoryAddressSigned || + relocation.kind == RelocationKind::MemoryAddressRelative || + relocation.kind == RelocationKind::TableIndexRelative; + if (compact) + { + result.data.insert(result.data.end(), source.begin() + cursor, source.begin() + relocation.offset); + if (fixed) + result.fixed(value, 4); + // The other type-index operand, besides call_indirect's + // unsigned immediate, is the signed 33-bit block type. + else if (relocation.kind == RelocationKind::TypeIndex && source[relocation.offset - 1] != 0x11) + result.signed_leb(value); + else if (signed_value) + result.signed_leb(static_cast(value)); + else + result.unsigned_leb(value); + cursor = relocation.offset + (fixed ? 4 : 5); + } + else if (fixed) { for (unsigned i = 0; i < 4; ++i) result.data[relocation.offset + i] = static_cast(value >> (i * 8)); } else { - const bool signed_value = constant_address || relocation.kind == RelocationKind::TableIndex || - relocation.kind == RelocationKind::MemoryAddressSigned || - relocation.kind == RelocationKind::MemoryAddressRelative || - relocation.kind == RelocationKind::TableIndexRelative; const uint64_t extended = signed_value ? uint64_t(int64_t(int32_t(value))) : uint64_t(value); for (unsigned i = 0; i < 5; ++i) result.data[relocation.offset + i] = ((extended >> (7 * i)) & 0x7f) | (i == 4 ? 0 : 0x80); } } + if (compact) + result.data.insert(result.data.end(), source.begin() + cursor, source.end()); return result; } diff --git a/dev/src/wasm/linker.cpp b/dev/src/wasm/linker.cpp index 28b57e8ef..e9161a513 100644 --- a/dev/src/wasm/linker.cpp +++ b/dev/src/wasm/linker.cpp @@ -421,6 +421,8 @@ void Linker::run(Bytes& output) } type_indices_.push_back(std::move(indices)); } + if (options_.wasm_link.fold_functions) + fold_functions(); emit(output); } diff --git a/dev/src/wasm/linker.h b/dev/src/wasm/linker.h index af5a9b4e6..54bd976d2 100644 --- a/dev/src/wasm/linker.h +++ b/dev/src/wasm/linker.h @@ -36,7 +36,10 @@ class Linker bool request_section_boundary(const std::string& name); void group_named_sections(); void prepare_data_exports(); - Bytes relocated(uint32_t object, const ObjectChunk& chunk, bool constant = false) const; + uint32_t relocation_value(uint32_t object, const Relocation& relocation, bool constant) const; + Bytes relocated(uint32_t object, const ObjectChunk& chunk, bool constant = false, bool code = false) const; + void fold_functions(); + Bytes forwarding_body(uint32_t target) const; void emit(Bytes& output); void data_section(Bytes& output) const; void prepare_address_globals(); @@ -66,6 +69,7 @@ class Linker // Exported data addresses are immutable i32 globals (index, address). std::map> data_exports_; std::vector ordered_functions_, ordered_data_, ordered_tags_; + std::vector folded_functions_; std::vector ordered_globals_, imported_globals_; std::vector> initializers_; std::vector types_; diff --git a/dev/src/wasm/local_cleanup.cpp b/dev/src/wasm/local_cleanup.cpp index fcea638dd..7b2894de8 100644 --- a/dev/src/wasm/local_cleanup.cpp +++ b/dev/src/wasm/local_cleanup.cpp @@ -1,6 +1,8 @@ #include "wasm/mir.h" #include "wasm/local_lifetimes.h" +#include + namespace wasm { namespace { @@ -70,6 +72,88 @@ size_t unread_value( return at; } +// Look for one straight-line store. A fixed window bounds the cost even +// when the whole function has many temporaries. +constexpr size_t kStackifyWindow = 24; + +size_t find_local_store(const Function& function, uint64_t local, size_t end, size_t limit) +{ + for (size_t i = end; i > limit;) + { + const Instruction& inst = function.instructions[--i]; + if (inst.op == Op::LocalSet && function.operands[inst.operands.first] == local) + return i; + if (inst.op != Op::LocalSet && value_inputs(inst.op) < 0) + break; + } + return end; +} + +bool overwritten(const Function& function, uint64_t local, size_t begin, size_t end) +{ + for (size_t i = begin; i < end; ++i) + { + const Instruction& inst = function.instructions[i]; + if (inst.op == Op::LocalSet && function.operands[inst.operands.first] == local) + return true; + } + return false; +} + +// The encoder visits relocated operands in emission order. Keep those +// instructions in place, even when their values are safe to rematerialize. +size_t stackifiable_value( + const Function& function, const std::vector& relocated, size_t store, size_t end, size_t limit) +{ + size_t need = 1; + for (size_t start = store; start > limit;) + { + const Instruction& inst = function.instructions[--start]; + const int inputs = value_inputs(inst.op); + if (inputs < 0 || (inst.operands.count != 0 && relocated[inst.operands.first])) + break; + if (inst.op == Op::LocalGet && overwritten(function, function.operands[inst.operands.first], store, end)) + break; + need = need + static_cast(inputs) - 1; + if (need == 0) + return start; + } + return store; +} + +// A pure producer and its local.set leave the stack unchanged. Move the +// producer to the single read of that local and drop the set and get. +void stackify_pure_values(Function& function, const std::vector& reads, const std::vector& relocated) +{ + auto& instructions = function.instructions; + size_t kept = 0; + for (const Instruction inst : instructions) + { + if (inst.op == Op::LocalGet) + { + const uint64_t local = function.operands[inst.operands.first]; + if (reads[local] == 1) + { + const size_t limit = kept > kStackifyWindow ? kept - kStackifyWindow : 0; + const size_t store = find_local_store(function, local, kept, limit); + if (store != kept) + { + const size_t start = stackifiable_value(function, relocated, store, kept, limit); + if (start != store) + { + std::rotate(instructions.begin() + start, instructions.begin() + store + 1, + instructions.begin() + kept); + --kept; + continue; + } + } + } + } + instructions[kept++] = inst; + } + instructions.resize(kept); +} + // The integer comparison that holds when `op` does not; Nop when `op` is not // an integer comparison of two values. Op inverse_comparison(Op op) @@ -153,12 +237,20 @@ void drop_branches_to_next(Function& function) } // namespace -void cleanup_locals(Function& function, bool optimize) +void cleanup_locals(Function& function, bool optimize, bool minimize_size) { std::vector uses; if (optimize) { + std::vector relocated(function.operands.size() + 1, 0); + for (const Relocation& relocation : function.relocations) + relocated[relocation.offset] = 1; count_reads(function, uses); + if (minimize_size) + { + stackify_pure_values(function, uses, relocated); + count_reads(function, uses); + } size_t kept = 0; for (size_t i = 0; i < function.instructions.size(); ++i) { @@ -183,9 +275,6 @@ void cleanup_locals(Function& function, bool optimize) // A value that no instruction reads is not stored, and not computed // when its operations have no effect: a step whose uses all went into // memory offsets. Removing one may leave the values it read unread. - std::vector relocated(function.operands.size() + 1, 0); - for (const Relocation& relocation : function.relocations) - relocated[relocation.offset] = 1; count_reads(function, uses); for (bool again = true; again;) { diff --git a/dev/src/wasm/mir.h b/dev/src/wasm/mir.h index db213841f..86ff53753 100644 --- a/dev/src/wasm/mir.h +++ b/dev/src/wasm/mir.h @@ -69,6 +69,6 @@ struct Function ValueType value_type(lowir::Type type); std::uint16_t effects(Op op); -void cleanup_locals(Function& function, bool optimize); +void cleanup_locals(Function& function, bool optimize, bool minimize_size); } // namespace wasm diff --git a/dev/src/wasm/object_lowering.cpp b/dev/src/wasm/object_lowering.cpp index dfa6a04c3..f7dcf0d93 100644 --- a/dev/src/wasm/object_lowering.cpp +++ b/dev/src/wasm/object_lowering.cpp @@ -1,6 +1,7 @@ #include "wasm/object.h" #include "machine/global_data.h" +#include "opt/optimizer.h" #include "wasm/object_cursor.h" #include "wasm/exceptions.h" #include "wasm/selector.h" @@ -323,6 +324,7 @@ void make_object(lowir::Program& program, const backend::Options& options, Objec object.tags.push_back(std::move(tag)); } append_nonlocal_objects(module, object, symbols); + const bool minimize_size = options.optimizer != nullptr && options.optimizer->minimize_size; bool uses_simd = false; for (const Signature& type : module.signatures) { @@ -337,8 +339,8 @@ void make_object(lowir::Program& program, const backend::Options& options, Objec if (module.exception_regions) prepare_exception_plan(program, id, object, symbols, groups[id], exceptions); Function function; - Selector(program, module, id, function, &exceptions).run(); - cleanup_locals(function, options.optimization_level != 0); + Selector(program, module, id, function, &exceptions, minimize_size).run(); + cleanup_locals(function, options.optimization_level != 0, minimize_size); for (ValueType local : function.locals) uses_simd = uses_simd || local == ValueType::V128; for (const auto& inst : function.instructions) diff --git a/dev/src/wasm/select_calls.cpp b/dev/src/wasm/select_calls.cpp index db9d5b328..29cbae088 100644 --- a/dev/src/wasm/select_calls.cpp +++ b/dev/src/wasm/select_calls.cpp @@ -5,7 +5,7 @@ namespace wasm { using namespace lowir; -void Selector::call(const lowir::Instruction& inst) +void Selector::call(const lowir::Instruction& inst, bool protected_by_group) { const lowir::Signature* signature = program_.call_boundary(inst); if (signature == nullptr || @@ -16,7 +16,7 @@ void Selector::call(const lowir::Instruction& inst) return; const uint32_t site = exceptions_ != nullptr && exceptions_->active ? exceptions_->analysis.eh_sites_[current_inst_] : 0; - if (site != 0) + if (site != 0 && !protected_by_group) exception_call(inst, signature, site - 1); else call_body(inst, *signature); diff --git a/dev/src/wasm/select_exceptions.cpp b/dev/src/wasm/select_exceptions.cpp index 703a0fc5e..ba21db522 100644 --- a/dev/src/wasm/select_exceptions.cpp +++ b/dev/src/wasm/select_exceptions.cpp @@ -88,11 +88,15 @@ void Selector::exception_match(uint32_t landing) exception_snapshot(landing, false); } -void Selector::exception_call(const lowir::Instruction& inst, const lowir::Signature* signature, uint32_t landing) +void Selector::save_exception_stack() { out_.emit(Op::GlobalGet, { 0 }); out_.relocate(RelocationKind::GlobalIndex, module_.stack_symbol); out_.emit(Op::LocalSet, { exception_stack_ }); +} + +void Selector::begin_exception_call() +{ out_.emit(Op::Block, { block_type(ValueType::Void) }); ++nesting_; out_.emit(Op::Block, { module_.exception_pair_type }); @@ -101,10 +105,10 @@ void Selector::exception_call(const lowir::Instruction& inst, const lowir::Signa out_.emit(Op::TryTable, { block_type(ValueType::Void), 1, static_cast(CatchKind::TagRef), 0, 0 }); out_.relocate(RelocationKind::TagIndex, module_.exception_tag_symbol, 3); ++nesting_; - if (signature != nullptr) - call_body(inst, *signature); - else - exception_throw(inst); +} + +void Selector::end_exception_call(uint32_t landing) +{ out_.emit(Op::End); --nesting_; out_.emit(Op::Br, { 1 }); @@ -123,6 +127,46 @@ void Selector::exception_call(const lowir::Instruction& inst, const lowir::Signa --nesting_; } +void Selector::exception_call(const lowir::Instruction& inst, const lowir::Signature* signature, uint32_t landing) +{ + save_exception_stack(); + begin_exception_call(); + if (signature != nullptr) + call_body(inst, *signature); + else + exception_throw(inst); + end_exception_call(landing); +} + +// Consecutive calls in one LowIR block can use the same landing edge and +// phi inputs. Snapshot the stack before each call so unwinding restores +// the same state as it would with each call's individual wrapper. +InstId Selector::grouped_exception_calls(InstId first) +{ + const auto& sites = exceptions_->analysis.eh_sites_; + const uint32_t site = sites[first]; + const auto matches = [&](InstId i) { + return i != kNoId && sites[i] == site && body_.instructions[i].op == Opcode::Call; + }; + if (site == 0 || !matches(body_.instructions[first].next)) + return first; + + out_.location = body_.instructions[first].location; + begin_exception_call(); + InstId next = first; + do + { + current_inst_ = next; + const auto& inst = body_.instructions[next]; + out_.location = inst.location; + save_exception_stack(); + call(inst, true); + next = inst.next; + } while (matches(next)); + end_exception_call(site - 1); + return next; +} + void Selector::exception_resume(uint32_t site) { restore_exception_context(); diff --git a/dev/src/wasm/selector.cpp b/dev/src/wasm/selector.cpp index cc1468d83..9da6b039c 100644 --- a/dev/src/wasm/selector.cpp +++ b/dev/src/wasm/selector.cpp @@ -8,12 +8,12 @@ namespace wasm { using namespace lowir; -Selector::Selector( - const Program& program, const Module& module, SymbolId symbol, Function& output, const ExceptionPlan* exceptions) +Selector::Selector(const Program& program, const Module& module, SymbolId symbol, Function& output, + const ExceptionPlan* exceptions, bool minimize_size) : program_(program), module_(module), body_(*program.functions[program.symbols[symbol].detail].body), signature_(program.signatures[program.functions[program.symbols[symbol].detail].signature]), boundary_(module.boundaries[program.functions[program.symbols[symbol].detail].signature]), out_(output), - exceptions_(exceptions) + exceptions_(exceptions), minimize_size_(minimize_size) {} uint32_t Selector::add_local(ValueType type) @@ -327,11 +327,22 @@ void Selector::dispatch() void Selector::block(BlockId id) { current_block_ = id; - for (InstId i = body_.blocks[id].first; i != kNoId; i = body_.instructions[i].next) + const bool group_calls = minimize_size_ && exceptions_ != nullptr && exceptions_->active; + for (InstId i = body_.blocks[id].first; i != kNoId;) { + if (group_calls && body_.instructions[i].op == Opcode::Call) + { + const InstId next = grouped_exception_calls(i); + if (next != i) + { + i = next; + continue; + } + } current_inst_ = i; out_.location = body_.instructions[i].location; instruction(body_.instructions[i]); + i = body_.instructions[i].next; } } diff --git a/dev/src/wasm/selector.h b/dev/src/wasm/selector.h index 9074e8a9d..726165f6d 100644 --- a/dev/src/wasm/selector.h +++ b/dev/src/wasm/selector.h @@ -16,7 +16,7 @@ class Selector { public: Selector(const lowir::Program& program, const Module& module, lowir::SymbolId symbol, Function& output, - const ExceptionPlan* exceptions = nullptr); + const ExceptionPlan* exceptions, bool minimize_size); void run(); private: @@ -55,12 +55,16 @@ class Selector void constant(lowir::Literal bits, lowir::Type type); void instruction(const lowir::Instruction& inst); void atomic_instruction(const lowir::Instruction& inst); - void call(const lowir::Instruction& inst); + void call(const lowir::Instruction& inst, bool protected_by_group = false); void plan_nonlocal_jumps(); bool nonlocal_call(const lowir::Instruction& inst); void nonlocal_dispatch(); void call_body(const lowir::Instruction& inst, const lowir::Signature& signature); void exception_call(const lowir::Instruction& inst, const lowir::Signature* signature, uint32_t landing); + lowir::InstId grouped_exception_calls(lowir::InstId first); + void save_exception_stack(); + void begin_exception_call(); + void end_exception_call(uint32_t landing); void exception_select(uint32_t landing); void exception_throw(const lowir::Instruction& inst); void exception_value(lowir::Type type); @@ -154,6 +158,7 @@ class Selector const Boundary& boundary_; Function& out_; const ExceptionPlan* exceptions_; + bool minimize_size_; uint32_t exception_pointer_ = lowir::kNoId; uint32_t exception_high_ = lowir::kNoId; uint32_t exception_reference_ = lowir::kNoId; diff --git a/pa37/tests/regression/600-link-folding-keeps-function-identity.t b/pa37/tests/regression/600-link-folding-keeps-function-identity.t new file mode 100644 index 000000000..940dc356d --- /dev/null +++ b/pa37/tests/regression/600-link-folding-keeps-function-identity.t @@ -0,0 +1,18 @@ +extern "C" __attribute__((noinline)) unsigned left(unsigned x) +{ + return ((x ^ 13579u) * 37u + 21u) ^ (x >> 2); +} + +extern "C" unsigned right(unsigned); +using Callback = unsigned (*)(unsigned); +Callback volatile first = left; +Callback volatile second = right; + +extern "C" unsigned check(unsigned x) +{ + if (first == second) + return 1; + if (first(x) != second(x)) + return 2; + return left(x) + right(x); +} diff --git a/pa37/tests/regression/600-link-folding-keeps-function-identity.t.1 b/pa37/tests/regression/600-link-folding-keeps-function-identity.t.1 new file mode 100644 index 000000000..a0131df5b --- /dev/null +++ b/pa37/tests/regression/600-link-folding-keeps-function-identity.t.1 @@ -0,0 +1,4 @@ +extern "C" __attribute__((noinline)) unsigned right(unsigned x) +{ + return ((x ^ 13579u) * 37u + 21u) ^ (x >> 2); +} diff --git a/pa37/tests/regression/600-link-folding-keeps-function-identity.wasm-expect b/pa37/tests/regression/600-link-folding-keeps-function-identity.wasm-expect new file mode 100644 index 000000000..ef281ff02 --- /dev/null +++ b/pa37/tests/regression/600-link-folding-keeps-function-identity.wasm-expect @@ -0,0 +1,11 @@ +{ + "source": true, + "units": ["600-link-folding-keeps-function-identity.t.1"], + "levels": [3], + "link_flags": ["-Oz", "-flto"], + "exports": ["left", "right"], + "calls": [{"export": "check", "args": ["11"], "result": "1004078"}], + "quality": { + "functions": {"right": {"instructions": 3}} + } +} diff --git a/pa37/tests/regression/600-size-stack-and-exception-regions.t b/pa37/tests/regression/600-size-stack-and-exception-regions.t new file mode 100644 index 000000000..64234bae4 --- /dev/null +++ b/pa37/tests/regression/600-size-stack-and-exception-regions.t @@ -0,0 +1,45 @@ +extern int step_one(int); +extern int step_two(int, int); +extern int step_three(int, int); +extern volatile int calls; + +extern "C" int grouped(int fail) +{ + calls = 0; + try { + int value = step_one(fail); + value = step_two(value, fail); + value = step_three(value, fail); + return value * 10 + calls; + } catch (...) { + return -calls; + } +} + +static __attribute__((noinline)) int leaf(int x) { return x * 5 + 2; } + +extern "C" int inferred(int fail) +{ + calls = 0; + try { + return leaf(step_two(leaf(1), fail)); + } catch (...) { + return -calls; + } +} + +__attribute__((weak, noinline)) int replaceable(int x) { return x; } + +extern "C" int override_catch(int x) +{ + try { + return replaceable(x); + } catch (...) { + return -42; + } +} + +extern "C" unsigned expression(unsigned a, unsigned b, unsigned c, unsigned d) +{ + return ((a << 5) + (b >> 3)) ^ (c * 7 + (d >> 2)); +} diff --git a/pa37/tests/regression/600-size-stack-and-exception-regions.t.1 b/pa37/tests/regression/600-size-stack-and-exception-regions.t.1 new file mode 100644 index 000000000..8f7159d82 --- /dev/null +++ b/pa37/tests/regression/600-size-stack-and-exception-regions.t.1 @@ -0,0 +1,28 @@ +volatile int calls; + +int step_one(int fail) +{ + ++calls; + if (fail == 1) throw fail; + return 4; +} + +int step_two(int x, int fail) +{ + ++calls; + if (fail == 2) throw fail; + return x + 1; +} + +int step_three(int x, int fail) +{ + ++calls; + if (fail == 3) throw fail; + return x * 2; +} + +int replaceable(int x) +{ + if (x < 0) throw x; + return x; +} diff --git a/pa37/tests/regression/600-size-stack-and-exception-regions.wasm-expect b/pa37/tests/regression/600-size-stack-and-exception-regions.wasm-expect new file mode 100644 index 000000000..538868720 --- /dev/null +++ b/pa37/tests/regression/600-size-stack-and-exception-regions.wasm-expect @@ -0,0 +1,26 @@ +{ + "source": true, + "units": ["600-size-stack-and-exception-regions.t.1"], + "levels": ["z"], + "wasi": true, + "target": "wasm32-wasip1", + "link_flags": ["-Oz", "-nostartfiles"], + "calls": [ + {"export": "grouped", "args": ["0"], "result": "103"}, + {"export": "grouped", "args": ["1"], "result": "-1"}, + {"export": "grouped", "args": ["2"], "result": "-2"}, + {"export": "grouped", "args": ["3"], "result": "-3"}, + {"export": "inferred", "args": ["0"], "result": "42"}, + {"export": "inferred", "args": ["2"], "result": "-1"}, + {"export": "override_catch", "args": ["-1"], "result": "-42"}, + {"export": "expression", "args": ["1", "8", "2", "4"], "result": "46"} + ], + "quality": { + "levels": ["z"], + "functions": { + "grouped": {"try_tables": 1}, + "inferred": {"try_tables": 1}, + "expression": {"local_ops": 4} + } + } +} diff --git a/pa37/tests/regression/600-source-lto-inline-variable.t b/pa37/tests/regression/600-source-lto-inline-variable.t new file mode 100644 index 000000000..586c4a215 --- /dev/null +++ b/pa37/tests/regression/600-source-lto-inline-variable.t @@ -0,0 +1,13 @@ +#include "600-source-lto-inline-variable.t.h" + +static int separate_value = 3; +extern "C" int* shared_address(); +extern "C" int* separate_address(); + +extern "C" int check() +{ + if (&shared_value != shared_address() || &separate_value == separate_address()) + return -1; + *shared_address() += 5; + return shared_value + separate_value + *separate_address(); +} diff --git a/pa37/tests/regression/600-source-lto-inline-variable.t.1 b/pa37/tests/regression/600-source-lto-inline-variable.t.1 new file mode 100644 index 000000000..8b50b9f99 --- /dev/null +++ b/pa37/tests/regression/600-source-lto-inline-variable.t.1 @@ -0,0 +1,5 @@ +#include "600-source-lto-inline-variable.t.h" + +static int separate_value = 11; +extern "C" int* shared_address() { return &shared_value; } +extern "C" int* separate_address() { return &separate_value; } diff --git a/pa37/tests/regression/600-source-lto-inline-variable.t.h b/pa37/tests/regression/600-source-lto-inline-variable.t.h new file mode 100644 index 000000000..43140b7c2 --- /dev/null +++ b/pa37/tests/regression/600-source-lto-inline-variable.t.h @@ -0,0 +1 @@ +inline int shared_value = 7; diff --git a/pa37/tests/regression/600-source-lto-inline-variable.wasm-expect b/pa37/tests/regression/600-source-lto-inline-variable.wasm-expect new file mode 100644 index 000000000..f1ef119d6 --- /dev/null +++ b/pa37/tests/regression/600-source-lto-inline-variable.wasm-expect @@ -0,0 +1,9 @@ +{ + "source": true, + "units": ["600-source-lto-inline-variable.t.1"], + "levels": [3], + "flags": ["-std=c++17"], + "source_link_flags": ["-flto=full"], + "link_flags": ["-Oz"], + "calls": [{"export": "check", "result": "26"}] +} diff --git a/scripts/CppgmWasmQuality.pm b/scripts/CppgmWasmQuality.pm index 0dd468ff6..86e5bd19a 100644 --- a/scripts/CppgmWasmQuality.pm +++ b/scripts/CppgmWasmQuality.pm @@ -22,7 +22,8 @@ sub function_metrics { my ($data) = @_; my $r = {data => $data, offset => 0}; my %metrics = (code_bytes => length($data), locals => 0, instructions => 0, - memory_ops => 0, zero_offset_memory_ops => 0, bulk_memory_ops => 0, control_depth => 0); + memory_ops => 0, zero_offset_memory_ops => 0, bulk_memory_ops => 0, control_depth => 0, + try_tables => 0, local_ops => 0); for (1 .. number($r)) { $metrics{locals} += number($r); byte($r); @@ -31,11 +32,13 @@ sub function_metrics { while ($r->{offset} < length($data)) { my $op = byte($r); ++$metrics{instructions}; + ++$metrics{local_ops} if $op >= 0x20 && $op <= 0x22; if ($op == 2 || $op == 3 || $op == 4 || $op == 0x1f) { leb($r, 5); ++$depth; $metrics{control_depth} = $depth if $depth > $metrics{control_depth}; if ($op == 0x1f) { + ++$metrics{try_tables}; for (1 .. number($r)) { my $kind = byte($r); number($r) if $kind < 2; @@ -98,7 +101,7 @@ sub function_metrics { sub check_quality { my ($path, $quality, $level) = @_; - return unless grep { $_ == $level } @{$quality->{levels} // [1, 2, 3]}; + return unless grep { $_ eq $level } @{$quality->{levels} // [1, 2, 3]}; if ($quality->{module}) { my $actual = CppgmWasmModule::module_sizes($path); check_bounds($actual, $quality->{module}, "$path: O$level module"); diff --git a/scripts/check_wasm.pl b/scripts/check_wasm.pl index 46a8982e8..7658f9039 100644 --- a/scripts/check_wasm.pl +++ b/scripts/check_wasm.pl @@ -242,16 +242,18 @@ sub reference_link_rejection { sub check_text_object { my ($index, $level, $input, $direct) = @_; my $target = $expect->{target} // 'wasm32-unknown-unknown'; - my $key = $expect->{source} ? "$input\0" . ($level ? 'optimize' : 'O0') : $input; + my $profile = $level eq 'z' ? 'size' : $level ? 'optimize' : 'O0'; + my $key = $expect->{source} ? "$input\0$profile" : $input; my ($status, $stdout, $stderr); if (!$rewritten_text{$key}) { my $text = $input; - my $name = "text-$index-" . ($level ? 'optimize' : 'O0'); + my $name = "text-$index-$profile"; if ($expect->{source}) { $text = "$directory/$name.lowir"; ($status, $stdout, $stderr) = command("$name-lowir", $source_compiler, '--target', $target, @target_flags, @{$expect->{flags} // []}, '-g0', '--emit-lowir', '-O0', - ($level ? ('-D__OPTIMIZE__=1') : ()), $input, '-o', $text); + ($level ? ('-D__OPTIMIZE__=1') : ()), ($level eq 'z' ? ('-D__OPTIMIZE_SIZE__=1') : ()), + $input, '-o', $text); die "$test: LowIR text lowering failed: $stdout$stderr\n" if $status; } my $rewritten = "$directory/$name.rewritten.lowir"; @@ -316,7 +318,8 @@ sub check_optimized_text_object { my $tool = $expect->{source} ? $source_compiler : $compiler; ($status, $stdout, $stderr) = command("compile-$level", $tool, "-O$level", '--target', ($expect->{target} // 'wasm32-unknown-unknown'), - @target_flags, ($expect->{assembly} ? ('-x', 'assembler-with-cpp') : ()), @{$expect->{flags} // []}, @{$expect->{link_flags} // []}, @exports, '-o', $module, $test, @units, @supplied_inputs); + @target_flags, ($expect->{assembly} ? ('-x', 'assembler-with-cpp') : ()), @{$expect->{flags} // []}, + @{$expect->{source_link_flags} // []}, @{$expect->{link_flags} // []}, @exports, '-o', $module, $test, @units, @supplied_inputs); if ($expect->{reject} || $expect->{reject_link}) { die "$test: invalid input accepted at O$level\n" if $status == 0; die "$test: rejection was not a compiler diagnostic: $stdout$stderr\n" diff --git a/scripts/tests/test_native_source_lto.py b/scripts/tests/test_native_source_lto.py new file mode 100644 index 000000000..eb79226dc --- /dev/null +++ b/scripts/tests/test_native_source_lto.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Check source LTO through the native driver and both ELF link paths.""" + +import os +import platform +import shlex +import subprocess +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +COMPILER = ROOT / "dev/cppgm" +FLAGS = ("--target=x86_64-linux-gnu", "-std=c++17", "-O3") + + +@unittest.skipUnless(platform.system() == "Linux" and platform.machine() == "x86_64", + "requires Linux x86-64") +class NativeSourceLto(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not COMPILER.is_file(): + subprocess.run(["make", "-C", ROOT / "dev", "cppgm"], check=True) + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.directory = Path(directory.name) + (self.directory / "first.cpp").write_text(""" +extern int next(int); +static int scale(int x) { return x * 3; } +inline int value = 7; +int main() { return next(scale(value)) != 35; } +""") + (self.directory / "second.cpp").write_text(""" +static int scale(int x) { return x + 3; } +inline int value = 7; +__attribute__((weak)) int adjustment() { return 0; } +int next(int x) { return scale(x) + value + adjustment(); } +""") + (self.directory / "override.cpp").write_text(""" +int adjustment() { return 4; } +""") + + def run_command(self, args, success=True): + result = subprocess.run(args, cwd=self.directory, capture_output=True, text=True, timeout=30) + if success: + self.assertEqual(result.returncode, 0, result.stderr) + return result + + def test_direct_link_with_an_existing_object(self): + self.run_command([COMPILER, *FLAGS, "-c", "override.cpp", "-o", "override.obj"]) + self.run_command([COMPILER, *FLAGS, "-flto=full", "first.cpp", "second.cpp", + "override.obj", "-o", "program"]) + self.run_command(["./program"]) + + def test_combined_host_object(self): + self.run_command([COMPILER, *FLAGS, "-flto=full", "-c", "first.cpp", "second.cpp", + "-o", "combined.o"]) + host = shlex.split(os.environ.get("CPPGM_HOST_CXX") or os.environ.get("CXX") or "g++") + self.run_command([*host, "combined.o", "override.cpp", "-o", "program"]) + self.run_command(["./program"]) + disassembly = self.run_command(["objdump", "-dr", "--disassemble=main", "combined.o"]).stdout + self.assertIn("
:", disassembly) + self.assertNotIn("_Z4nexti", disassembly) + + def test_source_group_errors_and_disable_flag(self): + self.run_command([COMPILER, *FLAGS, "-c", "override.cpp", "-o", "override.obj"]) + result = self.run_command([COMPILER, *FLAGS, "-flto=full", "first.cpp", "override.obj", + "second.cpp", "-o", "program"], success=False) + self.assertNotEqual(result.returncode, 0) + self.assertIn("needs consecutive source inputs", result.stderr) + self.run_command([COMPILER, *FLAGS, "-flto=full", "-fno-lto", "first.cpp", + "override.obj", "second.cpp", "-o", "program"]) + self.run_command(["./program"]) + result = self.run_command([COMPILER, *FLAGS, "-flto=full", "-c", "first.cpp", "second.cpp"], + success=False) + self.assertNotEqual(result.returncode, 0) + self.assertIn("requires source inputs and an explicit -o", result.stderr) + + def test_always_inline_copies_are_local_to_each_source(self): + sources = [] + declarations = [] + checks = [] + for index in range(24): + source = f"unit{index:02}.cpp" + function = f"test{index:02}" + (self.directory / source).write_text(f""" +static __attribute__((always_inline)) inline int value() {{ return {10 + index}; }} +int {function}() {{ return value(); }} +""") + sources.append(source) + declarations.append(f"int {function}();") + checks.append(f"{function}() != {10 + index}") + (self.directory / "main.cpp").write_text( + "\n".join(declarations) + "\nint main() { return " + " || ".join(checks) + "; }\n") + self.run_command([COMPILER, *FLAGS, "-flto=full", "main.cpp", *sources, "-o", "program"]) + self.run_command(["./program"]) + + def test_thread_local_initialization_stays_local_to_each_source(self): + (self.directory / "first.cpp").write_text(""" +int observed; +int init() { return ++observed; } +thread_local int a = init(); +int get_a() { return a; } +extern int get_b(); +int main() { + if (get_a() != 1 || observed != 1) return 1; + if (get_b() != 2 || observed != 2) return 2; + return 0; +} +""") + (self.directory / "second.cpp").write_text(""" +extern int init(); +thread_local int b = init(); +int get_b() { return b; } +""") + self.run_command([COMPILER, *FLAGS, "-flto=full", "first.cpp", "second.cpp", "-o", "program"]) + self.run_command(["./program"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_wasm_quality.py b/scripts/tests/test_wasm_quality.py index d11ec1762..dd5606cde 100644 --- a/scripts/tests/test_wasm_quality.py +++ b/scripts/tests/test_wasm_quality.py @@ -41,7 +41,8 @@ def metrics(self, body): def test_local_declarations_and_instructions_are_separate(self): self.assertEqual(self.metrics(bytes.fromhex("01027f200041016a0b")), dict(code_bytes=9, locals=2, instructions=4, memory_ops=0, - zero_offset_memory_ops=0, bulk_memory_ops=0, control_depth=0)) + zero_offset_memory_ops=0, bulk_memory_ops=0, control_depth=0, + try_tables=0, local_ops=1)) def test_simd_immediates_are_not_counted_as_instructions(self): body = b"\0\xfd\x0c" + bytes(range(16)) + b"\xfd\x1b\0\x0b"