diff --git a/Makefile b/Makefile index 90c03b6c36c4..9a8f54a07f86 100644 --- a/Makefile +++ b/Makefile @@ -242,6 +242,7 @@ LLVM_STATIC_LIBFILES = \ ipo \ passes \ orcjit \ + orcdebugging \ $(X86_LLVM_CONFIG_LIB) \ $(ARM_LLVM_CONFIG_LIB) \ $(OPENCL_LLVM_CONFIG_LIB) \ @@ -641,7 +642,6 @@ SOURCE_FILES = \ CodeGen_C_vectors HTML_TEMPLATE_FILES = \ - StmtToHTML_dependencies.html \ StmtToHTML.js \ StmtToHTML.css diff --git a/README.md b/README.md index 953ca58c968b..c22792f138e9 100644 --- a/README.md +++ b/README.md @@ -532,6 +532,7 @@ We have more documentation in `doc/`, the following links might be helpful: | --------------------------------------------- | ------------------------------------------------------------------------- | | [CMake build](doc/BuildingHalideWithCMake.md) | How to configure and build Halide using CMake. | | [CMake package](doc/HalideCMakePackage.md) | How to use the Halide CMake package to build your code. | +| [Debug symbols](doc/DebugSymbols.md) | How to step through compiled pipelines in a debugger, line by line. | | [Generator cache](doc/GeneratorCache.md) | How to speed up rebuilds with the opt-in generator compile cache. | | [Hexagon](doc/Hexagon.md) | How to use the Hexagon backend. | | [Python](doc/Python.md) | Documentation for the Python bindings. | diff --git a/cmake/FindHalide_LLVM.cmake b/cmake/FindHalide_LLVM.cmake index 8fe7014d6884..33a7ebed074a 100644 --- a/cmake/FindHalide_LLVM.cmake +++ b/cmake/FindHalide_LLVM.cmake @@ -158,7 +158,7 @@ if (Halide_LLVM_FOUND) if (Halide_LLVM_SHARED_LIBS) target_link_libraries(Halide_LLVM::Core INTERFACE LLVM ${CMAKE_DL_LIBS}) else () - _Halide_LLVM_link(Halide_LLVM::Core orcjit bitwriter linker passes) + _Halide_LLVM_link(Halide_LLVM::Core orcjit orcdebugging bitwriter linker passes) endif () endif () diff --git a/doc/DebugSymbols.md b/doc/DebugSymbols.md new file mode 100644 index 000000000000..6edaccfb8b5f --- /dev/null +++ b/doc/DebugSymbols.md @@ -0,0 +1,94 @@ +# Debug symbols + +The `debug_symbols` target feature makes Halide emit debug info for the code it +generates. The "source" that debug info refers to is the `.stmt` output: the +lowered IR exactly as it was handed to code generation. This lets you set +breakpoints on lines of the `.stmt`, step through it, inspect variables, and get +profilers to attribute time to its lines. + +## Ahead-of-time compilation + +Add the feature to the target, and also request the `stmt` output, so that the +debugger can find the file: + +```shell +$ ./my_generator -g my_pipeline -o out -e static_library,h,stmt target=host-debug_symbols +``` + +or, with CMake: + +```cmake +add_halide_library(my_pipeline FROM my_generators + FEATURES debug_symbols + STMT my_pipeline_stmt) +``` + +Without the `stmt` output, the debug info still refers to the file it would have +been written to, next to the compiled code. + +## JIT compilation + +With the feature in the JIT target (e.g. `HL_JIT_TARGET=host-debug_symbols`), +Halide writes the `.stmt` of each JIT module to the temp directory, as +`halide-jit--.stmt`, and registers the compiled code with the +debugger through the GDB JIT interface. Set `HL_DEBUG_CODEGEN=1` to see which +file a module refers to. + +## What you get + +- Every instruction is attributed to the line and column of the IR node it was + generated for. Binary operators point at the operator itself, calls and loads + at their name. +- Every function in the `.stmt`, including the closures of parallel loops, is a + function to the debugger. +- `let` variables, loop variables and function arguments are visible as local + variables. Loop variables are scoped to their loop. Buffer arguments + (`*.buffer`) are typed as `halide_buffer_t *`, so their fields and dimensions + can be printed. + +Halide's names contain dots, so quote them in GDB: + +``` +(gdb) break my_pipeline.stmt:42 +(gdb) info locals +(gdb) print 'f.s0.x' +(gdb) print *'input.buffer' +(gdb) print 'input.buffer'->dim[1] +``` + +## Pointing into the conceptual stmt + +With the `debug_symbols_conceptual` feature instead, the debug info points into +the conceptual stmt (the `conceptual_stmt` output): the IR before it is lowered +to device code offloading, closures for parallel loops, and the like, which is +usually easier to read. Code made from IR that is not in the conceptual stmt, +e.g. the call that runs a parallel loop, is attributed to the nearest enclosing +IR that is, which can be the start of the function. A target can't have both +features. + +## The html outputs + +The `stmt_html` and `conceptual_stmt_html` outputs show the IR exactly as the +`stmt` and `conceptual_stmt` outputs print it: the line numbers and columns are +those of these files. The host assembly is compiled with debug info for them +(even without the `debug_symbols` feature, in which case the other outputs get +none), and that debug info links each line of IR to the assembly generated for +it. Hover IR to see its assembly, double-click it to keep that shown and go +there, and double-click it again (or press Escape) to let go of it; the same +goes for assembly and the IR it came from (the toolbar can make going there +scroll smoothly). A line of IR is marked faintly. Within the line, the debug +info says which IR node each instruction was generated for: on an operator, a +keyword or a name, the assembly of that expression and of all that is nested in +it is marked strongly. With rainbow parentheses on, the assembly that is +selected is colored by the node each instruction was generated for, in the +colors of the punctuation of those nodes. The assembly pane shows the line +numbers of the assembly file, without the lines that hold the debug info. + +This needs every IR node to be printed in one place only, so lowering copies the +IR nodes that the stmt uses in more than one place. + +## Caveats + +- The code is still fully optimized, so many variables are ``, + and stepping can jump back and forth between lines. +- DWARF version 4 is emitted, or CodeView on Windows. diff --git a/python_bindings/halide/src/halide_/PyEnums.cpp b/python_bindings/halide/src/halide_/PyEnums.cpp index 5dbbb6f36e47..730dccb7e30c 100644 --- a/python_bindings/halide/src/halide_/PyEnums.cpp +++ b/python_bindings/halide/src/halide_/PyEnums.cpp @@ -274,6 +274,8 @@ void define_enums(py::module_ &m) { .value("HLSL_SM69", Target::Feature::HLSL_SM69) .value("NoMetadata", Target::Feature::NoMetadata) .value("ARM64e", Target::Feature::ARM64e) + .value("DebugSymbols", Target::Feature::DebugSymbols) + .value("DebugSymbolsConceptual", Target::Feature::DebugSymbolsConceptual) .value("FeatureEnd", Target::Feature::FeatureEnd); py::enum_(m, "TypeCode") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 114c53edfc84..47dd9bd5716c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -446,7 +446,7 @@ target_sources(Halide PRIVATE "${Halide_SOURCE_DIR}/tools/Halide.natvis") set(C_TEMPLATE_FILES CodeGen_C_prologue CodeGen_C_vectors) -set(HTML_TEMPLATE_FILES StmtToHTML_dependencies.html StmtToHTML.js StmtToHTML.css) +set(HTML_TEMPLATE_FILES StmtToHTML.js StmtToHTML.css) ## # Build and import the runtime. diff --git a/src/CodeGen_ARM.cpp b/src/CodeGen_ARM.cpp index d37b896c3bff..c3041caffe43 100644 --- a/src/CodeGen_ARM.cpp +++ b/src/CodeGen_ARM.cpp @@ -965,7 +965,9 @@ llvm::Function *CodeGen_ARM::define_intrin_wrapper(const std::string &inner_name llvm::Function::Create(wrapper_ty, llvm::GlobalValue::InternalLinkage, wrapper_name, module.get()); llvm::BasicBlock *block = llvm::BasicBlock::Create(module->getContext(), "entry", wrapper); - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); + // This code belongs to another function, with no debug info. + builder->SetCurrentDebugLocation(DebugLoc()); builder->SetInsertPoint(block); if (split_arg0) { @@ -993,8 +995,6 @@ llvm::Function *CodeGen_ARM::define_intrin_wrapper(const std::string &inner_name // Available regardless of SME streaming mode wrapper->addFnAttr("aarch64_pstate_sm_compatible"); - builder->restoreIP(here); - llvm::verifyFunction(*wrapper); return wrapper; } @@ -2674,7 +2674,9 @@ void CodeGen_ARM::visit(const Call *op) { fn = llvm::Function::Create(func_t, llvm::Function::InternalLinkage, op->name, module.get()); llvm::BasicBlock *block = llvm::BasicBlock::Create(module->getContext(), "entry", fn); - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); + // This code belongs to another function, with no debug info. + builder->SetCurrentDebugLocation(DebugLoc()); builder->SetInsertPoint(block); // Body @@ -2690,7 +2692,6 @@ void CodeGen_ARM::visit(const Call *op) { fn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(*context, 1, 16)); fn->addFnAttr(llvm::Attribute::NoInline); internal_assert(!verifyFunction(*fn, &llvm::errs())); - builder->restoreIP(here); } value = builder->CreateCall(fn, {}); return; diff --git a/src/CodeGen_C.cpp b/src/CodeGen_C.cpp index 3e201d82d63a..ba79bb68c2b3 100644 --- a/src/CodeGen_C.cpp +++ b/src/CodeGen_C.cpp @@ -14,7 +14,6 @@ #include "Param.h" #include "Simplify.h" #include "StrictifyFloat.h" -#include "Substitute.h" #include "Type.h" #include "Util.h" #include "Var.h" @@ -1376,15 +1375,18 @@ void CodeGen_C::close_scope(const std::string &comment) { } void CodeGen_C::visit(const Variable *op) { - if (starts_with(op->name, "::")) { + // A variable that a let defines is the id of the value of the let. + const string *bound = bound_ids.find(op->name); + const string &name = bound ? *bound : op->name; + if (starts_with(name, "::")) { // This is the name of a global, so we can't modify it. - id = op->name; + id = name; } else { // This substitution ensures const correctness for all calls - if (op->name == "__user_context") { + if (name == "__user_context") { id = "_ucon"; } else { - id = print_name(op->name); + id = print_name(name); } } } @@ -2136,7 +2138,6 @@ void CodeGen_C::visit(const Store *op) { void CodeGen_C::visit(const Let *op) { string id_value = print_expr(op->value); - Expr body = op->body; if (op->value.type().is_handle() && op->name != "__user_context") { // The body might contain a Load that references this directly // by name, so we can't rewrite the name. @@ -2144,11 +2145,10 @@ void CodeGen_C::visit(const Let *op) { stream << get_indent() << "auto " << name << " = " << id_value << ";\n"; stream << get_indent() << "halide_maybe_unused(" << name << ");\n"; - } else { - Expr new_var = Variable::make(op->value.type(), id_value); - body = substitute(op->name, new_var, body); + id_value = op->name; } - print_expr(body); + ScopedBinding bind(bound_ids, op->name, id_value); + print_expr(op->body); } void CodeGen_C::visit(const Select *op) { @@ -2230,8 +2230,6 @@ void CodeGen_C::visit(const VectorReduce *op) { void CodeGen_C::visit(const LetStmt *op) { string id_value = print_expr(op->value); - Stmt body = op->body; - if (op->value.type().is_handle() && op->name != "__user_context") { // The body might contain a Load or Store that references this // directly by name, so we can't rewrite the name. @@ -2239,11 +2237,10 @@ void CodeGen_C::visit(const LetStmt *op) { stream << get_indent() << "auto " << name << " = " << id_value << ";\n"; stream << get_indent() << "halide_maybe_unused(" << name << ");\n"; - } else { - Expr new_var = Variable::make(op->value.type(), id_value); - body = substitute(op->name, new_var, body); + id_value = op->name; } - body.accept(this); + ScopedBinding bind(bound_ids, op->name, id_value); + op->body.accept(this); } // Halide asserts have different semantics to C asserts. They're @@ -2350,7 +2347,10 @@ void CodeGen_C::visit(const For *op) { << "++)\n"; open_scope(); - op->body.accept(this); + { + ScopedBinding bind(bound_ids, op->name, op->name); + op->body.accept(this); + } close_scope("for " + print_name(op->name)); } diff --git a/src/CodeGen_C.h b/src/CodeGen_C.h index 7947a5332339..3d84588045d6 100644 --- a/src/CodeGen_C.h +++ b/src/CodeGen_C.h @@ -102,6 +102,11 @@ class CodeGen_C : public IRPrinter { /** A cache of generated values in scope */ std::map cache; + /** What the Variables with the names that the enclosing Lets, LetStmts + * and For loops define are printed as: the id of the value of a let, or + * else the name itself. */ + Scope bound_ids; + /** Emit an expression as an assignment, then return the id of the * resulting var */ std::string print_expr(const Expr &); diff --git a/src/CodeGen_Hexagon.cpp b/src/CodeGen_Hexagon.cpp index f99431df1d65..3ed1f6b09991 100644 --- a/src/CodeGen_Hexagon.cpp +++ b/src/CodeGen_Hexagon.cpp @@ -901,7 +901,9 @@ llvm::Function *CodeGen_Hexagon::define_hvx_intrinsic(llvm::Function *intrin, "halide.hexagon." + name, module.get()); llvm::BasicBlock *block = llvm::BasicBlock::Create(module->getContext(), "entry", wrapper); - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); + // This code belongs to another function, with no debug info. + builder->SetCurrentDebugLocation(DebugLoc()); builder->SetInsertPoint(block); vector args; @@ -977,8 +979,6 @@ llvm::Function *CodeGen_Hexagon::define_hvx_intrinsic(llvm::Function *intrin, // Always inline these wrappers. wrapper->addFnAttr(llvm::Attribute::AlwaysInline); - builder->restoreIP(here); - llvm::verifyFunction(*wrapper); return wrapper; } diff --git a/src/CodeGen_LLVM.cpp b/src/CodeGen_LLVM.cpp index 934da4ac2288..c3b79310acad 100644 --- a/src/CodeGen_LLVM.cpp +++ b/src/CodeGen_LLVM.cpp @@ -38,8 +38,10 @@ namespace Halide { -std::unique_ptr codegen_llvm(const Module &module, llvm::LLVMContext &context) { +std::unique_ptr codegen_llvm(const Module &module, llvm::LLVMContext &context, + const Internal::StmtSourceMap *debug_source) { std::unique_ptr cg(Internal::CodeGen_LLVM::new_for_target(module.target(), context)); + cg->debug_source = debug_source; return cg->compile(module); } @@ -170,6 +172,238 @@ llvm::GlobalValue::LinkageTypes llvm_linkage(LinkageType t) { } // namespace +struct CodeGen_LLVM::DebugInfo { + // What the debug info points into, which is own_source if compile() had + // to print it itself. + StmtSourceMap own_source; + const StmtSourceMap *source = nullptr; + + std::unique_ptr builder; + DICompileUnit *unit = nullptr; + DIFile *file = nullptr; + unsigned pointer_bits = 64; + + // Where the function compile() is generating starts in source. + std::optional function; + + // Called before compile() generates the function at the given index of + // its Module. + void set_function(size_t index, const LoweredFunc &f) { + if (!source->functions.empty()) { + function = source->functions[index]; + return; + } + // The source is the conceptual Stmt, which the functions themselves + // are not in. Each starts where the first of its code that is in it + // does. + class FirstPrinted : public IRGraphVisitor { + using IRGraphVisitor::include; + void include(const Expr &e) override { + if (!found && !(found = source.find(e.get(), 0))) { + IRGraphVisitor::include(e); + } + } + void include(const Stmt &s) override { + if (!found && !(found = source.find(s.get(), 0))) { + IRGraphVisitor::include(s); + } + } + + public: + const StmtSourceMap &source; + const StmtSourceMap::Location *found = nullptr; + explicit FirstPrinted(const StmtSourceMap &source) + : source(source) { + } + } first(*source); + first(f.body); + function = StmtSourceMap::Function{f.name, 0, 1, 1}; + if (first.found) { + function->start = first.found->start; + function->line = first.found->line; + function->column = first.found->column; + } + } + + // The innermost scope of the code being generated: the current function, + // or a loop within it. Null outside of functions from the source map. + DIScope *scope = nullptr; + + // The location new instructions get, and where printing of the IR node + // it belongs to began. + DILocation *location = nullptr; + uint32_t location_start = 0; + + std::vector> types; + DIType *buffer_ptr_type = nullptr; + + // While this lives, the location is that of the given node, if it was + // printed. Nodes made after printing, e.g. by codegen itself, keep the + // location of the nearest printed node they are generated within. A null + // DebugInfo does nothing. + struct At { + DebugInfo *const d; + IRBuilderBase &b; + DILocation *saved_location = nullptr; + uint32_t saved_start = 0; + + At(DebugInfo *d, const IRNode *node, IRBuilderBase &b) + : d(d), b(b) { + if (!d) { + return; + } + saved_location = d->location; + saved_start = d->location_start; + if (d->scope) { + if (const StmtSourceMap::Location *l = d->source->find(node, d->location_start)) { + d->location = DILocation::get(d->scope->getContext(), l->line, l->column, d->scope); + d->location_start = l->start; + } + // Also undoes any change made by moving the insertion point. + b.SetCurrentDebugLocation(d->location); + } + } + + ~At() { + if (!d) { + return; + } + d->location = saved_location; + d->location_start = saved_start; + if (d->scope) { + b.SetCurrentDebugLocation(d->location); + } + } + }; + + // Null for types a debugger can't show. + DIType *type_of(const Type &t) { + for (const auto &[k, v] : types) { + if (k == t) { + return v; + } + } + DIType *result = nullptr; + if (t.is_handle()) { + result = builder->createPointerType(nullptr, pointer_bits); + } else if (t.is_vector()) { + DIType *element = t.is_bool() ? nullptr : type_of(t.element_of()); + if (element) { + Metadata *lanes = builder->getOrCreateSubrange(0, t.lanes()); + result = builder->createVectorType((uint64_t)t.bits() * t.lanes(), 0, element, + builder->getOrCreateArray({lanes})); + } + } else if (t.is_bool()) { + result = builder->createBasicType("bool", 8, dwarf::DW_ATE_boolean); + } else if (t.is_int() || t.is_uint() || (t.is_float() && !t.is_bfloat())) { + unsigned encoding = t.is_int() ? dwarf::DW_ATE_signed : + t.is_uint() ? dwarf::DW_ATE_unsigned : + dwarf::DW_ATE_float; + std::ostringstream name; + name << t; + result = builder->createBasicType(name.str(), t.bits(), encoding); + } + types.emplace_back(t, result); + return result; + } + + // The debug info points into source, a printing of input or of its + // conceptual Stmt. If source is null, input is printed, or its conceptual + // Stmt if conceptual is set. + static std::unique_ptr make(llvm::Module &m, const Module &input, const Target &target, + const StmtSourceMap *source, bool conceptual, + StructType *buffer_t, StructType *type_t, StructType *dimension_t) { + auto d = std::make_unique(); + if (source) { + d->source = source; + } else { + if (conceptual) { + d->own_source = print_with_source_map(input.get_conceptual_stmt()); + d->own_source.path = input.name() + ".conceptual.stmt"; + } else { + d->own_source = print_with_source_map(input); + d->own_source.path = input.name() + ".stmt"; + } + d->source = &d->own_source; + } + internal_assert(d->source->functions.empty() || d->source->functions.size() == input.functions().size()) + << "The debug source of a Module must be a printing of that Module or of its conceptual Stmt\n"; + + const bool codeview = target.os == Target::Windows; + if (!m.getModuleFlag("Debug Info Version")) { + m.addModuleFlag(llvm::Module::Warning, "Debug Info Version", DEBUG_METADATA_VERSION); + } + if (codeview) { + if (!m.getModuleFlag("CodeView")) { + m.addModuleFlag(llvm::Module::Warning, "CodeView", 1); + } + } else if (!m.getModuleFlag("Dwarf Version")) { + // Version 5 could carry the text of the .stmt in the object, but + // LLVM then describes many optimized variables with typed DWARF + // expressions that gdb can't evaluate. + m.addModuleFlag(llvm::Module::Max, "Dwarf Version", 4); + } + + SmallString<256> path(d->source->path); + if (std::error_code error = sys::fs::make_absolute(path)) { + debug(1) << "Could not make " << d->source->path << " absolute: " << error.message() << "\n"; + } + MD5 md5; + md5.update(d->source->text); + SmallString<32> checksum; + MD5::MD5Result digest = md5.final(); + MD5::stringifyResult(digest, checksum); + + d->builder = std::make_unique(m); + d->file = d->builder->createFile(sys::path::filename(path), sys::path::parent_path(path), + DIFile::ChecksumInfo(DIFile::CSK_MD5, checksum)); + d->unit = d->builder->createCompileUnit(dwarf::DW_LANG_C99, d->file, "Halide", + /* isOptimized */ true, "", 0, ""); + d->pointer_bits = target.bits; + + // Describe halide_buffer_t, so that the debugger can show buffers. + const DataLayout &dl = m.getDataLayout(); + auto make_struct = [&](const char *name, StructType *st, + const std::vector> &fields) -> DIType * { + if (!st || st->getNumElements() != fields.size()) { + return nullptr; + } + const StructLayout *layout = dl.getStructLayout(st); + std::vector members; + for (size_t i = 0; i < fields.size(); i++) { + if (!fields[i].second) { + return nullptr; + } + members.push_back(d->builder->createMemberType( + d->unit, fields[i].first, d->file, 0, fields[i].second->getSizeInBits(), 0, + (uint64_t)layout->getElementOffsetInBits(i), DINode::FlagZero, fields[i].second)); + } + return d->builder->createStructType(d->unit, name, d->file, 0, (uint64_t)layout->getSizeInBits(), 0, + DINode::FlagZero, nullptr, d->builder->getOrCreateArray(members)); + }; + DIType *u8 = d->type_of(UInt(8)), *u16 = d->type_of(UInt(16)); + DIType *i32 = d->type_of(Int(32)), *u32 = d->type_of(UInt(32)), *u64 = d->type_of(UInt(64)); + DIType *ptr = d->type_of(Handle()); + DIType *type = make_struct("halide_type_t", type_t, {{"code", u8}, {"bits", u8}, {"lanes", u16}}); + DIType *dim = make_struct("halide_dimension_t", dimension_t, + {{"min", i32}, {"extent", i32}, {"stride", i32}, {"flags", u32}}); + DIType *dim_ptr = dim ? d->builder->createPointerType(dim, d->pointer_bits) : nullptr; + DIType *buffer = make_struct("halide_buffer_t", buffer_t, + {{"device", u64}, + {"device_interface", ptr}, + {"host", d->builder->createPointerType(u8, d->pointer_bits)}, + {"flags", u64}, + {"type", type}, + {"dimensions", i32}, + {"dim", dim_ptr}, + {"padding", ptr}}); + d->buffer_ptr_type = buffer ? d->builder->createPointerType(buffer, d->pointer_bits) : ptr; + return d; + } +}; + +CodeGen_LLVM::~CodeGen_LLVM() = default; + CodeGen_LLVM::CodeGen_LLVM(const Target &t) : builder(nullptr), @@ -723,6 +957,13 @@ std::unique_ptr CodeGen_LLVM::compile(const Module &input) { internal_assert(module && context && builder) << "The CodeGen_LLVM subclass should have made an initial module before calling CodeGen_LLVM::compile\n"; + user_assert(!(target.has_feature(Target::DebugSymbols) && target.has_feature(Target::DebugSymbolsConceptual))) + << "The debug info of " << input.name() << " can point into the stmt (debug_symbols) " + << "or into the conceptual stmt (debug_symbols_conceptual), but not both.\n"; + if (debug_source || target.has_feature(Target::DebugSymbols) || target.has_feature(Target::DebugSymbolsConceptual)) { + init_debug_info(debug_source, input, target.has_feature(Target::DebugSymbolsConceptual)); + } + // Generate the code for this module. debug(1) << "Generating llvm bitcode...\n"; for (const auto &b : input.buffers()) { @@ -841,6 +1082,9 @@ std::unique_ptr CodeGen_LLVM::compile(const Module &input) { // Define all functions int idx = 0; for (const auto &f : input.functions()) { + if (debug_info) { + debug_info->set_function(idx, f); + } const auto &names = function_names[idx++]; run_with_large_stack([&]() { @@ -870,6 +1114,8 @@ std::unique_ptr CodeGen_LLVM::compile(const Module &input) { std::unique_ptr CodeGen_LLVM::finish_codegen() { llvm::for_each(*module, set_function_attributes_from_halide_target_options); + finalize_debug_info(); + // Verify the module is ok internal_assert(!verifyModule(*module, &llvm::errs())); debug(2) << "Done generating llvm bitcode\n"; @@ -898,6 +1144,16 @@ void CodeGen_LLVM::begin_func(LinkageType linkage, const std::string &name, debug(1) << "Generating llvm bitcode prolog for function " << name << "...\n"; + if (debug_info && debug_info->function) { + std::vector> arg_types; + arg_types.reserve(args.size()); + for (const auto &arg : args) { + arg_types.emplace_back(arg.is_buffer(), arg.type); + } + const Type return_type = Int(32); + begin_debug_function(name, extern_name, nullptr, &return_type, arg_types); + } + // Null out the destructor block. destructor_block = nullptr; @@ -924,6 +1180,14 @@ void CodeGen_LLVM::begin_func(LinkageType linkage, const std::string &name, i++; } } + + for (size_t i = 0; i < args.size(); i++) { + if (args[i].is_buffer()) { + add_debug_variable(args[i].name + ".buffer", Handle(), sym_get(args[i].name + ".buffer"), i + 1); + } else { + add_debug_variable(args[i].name, args[i].type, sym_get(args[i].name), i + 1); + } + } } void CodeGen_LLVM::end_func(const std::vector &args) { @@ -938,6 +1202,8 @@ void CodeGen_LLVM::end_func(const std::vector &args) { } } + end_debug_function(); + bool valid = !verifyFunction(*function, &llvm::errs()); if (!valid) { function->print(dbgs()); @@ -947,6 +1213,69 @@ void CodeGen_LLVM::end_func(const std::vector &args) { current_function_args.clear(); } +void CodeGen_LLVM::init_debug_info(const StmtSourceMap *source, const Module &input, bool conceptual) { + debug_info = DebugInfo::make(*module, input, target, source, conceptual, + halide_buffer_t_type, type_t_type, dimension_t_type); +} + +void CodeGen_LLVM::begin_debug_function(const std::string &name, const std::string &linkage_name, + const IRNode *node, const Type *return_type, + const std::vector> &args) { + if (!debug_info) { + return; + } + DebugInfo &d = *debug_info; + uint32_t line = 0, column = 1, start = 0; + if (node) { + const StmtSourceMap::Location *l = d.source->find(node, 0); + if (!l) { + return; + } + line = l->line; + column = l->column; + start = l->start; + } else if (d.function) { + line = d.function->line; + column = d.function->column; + start = d.function->start; + } else { + return; + } + std::vector signature{return_type ? d.type_of(*return_type) : nullptr}; + for (const auto &[is_buffer, type] : args) { + signature.push_back(is_buffer ? d.buffer_ptr_type : d.type_of(type)); + } + // A combination of flags is not one of the enumerators. + const auto sp_flags = static_cast( // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange) + +DISubprogram::SPFlagDefinition | +DISubprogram::SPFlagOptimized); + DISubprogram *subprogram = d.builder->createFunction( + d.file, name, linkage_name, d.file, line, + d.builder->createSubroutineType(d.builder->getOrCreateTypeArray(signature)), + line, DINode::FlagPrototyped, sp_flags); + function->setSubprogram(subprogram); + d.scope = subprogram; + d.location = DILocation::get(*context, line, column, subprogram); + d.location_start = start; + builder->SetCurrentDebugLocation(d.location); +} + +void CodeGen_LLVM::end_debug_function() { + if (debug_info && debug_info->scope) { + debug_info->builder->finalizeSubprogram(function->getSubprogram()); + debug_info->function.reset(); + debug_info->scope = nullptr; + debug_info->location = nullptr; + builder->SetCurrentDebugLocation(DebugLoc()); + } +} + +void CodeGen_LLVM::finalize_debug_info() { + if (debug_info) { + debug_info->builder->finalize(); + debug_info.reset(); + } +} + void CodeGen_LLVM::compile_func(const LoweredFunc &f, const std::string &simple_name, const std::string &extern_name) { // Generate the function declaration and argument unpacking code. @@ -970,7 +1299,7 @@ void CodeGen_LLVM::compile_func(const LoweredFunc &f, const std::string &simple_ // Generate the function body. debug(1) << "Generating llvm bitcode for function " << f.name << "...\n"; - f.body.accept(this); + codegen(f.body); // Show one time warning and clear it. for (auto it = onetime_warnings.begin(); it != onetime_warnings.end(); it = onetime_warnings.erase(it)) { @@ -994,7 +1323,7 @@ std::vector get_constants(llvm::Type *t, It begin, It end) { BasicBlock *CodeGen_LLVM::get_destructor_block() { if (!destructor_block) { // Create it if it doesn't exist. - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); destructor_block = BasicBlock::Create(*context, "destructor_block", function); builder->SetInsertPoint(destructor_block); // The first instruction in the destructor block is a phi node @@ -1005,9 +1334,6 @@ BasicBlock *CodeGen_LLVM::get_destructor_block() { // The last instruction is the return op that returns it. builder->CreateRet(error_code); - - // Jump back to where we were. - builder->restoreIP(here); } internal_assert(destructor_block->getParent() == function); return destructor_block; @@ -1033,7 +1359,7 @@ Value *CodeGen_LLVM::register_destructor(llvm::Function *destructor_fn, Value *o // Switch to the destructor block, and add code that cleans up // this object if the contents of the stack slot is not nullptr. - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); BasicBlock *dtors = get_destructor_block(); builder->SetInsertPoint(dtors->getFirstNonPHIIt()); @@ -1060,9 +1386,6 @@ Value *CodeGen_LLVM::register_destructor(llvm::Function *destructor_fn, Value *o Value *args[] = {get_user_context(), destructor_fn, stack_slot, should_call}; builder->CreateCall(call_destructor, args); - // Switch back to the original location - builder->restoreIP(here); - // Return the stack slot so that it's possible to cleanup the object early. return stack_slot; } @@ -1537,6 +1860,34 @@ void CodeGen_LLVM::sym_pop(const string &name) { symbol_table.pop(name); } +void CodeGen_LLVM::add_debug_variable(const string &name, const Type &type, llvm::Value *value, unsigned arg_no) { + if (!debug_info || !debug_info->scope || !value || !builder->GetInsertBlock()) { + return; + } + DebugInfo &d = *debug_info; + DIType *t = (type.is_handle() && ends_with(name, ".buffer")) ? d.buffer_ptr_type : d.type_of(type); + llvm::Type *value_type = value->getType(); + if (!t || isa(value_type)) { + return; + } + // A bool is an i1 in a register, but a byte to the debugger. + if (!value_type->isIntegerTy(1) && + module->getDataLayout().getTypeSizeInBits(value_type) != t->getSizeInBits()) { + return; + } + const unsigned line = d.location->getLine(); + DILocalVariable *var = + arg_no ? + d.builder->createParameterVariable(d.scope, name, arg_no, d.file, line, t, /* AlwaysPreserve */ true) : + d.builder->createAutoVariable(d.scope, name, d.file, line, t, /* AlwaysPreserve */ true); + const DILocation *location = DILocation::get(*context, line, d.location->getColumn(), d.scope); +#if LLVM_VERSION >= 240 + d.builder->insertDbgValue(value, var, d.builder->createExpression(), location, builder->GetInsertPoint()); +#else + d.builder->insertDbgValueIntrinsic(value, var, d.builder->createExpression(), location, builder->GetInsertPoint()); +#endif +} + llvm::Value *CodeGen_LLVM::sym_get(const string &name, bool must_succeed) const { // look in the symbol table if (const auto *v = symbol_table.find(name)) { @@ -1558,7 +1909,10 @@ Value *CodeGen_LLVM::codegen(const Expr &e) { internal_assert(e.defined()); debug(4) << "Codegen: " << e.type() << ", " << e << "\n"; value = nullptr; - e.accept(this); + { + DebugInfo::At debug_location(debug_info.get(), e.get(), *builder); + e.accept(this); + } internal_assert(value) << "Codegen of an expr did not produce an llvm value\n" << e; @@ -1604,6 +1958,7 @@ Value *CodeGen_LLVM::codegen(const Expr &e) { void CodeGen_LLVM::codegen(const Stmt &s) { internal_assert(s.defined()); debug(4) << "Codegen: " << s << "\n"; + DebugInfo::At debug_location(debug_info.get(), s.get(), *builder); value = nullptr; s.accept(this); } @@ -3991,7 +4346,9 @@ void CodeGen_LLVM::visit(const Call *op) { FunctionType *func_t = FunctionType::get(i32_t, {}, false); fn = llvm::Function::Create(func_t, llvm::Function::InternalLinkage, op->name, module.get()); llvm::BasicBlock *block = llvm::BasicBlock::Create(module->getContext(), "entry", fn); - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); + // This code belongs to another function, with no debug info. + builder->SetCurrentDebugLocation(DebugLoc()); builder->SetInsertPoint(block); Value *ret = builder->CreateVScale(i32_t); builder->CreateRet(ret); @@ -4000,7 +4357,6 @@ void CodeGen_LLVM::visit(const Call *op) { fn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(*context, 1, 16)); fn->addFnAttr(llvm::Attribute::NoInline); internal_assert(!verifyFunction(*fn, &llvm::errs())); - builder->restoreIP(here); } value = builder->CreateCall(fn, {}); } else if (op->is_intrinsic()) { @@ -4229,13 +4585,17 @@ void CodeGen_LLVM::visit(const Prefetch *op) { } void CodeGen_LLVM::visit(const Let *op) { - sym_push(op->name, codegen(op->value)); + Value *v = codegen(op->value); + sym_push(op->name, v); + add_debug_variable(op->name, op->value.type(), v); value = codegen(op->body); sym_pop(op->name); } void CodeGen_LLVM::visit(const LetStmt *op) { - sym_push(op->name, codegen(op->value)); + Value *v = codegen(op->value); + sym_push(op->name, v); + add_debug_variable(op->name, op->value.type(), v); codegen(op->body); sym_pop(op->name); } @@ -4380,6 +4740,18 @@ void CodeGen_LLVM::visit(const For *op) { // Within the loop, the variable is equal to the phi value sym_push(op->name, phi); + // The loop variable only exists in the debugger within the loop, + // which includes the code that steps it, like a C for loop. + DIScope *outer_scope = debug_info ? debug_info->scope : nullptr; + if (outer_scope) { + DebugInfo &d = *debug_info; + const unsigned line = d.location->getLine(), column = d.location->getColumn(); + d.scope = d.builder->createLexicalBlock(outer_scope, d.file, line, column); + d.location = DILocation::get(*context, line, column, d.scope); + builder->SetCurrentDebugLocation(d.location); + } + add_debug_variable(op->name, Int(32), phi); + // Emit the loop body codegen(op->body); @@ -4397,6 +4769,9 @@ void CodeGen_LLVM::visit(const For *op) { // Pop the loop variable from the scope sym_pop(op->name); + if (outer_scope) { + debug_info->scope = outer_scope; + } } else { internal_error << "Unknown type of For node. Only Serial and Parallel For nodes should survive down to codegen.\n"; } @@ -5182,7 +5557,7 @@ void CodeGen_LLVM::visit(const Atomic *op) { } Value *CodeGen_LLVM::create_alloca_at_entry(llvm::Type *t, int n, bool zero_initialize, const string &name) { - IRBuilderBase::InsertPoint here = builder->saveIP(); + IRBuilderBase::InsertPointGuard insert_point_guard(*builder); BasicBlock *entry = &builder->GetInsertBlock()->getParent()->getEntryBlock(); if (entry->empty()) { builder->SetInsertPoint(entry); @@ -5210,7 +5585,6 @@ Value *CodeGen_LLVM::create_alloca_at_entry(llvm::Type *t, int n, bool zero_init builder->CreateMemSet(ptr, Constant::getNullValue(t), n, llvm::Align(align)); } } - builder->restoreIP(here); return ptr; } diff --git a/src/CodeGen_LLVM.h b/src/CodeGen_LLVM.h index 13b088cb1370..566201d3185d 100644 --- a/src/CodeGen_LLVM.h +++ b/src/CodeGen_LLVM.h @@ -54,6 +54,8 @@ struct ExternSignature; namespace Internal { +struct StmtSourceMap; + /** A code generator abstract base class. Actual code generators * (e.g. CodeGen_X86) inherit from this. This class is responsible * for taking a Halide Stmt and producing llvm bitcode, machine @@ -65,6 +67,16 @@ class CodeGen_LLVM : public IRVisitor { /** Create an instance of CodeGen_LLVM suitable for the target. */ static std::unique_ptr new_for_target(const Target &target, llvm::LLVMContext &context); + ~CodeGen_LLVM() override; + + /** If set, compile() emits debug info that points into this printing, + * which must be one of the Module passed to it, or of the conceptual + * Stmt of that Module. If null, and the target has the DebugSymbols or + * DebugSymbolsConceptual feature, compile() prints the one the feature + * is about itself, and the debug info refers to a file named after the + * Module. */ + const StmtSourceMap *debug_source = nullptr; + /** Takes a halide Module and compiles it to an llvm Module. */ virtual std::unique_ptr compile(const Module &module); @@ -191,6 +203,34 @@ class CodeGen_LLVM : public IRVisitor { bool in_strict_float = false; bool any_strict_float = false; + /** Debug info state for targets with the DebugSymbols feature. Null + * otherwise, and outside of compile(). */ + struct DebugInfo; + std::unique_ptr debug_info; + + /** Describe a named value to the debugger, if there is debug info. An + * arg_no above zero makes it the arg_no-th parameter of the function. */ + void add_debug_variable(const std::string &name, const Type &type, llvm::Value *value, unsigned arg_no = 0); + + /** Set up debug_info for the module being generated, pointing into + * source, a printing of input or of its conceptual Stmt. If source is + * null, input is printed, or its conceptual Stmt if conceptual is set. */ + void init_debug_info(const StmtSourceMap *source, const Module &input, bool conceptual); + + /** If there is debug info, give the function being generated a + * subprogram, starting at where node was printed. If node is null, it is + * the function of the Module being compiled. A null return_type is void. + * The args say whether each argument is a buffer, and its type. */ + void begin_debug_function(const std::string &name, const std::string &linkage_name, + const IRNode *node, const Type *return_type, + const std::vector> &args); + + /** Finish the subprogram of the function being generated, if any. */ + void end_debug_function(); + + /** Finish the debug info of the module being generated, if any. */ + void finalize_debug_info(); + /** Emit any target-specific fence required after non-temporal stores. */ virtual void emit_streaming_store_fence(); @@ -254,8 +294,8 @@ class CodeGen_LLVM : public IRVisitor { llvm::Type *void_t = nullptr, *i1_t = nullptr, *i8_t = nullptr, *i16_t = nullptr, *i32_t = nullptr, *i64_t = nullptr, *f16_t = nullptr, *f32_t = nullptr, *f64_t = nullptr; llvm::PointerType *ptr_t = nullptr; llvm::StructType *halide_buffer_t_type = nullptr, - *type_t_type, - *dimension_t_type, + *type_t_type = nullptr, + *dimension_t_type = nullptr, *metadata_t_type = nullptr, *argument_t_type = nullptr, *scalar_value_t_type = nullptr, @@ -813,9 +853,11 @@ class CodeGen_LLVM : public IRVisitor { } // namespace Internal -/** Given a Halide module, generate an llvm::Module. */ +/** Given a Halide module, generate an llvm::Module. See + * CodeGen_LLVM::debug_source for that. */ std::unique_ptr codegen_llvm(const Module &module, - llvm::LLVMContext &context); + llvm::LLVMContext &context, + const Internal::StmtSourceMap *debug_source = nullptr); } // namespace Halide diff --git a/src/IRPrinter.cpp b/src/IRPrinter.cpp index 939b18d8494b..d19f56e08db4 100644 --- a/src/IRPrinter.cpp +++ b/src/IRPrinter.cpp @@ -1,5 +1,7 @@ +#include #include #include +#include #include "IRPrinter.h" @@ -103,18 +105,7 @@ ostream &operator<<(ostream &stream, const Buffer<> &buffer) { } ostream &operator<<(ostream &stream, const Module &m) { - for (const auto &s : m.submodules()) { - stream << s << "\n"; - } - - // The module retains implied features, but print it in minimal form. - stream << "module name=" << m.name() << ", target=" << m.target().without_implied_features().to_string() << "\n"; - for (const auto &b : m.buffers()) { - stream << b << "\n"; - } - for (const auto &f : m.functions()) { - stream << f << "\n"; - } + Internal::IRPrinter(stream).print(m); return stream; } @@ -415,26 +406,12 @@ ostream &operator<<(ostream &out, const NameMangling &m) { } ostream &operator<<(ostream &stream, const Stmt &ir) { - if (!ir.defined()) { - stream << "(undefined)\n"; - } else { - Internal::IRPrinter p(stream); - p.print(ir); - } + IRPrinter(stream).print(ir); return stream; } ostream &operator<<(ostream &stream, const LoweredFunc &function) { - stream << function.linkage << " func " << function.name << " ("; - for (size_t i = 0; i < function.args.size(); i++) { - stream << function.args[i].name; - if (i + 1 < function.args.size()) { - stream << ", "; - } - } - stream << ") {\n"; - stream << function.body; - stream << "}\n\n"; + IRPrinter(stream).print(function); return stream; } @@ -588,24 +565,7 @@ IRPrinter::IRPrinter(ostream &s) use_colors = get_env_variable("NO_COLOR").empty() && supports_ansi(terminal); } - if (use_colors) { - ansi = true; - // Simple palette using standard VGA colors. - // clang-format off - ansi_hl = "\033[4m"; - ansi_dim = "\033[2m"; - ansi_kw = "\033[35;1m"; - ansi_imm_int = "\033[36m"; - ansi_imm_float = "\033[96m"; - ansi_imm_str = "\033[32m"; - ansi_var = ""; - ansi_buf = "\033[33m"; - ansi_fn = "\033[31m"; - ansi_type = "\033[34m"; - ansi_reset_col = "\033[39m"; - ansi_reset = "\033[0m"; - // clang-format on - } + ansi = use_colors; }; switch (debug_stream_sink(stream)) { @@ -629,86 +589,324 @@ IRPrinter::IRPrinter(ostream &s) } } -#define ansi_helper(name) \ - template \ - Ansi IRPrinter::name(const T &t) { \ - return {t, ansi ? ansi_##name : nullptr, ansi ? ansi_reset_col : nullptr}; \ - } -#define ansi_helper_r(name) \ - template \ - Ansi IRPrinter::name(const T &t) { \ - return {t, ansi ? ansi_##name : nullptr, ansi ? ansi_reset : nullptr}; \ +#define styled_helper(name, style) \ + template \ + StyledText IRPrinter::name(const T &t) { \ + return {t, this, IRPrinterStyle::style}; \ } -ansi_helper_r(hl); -ansi_helper_r(kw); -ansi_helper(imm_int); -ansi_helper(imm_float); -ansi_helper(imm_str); -ansi_helper(var); -ansi_helper(buf); -ansi_helper(fn); -ansi_helper(type); +styled_helper(hl, Highlight); +styled_helper(kw, Keyword); +styled_helper(imm_int, ImmInt); +styled_helper(imm_float, ImmFloat); +styled_helper(imm_str, ImmString); +styled_helper(buf, Buffer); +styled_helper(fn, Function); +styled_helper(type, Type); template -Ansi IRPrinter::typep(const T &t) { - return {t, ansi ? "\033[34m(" : "(", ansi ? ")\033[0m" : ")"}; +StyledText IRPrinter::var(const T &t) { + // The variables of the loops over GPU threads stand out. + IRPrinterStyle style = IRPrinterStyle::Var; + if (t == ".thread_id_x") { + style = IRPrinterStyle::GPUThreadX; + } else if (t == ".thread_id_y") { + style = IRPrinterStyle::GPUThreadY; + } else if (t == ".thread_id_z") { + style = IRPrinterStyle::GPUThreadZ; + } + return {t, this, style}; } template -Ansi IRPrinter::paren(const T &t, bool bold, int depth) { +StyledText IRPrinter::paren(const T &t, bool bold) { + return {t, this, bold ? IRPrinterStyle::BoldParen : IRPrinterStyle::Paren}; +} + +void IRPrinter::begin_style(IRPrinterStyle style) const { if (!ansi) { - return {t, nullptr, nullptr}; - } - if (depth == -1) { - depth = paren_depth; - } - const char *open = ""; - if (bold) { - // clang-format off - switch (depth % 6) { - case 0: open = "\033[91;1m"; break; - case 1: open = "\033[92;1m"; break; - case 2: open = "\033[93;1m"; break; - case 3: open = "\033[94;1m"; break; - case 4: open = "\033[95;1m"; break; - case 5: open = "\033[96;1m"; break; - default: break; - } - // clang-format on + return; + } + // A simple palette using standard VGA colors, indexed by IRPrinterStyle. + // clang-format off + static const char *const styles[] = { + "\033[4m", // Highlight + "\033[2m", // Dim + "\033[35;1m", // Keyword + "\033[36m", // ImmInt + "\033[96m", // ImmFloat + "\033[32m", // ImmString + "", // Var + "\033[33m", // Buffer + "\033[31m", // Function + "\033[34m", // Type + "\033[31m", // GPUThreadX + "\033[32m", // GPUThreadY + "\033[34m", // GPUThreadZ + }; + static const char *const parens[2][6] = { + {"\033[91m", "\033[92m", "\033[93m", "\033[94m", "\033[95m", "\033[96m"}, + {"\033[91;1m", "\033[92;1m", "\033[93;1m", "\033[94;1m", "\033[95;1m", "\033[96;1m"}}; + // clang-format on + if (style == IRPrinterStyle::Paren || style == IRPrinterStyle::BoldParen) { + stream << parens[style == IRPrinterStyle::BoldParen][paren_depth % 6]; } else { - // clang-format off - switch (depth % 6) { - case 0: open = "\033[91m"; break; - case 1: open = "\033[92m"; break; - case 2: open = "\033[93m"; break; - case 3: open = "\033[94m"; break; - case 4: open = "\033[95m"; break; - case 5: open = "\033[96m"; break; - default: break; - } - // clang-format on + stream << styles[(int)style]; + } +} + +void IRPrinter::end_style(IRPrinterStyle style) const { + if (!ansi) { + return; } - return {t, open, ansi_reset}; + // Immediates and names only have a color, and can be within text that is + // styled otherwise. The other styles end by resetting all attributes. + const bool color_only = style >= IRPrinterStyle::ImmInt && style < IRPrinterStyle::Paren; + stream << (color_only ? "\033[39m" : "\033[0m"); +} + +void IRPrinter::print_type_in_parens(const Type &t) { + begin_style(IRPrinterStyle::Type); + stream << "(" << t << ")"; + end_style(IRPrinterStyle::Type); +} + +void IRPrinter::print_node(const IRNode *node) { + begin_node(node); + node->accept(this); + end_node(node); } void IRPrinter::print(const Expr &ir) { ScopedValue old(implicit_parens, false); - ir.accept(this); + print_node(ir.get()); } void IRPrinter::print_no_parens(const Expr &ir) { ScopedValue old(implicit_parens, true); - ir.accept(this); + print_node(ir.get()); } void IRPrinter::print(const Stmt &ir) { - ir.accept(this); + if (!ir.defined()) { + stream << "(undefined)\n"; + return; + } + print_node(ir.get()); } void IRPrinter::print_summary(const Stmt &ir) { ScopedValue old(is_summary, true); - ir.accept(this); + print_node(ir.get()); +} + +void IRPrinter::print(const LoweredFunc &function) { + if (record) { + record->function_starts.push_back((uint32_t)stream.tellp()); + } + stream << function.linkage << " func " << function.name << " ("; + for (size_t i = 0; i < function.args.size(); i++) { + stream << function.args[i].name; + if (i + 1 < function.args.size()) { + stream << ", "; + } + } + stream << ") {\n"; + print(function.body); + stream << "}\n\n"; +} + +void IRPrinter::print(const Module &m) { + for (const auto &s : m.submodules()) { + print(s); + stream << "\n"; + } + + // The module retains implied features, but print it in minimal form. + stream << "module name=" << m.name() << ", target=" << m.target().without_implied_features().to_string() << "\n"; + for (const auto &b : m.buffers()) { + stream << b << "\n"; + } + for (const auto &f : m.functions()) { + print(f); + stream << "\n"; + } +} + +void IRPrinter::begin_node(const IRNode *node) { + if (record) { + const uint32_t at = (uint32_t)stream.tellp(); + record->locations.push_back({node, at, at, at, current_location}); + current_location = (int)record->locations.size() - 1; + } +} + +void IRPrinter::end_node(const IRNode *) { + if (record) { + IRPrinterRecord::Location &l = record->locations[current_location]; + l.end = (uint32_t)stream.tellp(); + current_location = l.parent; + } +} + +void IRPrinter::anchor() { + if (record && current_location >= 0) { + record->locations[current_location].anchor = (uint32_t)stream.tellp(); + } +} + +namespace { + +// Turn the locations recorded while printing text into a source map of it. +// If the text is that of a Module, m is set. +StmtSourceMap make_source_map(string text, const IRPrinterRecord &record, const Module *m) { + StmtSourceMap result; + result.text = std::move(text); + const string &t = result.text; + + vector line_starts{0}; + for (uint32_t i = 0; i < (uint32_t)t.size(); i++) { + if (t[i] == '\n') { + line_starts.push_back(i + 1); + } + } + auto line_of = [&](uint32_t offset) { + return (uint32_t)(std::upper_bound(line_starts.begin(), line_starts.end(), offset) - line_starts.begin()); + }; + + // Offsets usually sit on indentation or on the space in front of an + // operator. Point at the first thing actually printed instead. + auto line_and_column = [&](uint32_t offset, uint32_t &line, uint32_t &column) { + while (offset < t.size() && (t[offset] == ' ' || t[offset] == '\n')) { + offset++; + } + line = line_of(offset); + column = offset - line_starts[line - 1] + 1; + }; + + // The end is just past the last thing printed, which is usually a + // newline. + auto end_line = [&](uint32_t start, uint32_t end) { + while (end > start && (t[end - 1] == ' ' || t[end - 1] == '\n')) { + end--; + } + return line_of(end > start ? end - 1 : start); + }; + + result.locations.resize(record.locations.size()); + for (size_t i = 0; i < record.locations.size(); i++) { + const IRPrinterRecord::Location &r = record.locations[i]; + StmtSourceMap::Location &l = result.locations[i]; + l.node = r.node; + l.start = r.start; + l.end = r.end; + l.order = (uint32_t)i + 1; + line_and_column(r.anchor, l.line, l.column); + l.end_line = end_line(l.start, l.end); + } + std::sort(result.locations.begin(), result.locations.end(), + [](const StmtSourceMap::Location &a, const StmtSourceMap::Location &b) { + return a.node != b.node ? std::less<>()(a.node, b.node) : a.start < b.start; + }); + + // Nodes nested in one another can share an anchor, e.g. a Block and its + // first Stmt. The innermost one began printing last, or ended first. + result.by_anchor.resize(result.locations.size()); + for (uint32_t i = 0; i < (uint32_t)result.by_anchor.size(); i++) { + result.by_anchor[i] = i; + } + std::sort(result.by_anchor.begin(), result.by_anchor.end(), [&](uint32_t i, uint32_t j) { + const StmtSourceMap::Location &a = result.locations[i], &b = result.locations[j]; + return std::tie(a.line, a.column, b.start, a.end) < std::tie(b.line, b.column, a.start, b.end); + }); + + if (m) { + // The functions of submodules are printed first, so those of the + // Module itself are the last ones. + const size_t n = m->functions().size(); + internal_assert(record.function_starts.size() >= n); + result.functions.resize(n); + for (size_t i = 0; i < n; i++) { + StmtSourceMap::Function &f = result.functions[i]; + f.name = m->functions()[i].name; + f.start = record.function_starts[record.function_starts.size() - n + i]; + line_and_column(f.start, f.line, f.column); + } + } + return result; +} + +} // namespace + +StmtSourceMap print_with_source_map(const Module &m) { + std::ostringstream stream; + IRPrinterRecord record; + IRPrinter printer(stream); + printer.record = &record; + printer.print(m); + return make_source_map(std::move(stream).str(), record, &m); +} + +StmtSourceMap print_with_source_map(const Stmt &s) { + std::ostringstream stream; + IRPrinterRecord record; + IRPrinter printer(stream); + printer.record = &record; + printer.print(s); + return make_source_map(std::move(stream).str(), record, nullptr); +} + +const StmtSourceMap::Location *StmtSourceMap::find(const IRNode *node, uint32_t parent_start) const { + auto it = std::lower_bound(locations.begin(), locations.end(), parent_start, + [&](const Location &l, uint32_t start) { + return l.node != node ? std::less<>()(l.node, node) : l.start < start; + }); + if (it != locations.end() && it->node == node) { + return &*it; + } + if (it != locations.begin() && (it - 1)->node == node) { + return &*(it - 1); + } + return nullptr; +} + +const StmtSourceMap::Location *StmtSourceMap::at(uint32_t line, uint32_t column) const { + auto it = std::lower_bound(by_anchor.begin(), by_anchor.end(), std::make_pair(line, column), + [&](uint32_t i, const std::pair &lc) { + return std::make_pair(locations[i].line, locations[i].column) < lc; + }); + if (it != by_anchor.end() && locations[*it].line == line && locations[*it].column == column) { + return &locations[*it]; + } + return nullptr; +} + +std::vector map_locations(const StmtSourceMap &from, const StmtSourceMap &to) { + // Walk the locations of from in the order they were printed, which visits + // each node before the nodes nested in it. + std::vector order(from.locations.size()); + for (uint32_t i = 0; i < (uint32_t)order.size(); i++) { + order[i] = i; + } + std::sort(order.begin(), order.end(), [&](uint32_t i, uint32_t j) { + const StmtSourceMap::Location &a = from.locations[i], &b = from.locations[j]; + return a.start != b.start ? a.start < b.start : a.end > b.end; + }); + + std::vector result(from.locations.size(), nullptr); + // The enclosing nodes of the current one. + std::vector stack; + for (uint32_t i : order) { + const StmtSourceMap::Location &l = from.locations[i]; + while (!stack.empty() && from.locations[stack.back()].end < l.end) { + stack.pop_back(); + } + const StmtSourceMap::Location *parent = stack.empty() ? nullptr : result[stack.back()]; + const StmtSourceMap::Location *found = to.find(l.node, parent ? parent->start : 0); + result[i] = found ? found : parent; + stack.push_back(i); + } + return result; } void IRPrinter::print_list(const std::vector &exprs) { @@ -724,15 +922,21 @@ void IRPrinter::visit(const IntImm *op) { if (op->type == Int(32)) { stream << imm_int(op->value); } else { - stream << ansi_imm_int << op->value << "_i" << op->type.bits() << ansi_reset; + begin_style(IRPrinterStyle::ImmInt); + stream << op->value << "_i" << op->type.bits(); + end_style(IRPrinterStyle::ImmInt); } } void IRPrinter::visit(const UIntImm *op) { if (op->type.bits() == 1) { - stream << ansi_imm_int << (op->value ? "true" : "false") << ansi_reset; + begin_style(IRPrinterStyle::ImmInt); + stream << (op->value ? "true" : "false"); + end_style(IRPrinterStyle::ImmInt); } else { - stream << ansi_imm_int << op->value << "_u" << op->type.bits() << ansi_reset; + begin_style(IRPrinterStyle::ImmInt); + stream << op->value << "_u" << op->type.bits(); + end_style(IRPrinterStyle::ImmInt); } } @@ -742,7 +946,7 @@ void IRPrinter::visit(const FloatImm *op) { stream << std::scientific; } - stream << ansi_imm_float; + begin_style(IRPrinterStyle::ImmFloat); switch (op->type.bits()) { case 64: @@ -758,7 +962,7 @@ void IRPrinter::visit(const FloatImm *op) { internal_error << "Bad bit-width for float: " << op->type << "\n"; } - stream << ansi_reset; + end_style(IRPrinterStyle::ImmFloat); if (use_scientific_format) { stream << std::fixed; @@ -766,7 +970,7 @@ void IRPrinter::visit(const FloatImm *op) { } void IRPrinter::visit(const StringImm *op) { - stream << ansi_imm_str; + begin_style(IRPrinterStyle::ImmString); stream << "\""; for (unsigned char c : op->value) { if (c >= ' ' && c <= '~' && c != '\\' && c != '"') { @@ -796,7 +1000,7 @@ void IRPrinter::visit(const StringImm *op) { } } stream << "\""; - stream << ansi_reset; + end_style(IRPrinterStyle::ImmString); } void IRPrinter::visit(const Cast *op) { @@ -820,9 +1024,10 @@ void IRPrinter::visit(const Variable *op) { if (op->type.is_handle()) { stream << type(op->type); } else { - stream << typep(op->type); + print_type_in_parens(op->type); } } + anchor(); stream << var(op->name); } @@ -855,44 +1060,33 @@ void IRPrinter::closef() { paren_depth--; } -void IRPrinter::visit(const Add *op) { +void IRPrinter::print_binary(const Expr &a, const char *op, const Expr &b) { open(); - print(op->a); - stream << paren(" + "); - print(op->b); + print(a); + anchor(); + stream << paren(op); + print(b); close(); } +void IRPrinter::visit(const Add *op) { + print_binary(op->a, " + ", op->b); +} + void IRPrinter::visit(const Sub *op) { - open(); - print(op->a); - stream << paren(" - "); - print(op->b); - close(); + print_binary(op->a, " - ", op->b); } void IRPrinter::visit(const Mul *op) { - open(); - print(op->a); - stream << paren("*"); - print(op->b); - close(); + print_binary(op->a, "*", op->b); } void IRPrinter::visit(const Div *op) { - open(); - print(op->a); - stream << paren("/"); - print(op->b); - close(); + print_binary(op->a, "/", op->b); } void IRPrinter::visit(const Mod *op) { - open(); - print(op->a); - stream << paren(" % "); - print(op->b); - close(); + print_binary(op->a, " % ", op->b); } void IRPrinter::visit(const Min *op) { @@ -912,67 +1106,35 @@ void IRPrinter::visit(const Max *op) { } void IRPrinter::visit(const EQ *op) { - open(); - print(op->a); - stream << paren(" == "); - print(op->b); - close(); + print_binary(op->a, " == ", op->b); } void IRPrinter::visit(const NE *op) { - open(); - print(op->a); - stream << paren(" != "); - print(op->b); - close(); + print_binary(op->a, " != ", op->b); } void IRPrinter::visit(const LT *op) { - open(); - print(op->a); - stream << paren(" < "); - print(op->b); - close(); + print_binary(op->a, " < ", op->b); } void IRPrinter::visit(const LE *op) { - open(); - print(op->a); - stream << paren(" <= "); - print(op->b); - close(); + print_binary(op->a, " <= ", op->b); } void IRPrinter::visit(const GT *op) { - open(); - print(op->a); - stream << paren(" > "); - print(op->b); - close(); + print_binary(op->a, " > ", op->b); } void IRPrinter::visit(const GE *op) { - open(); - print(op->a); - stream << paren(" >= "); - print(op->b); - close(); + print_binary(op->a, " >= ", op->b); } void IRPrinter::visit(const And *op) { - open(); - print(op->a); - stream << paren(" && "); - print(op->b); - close(); + print_binary(op->a, " && ", op->b); } void IRPrinter::visit(const Or *op) { - open(); - print(op->a); - stream << paren(" || "); - print(op->b); - close(); + print_binary(op->a, " || ", op->b); } void IRPrinter::visit(const Not *op) { @@ -1000,18 +1162,19 @@ void IRPrinter::visit(const Load *op) { stream << kw("streaming "); } if (!known_type.contains(op->name)) { - stream << typep(op->type); + print_type_in_parens(op->type); } paren_depth++; + anchor(); stream << buf(op->name) << paren("["); print_no_parens(op->index); if (show_alignment) { - stream << ansi_dim; + begin_style(IRPrinterStyle::Dim); stream << " aligned(" << imm_int(op->alignment.modulus) << ", " << imm_int(op->alignment.remainder) << ")"; - stream << ansi_reset; + end_style(IRPrinterStyle::Dim); } stream << paren("]"); paren_depth--; @@ -1032,10 +1195,10 @@ void IRPrinter::visit(const Ramp *op) { } void IRPrinter::visit(const Broadcast *op) { - stream << ansi_kw; + begin_style(IRPrinterStyle::Keyword); stream << "x" << op->lanes; stream << "("; - stream << ansi_reset; + end_style(IRPrinterStyle::Keyword); paren_depth++; print_no_parens(op->value); paren_depth--; @@ -1045,25 +1208,13 @@ void IRPrinter::visit(const Broadcast *op) { void IRPrinter::visit(const Call *op) { if (op->is_intrinsic(Call::bitwise_or)) { - open(); - print(op->args[0]); - stream << paren(" | "); - print(op->args[1]); - close(); + print_binary(op->args[0], " | ", op->args[1]); } else if (op->is_intrinsic(Call::bitwise_and)) { - open(); - print(op->args[0]); - stream << paren(" & "); - print(op->args[1]); - close(); + print_binary(op->args[0], " & ", op->args[1]); } else if (op->is_intrinsic(Call::bitwise_xor)) { - open(); - print(op->args[0]); - stream << paren(" ^ "); - print(op->args[1]); - close(); + print_binary(op->args[0], " ^ ", op->args[1]); } else if (op->is_intrinsic(Call::bitwise_not)) { - stream << ansi_kw << "~(" << ansi_reset; + stream << kw("~("); paren_depth++; print_no_parens(op->args[0]); paren_depth--; @@ -1076,9 +1227,10 @@ void IRPrinter::visit(const Call *op) { if (op->type.is_handle()) { stream << type(op->type); // Already has parens } else { - stream << typep(op->type); + print_type_in_parens(op->type); } } + anchor(); openf(op->name.c_str()); print_list(op->args); closef(); @@ -1166,6 +1318,7 @@ void IRPrinter::visit(const Acquire *op) { } void IRPrinter::print_lets(const Let *let) { + begin_node(let); stream << get_indent(); ScopedBinding<> bind(known_type, let->name); stream << kw("let ") << var(let->name) << kw(" = "); @@ -1180,6 +1333,7 @@ void IRPrinter::print_lets(const Let *let) { print_no_parens(let->body); stream << "\n"; } + end_node(let); } void IRPrinter::print_braced_stmt(const Stmt &stmt, int extra_indent) { @@ -1215,12 +1369,12 @@ void IRPrinter::visit(const Store *op) { stream << buf(op->name) << paren("["); print_no_parens(op->index); if (show_alignment) { - stream << ansi_dim; + begin_style(IRPrinterStyle::Dim); stream << " aligned(" << imm_int(op->alignment.modulus) << ", " << imm_int(op->alignment.remainder) << ")"; - stream << ansi_reset; + end_style(IRPrinterStyle::Dim); } stream << paren("] = "); if (const Let *let = op->value.as()) { @@ -1417,34 +1571,34 @@ void IRPrinter::visit(const Fork *op) { void IRPrinter::visit(const IfThenElse *op) { stream << get_indent(); - while (true) { - stream << paren("if ("); - print_no_parens(op->condition); - stream << paren(") {\n"); + print_if_chain(op); +} + +void IRPrinter::print_if_chain(const IfThenElse *op) { + stream << paren("if ("); + print_no_parens(op->condition); + stream << paren(") {\n"); + paren_depth++; + indent++; + print(op->then_case); + indent--; + paren_depth--; + + if (const IfThenElse *nested_if = op->else_case.as()) { + stream << get_indent() << paren("} else "); + begin_node(nested_if); + print_if_chain(nested_if); + end_node(nested_if); + return; + } + if (op->else_case.defined()) { + stream << get_indent() << paren("}") << (" else {\n"); paren_depth++; indent++; - print(op->then_case); + print(op->else_case); indent--; paren_depth--; - - if (!op->else_case.defined()) { - break; - } - - if (const IfThenElse *nested_if = op->else_case.as()) { - stream << get_indent() << paren("} else "); - op = nested_if; - } else { - stream << get_indent() << paren("}") << (" else {\n"); - paren_depth++; - indent++; - print(op->else_case); - indent--; - paren_depth--; - break; - } } - stream << get_indent() << paren("}\n"); } @@ -1498,7 +1652,7 @@ void IRPrinter::visit(const Shuffle *op) { } void IRPrinter::visit(const VectorReduce *op) { - stream << typep(op->type); + print_type_in_parens(op->type); paren_depth++; stream << paren("vector_reduce_", false) << paren(op->op, false) << paren("("); print_no_parens(op->value); diff --git a/src/IRPrinter.h b/src/IRPrinter.h index 94a0b08a8d8e..cfcd1c8eb6f7 100644 --- a/src/IRPrinter.h +++ b/src/IRPrinter.h @@ -123,23 +123,128 @@ struct Indentation { }; std::ostream &operator<<(std::ostream &stream, const Indentation &); +/** The kinds of text that IRPrinter styles, e.g. with colors. */ +enum class IRPrinterStyle { + Highlight, + Dim, + Keyword, + ImmInt, + ImmFloat, + ImmString, + Var, + Buffer, + Function, + Type, + /** The variables of the loops over GPU threads: .thread_id_x, + * .thread_id_y and .thread_id_z. */ + GPUThreadX, + GPUThreadY, + GPUThreadZ, + /** Punctuation and operators, styled by how deeply they are nested. */ + Paren, + BoldParen, +}; + +class IRPrinter; + +/** Text that an IRPrinter styles, as made by its kw(), var(), paren(), ... + * helpers. Writing it to a stream writes the text between the printer's + * begin_style() and end_style(). */ template -struct Ansi { +struct StyledText { const T &cnt; - const char *open, *close; + const IRPrinter *printer; + IRPrinterStyle style; }; -template -std::ostream &operator<<(std::ostream &out, const Ansi &a) { - if (a.open) { - out << a.open; - } - out << a.cnt; - if (a.close) { - out << a.close; - } - return out; -} +/** Where an IRPrinter printed things, as byte offsets into its stream. */ +struct IRPrinterRecord { + struct Location { + const IRNode *node; + /** Where printing of the node began. */ + uint32_t start; + /** The node's most telling character, e.g. the operator of a binary + * op. Equal to start for most nodes. */ + uint32_t anchor; + /** Where printing of the node ended. */ + uint32_t end; + /** The index of the location of the node this one is printed + * within, or -1. */ + int parent; + }; + std::vector locations; + + /** Where each LoweredFunc began, in the order they were printed. */ + std::vector function_starts; +}; + +/** The text of a Module or Stmt exactly as operator<< prints it (minus any + * ANSI colors), together with where each IR node in it ended up in that text. + * Debug info uses this to point into the .stmt files. */ +struct StmtSourceMap { + struct Location { + const IRNode *node; + /** Byte offsets at which printing of the node began and ended. A node + * shared by several parents is printed once per parent, this tells + * the copies apart. */ + uint32_t start, end; + /** 1-based line and column of the node's anchor. */ + uint32_t line, column; + /** The place of the node among those printed, in the order they + * began printing, counting from 1. */ + uint32_t order; + /** 1-based line of the last character of the node, e.g. its closing + * brace. */ + uint32_t end_line; + }; + + struct Function { + std::string name; + /** Byte offset of the function header. */ + uint32_t start; + /** 1-based line and column of the function header. */ + uint32_t line, column; + }; + + std::string text; + + /** The file debug info refers to. The text is expected to be written + * there by whoever sets it. */ + std::string path; + + /** Sorted by node, then by start. */ + std::vector locations; + + /** In Module::functions() order. Empty when printing a Stmt. */ + std::vector functions; + + /** Find the printed copy of node that sits under a parent which began + * printing at parent_start: the first copy at or after parent_start, or + * the last copy before it if there is none. Returns nullptr if the node + * was never printed. */ + const Location *find(const IRNode *node, uint32_t parent_start) const; + + /** The location with the given anchor. Of nested nodes that share one, + * the innermost. Returns nullptr if there is none. */ + const Location *at(uint32_t line, uint32_t column) const; + + /** Indices into locations, sorted by line and column, for at(). */ + std::vector by_anchor; +}; + +/** Print a Module the same way operator<< does, without colors, and record + * where all IR nodes of its functions went. */ +StmtSourceMap print_with_source_map(const Module &m); + +/** Print a Stmt the same way operator<< does, without colors, and record + * where all of its IR nodes went. */ +StmtSourceMap print_with_source_map(const Stmt &s); + +/** For each location of from, in from.locations order: the location in to of + * the same IR node, or else that of its nearest enclosing node that to has, or + * else nullptr. Nodes are printed in both when to is a printing of IR that + * from's IR was lowered from, e.g. the conceptual Stmt of a Module. */ +std::vector map_locations(const StmtSourceMap &from, const StmtSourceMap &to); /** An IRVisitor that emits IR to the given output stream in a human * readable form. Can be subclassed if you want to modify the way in @@ -167,6 +272,22 @@ class IRPrinter : public IRVisitor { * trailing punctuation. */ void print_list(const std::vector &exprs); + /** Emit a LoweredFunc on the output stream */ + void print(const LoweredFunc &); + + /** Emit a Module on the output stream */ + void print(const Module &); + + /** Called before and after text of the given style is emitted. By + * default, these emit the colors of the style, if the output stream is a + * terminal. */ + virtual void begin_style(IRPrinterStyle style) const; + virtual void end_style(IRPrinterStyle style) const; + + /** If set, where every node and LoweredFunc is printed gets noted here, + * as offsets into the stream, which must support tellp(). */ + IRPrinterRecord *record = nullptr; + protected: Indentation get_indent() const { return Indentation{indent}; @@ -191,33 +312,33 @@ class IRPrinter : public IRVisitor { bool ansi = false; int paren_depth = 0; - const char *ansi_hl = ""; - const char *ansi_dim = ""; - const char *ansi_kw = ""; - const char *ansi_imm_int = ""; - const char *ansi_imm_float = ""; - const char *ansi_imm_str = ""; - const char *ansi_var = ""; - const char *ansi_buf = ""; - const char *ansi_fn = ""; - const char *ansi_type = ""; - const char *ansi_reset_col = ""; - const char *ansi_reset = ""; + /** The index in record->locations of the node being printed, or -1. */ + int current_location = -1; + + /** Mark the current stream position as the anchor of the node being + * printed. */ + void anchor(); // clang-format off - template Ansi hl(const T &t); - template Ansi kw(const T &t); - template Ansi imm_int(const T &t); - template Ansi imm_float(const T &t); - template Ansi imm_str(const T &t); - template Ansi var(const T &t); - template Ansi buf(const T &t); - template Ansi fn(const T &t); - template Ansi type(const T &t); - template Ansi typep(const T &t); - template Ansi paren(const T &t, bool bold = true, int d = -1); + template StyledText hl(const T &t); + template StyledText kw(const T &t); + template StyledText imm_int(const T &t); + template StyledText imm_float(const T &t); + template StyledText imm_str(const T &t); + template StyledText var(const T &t); + template StyledText buf(const T &t); + template StyledText fn(const T &t); + template StyledText type(const T &t); + template StyledText paren(const T &t, bool bold = true); // clang-format on + /** Emits a type in parentheses, styled as a type */ + void print_type_in_parens(const Type &); + + /** Emits a binary operator between its operands, in parentheses unless + * implicit_parens is set */ + void print_binary(const Expr &a, const char *op, const Expr &b); + /** Either emits "(" or "", depending on the value of implicit_parens */ void open(); @@ -240,6 +361,10 @@ class IRPrinter : public IRVisitor { /** A helper for printing a chain of lets with line breaks */ void print_lets(const Let *let); + /** A helper for printing an if statement from its "if" on, and the ifs + * chained in as its else case with it */ + void print_if_chain(const IfThenElse *op); + /** A helper for printing a braced statement */ void print_braced_stmt(const Stmt &, int extra_indent = 2); @@ -293,8 +418,25 @@ class IRPrinter : public IRVisitor { void visit(const StreamingStore *) override; void visit(const StreamingLoads *) override; void visit(const HoistedStorage *) override; + + /** Called before and after an Expr or Stmt is emitted. By default, + * these note where it went in record, if that is set. */ + virtual void begin_node(const IRNode *node); + virtual void end_node(const IRNode *node); + +private: + /** Emit a node, between begin_node() and end_node(). */ + void print_node(const IRNode *); }; +template +std::ostream &operator<<(std::ostream &out, const StyledText &a) { + a.printer->begin_style(a.style); + out << a.cnt; + a.printer->end_style(a.style); + return out; +} + /** Debugging helpers for interactive debuggers (LLDB/GDB). * * These render a value with the IR printer and return the resulting string, so diff --git a/src/JITModule.cpp b/src/JITModule.cpp index 2aa7d111d3c8..3c167920280f 100644 --- a/src/JITModule.cpp +++ b/src/JITModule.cpp @@ -17,6 +17,7 @@ #include "CodeGen_Internal.h" #include "CodeGen_LLVM.h" #include "Debug.h" +#include "IRPrinter.h" #include "JITModule.h" #include "LLVM_Headers.h" #include "LLVM_Output.h" @@ -340,10 +341,49 @@ JITModule::JITModule() { jit_module = new JITModuleContents(); } +namespace { + +// Debug info of JIT-compiled code points into a .stmt file in the temp +// directory, named after its contents so that recompiling the same pipeline +// reuses it. +std::string write_jit_stmt_file(const std::string &module_name, const std::string &text, const std::string &extension) { + llvm::MD5 md5; + md5.update(text); + llvm::MD5::MD5Result digest = md5.final(); + llvm::SmallString<32> checksum; + llvm::MD5::stringifyResult(digest, checksum); + + llvm::SmallString<256> path; + llvm::sys::path::system_temp_directory(/* ErasedOnReboot */ true, path); + llvm::sys::path::append(path, "halide-jit-" + module_name + "-" + checksum.str().substr(0, 16).str() + extension); + if (!llvm::sys::fs::exists(path)) { + std::error_code error; + llvm::raw_fd_ostream out(path, error); + if (error) { + debug(1) << "Could not write " << path.str().str() << ": " << error.message() << "\n"; + } else { + out << text; + } + } + debug(1) << "Debug info of JIT module " << module_name << " refers to " << path.str().str() << "\n"; + return path.str().str(); +} + +} // namespace + JITModule::JITModule(const Module &m, const LoweredFunc &fn, const std::vector &dependencies) { jit_module = new JITModuleContents(); - std::unique_ptr llvm_module(compile_module_to_llvm_module(m, *jit_module->context)); + std::optional debug_source; + if (m.target().has_feature(Target::DebugSymbols)) { + debug_source = print_with_source_map(m); + debug_source->path = write_jit_stmt_file(m.name(), debug_source->text, ".stmt"); + } else if (m.target().has_feature(Target::DebugSymbolsConceptual)) { + debug_source = print_with_source_map(m.get_conceptual_stmt()); + debug_source->path = write_jit_stmt_file(m.name(), debug_source->text, ".conceptual.stmt"); + } + std::unique_ptr llvm_module( + compile_module_to_llvm_module(m, *jit_module->context, debug_source ? &*debug_source : nullptr)); std::vector deps_with_runtime = dependencies; std::vector shared_runtime = JITSharedRuntime::get(llvm_module.get(), m.target()); deps_with_runtime.insert(deps_with_runtime.end(), shared_runtime.begin(), shared_runtime.end()); @@ -422,9 +462,13 @@ void compile_module_impl( llvm::jitlink::JITLinkMemoryManager & #endif ) { - return std::make_unique(session, [&](const llvm::MemoryBuffer &) { + auto layer = std::make_unique(session, [&](const llvm::MemoryBuffer &) { return std::make_unique(dependencies); }); + if (target.has_feature(Target::DebugSymbols) || target.has_feature(Target::DebugSymbolsConceptual)) { + layer->registerJITEventListener(*llvm::JITEventListener::createGDBRegistrationListener()); + } + return layer; }; } else { linkerBuilder = [](llvm::orc::ExecutionSession &session @@ -447,6 +491,30 @@ void compile_module_impl( .setObjectLinkingLayerCreator(linkerBuilder) .create()); + if ((target.has_feature(Target::DebugSymbols) || target.has_feature(Target::DebugSymbolsConceptual)) && + llvm::isa(JIT->getObjLinkingLayer())) { + // Tell debuggers about the code, through the GDB JIT interface. The + // function that registers it with the debugger is looked up among the + // symbols of the process, which do not include it when LLVM is linked + // statically, so define it there. It is also exported from libHalide + // (see exported_symbols.ldscript/.osx) for lookups that go through + // dlsym. + if (llvm::orc::JITDylibSP process = JIT->getProcessSymbolsJITDylib()) { + llvm::orc::SymbolMap symbols; + symbols[JIT->mangleAndIntern("llvm_orc_registerJITLoaderGDBAllocAction")] = + llvm::orc::ExecutorSymbolDef(llvm::orc::ExecutorAddr::fromPtr(&llvm_orc_registerJITLoaderGDBAllocAction), + llvm::JITSymbolFlags::Exported); + if (llvm::Error error = process->define(llvm::orc::absoluteSymbols(std::move(symbols)))) { + debug(1) << "Could not define the debugger registration function for JIT code: " + << llvm::toString(std::move(error)) << "\n"; + } + } + if (llvm::Error error = llvm::orc::enableDebuggerSupport(*JIT)) { + debug(1) << "Could not enable debugger support for JIT code: " + << llvm::toString(std::move(error)) << "\n"; + } + } + auto ctors = llvm::orc::getConstructors(*m); llvm::orc::CtorDtorRunner ctorRunner(JIT->getMainJITDylib()); ctorRunner.add(ctors); diff --git a/src/LLVM_Headers.h b/src/LLVM_Headers.h index 980db363bd64..c17492c2ce91 100644 --- a/src/LLVM_Headers.h +++ b/src/LLVM_Headers.h @@ -36,13 +36,19 @@ #include #include #include +#include +#include #include #include #include +#include #include #include #include +#include #include +#include +#include #include #include #include @@ -79,6 +85,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/LLVM_Output.cpp b/src/LLVM_Output.cpp index 5381016cc44a..956aaedc9fd6 100644 --- a/src/LLVM_Output.cpp +++ b/src/LLVM_Output.cpp @@ -428,8 +428,9 @@ void emit_file(const llvm::Module &module_in, Internal::LLVMOStream &out, } // namespace -std::unique_ptr compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) { - return codegen_llvm(module, context); +std::unique_ptr compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context, + const Internal::StmtSourceMap *debug_source) { + return codegen_llvm(module, context, debug_source); } void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream &out) { diff --git a/src/LLVM_Output.h b/src/LLVM_Output.h index 768b3c6d713d..a234e0777d5c 100644 --- a/src/LLVM_Output.h +++ b/src/LLVM_Output.h @@ -25,10 +25,16 @@ struct Target; namespace Internal { typedef llvm::raw_pwrite_stream LLVMOStream; -} +struct StmtSourceMap; +} // namespace Internal -/** Generate an LLVM module. */ -std::unique_ptr compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context); +/** Generate an LLVM module. If debug_source is set, it gets debug info that + * points into it, which must be a printing of the module or of its + * conceptual Stmt (see print_with_source_map). If it is null, targets with a + * debug symbols feature get debug info that points into a printing made + * here, and refers to a file named after the module. */ +std::unique_ptr compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context, + const Internal::StmtSourceMap *debug_source = nullptr); /** Construct an llvm output stream for writing to files. */ std::unique_ptr make_raw_fd_ostream(const std::string &filename); diff --git a/src/Lower.cpp b/src/Lower.cpp index 58b8f8bdb989..8f160d7443df 100644 --- a/src/Lower.cpp +++ b/src/Lower.cpp @@ -147,6 +147,29 @@ class LoweringLogger { } }; +// Rebuild every node of s, so that no node is used in more than one place. +// Rebuilding the nodes that have no IR in them forces all others to be +// rebuilt too. +Stmt copy_shared_nodes(const Stmt &s) { + return mutate_with( + s, + [](auto *self, const IntImm *op) { return IntImm::make(op->type, op->value); }, + [](auto *self, const UIntImm *op) { return UIntImm::make(op->type, op->value); }, + [](auto *self, const FloatImm *op) { return FloatImm::make(op->type, op->value); }, + [](auto *self, const StringImm *op) { return StringImm::make(op->value); }, + [](auto *self, const Variable *op) { + return Variable::make(op->type, op->name, op->image, op->param, op->reduction_domain); + }, + [](auto *self, const Call *op) -> Expr { + if (op->args.empty()) { + return Call::make(op->type, op->name, op->args, op->call_type, op->func, + op->value_index, op->image, op->param); + } + return self->visit_base(op); + }, + [](auto *self, const Free *op) { return Free::make(op->name); }); +} + void lower_impl(const vector &output_funcs, const string &pipeline_name, const Target &t, @@ -514,6 +537,12 @@ void lower_impl(const vector &output_funcs, } } + // The html outputs and the debug symbols say where code came from by the + // IR node of the stmt it was made from, which must then be printed in one + // place only. + s = copy_shared_nodes(s); + log("Lowering after copying shared IR nodes:", s); + // Make a copy of the Stmt code, before we lower anything to less human-readable code. result_module.set_conceptual_code_stmt(s); debug(1) << "Lowering after reaching conceptual Stmt:\n" diff --git a/src/Module.cpp b/src/Module.cpp index a4f2290c812f..9c4bfd0dc434 100644 --- a/src/Module.cpp +++ b/src/Module.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include "CodeGen_C.h" @@ -14,6 +15,7 @@ #include "Debug.h" #include "HexagonOffload.h" #include "IROperator.h" +#include "IRPrinter.h" #include "LLVM_Headers.h" #include "LLVM_Output.h" #include "LLVM_Runtime_Linker.h" @@ -614,10 +616,24 @@ void Module::compile(const std::map &output_files) TemporaryFileDir temp_assembly_dir; + // Debug info can point into the stmt, or into the conceptual stmt. + const bool conceptual_debug_symbols = target().has_feature(Target::DebugSymbolsConceptual); + const bool debug_symbols = target().has_feature(Target::DebugSymbols) || conceptual_debug_symbols; + const bool html = contains(output_files, OutputFileType::stmt_html) || + contains(output_files, OutputFileType::conceptual_stmt_html); + std::string assembly_path; if (contains(output_files, OutputFileType::assembly)) { assembly_path = output_files.at(OutputFileType::assembly); - } else if (contains(output_files, OutputFileType::stmt_html) || contains(output_files, OutputFileType::conceptual_stmt_html)) { + } + + // The html shows which assembly came from which line of IR, according to + // the debug info in it. Without the debug_symbols feature, only that + // assembly gets debug info, so it can't double as the assembly output. + std::string html_assembly_path; + if (html && debug_symbols && !assembly_path.empty()) { + html_assembly_path = assembly_path; + } else if (html) { // We need assembly in order to generate stmt_html, but the user doesn't // want it on its own, so we will generate it to a temp directory, since some // build systems (e.g. Bazel) are strict about what you can generate to the 'expected' @@ -625,22 +641,66 @@ void Module::compile(const std::map &output_files) std::string path; if (contains(output_files, OutputFileType::stmt_html)) { path = output_files.at(OutputFileType::stmt_html); - } else if (contains(output_files, OutputFileType::conceptual_stmt_html)) { - path = output_files.at(OutputFileType::conceptual_stmt_html); } else { - internal_error << "A html file path is required to determine the output of the temporary assembly file.\n"; + path = output_files.at(OutputFileType::conceptual_stmt_html); + } + html_assembly_path = temp_assembly_dir.add_temp_file(path, + get_output_info(target()).at(OutputFileType::assembly).extension, + target()); + debug(1) << "Module.compile(): creating temp file for assembly output at " << html_assembly_path << "\n"; + } + + // Debug info points into the stmt (or conceptual stmt) output. If that + // isn't requested, it points to where it would go if it were: next to the + // compiled code. + auto stmt_path = [&](OutputFileType stmt) { + if (contains(output_files, stmt)) { + return output_files.at(stmt); + } + const auto info = get_output_info(target()); + for (OutputFileType t : {OutputFileType::object, OutputFileType::static_library, + OutputFileType::assembly, OutputFileType::bitcode, + OutputFileType::llvm_assembly, OutputFileType::stmt_html, + OutputFileType::conceptual_stmt_html}) { + if (contains(output_files, t)) { + std::string path = output_files.at(t); + const std::string &extension = info.at(t).extension; + if (ends_with(path, extension)) { + path.resize(path.size() - extension.size()); + } + return path + info.at(stmt).extension; + } } - assembly_path = temp_assembly_dir.add_temp_file(path, - get_output_info(target()).at(OutputFileType::assembly).extension, - target()); - debug(1) << "Module.compile(): creating temp file for assembly output at " << assembly_path << "\n"; + return name() + info.at(stmt).extension; + }; + std::optional debug_source; + if (debug_symbols || html) { + debug_source = Internal::print_with_source_map(*this); + debug_source->path = stmt_path(OutputFileType::stmt); + } + std::optional conceptual_source; + if (conceptual_debug_symbols || contains(output_files, OutputFileType::conceptual_stmt_html)) { + conceptual_source = Internal::print_with_source_map(get_conceptual_stmt()); + conceptual_source->path = stmt_path(OutputFileType::conceptual_stmt); } if (contains(output_files, OutputFileType::object) || contains(output_files, OutputFileType::assembly) || contains(output_files, OutputFileType::bitcode) || contains(output_files, OutputFileType::llvm_assembly) || - contains(output_files, OutputFileType::static_library) || !assembly_path.empty()) { + contains(output_files, OutputFileType::static_library) || !html_assembly_path.empty()) { llvm::LLVMContext context; - std::unique_ptr llvm_module(compile_module_to_llvm_module(*this, context)); + const Internal::StmtSourceMap *source = conceptual_debug_symbols ? &*conceptual_source : + debug_source ? &*debug_source : + nullptr; + std::unique_ptr llvm_module(compile_module_to_llvm_module(*this, context, source)); + + if (!html_assembly_path.empty() && html_assembly_path != assembly_path) { + debug(1) << "Module.compile(): assembly for html " << html_assembly_path << "\n"; + auto out = make_raw_fd_ostream(html_assembly_path); + compile_llvm_module_to_assembly(*llvm_module, *out); + } + if (html && !debug_symbols) { + llvm::StripDebugInfo(*llvm_module); + } if (contains(output_files, OutputFileType::object)) { const auto &f = output_files.at(OutputFileType::object); @@ -669,7 +729,6 @@ void Module::compile(const std::map &output_files) Target base_target(target().os, target().arch, target().bits, target().processor_tune); create_static_library(temp_object_dir.files(), base_target, output_files.at(OutputFileType::static_library)); } - // Don't use contains() here, we might need assembly output for stmt_html if (!assembly_path.empty()) { debug(1) << "Module.compile(): assembly " << assembly_path << "\n"; auto out = make_raw_fd_ostream(assembly_path); @@ -690,24 +749,32 @@ void Module::compile(const std::map &output_files) if (contains(output_files, OutputFileType::stmt)) { debug(1) << "Module.compile(): stmt " << output_files.at(OutputFileType::stmt) << "\n"; std::ofstream file(output_files.at(OutputFileType::stmt)); - file << *this; + if (debug_source) { + file << debug_source->text; + } else { + file << *this; + } } if (contains(output_files, OutputFileType::conceptual_stmt)) { debug(1) << "Module.compile(): conceptual_stmt " << output_files.at(OutputFileType::conceptual_stmt) << "\n"; std::ofstream file(output_files.at(OutputFileType::conceptual_stmt)); - file << get_conceptual_stmt(); + if (conceptual_source) { + file << conceptual_source->text; + } else { + file << get_conceptual_stmt(); + } } if (contains(output_files, OutputFileType::stmt_html)) { - internal_assert(!assembly_path.empty()); debug(1) << "Module.compile(): stmt_html " << output_files.at(OutputFileType::stmt_html) << "\n"; Internal::print_to_stmt_html(output_files.at(OutputFileType::stmt_html), - *this, assembly_path); + *this, html_assembly_path, *debug_source, + conceptual_debug_symbols ? &*conceptual_source : nullptr); } if (contains(output_files, OutputFileType::conceptual_stmt_html)) { - internal_assert(!assembly_path.empty()); debug(1) << "Module.compile(): conceptual_stmt_html " << output_files.at(OutputFileType::conceptual_stmt_html) << "\n"; Internal::print_to_conceptual_stmt_html(output_files.at(OutputFileType::conceptual_stmt_html), - *this, assembly_path); + *this, html_assembly_path, *debug_source, *conceptual_source, + conceptual_debug_symbols); } if (contains(output_files, OutputFileType::device_code)) { debug(1) << "Module.compile(): device_code " << output_files.at(OutputFileType::device_code) << "\n"; diff --git a/src/StmtToHTML.cpp b/src/StmtToHTML.cpp index b0987c86cb6f..aacc010505ff 100644 --- a/src/StmtToHTML.cpp +++ b/src/StmtToHTML.cpp @@ -1,20 +1,17 @@ #include "StmtToHTML.h" #include "Debug.h" #include "Error.h" -#include "IROperator.h" #include "IRPrinter.h" #include "IRVisitor.h" #include "Module.h" -#include "Scope.h" -#include "Substitute.h" #include "Util.h" -#include +#include +#include #include -#include -#include -#include +#include #include +#include #include // Setting this to 0 is meant to speed up the development iteration cycle. @@ -28,2377 +25,422 @@ #include #endif -extern "C" unsigned char halide_html_template_StmtToHTML_dependencies_html[]; extern "C" unsigned char halide_html_template_StmtToHTML_css[]; extern "C" unsigned char halide_html_template_StmtToHTML_js[]; namespace Halide { namespace Internal { -// Classes defined within this file -class CostModel; -class AssemblyInfo; -template -class HTMLCodePrinter; -class PipelineHTMLInspector; - -/** IRCostModel - * A basic cost model for Halide IR. Estimates computation - * cost through simple op-counting and data-movement cost - * by counting the number of bits being moved. - */ -class IRCostModel : public IRVisitor { -public: - IRCostModel() = default; - - // Pre-compute all costs to avoid repeated work - void compute_all_costs(const Module &m) { - // Compute all node costs - for (const auto &fn : m.functions()) { - fn.body.accept(this); - } - } - - void compute_conceptual_costs(const Module &m) { - m.get_conceptual_stmt().accept(this); - } - - void finalize_cost_computation() { - // Compute the max cost for each category - max_compute_cost = -1; - for (auto const &entry : compute_cost) { - max_compute_cost = std::max(entry.second, max_compute_cost); - } - - max_data_cost = -1; - for (auto const &entry : data_cost) { - max_data_cost = std::max(entry.second, max_data_cost); - } - - max_compute_cost_inclusive = -1; - for (auto const &entry : compute_cost_inclusive) { - max_compute_cost_inclusive = std::max(entry.second, max_compute_cost_inclusive); - } - - max_data_cost_inclusive = -1; - for (auto const &entry : data_cost_inclusive) { - max_data_cost_inclusive = std::max(entry.second, max_data_cost_inclusive); - } - } - - // Returns the compute cost of a node (estimated using simple op-counting) - int get_compute_cost(const IRNode *node, bool include_subtree_cost) { - internal_assert(node != nullptr) << "IRCostModel::get_compute_cost(): node is nullptr\n"; - - int cost = -1; - if (compute_cost.count(node)) { - cost = include_subtree_cost ? compute_cost_inclusive[node] : compute_cost[node]; - } else { - internal_error << "IRCostModel::get_compute_cost(): cost lookup failed\n"; - } - - internal_assert(cost >= 0) << "Cost must not be negative.\n"; - return cost; - } - - // Returns the data movement cost of a node (the number of bits moved in load/store/shuffle ops) - int get_data_movement_cost(const IRNode *node, bool include_subtree_cost) { - internal_assert(node != nullptr) << "IRCostModel::get_data_movement_cost(): node is nullptr\n"; - - int cost = -1; - if (compute_cost.count(node)) { - cost = include_subtree_cost ? data_cost_inclusive[node] : data_cost[node]; - } else { - internal_error << "IRCostModel::get_data_movement_cost(): cost lookup failed\n"; - } - - internal_assert(cost >= 0) << "Cost cost must not be negative.\n"; - return cost; - } - - // Returns the max compute cost of any node in the program - int get_max_compute_cost(bool include_subtree_cost) { - return include_subtree_cost ? max_compute_cost_inclusive : max_compute_cost; - } - - // Returns the max data movement cost of any node in the program - int get_max_data_movement_cost(bool include_subtree_cost) { - return include_subtree_cost ? max_data_cost_inclusive : max_data_cost; - } - -private: - // Cost database. We track two costs: - // - The line cost of a node is the sum of the node cost - // plus the cost of any children that are printed on - // a single line (since we display cost by each line in - // the program) - // - The inclusive cost is the cost of the entire sub-tree. - // We display this cost when the user collapses a program - // block in the IR. - std::map compute_cost; - std::map data_cost; - - std::map compute_cost_inclusive; - std::map data_cost_inclusive; - - // We also track the max costs to determine the cost color - // intensity for a given line of code - int max_compute_cost = -1; - int max_data_cost = -1; - - int max_compute_cost_inclusive = -1; - int max_data_cost_inclusive = -1; - - /* Utility functions to store node costs in the cost database */ - void set_compute_costs(const IRNode *node, int node_cost, const std::vector &child_nodes) { - set_compute_costs(node, node_cost, child_nodes, child_nodes); - } - - void set_compute_costs(const IRNode *node, int node_cost, const std::vector &child_nodes, const std::vector &inline_child_nodes) { - int subtree_cost = 0; - for (const IRNode *child_node : child_nodes) { - // Certain child nodes can be null. Ex: else-case - // in an if statement - if (child_node) { - subtree_cost += get_compute_cost(child_node, true); - } - } - - int line_cost = node_cost; - for (const IRNode *child_node : inline_child_nodes) { - if (child_node) { - line_cost += get_compute_cost(child_node, true); - } - } - - compute_cost[node] = line_cost; - compute_cost_inclusive[node] = node_cost + subtree_cost; - } - - void set_data_costs(const IRNode *node, int node_cost, const std::vector &child_nodes) { - set_data_costs(node, node_cost, child_nodes, child_nodes); - } - - void set_data_costs(const IRNode *node, int node_cost, const std::vector &child_nodes, const std::vector &inline_child_nodes) { - int subtree_cost = 0; - for (const IRNode *child_node : child_nodes) { - // Certain child nodes can be null. Ex: else-case - // in an if statement - if (child_node) { - subtree_cost += get_data_movement_cost(child_node, true); - } - } - - int line_cost = node_cost; - for (const IRNode *child_node : inline_child_nodes) { - if (child_node) { - line_cost += get_data_movement_cost(child_node, true); - } - } - - data_cost[node] = line_cost; - data_cost_inclusive[node] = node_cost + subtree_cost; - } - - /* Visitor functions for each IR node */ - using IRVisitor::visit; - - void visit(const IntImm *op) override { - set_compute_costs(op, 0, {}); - set_data_costs(op, 0, {}); - } - - void visit(const UIntImm *op) override { - set_compute_costs(op, 0, {}); - set_data_costs(op, 0, {}); - } - - void visit(const FloatImm *op) override { - set_compute_costs(op, 0, {}); - set_data_costs(op, 0, {}); - } - - void visit(const StringImm *op) override { - set_compute_costs(op, 0, {}); - set_data_costs(op, 0, {}); - } - - void visit(const Variable *op) override { - set_compute_costs(op, 0, {}); - set_data_costs(op, 0, {}); - } - - void visit(const Cast *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->value.get()}); - set_data_costs(op, 0, {op->value.get()}); - } - - void visit(const Reinterpret *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->value.get()}); - set_data_costs(op, 0, {op->value.get()}); - } - - void visit(const Add *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Sub *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Mul *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Div *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Mod *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Min *op) override { - IRVisitor::visit(op); - // This cost model treats min as a single op - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Max *op) override { - IRVisitor::visit(op); - // This cost model treats max as a single op - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const EQ *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const NE *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const LT *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const LE *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const GT *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const GE *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const And *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Or *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get(), op->b.get()}); - set_data_costs(op, 0, {op->a.get(), op->b.get()}); - } - - void visit(const Not *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->a.get()}); - set_data_costs(op, 0, {op->a.get()}); - } - - void visit(const Select *op) override { - IRVisitor::visit(op); - set_compute_costs(op, op->type.lanes(), {op->condition.get(), op->true_value.get(), op->false_value.get()}); - set_data_costs(op, 0, {op->condition.get(), op->true_value.get(), op->false_value.get()}); - } - - void visit(const Load *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->predicate.get(), op->index.get()}); - set_data_costs(op, op->type.bits() * op->type.lanes(), {op->predicate.get(), op->index.get()}); - } - - void visit(const Ramp *op) override { - // The cost of a Ramp is higher when the stride is not 1, - // but currently the cost model does not consider such cases - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->base.get(), op->stride.get()}); - set_data_costs(op, 0, {op->base.get(), op->stride.get()}); - } - - void visit(const Broadcast *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 1, {op->value.get()}); - set_data_costs(op, 0, {op->value.get()}); - } - - void visit(const Call *op) override { - IRVisitor::visit(op); - std::vector args; - args.reserve(op->args.size()); - for (const auto &arg : op->args) { - args.push_back(arg.get()); - } - set_compute_costs(op, 1, args); - // Currently there is no special handling - // for intrinsics such as `prefetch` - set_data_costs(op, 0, args); - } - - void visit(const Let *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->value.get(), op->body.get()}); - set_data_costs(op, 0, {op->value.get(), op->body.get()}); - } - - void visit(const Shuffle *op) override { - IRVisitor::visit(op); - std::vector args; - args.reserve(op->vectors.size()); - for (const auto &arg : op->vectors) { - args.push_back(arg.get()); - } - set_compute_costs(op, 0, args); - set_data_costs(op, op->type.bits() * op->type.lanes(), args); - } - - void visit(const VectorReduce *op) override { - IRVisitor::visit(op); - const int factor = op->value.type().lanes() / op->type.lanes(); - const int op_count = op->type.lanes() * (factor - 1); - set_compute_costs(op, op_count, {op->value.get()}); - set_data_costs(op, 0, {op->value.get()}); - } - - void visit(const LetStmt *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->value.get(), op->body.get()}, {op->value.get()}); - set_data_costs(op, 0, {op->value.get(), op->body.get()}, {op->value.get()}); - } - - void visit(const AssertStmt *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 1, {op->condition.get()}); - set_data_costs(op, 0, {op->condition.get()}); - } - - void visit(const ProducerConsumer *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->body.get()}, {}); - set_data_costs(op, 0, {op->body.get()}, {}); - } - - void visit(const For *op) override { - // The cost of a loop-node essentially depends on its iteration - // count. The cost model currently ignores such costs. - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->min.get(), op->max.get(), op->body.get()}, {op->min.get(), op->max.get()}); - set_data_costs(op, 0, {op->min.get(), op->max.get(), op->body.get()}, {op->min.get(), op->max.get()}); - } - - void visit(const Acquire *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 1, {op->semaphore.get(), op->count.get(), op->body.get()}, {op->semaphore.get(), op->count.get()}); - set_data_costs(op, 0, {op->semaphore.get(), op->count.get(), op->body.get()}, {op->semaphore.get(), op->count.get()}); - } - - void visit(const Store *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->predicate.get(), op->value.get(), op->index.get()}); - set_data_costs(op, op->value.type().bits() * op->value.type().lanes(), {op->predicate.get(), op->value.get(), op->index.get()}); - } - - void visit(const Provide *op) override { - IRVisitor::visit(op); - std::vector args; - args.reserve(op->values.size() + op->args.size() + 1); - for (const auto &arg : op->values) { - args.push_back(arg.get()); - } - for (const auto &arg : op->args) { - args.push_back(arg.get()); - } - args.push_back(op->predicate.get()); - set_compute_costs(op, 0, args, {}); - set_data_costs(op, 0, args, {}); - } - - void visit(const Allocate *op) override { - // We do not model allocation/de-allocation costs - IRVisitor::visit(op); - std::vector args_inline; - args_inline.reserve(op->extents.size() + 2); - for (const auto &arg : op->extents) { - args_inline.push_back(arg.get()); - } - args_inline.push_back(op->new_expr.get()); - std::vector args = args_inline; - args.push_back(op->body.get()); - set_compute_costs(op, 0, args, args_inline); - set_data_costs(op, 0, args, args_inline); - } - - void visit(const Free *op) override { - // We do not model allocation/de-allocation costs - IRVisitor::visit(op); - set_compute_costs(op, 0, {}); - set_data_costs(op, 0, {}); - } - - void visit(const Realize *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->condition.get(), op->body.get()}, {op->condition.get()}); - set_data_costs(op, 0, {op->condition.get(), op->body.get()}, {op->condition.get()}); - } - - void visit(const Prefetch *op) override { - IRVisitor::visit(op); - std::vector args_inline; - for (const auto &arg : op->bounds) { - args_inline.push_back(arg.min.get()); - } - args_inline.push_back(op->condition.get()); - std::vector args = args_inline; - args.push_back(op->body.get()); - set_compute_costs(op, 0, args); - int elem_size = 0; - for (const auto &etype : op->types) { - elem_size += etype.bits() * etype.lanes(); - } - set_data_costs(op, elem_size, args, args_inline); - } - - void visit(const Block *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->first.get(), op->rest.get()}, {}); - set_data_costs(op, 0, {op->first.get(), op->rest.get()}, {}); - } - - void visit(const Fork *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->first.get(), op->rest.get()}, {}); - set_data_costs(op, 0, {op->first.get(), op->rest.get()}, {}); - } - - void visit(const IfThenElse *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 1, {op->condition.get(), op->then_case.get()}, {op->condition.get()}); - set_data_costs(op, 0, {op->condition.get(), op->then_case.get()}, {op->condition.get()}); - } - - void visit(const Evaluate *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->value.get()}); - set_data_costs(op, 0, {op->value.get()}); - } - - void visit(const Atomic *op) override { - IRVisitor::visit(op); - set_compute_costs(op, 0, {op->body.get()}, {}); - set_data_costs(op, 0, {op->body.get()}, {}); - } -}; - -/** GetAssemblyInfo - * Used to map some Halide IR nodes to line-numbers in the - * assembly file containing the corresponding generated code. - */ -class AssemblyInfo : public IRVisitor { -public: - AssemblyInfo() = default; - - void gather_nodes_from_functions(const Module &m) { - // Traverse the module to populate the list of - // nodes we need to map and generate their assembly - // markers (comments that appear in the assembly code - // associating the code with this node) - ids_are_known = true; - for (const auto &fn : m.functions()) { - fn.body.accept(this); - } - } - - void gather_nodes_from_conceptual_stmt(const Module &m) { - // Traverse the module's conceptual Stmt to populate the list of - // nodes we need to map and generate their assembly - // markers (comments that appear in the assembly code - // associating the code with this node) - ids_are_known = false; - m.get_conceptual_stmt().accept(this); - } - - void generate(std::string_view code) { - // Find markers in asm code - int lno = 1; - size_t start = 0; - - std::vector matched_nodes; - while (start < code.size()) { - size_t end = code.find('\n', start); - if (end == std::string_view::npos) { - end = code.size(); - } - std::string_view line = code.substr(start, end - start); - std::string_view marker_prefix("%\"", 2); - - // Quick check if the line contains %". - if (line.find(marker_prefix) != std::string_view::npos) { - // Try all markers - matched_nodes.clear(); - for (auto const &[node, marker] : markers) { - if (std::regex_search(line.begin(), line.end(), marker)) { - // Save line number - lnos[node] = lno; - // Save this node's id - matched_nodes.push_back(node); - } - } - // We map to the first match, stop - // checking matched nodes - for (auto const &node : matched_nodes) { - markers.erase(node); - } - } - - start = end + 1; - lno++; - } - } - - int get_asm_lno(uint64_t node_id) { - if (lnos.count(node_id)) { - return lnos[node_id]; - } - return -1; - } - - std::string get_label(uint64_t node_id) { - if (labels.count(node_id)) { - return labels[node_id]; - } - return "(label not found)"; - } - -private: - // Generate asm markers for Halide loops - bool ids_are_known{true}; - int loop_id = 0; - int gen_loop_id() { - return ++loop_id; - } - - std::string gen_loop_asm_marker(int id, const std::string &loop_var) { - std::regex dollar("\\$"); - std::string marker = "%\""; - if (ids_are_known) { - marker += std::to_string(id); - } else { - marker += "\\d+"; - } - marker += "_for_" + loop_var; - marker = std::regex_replace(marker, dollar, "\\$"); - return marker; - } - - // Generate asm markers for Halide producer/consumer nodes - int prodcons_id = 0; - int gen_prodcons_id() { - return ++prodcons_id; - } - - std::string gen_prodcons_asm_marker(int id, const std::string &var, bool is_producer) { - std::regex dollar("\\$"); - std::string marker = "%\""; - if (ids_are_known) { - marker += std::to_string(id); - } else { - marker += "\\d+"; - } - marker += (is_producer ? "_produce_" : "_consume_") + var; - marker = std::regex_replace(marker, dollar, "\\$"); - return marker; - } - - // Mapping of IR nodes to their asm markers - std::map markers; - std::map labels; - - // Mapping of IR nodes to their asm line numbers - std::map lnos; - - using IRVisitor::visit; - - void visit(const ProducerConsumer *op) override { - // Generate asm marker - std::string marker = gen_prodcons_asm_marker(gen_prodcons_id(), op->name, op->is_producer); - markers[(uint64_t)op] = std::regex(marker); - labels[(uint64_t)op] = marker; - // Continue traversal - IRVisitor::visit(op); - } - - void visit(const For *op) override { - // Generate asm marker - std::string marker = gen_loop_asm_marker(gen_loop_id(), op->name); - markers[(uint64_t)op] = std::regex(marker); - labels[(uint64_t)op] = marker; - // Continue traversal - IRVisitor::visit(op); - } -}; - -/** HTMLCodePrinter - * Prints IR code in HTML. Very similar to generating a stmt - * file, except that the generated html is more interactive. - */ -template -class HTMLCodePrinter : public IRVisitor { -public: - HTMLCodePrinter(T &os, std::map &nids, bool enable_assembly_features) - : stream(os), node_ids(nids), context_stack(1, 0), - enable_assembly_features(enable_assembly_features) { - } - - // Make class non-copyable and non-moveable - HTMLCodePrinter(const HTMLCodePrinter &) = delete; - HTMLCodePrinter &operator=(const HTMLCodePrinter &) = delete; - - void init_cost_info(IRCostModel cm) { - cost_model = std::move(cm); - } - - void print_conceptual_stmt(const Module &m, AssemblyInfo host_asm_info, AssemblyInfo device_asm_info) { - host_assembly_info = std::move(host_asm_info); - device_assembly_info = std::move(device_asm_info); - - // Generate a unique ID for this module - int id = gen_unique_id(); - - // Enter new scope for this module - scope.push(m.name(), id); - - // Open div to hold this module - print_opening_tag("div", "Module"); - - // Generate the show hide icon/text buttons - print_show_hide_btn_begin(id); - - // -- print text - print_opening_tag("span", "matched"); - print_html_element("span", "keyword", "module"); - // The module retains implied features, but print it in minimal form. - print_text(" name=" + m.name() + ", target=" + m.target().without_implied_features().to_string()); - print_closing_tag("span"); - - // Open code block to hold module body - print_opening_brace(); - print_show_hide_btn_end(nullptr); - - // Open indented div to hold body code - print_opening_tag("div", "indent ModuleBody", "", id); - - print(m.get_conceptual_stmt()); - - // Close indented div holding body code - print_closing_tag("div"); - - // Close code block holding module body - print_html_element("span", "matched ClosingBrace cb-" + std::to_string(id), "}"); - - // Close div holding this module - print_closing_tag("div"); - - // Pop out to outer scope - scope.pop(m.name()); - } - - void print(const Module &m, AssemblyInfo host_asm_info, AssemblyInfo device_asm_info) { - host_assembly_info = std::move(host_asm_info); - device_assembly_info = std::move(device_asm_info); - - // Generate a unique ID for this module - int id = gen_unique_id(); - - // Enter new scope for this module - scope.push(m.name(), id); - - // The implementation doesn't need to support submodules: - // we only call this for Modules that have already had their submodules - // resolved. - internal_assert(m.submodules().empty()) << "StmtToHTML does not support submodules."; - - // Open div to hold this module - print_opening_tag("div", "Module"); - - // Generate the show hide icon/text buttons - print_show_hide_btn_begin(id); - - // -- print text - print_opening_tag("span", "matched"); - print_html_element("span", "keyword", "module"); - // The module retains implied features, but print it in minimal form. - print_text(" name=" + m.name() + ", target=" + m.target().without_implied_features().to_string()); - print_closing_tag("span"); - - // Open code block to hold module body - print_opening_brace(); - print_show_hide_btn_end(nullptr); - - // Open indented div to hold body code - print_opening_tag("div", "indent ModuleBody", "", id); - - // Print module buffers - for (const auto &buf : m.buffers()) { - print(buf); - } - - // Print module functions - for (const auto &fn : m.functions()) { - print(fn); - } - - // Close indented div holding body code - print_closing_tag("div"); - - // Close code block holding module body - print_html_element("span", "matched ClosingBrace cb-" + std::to_string(id), "}"); - - // Close div holding this module - print_closing_tag("div"); - - // Pop out to outer scope - scope.pop(m.name()); - } - - std::string escape_html(std::string src) { - src = replace_all(std::move(src), "&", "&"); - src = replace_all(std::move(src), "<", "<"); - src = replace_all(std::move(src), ">", ">"); - src = replace_all(std::move(src), "\"", """); - src = replace_all(std::move(src), "/", "/"); - src = replace_all(std::move(src), "'", "'"); - return src; - } - - // CUDA kernels are embedded into modules as PTX assembly. This - // routine pretty - prints that assembly format. - void print_cuda_gpu_source_kernels(const std::string &str) { - print_opening_tag("div", "code ptx"); - - int current_id = -1; - int brace_depth = 0; // Counting the inline asm braces. - bool in_func_signature = false; - - std::string current_kernel; - std::istringstream ss(str); - - for (std::string line; std::getline(ss, line);) { - if (line.empty() || line == "\t") { - stream << "\n"; - continue; - } - bool indent = false; - if (line[0] == '\t') { - // Replace first tab with four spaces. - line = line.substr(1); - indent = true; - } - line = escape_html(line); - - bool should_print_open_indent = false; - - if (starts_with(line, ".visible .entry")) { - std::vector parts = split_string(line, " "); - if (parts.size() == 3) { - in_func_signature = true; - brace_depth = 0; - current_id = gen_unique_id(); - print_show_hide_btn_begin(current_id); - std::string kernel_name = parts[2].substr(0, parts[2].length() - 1); - line = ".visible .entry "; - line += kernel_name + " ("; - current_kernel = kernel_name; - } - } else if (starts_with(line, ")") && in_func_signature) { - in_func_signature = false; - line = ")" + line.substr(1); - } else if (starts_with(line, "{") && brace_depth <= 0) { - print_opening_brace(); - brace_depth = 1; - internal_assert(current_id != -1); - should_print_open_indent = true; - current_id = -1; - line = line.substr(1); - scope.push(current_kernel, gen_unique_id()); - } else if (starts_with(line, "{") && brace_depth) { - brace_depth++; - } else if (starts_with(line, "}") && (--brace_depth <= 0)) { - print_closing_tag("div"); - line = "}" + line.substr(1); - brace_depth = 0; - scope.pop(current_kernel); - } - - line = replace_all(std::move(line), ".f32", ".f32"); - line = replace_all(std::move(line), ".f64", ".f64"); - - line = replace_all(std::move(line), ".s8", ".s8"); - line = replace_all(std::move(line), ".s16", ".s16"); - line = replace_all(std::move(line), ".s32", ".s32"); - line = replace_all(std::move(line), ".s64", ".s64"); - - line = replace_all(std::move(line), ".u8", ".u8"); - line = replace_all(std::move(line), ".u16", ".u16"); - line = replace_all(std::move(line), ".u32", ".u32"); - line = replace_all(std::move(line), ".u64", ".u64"); - - line = replace_all(std::move(line), ".b8", ".b8"); - line = replace_all(std::move(line), ".b16", ".b16"); - line = replace_all(std::move(line), ".b32", ".b32"); - line = replace_all(std::move(line), ".b64", ".b64"); - - line = replace_all(std::move(line), ".v2", ".v2"); - line = replace_all(std::move(line), ".v4", ".v4"); - - line = replace_all(std::move(line), "ld.", "ld."); - line = replace_all(std::move(line), "st.", "st."); - - size_t idx; - if ((idx = line.find("//")) != std::string::npos) { - line.insert(idx, ""); - line += ""; - } - - // Predicated instructions - if (!line.empty() && line.front() == '@' && indent) { - idx = line.find(' '); - std::string pred = line.substr(1, idx - 1); - line = "@" + variable(pred, Bool()) + "" + line.substr(idx); - } - - // Labels (depending on the LLVM version we get L with or without a dollar) - if (starts_with(line, "$L_") && !indent && (idx = line.find(':')) != std::string::npos) { - std::string label = line.substr(0, idx); - line = "" + variable(label, "Label") + ":" + line.substr(idx + 1); - } - - // Highlight operands - if ((idx = line.find(" \t")) != std::string::npos && line.back() == ';') { - std::string operands_str = line.substr(idx + 2); - operands_str = operands_str.substr(0, operands_str.length() - 1); - std::vector operands = split_string(operands_str, ", "); - operands_str = ""; - for (size_t opidx = 0; opidx < operands.size(); ++opidx) { - const std::string &op = operands[opidx]; - internal_assert(!op.empty()); - if (opidx != 0) { - operands_str += ", "; - } - if (op.back() == '}') { - std::string reg = op.substr(0, op.size() - 1); - operands_str += variable(reg, "reg") + '}'; - } else if (op.front() == '%') { - operands_str += variable(op, ""); - } else if (op.find_first_not_of("-0123456789") == std::string::npos) { - operands_str += ""; - operands_str += op; - operands_str += ""; - } else if (starts_with(op, "0f") && - op.find_first_not_of("0123456789ABCDEF", 2) == std::string::npos) { - operands_str += ""; - operands_str += op; - operands_str += ""; - } else if (op.front() == '[' && op.back() == ']') { - size_t idx = op.find('+'); - if (idx == std::string::npos) { - std::string reg = op.substr(1, op.size() - 2); - operands_str += '[' + variable(reg, "reg") + ']'; - } else { - std::string reg = op.substr(1, idx - 1); - std::string offset = op.substr(idx + 1); - offset = offset.substr(0, offset.size() - 1); - operands_str += '[' + variable(reg, "reg") + "+"; - operands_str += ""; - operands_str += offset; - operands_str += ""; - operands_str += ']'; - } - } else if (op.front() == '{') { - std::string reg = op.substr(1); - operands_str += '{' + variable(reg, "reg"); - } else if (starts_with(op, "$L_")) { - // Labels - operands_str += "" + variable(op, "Label") + ""; - } else { - operands_str += op; - } - } - operands_str += ";"; - // NOLINTNEXTLINE(performance-inefficient-string-concatenation) - line = line.substr(0, idx + 2) + operands_str; - } - - stream << ""; - if (indent) { - stream << " "; - } - stream << line << "\n"; - - // Indent-divs can only be opened after the line is finished. - if (should_print_open_indent) { - print_show_hide_btn_end(nullptr); - print_opening_tag("div", "indent", "", current_id); - } - } - print_closing_tag("div"); - } - -private: - // Handle to output file stream - T &stream; - - // Used to generate unique ids - int id = 0; - std::map &node_ids; - - // Used to track scope during IR traversal - Scope scope; - - /* All spans and divs will have an id of the form "x-y", where x - * is shared among all spans/divs in the same context, and y is unique. - * These variables are used to track the context within generated HTML */ - std::vector context_stack; - std::vector context_stack_tags; - - // Holds cost information for visualized program - IRCostModel cost_model; - AssemblyInfo host_assembly_info; - AssemblyInfo device_assembly_info; - bool enable_assembly_features; - - /* Private print functions to handle various IR types */ - void print(const Buffer<> &buf) { - // Open div to hold this buffer - print_opening_tag("div", "Buffer"); - - // Print buffer name and move on - print_html_element("span", "keyword", "buffer "); - print_variable(buf.name(), buf.type()); - - // Close div holding this buffer - print_closing_tag("div"); - } - - void print(const LoweredFunc &fn) { - // Generate a unique ID for this function - int id = gen_unique_id(); - - // Enter new scope for this function - scope.push(fn.name, id); - - // Open div to hold this buffer - print_opening_tag("div", "Function"); - - // Generate the show hide icon/text buttons - print_show_hide_btn_begin(id); - - // -- print text (fn name and args) - print_opening_tag("span", "matched"); - print_html_element("span", "keyword ", "func ", "lowered-func-" + fn.name); - print_text(fn.name + "("); - print_closing_tag("span"); - print_fndecl_args(fn.args); - print_html_element("span", "matched", ")"); - - // Open code block to hold function body - print_opening_brace(); - print_show_hide_btn_end(nullptr); - - // Open indented div to hold body code - print_opening_tag("div", "indent FunctionBody", "", id); - - // Print function body - print(fn.body); - - // Close indented div holding body code - print_closing_tag("div"); - - // Close code block holding func body - print_html_element("span", "matched ClosingBrace cb-" + std::to_string(id), "}"); - - // Close div holding this function - print_closing_tag("div"); - - // Pop out to outer scope - scope.pop(fn.name); - } - - void print(const Expr &ir) { - static int depth = 0; - depth++; - print_opening_tag("span", "expr-depth-" + std::to_string(depth)); - ir.accept(this); - print_closing_tag("span"); - depth--; - } - - void print(const Stmt &ir) { - ir.accept(this); - } - - std::string type_to_string(Type t) { - std::ostringstream ss; - ss << t; - return ss.str(); - } - - /* Methods used to emit common HTML patterns */ - - // Prints the opening tag for the specified html element. A unique ID is - // auto-generated unless provided. - void print_opening_tag(const std::string &tag, const std::string &cls, const std::string &tooltip = "", int id = -1) { - stream << "<" << tag << " class='" << cls << "'"; - if (!tooltip.empty()) { - stream << " title='" << tooltip << "'"; - } - stream << " id='"; - if (id == -1) { - stream << context_stack.back() << "-"; - stream << gen_unique_id(); - } else { - stream << id; - } - stream << "'>"; - context_stack.push_back(gen_unique_id()); - context_stack_tags.push_back(tag); - } - - // Prints the closing tag for the specified html element. - void print_closing_tag(const std::string &tag) { - internal_assert(!context_stack.empty() && tag == context_stack_tags.back()) - << "closing tag: " << tag << ", stack size: " << context_stack.size() << ", last element: " << (context_stack_tags.empty() ? "null" : context_stack_tags.back()); - context_stack.pop_back(); - context_stack_tags.pop_back(); - stream << ""; - } - - // Prints an html element: opening tag, body and closing tag - void print_html_element(const std::string &tag, const std::string &cls, const std::string &body, const std::string &tooltip = "", int id = -1) { - print_opening_tag(tag, cls, tooltip, id); - stream << body; - print_closing_tag(tag); - } - - void print_opening_brace() { - print_html_element("span", "matched OpeningBrace", "{"); - } - - void print_closing_brace() { - print_html_element("span", "matched ClosingBrace", "}"); - } - - // Prints the opening/closing tags for an anchor that toggles code block view - void print_show_hide_btn_begin(int id, bool collapsed = false) { - stream << ""; - stream << "
"; - if (op) { - print_assembly_button(op); - } - stream << "
"; - } - - // Prints newline to stream - void print_ln() { - stream << "\n"; - } - - // Prints a variable to stream - void print_variable(const std::string &x, Type type) { - stream << variable(x, type); - } - - std::string variable(const std::string &x, const std::string &tooltip) { - int id; - if (const int *i = scope.find(x)) { - id = *i; - } else { - id = gen_unique_id(); - scope.push(x, id); - } - std::ostringstream s; - s << "" << x << ""; - return s.str(); - } - - std::string variable(const std::string &x, Type type) { - return variable(x, type_to_string(type)); - } - - // Prints text to stream - void print_text(const std::string &x) { - stream << x; - } - - // Prints a button to sync text with visualization - void print_assembly_button(const void *op) { - if (!enable_assembly_features) { - return; - } - { - int asm_lno = host_assembly_info.get_asm_lno((uint64_t)op); - if (asm_lno != -1) { - stream << "
" - << "Jump to Host Assembly" - << "" << host_assembly_info.get_label((uint64_t)op) << "" - << "
"; - } - } - { - int asm_lno = device_assembly_info.get_asm_lno((uint64_t)op); - if (asm_lno != -1) { - stream << "
" - << "Jump to Device Code" - << "" << device_assembly_info.get_label((uint64_t)op) << "" - << "
"; - } - } - } - - // Prints the args in a function declaration - void print_fndecl_args(const std::vector &args) { - bool print_delim = false; - for (const auto &arg : args) { - if (print_delim) { - print_html_element("span", "matched", ","); - print_text(" "); - } - print_variable(arg.name, arg.type); - print_delim = true; - } - } - - /* Helper functions for printing IR nodes */ - void print_constant(const std::string &cls, const Expr &c) { - print_opening_tag("span", cls, type_to_string(c.type())); - stream << c; - print_closing_tag("span"); - } - - void print_type(Type t) { - print_opening_tag("span", "Type"); - stream << t; - print_closing_tag("span"); - } - - void print_binary_op(const Expr &a, const Expr &b, const std::string &op, Type result_type) { - std::string result_type_str = type_to_string(result_type); - print_opening_tag("span", "BinaryOp"); - print_html_element("span", "matched", "(", result_type_str); - print(a); - print_text(" "); - print_html_element("span", "matched Operator", op, result_type_str); - print_text(" "); - print(b); - print_html_element("span", "matched", ")", result_type_str); - print_closing_tag("span"); - } - - void print_function_call(const std::string &fn_name, const std::vector &args, const std::string &tooltip) { - print_html_element("span", "Symbol matched", fn_name + "(", tooltip); - bool print_delim = false; - for (const auto &arg : args) { - if (print_delim) { - print_html_element("span", "matched", ", "); - } - print(arg); - print_delim = true; - } - print_html_element("span", "matched", ")", tooltip); - } - - // To avoid generating ridiculously deep DOMs, we flatten blocks here. - void print_block_stmt(const Stmt &stmt) { - for (const Stmt &s : Block::to_vector(stmt)) { - print(s); - } - } - - // We also flatten forks - void visit_fork_stmt(const Stmt &stmt) { - if (const Fork *f = stmt.as()) { - visit_fork_stmt(f->first); - visit_fork_stmt(f->rest); - } else if (stmt.defined()) { - // Give task a unique id - int id = gen_unique_id(); - - // Start a dive to hold code for this task - print_opening_tag("div", "ForkTask"); - - // Generate the show hide icon/text buttons - print_show_hide_btn_begin(id); - - // -- print text - print_html_element("span", "keyword matched", "task"); - - // Open code block to hold task body - print_opening_brace(); - print_show_hide_btn_end(nullptr); - - // Open indented div to hold body code - print_opening_tag("div", "indent ForkTask", "", id); - - // Print task body - print(stmt); - - // Close indented div holding body code - print_closing_tag("div"); - - // Close code block holding task body - print_html_element("span", "matched ClosingBrace cb-" + std::to_string(id), "}"); - - // Close div holding this fork task - print_closing_tag("div"); - } - } - - // Prints compute and data cost buttons/indicators - void print_cost_buttons(const IRNode *op) { - int id = gen_node_id(op); - print_cost_buttons(op, id); - } - - void print_cost_buttons(const IRNode *op, int id) { - print_opening_tag("div", "node-cost"); - print_compute_cost(op, id); - print_data_movement_cost(op, id); - print_closing_tag("div"); - } - - // Prints the button/indicator for the compute cost of a line in the program - void print_compute_cost(const IRNode *op, int id) { - int max_line_cost = cost_model.get_max_compute_cost(false); - int max_block_cost = cost_model.get_max_compute_cost(true); - int line_cost = cost_model.get_compute_cost(op, false); - int block_cost = cost_model.get_compute_cost(op, true); - if ((op != nullptr) && - ((op->node_type == IRNodeType::LetStmt) || op->node_type == IRNodeType::Allocate)) { - block_cost = line_cost; - } - std::string _id = "cc-" + std::to_string(id); - print_cost_btn(line_cost, block_cost, max_line_cost, max_block_cost, _id, "Op Count: "); - } - - // Prints the button/indicator for the data movement cost of a line in the program - void print_data_movement_cost(const IRNode *op, int id) { - int max_line_cost = cost_model.get_max_data_movement_cost(false); - int max_block_cost = cost_model.get_max_data_movement_cost(true); - int line_cost = cost_model.get_data_movement_cost(op, false); - int block_cost = cost_model.get_data_movement_cost(op, true); - if ((op != nullptr) && - ((op->node_type == IRNodeType::LetStmt) || op->node_type == IRNodeType::Allocate)) { - block_cost = line_cost; - } - std::string _id = "dc-" + std::to_string(id); - print_cost_btn(line_cost, block_cost, max_line_cost, max_block_cost, _id, "Bits Moved: "); - } - - // Prints a cost button/indicator - void print_cost_btn(int line_cost, int block_cost, int max_line_cost, int max_block_cost, const std::string &id, const std::string &prefix) { - const int num_cost_buckets = 20; - const auto compand = [](int v) -> int { return (int)std::sqrt(v * 10); }; - - int max_cost = std::max(max_line_cost, max_block_cost); // This should always be the block cost. - int line_cost_bin_size = (compand(max_cost) / num_cost_buckets) + 1; - int block_cost_bin_size = (compand(max_cost) / num_cost_buckets) + 1; - - int line_costc = compand(line_cost) / line_cost_bin_size; - int block_costc = compand(block_cost) / block_cost_bin_size; - - if (line_costc >= num_cost_buckets) { - line_costc = num_cost_buckets - 1; - } - if (block_costc >= num_cost_buckets) { - block_costc = num_cost_buckets - 1; - } - - std::string line_cost_class; - std::string block_cost_class; - if (line_cost == 0) { - line_cost_class = "CostColorNone"; - } else { - line_cost_class = "CostColor" + std::to_string(line_costc); - } - if (block_cost == 0) { - block_cost_class = "CostColorNone"; - } else { - block_cost_class = "CostColor" + std::to_string(block_costc); - } - if (block_cost == line_cost) { - block_cost_class += " NoChildCost"; - } - - stream << "
"; - - stream << "" - << prefix << line_cost; - if (line_cost != block_cost) { - stream << "
Total " << prefix << block_cost; - } - stream << "
"; - - stream << "
"; - } - - /* Misc utility methods */ - int gen_unique_id() { - return id++; - } - - int gen_node_id(const IRNode *node) { - if (node_ids.count(node) == 0) { - node_ids[node] = gen_unique_id(); - } - return node_ids[node]; - } - - /* All visitor functions inherited from IRVisitor */ - - void visit(const IntImm *op) override { - print_constant("IntImm Imm", Expr(op)); - } - - void visit(const UIntImm *op) override { - print_constant("UIntImm Imm", Expr(op)); - } - - void visit(const FloatImm *op) override { - print_constant("FloatImm Imm", Expr(op)); - } - - void visit(const StringImm *op) override { - print_constant("StringImm Imm", Expr(op)); - } - - void visit(const Variable *op) override { - print_variable(op->name, op->type); - } - - void visit(const Cast *op) override { - std::string type_str = type_to_string(op->type); - print_opening_tag("span", "Cast"); - print_opening_tag("span", "matched"); - print_type(op->type); - print_text("("); - print_closing_tag("span"); - print(op->value); - print_html_element("span", "matched", ")"); - print_closing_tag("span"); - } - - void visit(const Reinterpret *op) override { - std::string type_str = type_to_string(op->type); - print_opening_tag("span", "Reinterpret"); - print_opening_tag("span", "matched Symbol", type_str); - print_text("reinterpret<"); - print_type(op->type); - print_text(">"); - print_closing_tag("span"); - print_html_element("span", "matched", "(", type_str); - print(op->value); - print_html_element("span", "matched", ")", type_str); - print_closing_tag("span"); - } - - void visit(const Add *op) override { - print_binary_op(op->a, op->b, "+", op->type); - } - - void visit(const Sub *op) override { - print_binary_op(op->a, op->b, "-", op->type); - } - - void visit(const Mul *op) override { - print_binary_op(op->a, op->b, "*", op->type); - } - - void visit(const Div *op) override { - print_binary_op(op->a, op->b, "/", op->type); - } - - void visit(const Mod *op) override { - print_binary_op(op->a, op->b, "%", op->type); - } - - void visit(const Min *op) override { - print_function_call("min", {op->a, op->b}, type_to_string(op->type)); - } - - void visit(const Max *op) override { - print_function_call("max", {op->a, op->b}, type_to_string(op->type)); - } - - void visit(const EQ *op) override { - print_binary_op(op->a, op->b, "==", op->type); - } - - void visit(const NE *op) override { - print_binary_op(op->a, op->b, "!=", op->type); - } - - void visit(const LT *op) override { - print_binary_op(op->a, op->b, "<", op->type); - } - - void visit(const LE *op) override { - print_binary_op(op->a, op->b, "<=", op->type); - } - - void visit(const GT *op) override { - print_binary_op(op->a, op->b, ">", op->type); - } - - void visit(const GE *op) override { - print_binary_op(op->a, op->b, ">=", op->type); - } - - void visit(const And *op) override { - print_binary_op(op->a, op->b, "&&", op->type); - } - - void visit(const Or *op) override { - print_binary_op(op->a, op->b, "||", op->type); - } +namespace { - void visit(const Not *op) override { - print_opening_tag("span", "Not"); - print_text("!"); - print(op->a); - print_closing_tag("span"); - } +std::string escape_html(std::string src) { + src = replace_all(std::move(src), "&", "&"); + src = replace_all(std::move(src), "<", "<"); + src = replace_all(std::move(src), ">", ">"); + src = replace_all(std::move(src), "\"", """); + src = replace_all(std::move(src), "/", "/"); + src = replace_all(std::move(src), "'", "'"); + return src; +} - void visit(const Select *op) override { - print_opening_tag("span", "Select"); - print_function_call("select", {op->condition, op->true_value, op->false_value}, type_to_string(op->type)); - print_closing_tag("span"); - } +bool begins_with(std::string_view s, std::string_view prefix) { + return s.substr(0, prefix.size()) == prefix; +} - void visit(const Load *op) override { - std::string type_str = type_to_string(op->type); - int id = gen_node_id(op); - print_opening_tag("span", "Load", "load-" + std::to_string(id)); - print_opening_tag("span", "matched", type_str); - if (op->is_streaming) { - print_html_element("span", "keyword", "streaming "); - } - stream << variable(op->name, type_to_string(op->type) + "*"); - print_text("["); - print_closing_tag("span"); - print(op->index); - if (op->alignment.modulus != 1) { - print_opening_tag("span", "Alignment"); - stream << " aligned(" - << op->alignment.modulus - << ", " - << op->alignment.remainder << ")"; - print_closing_tag("span"); - } - print_html_element("span", "matched", "]", type_str); - if (!is_const_one(op->predicate)) { - print_html_element("span", "keyword", " if "); - print(op->predicate); +// Writes a line of text into a diff --git a/src/runtime/HalideRuntime.h b/src/runtime/HalideRuntime.h index b66bfd39ff48..da41823da139 100644 --- a/src/runtime/HalideRuntime.h +++ b/src/runtime/HalideRuntime.h @@ -1646,7 +1646,10 @@ typedef enum halide_target_feature_t { halide_target_feature_hlsl_sm69, ///< Enable D3D12 Shader Model 6.9 (long vectors 5-1024 lanes, native 16-bit/wave/int64 required) halide_target_feature_no_metadata, ///< Don't emit the _argv() and _metadata() entry points for exported functions, keeping the argument names and target string out of the binary. halide_target_feature_arm64e, ///< Enable Apple ARM64e pointer authentication ABI (requires ARMv8.3a; 64-bit iOS/macOS only). - halide_target_feature_end ///< A sentinel. Every target is considered to have this feature, and setting this feature does nothing. + halide_target_feature_debug_symbols, ///< Emit debug info that maps the generated code to the lines of the .stmt output, so debuggers and profilers can step through and annotate the lowered IR. + /// Like debug_symbols, but map the generated code to the lines of the .conceptual.stmt output instead. + halide_target_feature_debug_symbols_conceptual, + halide_target_feature_end ///< A sentinel. Every target is considered to have this feature, and setting this feature does nothing. } halide_target_feature_t; /** The specific processor a compilation Target can be tuned for. diff --git a/test/correctness/CMakeLists.txt b/test/correctness/CMakeLists.txt index aaad8860ba72..ae473a750ac9 100644 --- a/test/correctness/CMakeLists.txt +++ b/test/correctness/CMakeLists.txt @@ -153,6 +153,7 @@ tests( dead_realization_in_specialization.cpp debug_helpers.cpp debug_log_file.cpp + debug_symbols.cpp debug_to_file.cpp debug_to_file_multiple_outputs.cpp debug_to_file_reorder.cpp diff --git a/test/correctness/debug_symbols.cpp b/test/correctness/debug_symbols.cpp new file mode 100644 index 000000000000..76026f296080 --- /dev/null +++ b/test/correctness/debug_symbols.cpp @@ -0,0 +1,469 @@ +#include "Halide.h" +#include "halide_test_dirs.h" + +#include +#include +#include +#include +#include +#include + +using namespace Halide; + +namespace { + +std::string read_file(const std::string &path) { + std::ifstream in(path); + std::stringstream ss; + ss << in.rdbuf(); + return ss.str(); +} + +std::vector split_lines(const std::string &text) { + std::vector lines; + std::istringstream in(text); + std::string line; + while (std::getline(in, line)) { + lines.push_back(line); + } + return lines; +} + +// The text of each line of IR in an html output, in order of their line +// numbers, which must be consecutive from 1. +bool html_lines(const std::string &html, std::vector &lines) { + // A line may have more classes than 'l', e.g. when it is shaded. + const std::string line_open = "
0) { + if (html.compare(c, 5, "', c) + 1; + } else if (html.compare(c, 7, "") == 0) { + depth--; + c += 7; + } else if (html.compare(c, 5, "&") == 0) { + text += '&'; + c += 5; + } else if (html.compare(c, 4, "<") == 0) { + text += '<'; + c += 4; + } else if (html.compare(c, 4, ">") == 0) { + text += '>'; + c += 4; + } else { + text += html[c++]; + } + } + lines.push_back(text); + } + return true; +} + +bool check_html(const std::string &html_path, const std::string &stmt_path) { + const std::string html = read_file(html_path); + const std::vector stmt_lines = split_lines(read_file(stmt_path)); + std::vector lines; + if (!html_lines(html, lines)) { + return false; + } + if (lines != stmt_lines) { + for (size_t i = 0; i < std::max(lines.size(), stmt_lines.size()); i++) { + std::string a = i < lines.size() ? lines[i] : "(none)"; + std::string b = i < stmt_lines.size() ? stmt_lines[i] : "(none)"; + if (a != b) { + printf("%s line %d is\n %s\ninstead of\n %s\n", html_path.c_str(), (int)i + 1, a.c_str(), b.c_str()); + break; + } + } + return false; + } + // Some IR lines are linked to their assembly. + const std::string asm_lines = "const asmIRLines = ["; + size_t at = html.find(asm_lines); + if (html.find("data-asm='1'") == std::string::npos || at == std::string::npos) { + printf("%s links no IR to assembly\n", html_path.c_str()); + return false; + } + // ... and the assembly is linked to lines that exist. + std::istringstream in(html.substr(at + asm_lines.size(), html.find(']', at) - at - asm_lines.size())); + int linked = 0; + std::set linked_line_set; + for (std::string n; std::getline(in, n, ',');) { + int line = std::atoi(n.c_str()); + if (line < 0 || line > (int)lines.size()) { + printf("%s links assembly to line %d of %d\n", html_path.c_str(), line, (int)lines.size()); + return false; + } + linked += line > 0; + if (line > 0) { + linked_line_set.insert(line); + } + } + const int linked_lines = (int)linked_line_set.size(); + if (linked == 0) { + printf("%s links no assembly to IR\n", html_path.c_str()); + return false; + } + // The assembly is also linked to the IR nodes it was generated for. The + // html has the expressions among them, and the Stmts that have + // punctuation. On one line, several nodes have assembly of their own. + const std::string asm_nodes = "const asmIRNodes = ["; + at = html.find(asm_nodes); + if (at == std::string::npos) { + printf("%s links no assembly to IR nodes\n", html_path.c_str()); + return false; + } + std::istringstream nodes_in(html.substr(at + asm_nodes.size(), html.find(']', at) - at - asm_nodes.size())); + std::set nodes; + for (std::string n; std::getline(nodes_in, n, ',');) { + if (int node = std::atoi(n.c_str())) { + nodes.insert(node); + } + } + int nodes_in_html = 0; + for (int node : nodes) { + nodes_in_html += html.find("data-g='" + std::to_string(node) + "'") != std::string::npos; + } + if (nodes_in_html <= linked_lines) { + printf("%s links assembly to %d IR nodes that are in it, on %d lines\n", + html_path.c_str(), nodes_in_html, linked_lines); + return false; + } + return true; +} + +size_t count(const std::string &text, const std::string &needle) { + size_t n = 0; + for (size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) { + n++; + } + return n; +} + +} // namespace + +int main(int argc, char **argv) { + Target target = get_host_target(); + if (target.os == Target::Windows) { + printf("[SKIP] This test checks the DWARF of the LLVM assembly.\n"); + return 0; + } + target = target.with_feature(Target::DebugSymbols); + + ImageParam input(Int(32), 2, "input"); + Param scale("scale"), offset("offset"); + Var x("x"), y("y"); + Func f("f"); + f(x, y) = input(x, y) * scale + offset; + f.parallel(y).vectorize(x, 8); + + const std::string dir = Internal::get_test_tmp_dir(); + const std::string stmt_path = dir + "debug_symbols.stmt"; + const std::string ll_path = dir + "debug_symbols.ll"; + const std::string object_path = dir + "debug_symbols.o"; + for (const auto &p : {stmt_path, ll_path, object_path}) { + Internal::ensure_no_file_exists(p); + } + f.compile_to({{OutputFileType::stmt, stmt_path}, + {OutputFileType::llvm_assembly, ll_path}, + {OutputFileType::object, object_path}}, + {input, scale, offset}, "debug_symbols", target); + Internal::assert_file_exists(object_path); + + const std::string stmt = read_file(stmt_path); + const std::string ll = read_file(ll_path); + const std::vector stmt_lines = split_lines(stmt); + + // The debug info refers to the stmt file. + if (ll.find("!DIFile(filename: \"debug_symbols.stmt\"") == std::string::npos || + ll.find("checksumkind: CSK_MD5") == std::string::npos) { + printf("Missing or incomplete DIFile for the stmt\n"); + return 1; + } + + // One subprogram per function in the stmt: the pipeline, and the closure + // of its parallel loop. + const size_t functions = count(stmt, " func "); + const size_t subprograms = count(ll, "distinct !DISubprogram("); + if (functions < 2 || subprograms != functions) { + printf("Expected one subprogram for each of the %d functions, got %d\n", + (int)functions, (int)subprograms); + return 1; + } + + // Every location points at something printed in the stmt. + std::map> locations; + std::regex location_re(R"((!\d+) = (?:distinct )?!DILocation\(line: (\d+), column: (\d+))"); + for (std::sregex_iterator it(ll.begin(), ll.end(), location_re), end; it != end; ++it) { + int line = std::stoi((*it)[2]), column = std::stoi((*it)[3]); + locations[(*it)[1]] = {line, column}; + if (line == 0) { + // LLVM merged instructions from different lines. + continue; + } + if (line > (int)stmt_lines.size() || column < 1 || + column > (int)stmt_lines[line - 1].size() || + stmt_lines[line - 1][column - 1] == ' ') { + printf("Location %d:%d does not point at the stmt's text\n", line, column); + return 1; + } + } + if (locations.empty()) { + printf("No locations\n"); + return 1; + } + + // Multiplies point at the operator that made them. + std::regex mul_re(R"(= mul [^\n]*!dbg (!\d+))"); + int muls = 0; + for (std::sregex_iterator it(ll.begin(), ll.end(), mul_re), end; it != end; ++it) { + auto loc = locations.find((*it)[1]); + if (loc != locations.end() && loc->second.first > 0 && + stmt_lines[loc->second.first - 1][loc->second.second - 1] == '*') { + muls++; + } + } + if (muls == 0) { + printf("No multiply points at a '*' in the stmt\n"); + return 1; + } + + // Every loop variable is visible to the debugger. + std::regex for_re(R"(\bfor \(([^,]+),)"); + int loops = 0; + for (std::sregex_iterator it(stmt.begin(), stmt.end(), for_re), end; it != end; ++it) { + std::string var = "!DILocalVariable(name: \"" + (*it)[1].str() + "\""; + if (ll.find(var) == std::string::npos) { + printf("No variable for loop over %s\n", (*it)[1].str().c_str()); + return 1; + } + loops++; + } + if (loops == 0) { + printf("No loops in the stmt\n"); + return 1; + } + + // So are the buffers, as halide_buffer_t. + if (ll.find("!DILocalVariable(name: \"input.buffer\", arg: ") == std::string::npos || + ll.find("!DICompositeType(tag: DW_TAG_structure_type, name: \"halide_buffer_t\"") == std::string::npos) { + printf("No description of the input buffer\n"); + return 1; + } + + // JIT compilation with debug info still computes the right thing. + Buffer in(37, 5); + in.for_each_element([&](int x, int y) { in(x, y) = x * 7 - y; }); + input.set(in); + scale.set(3); + offset.set(-11); + Buffer out = f.realize({37, 5}, get_jit_target_from_environment().without_feature(Target::DebugSymbolsConceptual).with_feature(Target::DebugSymbols)); + for (int y = 0; y < out.height(); y++) { + for (int x = 0; x < out.width(); x++) { + int correct = in(x, y) * 3 - 11; + if (out(x, y) != correct) { + printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), correct); + return 1; + } + } + } + + // The source maps hold the text of the stmt files. + { + Module m = f.compile_to_module({input, scale, offset}, "debug_symbols", target); + std::ostringstream module_text, conceptual_text; + module_text << m; + conceptual_text << m.get_conceptual_stmt(); + if (Internal::print_with_source_map(m).text != module_text.str() || + Internal::print_with_source_map(m.get_conceptual_stmt()).text != conceptual_text.str()) { + printf("Source map text differs from the printed IR\n"); + return 1; + } + } + + // Each IR node of the conceptual stmt is printed in one place only, even + // where the IR repeats, as in unrolled loops and the checks of the + // buffers. + { + Func u("u"); + Var ux("ux"); + u(ux) = input(0, 0) * 3 + input(1, 0); + u.bound(ux, 0, 4).unroll(ux); + Module m = Pipeline(u).compile_to_module({input}, "debug_symbols_unrolled", get_host_target()); + std::map printed; + for (const auto &l : Internal::print_with_source_map(m.get_conceptual_stmt()).locations) { + if (++printed[l.node] > 1) { + printf("An IR node is printed more than once in the conceptual stmt\n"); + return 1; + } + } + } + + // The html outputs show the IR exactly as the stmt files do, and link it + // to the assembly. Without debug_symbols, only the html has debug info. + { + Func g("g"), h("h"); + RDom r(0, 10); + g(x, y) = x + y; + g(r, y) += select(g(r, y) > 3, g(r, y) / 2, offset); + h(x, y) = g(x, y) * scale; + g.compute_at(h, y); + h.specialize(scale > 2).vectorize(x, 4); + h.parallel(y); + + const std::string html_path = dir + "debug_symbols_html.stmt.html"; + const std::string conceptual_html_path = dir + "debug_symbols_html.conceptual.stmt.html"; + const std::string html_stmt_path = dir + "debug_symbols_html.stmt"; + const std::string conceptual_stmt_path = dir + "debug_symbols_html.conceptual.stmt"; + const std::string html_object_path = dir + "debug_symbols_html.o"; + for (const auto &p : {html_path, conceptual_html_path, html_stmt_path, conceptual_stmt_path, html_object_path}) { + Internal::ensure_no_file_exists(p); + } + h.compile_to({{OutputFileType::stmt_html, html_path}, + {OutputFileType::conceptual_stmt_html, conceptual_html_path}, + {OutputFileType::stmt, html_stmt_path}, + {OutputFileType::conceptual_stmt, conceptual_stmt_path}, + {OutputFileType::object, html_object_path}}, + {scale, offset}, "debug_symbols_html", get_host_target()); + if (!check_html(html_path, html_stmt_path) || + !check_html(conceptual_html_path, conceptual_stmt_path)) { + return 1; + } + // The object did not ask for debug info. + const std::string object = read_file(html_object_path); + if (object.find(".debug_line") != std::string::npos || + object.find("debug_symbols_html.stmt") != std::string::npos) { + printf("The object has debug info without debug_symbols\n"); + return 1; + } + } + + // The html links the IR to the assembly for other platforms too, whose + // assembly carries the debug info differently (e.g. CodeView on Windows). + for (const char *other : {"x86-64-windows", "arm-64-macos", "arm-64-linux"}) { + Func k("k"); + k(x, y) = x * scale + offset; + k.vectorize(x, 4).parallel(y); + const std::string other_html_path = dir + "debug_symbols_" + other + ".stmt.html"; + const std::string other_stmt_path = dir + "debug_symbols_" + other + ".stmt"; + for (const auto &p : {other_html_path, other_stmt_path}) { + Internal::ensure_no_file_exists(p); + } + try { + k.compile_to({{OutputFileType::stmt_html, other_html_path}, + {OutputFileType::stmt, other_stmt_path}}, + {scale, offset}, "debug_symbols_other", Target(other)); + } catch (const Halide::CompileError &e) { + printf("[SKIP] Can't compile for %s: %s\n", other, e.what()); + continue; + } + if (!check_html(other_html_path, other_stmt_path)) { + return 1; + } + } + + // With debug_symbols_conceptual, the debug info points into the + // conceptual stmt instead. + { + const Target conceptual_target = get_host_target().with_feature(Target::DebugSymbolsConceptual); + const std::string c_stmt_path = dir + "debug_symbols_c.stmt"; + const std::string c_conceptual_path = dir + "debug_symbols_c.conceptual.stmt"; + const std::string c_ll_path = dir + "debug_symbols_c.ll"; + const std::string c_html_path = dir + "debug_symbols_c.stmt.html"; + const std::string c_conceptual_html_path = dir + "debug_symbols_c.conceptual.stmt.html"; + for (const auto &p : {c_stmt_path, c_conceptual_path, c_ll_path, c_html_path, c_conceptual_html_path}) { + Internal::ensure_no_file_exists(p); + } + f.compile_to({{OutputFileType::stmt, c_stmt_path}, + {OutputFileType::conceptual_stmt, c_conceptual_path}, + {OutputFileType::llvm_assembly, c_ll_path}, + {OutputFileType::stmt_html, c_html_path}, + {OutputFileType::conceptual_stmt_html, c_conceptual_html_path}}, + {input, scale, offset}, "debug_symbols_c", conceptual_target); + + const std::string c_ll = read_file(c_ll_path); + const std::vector c_lines = split_lines(read_file(c_conceptual_path)); + if (c_ll.find("!DIFile(filename: \"debug_symbols_c.conceptual.stmt\"") == std::string::npos) { + printf("The debug info does not refer to the conceptual stmt\n"); + return 1; + } + std::map> c_locations; + std::regex location_re(R"((!\d+) = (?:distinct )?!DILocation\(line: (\d+), column: (\d+))"); + for (std::sregex_iterator it(c_ll.begin(), c_ll.end(), location_re), end; it != end; ++it) { + int line = std::stoi((*it)[2]), column = std::stoi((*it)[3]); + c_locations[(*it)[1]] = {line, column}; + if (line == 0) { + continue; + } + if (line > (int)c_lines.size() || column < 1 || + column > (int)c_lines[line - 1].size() || + c_lines[line - 1][column - 1] == ' ') { + printf("Location %d:%d does not point at the conceptual stmt's text\n", line, column); + return 1; + } + } + std::regex mul_re(R"(= mul [^\n]*!dbg (!\d+))"); + int c_muls = 0; + for (std::sregex_iterator it(c_ll.begin(), c_ll.end(), mul_re), end; it != end; ++it) { + auto loc = c_locations.find((*it)[1]); + if (loc != c_locations.end() && loc->second.first > 0 && + c_lines[loc->second.first - 1][loc->second.second - 1] == '*') { + c_muls++; + } + } + if (c_muls == 0) { + printf("No multiply points at a '*' in the conceptual stmt\n"); + return 1; + } + if (!check_html(c_html_path, c_stmt_path) || + !check_html(c_conceptual_html_path, c_conceptual_path)) { + return 1; + } + + // The debug info can't point into both. Without exceptions, asking for + // both aborts. + if (Halide::exceptions_enabled()) { + bool refused = false; + try { + f.compile_to({{OutputFileType::llvm_assembly, c_ll_path}}, + {input, scale, offset}, "debug_symbols_c", + conceptual_target.with_feature(Target::DebugSymbols)); + } catch (const Halide::CompileError &) { + refused = true; + } + if (!refused) { + printf("Asking for both kinds of debug symbols was not an error\n"); + return 1; + } + } + + // JIT compilation with it still computes the right thing. + Buffer c_out = f.realize({37, 5}, get_jit_target_from_environment().without_feature(Target::DebugSymbols).with_feature(Target::DebugSymbolsConceptual)); + for (int y = 0; y < c_out.height(); y++) { + for (int x = 0; x < c_out.width(); x++) { + if (c_out(x, y) != in(x, y) * 3 - 11) { + printf("c_out(%d, %d) = %d instead of %d\n", x, y, c_out(x, y), in(x, y) * 3 - 11); + return 1; + } + } + } + } + + printf("Success!\n"); + return 0; +} diff --git a/test/correctness/stmt_to_html.cpp b/test/correctness/stmt_to_html.cpp index dae0cdc95527..9c017c65bc04 100644 --- a/test/correctness/stmt_to_html.cpp +++ b/test/correctness/stmt_to_html.cpp @@ -1,10 +1,137 @@ #include "Halide.h" #include "halide_test_dirs.h" +#include #include +#include +#include using namespace Halide; +namespace { + +std::string read_file(const std::string &path) { + std::ifstream in(path); + std::stringstream ss; + ss << in.rdbuf(); + return ss.str(); +} + +std::vector split_lines(const std::string &text) { + std::vector lines; + std::istringstream in(text); + std::string line; + while (std::getline(in, line)) { + lines.push_back(line); + } + return lines; +} + +// The text of each line of IR in an html output, in order of their line +// numbers, which must be consecutive from 1. +bool html_lines(const std::string &html, std::vector &lines) { + // A line may have more classes than 'l', e.g. when it is shaded. + const std::string line_open = "
0) { + if (html.compare(c, 5, "', c) + 1; + } else if (html.compare(c, 7, "") == 0) { + depth--; + c += 7; + } else if (html.compare(c, 5, "&") == 0) { + text += '&'; + c += 5; + } else if (html.compare(c, 4, "<") == 0) { + text += '<'; + c += 4; + } else if (html.compare(c, 4, ">") == 0) { + text += '>'; + c += 4; + } else { + text += html[c++]; + } + } + lines.push_back(text); + } + return true; +} + +bool check_html(const std::string &html_path, const std::string &stmt_path) { + const std::string html = read_file(html_path); + const std::vector stmt_lines = split_lines(read_file(stmt_path)); + std::vector lines; + if (!html_lines(html, lines)) { + return false; + } + if (lines != stmt_lines) { + for (size_t i = 0; i < std::max(lines.size(), stmt_lines.size()); i++) { + std::string a = i < lines.size() ? lines[i] : "(none)"; + std::string b = i < stmt_lines.size() ? stmt_lines[i] : "(none)"; + if (a != b) { + printf("%s line %d is\n %s\ninstead of\n %s\n", html_path.c_str(), (int)i + 1, a.c_str(), b.c_str()); + break; + } + } + return false; + } + // Some loops are linked to their assembly. + const std::string asm_lines = "const asmIRLines = ["; + size_t at = html.find(asm_lines); + if (html.find("data-asm='1'") == std::string::npos || at == std::string::npos) { + printf("%s links no IR to assembly\n", html_path.c_str()); + return false; + } + // ... and the assembly is linked to lines that exist. + std::istringstream in(html.substr(at + asm_lines.size(), html.find(']', at) - at - asm_lines.size())); + int linked = 0, mapped = 0; + for (std::string n; std::getline(in, n, ',');) { + mapped++; + int line = std::atoi(n.c_str()); + if (line < 0 || line > (int)lines.size()) { + printf("%s links assembly to line %d of %d\n", html_path.c_str(), line, (int)lines.size()); + return false; + } + linked += line > 0; + } + if (linked == 0) { + printf("%s links no assembly to IR\n", html_path.c_str()); + return false; + } + // The assembly is there as text, with a link for each of its lines. + const std::string asm_open = "