From 29157b2e144382096ae6c4024fc310aca41973e4 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 4 Dec 2026 01:06:03 +0000 Subject: [PATCH 1/5] --di: a debugger stops once at each statement, leaves at the closing brace, and steps over compiler glue Every op had the place of the expression it was made for, so the line table had a row for each expression and, under CodeView, a column for each (the Visual Studio debugger and cppvsdbg step through those), went back and forth over a statement on several lines, back to a variable's declaration to release it at the end of its scope, returned through the function's first line, and stepped into the compiler's glue shown at the user's lines. - MLIRGen records the statements it generates (ts.debug_statements, only nodes of the file being generated: other files' trees are generated under its name too). - DebugStepLocationsPass, ahead of DIScopeForLLVMFuncOpPass: an op's place becomes the start of the innermost statement it is in; no columns under CodeView (as clang); a function with no statement (a thunk marked LocalToUnit, `.new`, `.instanceOf`, the rc/own routines) gets line 0 throughout, so it has no source; calls into such glue and code that goes back to an earlier statement in the same block get line 0; without --opt `callsite(a at b)` becomes `b` (a fake inline frame). - A function's way out is its closing brace: the exit and its return block (made with the entry). - debug-info-steps.cmake checks the rows of each function under all four models; jit-native's cdb check takes any line of `greeting` (line 3 now under --opt, the only code left is the return). Co-Authored-By: Claude Opus 5.5 --- docs/whats-new.md | 1 + tslang/include/TypeScript/Defines.h | 3 + .../MLIRLogic/MLIRDebugInfoHelper.h | 10 +- tslang/include/TypeScript/Passes.h | 3 + tslang/lib/TypeScript/CMakeLists.txt | 1 + .../lib/TypeScript/DebugStepLocationsPass.cpp | 583 ++++++++++++++++++ tslang/lib/TypeScript/LowerToAffineLoops.cpp | 13 + tslang/lib/TypeScript/MLIRGenCast.cpp | 6 +- tslang/lib/TypeScript/MLIRGenClasses.cpp | 4 +- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 12 +- tslang/lib/TypeScript/MLIRGenImpl.h | 107 +++- tslang/lib/TypeScript/MLIRGenModule.cpp | 17 + tslang/lib/TypeScript/MLIRGenStatements.cpp | 28 +- tslang/test/tester/CMakeLists.txt | 7 + tslang/test/tester/debug-info-steps.cmake | 122 ++++ tslang/test/tester/jit-native.cmake | 11 +- tslang/test/tester/tests/00debug_steps.ts | 31 + tslang/tslang/transform.cpp | 1 + 18 files changed, 945 insertions(+), 15 deletions(-) create mode 100644 tslang/lib/TypeScript/DebugStepLocationsPass.cpp create mode 100644 tslang/test/tester/debug-info-steps.cmake create mode 100644 tslang/test/tester/tests/00debug_steps.ts diff --git a/docs/whats-new.md b/docs/whats-new.md index 145a533bc..f4bbd8398 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,6 @@ # What's new +- Stepping through a program built with `--di` stops once at each statement: the line table has one row for a statement where it had one for each expression in it (and a column for each, which the Visual Studio debugger and VS Code's cppvsdbg step through), and a debugger no longer goes back and forth over a statement written on several lines or back to a variable's declaration at the end of its scope, leaves a function at its closing brace (not at its first line), and steps over the compiler's own functions (a class's `.new` and `.instanceOf`, a cast's thunk, the reference counting routines), which have no source line. Under CodeView the line table has no columns, as clang leaves them out for the Microsoft debuggers - A function of the program named as a function of the default library is the program's own: `function sleep(ms: number): string` beside the library's generic `sleep` compiles and is called (it took the library's type, "can't find return variable"), a program's `__is_any` or a generic function of that name is called instead of the library's, and one named as a function the library declares keeps the signature it is written with. The library's own code, its generics made in the program included (a `Map`'s hashing, `toSpliced`), still calls the library's - **JSX** runs as it is: with no factory named, an element is a call of the default library's `h`, which makes a `JsxElement` (its tag, attributes and children) that prints and turns into a string as HTML (`print(

a < b

)` prints `

a < b

`). A tag that is a function is a component, called with the attributes and the children; `<>...` is a `Fragment`. tsc's default, `React.createElement`, is used only when named. When a statement fails with an error of its own, the "failed statement" error that followed it is no longer printed, and the error of a JSX factory that can't be found is shorter. Needs the default library of the same release - A mixed array literal is typed as tsc types it: an array of the union of its elements' types, `[1, "a"]` a `(s32 | string)[]` and `[3, { a: 4 }]` a `(s32 | { a: s32 })[]` (they were tuples), so it can grow and takes either member. It stays a tuple where the context asks for one: destructured (`const [n, s] = [1, "a"]`, `[x, y] = [y, x]`), given to a tuple parameter or a generic one inferred as a tuple, or pushed into an array of tuples. Code that indexes such a literal as a tuple (`[1, [2, 2]][1][1]`, which tsc refuses too) needs a tuple type (`const t: [number, number[]] = ...`). A union of primitives and object shapes (`number | { a: number }`) can be cast and printed: each member is told apart by its tag, and `print([3, { a: 4 }])` prints `[ 3, { a: 4 } ]` diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 6744f4e25..6e9b8f013 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -195,6 +195,9 @@ // routine of the base (OwnershipRoutineLogic) compares an object's vtable with each subclass's and // releases the fields of the class it is, not only the base's (rc and own). #define CLASS_BASES_ATTR_NAME "ts.class_bases" +// On the module, under --di: the statements of each file, as {file: [line, column, end line, end column]...} - +// where a debugger stops (DebugStepLocationsPass, which removes it). +#define DEBUG_STATEMENTS_ATTR_NAME "ts.debug_statements" // The classes the module knows (its own and those it imports or declares) whose objects can't say which class they // are: a @cpp class (a C++ vtable), a @value or a static one (no RTTI). A union of classes is stored as the object's // pointer alone, the class asked of the object (`.instanceOf`), unless one of these is among them (user ruling diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h index abacc1f17..d071b588e 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h @@ -151,7 +151,10 @@ class MLIRDebugInfoHelper || isa(scope)); } - mlir::Location getSubprogram(mlir::Location functionLocation, StringRef functionName, StringRef linkageName, mlir::Location functionBlockLocation) { + // glue: compiler glue with no source to step through (a thunk). LocalToUnit - it is internal - marks it for + // DebugStepLocationsPass, which leaves it no line, so a debugger steps over it (the LLVM dialect has no + // DIFlagArtificial for a subprogram). + mlir::Location getSubprogram(mlir::Location functionLocation, StringRef functionName, StringRef linkageName, mlir::Location functionBlockLocation, bool glue = false) { if (auto compileUnitAttr = dyn_cast_or_null(debugScope.lookup(CU_DEBUG_SCOPE))) { @@ -184,6 +187,11 @@ class MLIRDebugInfoHelper subprogramFlags = subprogramFlags | mlir::LLVM::DISubprogramFlags::Optimized; } + if (glue) + { + subprogramFlags = subprogramFlags | mlir::LLVM::DISubprogramFlags::LocalToUnit; + } + // add return types auto type = mlir::LLVM::DISubroutineTypeAttr::get(builder.getContext(), llvm::dwarf::DW_CC_normal, {/*Add Types here*/}); diff --git a/tslang/include/TypeScript/Passes.h b/tslang/include/TypeScript/Passes.h index a805dd6db..1867ae51d 100644 --- a/tslang/include/TypeScript/Passes.h +++ b/tslang/include/TypeScript/Passes.h @@ -87,6 +87,9 @@ std::unique_ptr createProcessHeapPass(); /// location of its own takes the call's, and one outside any function (a string literal's global) /// the location it was written at. Schedule before it, under --di --opt. std::unique_ptr createInlinedLocationPass(); +/// Under --di, ahead of DIScopeForLLVMFuncOpPass: a debugger stops once at each statement, not at every +/// expression, and steps over compiler glue (DEBUG_STATEMENTS_ATTR_NAME holds the statements). +std::unique_ptr createDebugStepLocationsPass(const CompileOptions &, bool optimized); /// MemAlloc Pass to replace ts_malloc, ts_realloc, ts_free std::unique_ptr createMemAllocPass(CompileOptions&); diff --git a/tslang/lib/TypeScript/CMakeLists.txt b/tslang/lib/TypeScript/CMakeLists.txt index 1b83dc53d..affc882f2 100644 --- a/tslang/lib/TypeScript/CMakeLists.txt +++ b/tslang/lib/TypeScript/CMakeLists.txt @@ -63,6 +63,7 @@ add_mlir_dialect_library(MLIRTypeScript GCPass.cpp ProcessHeapPass.cpp InlinedLocationPass.cpp + DebugStepLocationsPass.cpp AsyncTargetWidthPass.cpp ObjDumper.cpp LibraryDeclarations.cpp diff --git a/tslang/lib/TypeScript/DebugStepLocationsPass.cpp b/tslang/lib/TypeScript/DebugStepLocationsPass.cpp new file mode 100644 index 000000000..486b482e3 --- /dev/null +++ b/tslang/lib/TypeScript/DebugStepLocationsPass.cpp @@ -0,0 +1,583 @@ +#include "mlir/Pass/Pass.h" + +#include "TypeScript/Defines.h" +#include "TypeScript/TypeScriptDialect.h" +#include "TypeScript/TypeScriptOps.h" +#include "TypeScript/Passes.h" +#include "TypeScript/Pass/ModulePass.h" + +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" +#include "mlir/IR/AttrTypeSubElements.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" + +#include "llvm/ADT/StringMap.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/Path.h" +#include "llvm/TargetParser/Triple.h" + +#define DEBUG_TYPE "pass" + +using namespace ::typescript; +namespace mlir_ts = mlir::typescript; + +namespace +{ + +// A statement of the source as MLIRGen recorded it (DEBUG_STATEMENTS_ATTR_NAME): where it starts, +// where it ends (exclusive), and the statement around it. +struct StatementRange +{ + int32_t line; + int32_t column; + int32_t endLine; + int32_t endColumn; + int parent; + + bool startsAtOrBefore(int32_t l, int32_t c) const + { + return line < l || (line == l && column <= c); + } + + bool contains(int32_t l, int32_t c) const + { + return startsAtOrBefore(l, c) && (l < endLine || (l == endLine && c < endColumn)); + } +}; + +// The statements of one file, sorted by where they start, each knowing the one around it: the +// statement a place is in is found from the last one starting before it, walking out. +class FileStatements +{ + llvm::SmallVector ranges; + + public: + void add(int32_t line, int32_t column, int32_t endLine, int32_t endColumn) + { + ranges.push_back({line, column, endLine, endColumn, -1}); + } + + void index() + { + // an outer statement before the ones it holds: by start, and the longer first at one start + llvm::sort(ranges, [](const StatementRange &a, const StatementRange &b) { + if (a.line != b.line) + return a.line < b.line; + if (a.column != b.column) + return a.column < b.column; + return a.endLine != b.endLine ? a.endLine > b.endLine : a.endColumn > b.endColumn; + }); + + llvm::SmallVector open; + for (int i = 0, e = ranges.size(); i < e; i++) + { + while (!open.empty() && !ranges[open.back()].contains(ranges[i].line, ranges[i].column)) + { + open.pop_back(); + } + + ranges[i].parent = open.empty() ? -1 : open.back(); + open.push_back(i); + } + } + + const StatementRange *find(int32_t line, int32_t column) const + { + auto it = llvm::upper_bound(ranges, std::make_pair(line, column), + [](std::pair place, const StatementRange &range) { + return place.first < range.line || + (place.first == range.line && place.second < range.column); + }); + for (int i = (int)(it - ranges.begin()) - 1; i >= 0; i = ranges[i].parent) + { + if (ranges[i].contains(line, column)) + { + return &ranges[i]; + } + } + + return nullptr; + } +}; + +// Under --di, after LowerToLLVM and ahead of DIScopeForLLVMFuncOpPass: the locations the line +// table is made from, cut down to what a debugger should stop at. +// +// MLIRGen gives every op the place of the expression it was made for. Turned into a line table +// as it is, a debugger stops at each of them - the Visual Studio debugger (and VS Code's cppvsdbg) +// at every column of a line, so `return Math.sqrt(this.x * this.x + this.y * this.y)` took a dozen +// steps - goes back and forth over a statement written on several lines, steps into compiler +// glue (a class's `.new`, a cast's thunk, the reference counting routines) shown at the user line +// it was made for, and goes back to a variable's declaration to release it at the end of a scope. +// +// - In a function of the program, an op's place becomes the start of the innermost statement it +// is in: one stop for each statement, and the column only where the debugger handles columns +// (not with CodeView: the Microsoft debuggers want an end column, which is never there - clang +// leaves columns out for CodeView too). +// - Ops of no statement that are before the function (what a class's parameter properties make, +// at the start of the file), calls into compiler glue, and code that goes back to a statement +// already passed in the same block (releasing a variable at the end of its scope) get line 0: +// no stop of their own - CodeView adds no row for them, so they belong to the row before; +// DWARF debuggers skip line 0. +// - A function with no statement of the program in it - compiler glue: a thunk, a class's `.new`, +// `.instanceOf`, a routine the lowering made - gets line 0 for all its ops: a function with no +// source, which a debugger steps over. +// - Without --opt, a call is no inlining: `callsite(a at b)` on it (which the debugger showed as an +// inline frame of the function inside itself) becomes `b`. +class DebugStepLocationsPass : public mlir::PassWrapper +{ + bool codeView; + bool optimized; + + llvm::StringMap statements; + llvm::DenseSet hiddenFunctions; + llvm::DenseSet hiddenNames; + + public: + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DebugStepLocationsPass) + + DebugStepLocationsPass(bool codeView, bool optimized) : codeView(codeView), optimized(optimized) + { + } + + void runOnModule() override + { + auto module = getModule(); + loadStatements(module); + + module.walk([&](mlir::LLVM::LLVMFuncOp funcOp) { + if (!funcOp.isExternal() && isHidden(funcOp)) + { + hiddenFunctions.insert(funcOp); + hiddenNames.insert(funcOp.getSymNameAttr()); + } + }); + + module.walk([&](mlir::LLVM::LLVMFuncOp funcOp) { + if (funcOp.isExternal()) + { + return; + } + + if (hiddenFunctions.contains(funcOp)) + { + hideFunction(funcOp); + } + else + { + stepByStatement(funcOp); + } + }); + } + + private: + void loadStatements(mlir::ModuleOp module) + { + auto table = module->getAttrOfType(DEBUG_STATEMENTS_ATTR_NAME); + if (!table) + { + return; + } + + for (auto entry : table) + { + auto values = mlir::dyn_cast(entry.getValue()); + if (!values) + { + continue; + } + + auto &file = statements[entry.getName().getValue()]; + auto data = values.asArrayRef(); + for (size_t i = 0; i + 3 < data.size(); i += 4) + { + file.add(data[i], data[i + 1], data[i + 2], data[i + 3]); + } + + file.index(); + } + + // what it was kept for is done: the module goes on without it + module->removeAttr(DEBUG_STATEMENTS_ATTR_NAME); + } + + const StatementRange *statementAt(mlir::FileLineColLoc fileLoc) const + { + auto it = statements.find(fileLoc.getFilename().getValue()); + if (it == statements.end()) + { + return nullptr; + } + + return it->second.find(fileLoc.getLine(), fileLoc.getColumn()); + } + + // the place the debugger shows for a location: what DIScopeForLLVMFuncOpPass and the + // translation take from it + static mlir::FileLineColLoc fileLocOf(mlir::Location loc) + { + if (auto fileLoc = mlir::dyn_cast(loc)) + { + return fileLoc; + } + + if (auto nameLoc = mlir::dyn_cast(loc)) + { + return fileLocOf(nameLoc.getChildLoc()); + } + + if (auto opaqueLoc = mlir::dyn_cast(loc)) + { + return fileLocOf(opaqueLoc.getFallbackLocation()); + } + + if (auto fusedLoc = mlir::dyn_cast(loc)) + { + for (auto nested : fusedLoc.getLocations()) + { + if (auto fileLoc = fileLocOf(nested)) + { + return fileLoc; + } + } + } + + if (auto callSiteLoc = mlir::dyn_cast(loc)) + { + return fileLocOf(callSiteLoc.getCallee()); + } + + return mlir::FileLineColLoc(); + } + + static mlir::LLVM::DISubprogramAttr subprogramOf(mlir::LLVM::LLVMFuncOp funcOp) + { + if (auto fused = funcOp->getLoc()->findInstanceOf>()) + { + return fused.getMetadata(); + } + + return {}; + } + + bool isHidden(mlir::LLVM::LLVMFuncOp funcOp) + { + auto subprogram = subprogramOf(funcOp); + if (!subprogram) + { + // made after MLIRGen: a routine of the lowering + return true; + } + + // a thunk MLIRGen made (MLIRDebugInfoHelper::getSubprogram's `glue`) + if (bitEnumContainsAll(subprogram.getSubprogramFlags(), mlir::LLVM::DISubprogramFlags::LocalToUnit)) + { + return true; + } + + auto result = funcOp->walk([&](mlir::Operation *op) { + if (auto fileLoc = fileLocOf(op->getLoc())) + { + if (statementAt(fileLoc)) + { + return mlir::WalkResult::interrupt(); + } + } + + return mlir::WalkResult::advance(); + }); + + return !result.wasInterrupted(); + } + + // Replaces each file:line:column in a location, keeping what is around it (the scopes MLIRGen + // fused in, the names). + static mlir::Location rewrite(mlir::Location loc, llvm::function_ref fn, + bool collapseCallSites) + { + if (auto fileLoc = mlir::dyn_cast(loc)) + { + return fn(fileLoc); + } + + if (auto nameLoc = mlir::dyn_cast(loc)) + { + auto child = rewrite(nameLoc.getChildLoc(), fn, collapseCallSites); + return child == nameLoc.getChildLoc() ? loc : mlir::NameLoc::get(nameLoc.getName(), child); + } + + if (auto opaqueLoc = mlir::dyn_cast(loc)) + { + auto fallback = rewrite(opaqueLoc.getFallbackLocation(), fn, collapseCallSites); + return fallback == opaqueLoc.getFallbackLocation() + ? loc + : mlir::OpaqueLoc::get(opaqueLoc.getUnderlyingLocation(), opaqueLoc.getUnderlyingTypeID(), + fallback); + } + + if (auto fusedLoc = mlir::dyn_cast(loc)) + { + llvm::SmallVector nested; + auto changed = false; + for (auto inner : fusedLoc.getLocations()) + { + nested.push_back(rewrite(inner, fn, collapseCallSites)); + changed |= nested.back() != inner; + } + + // FusedLoc::get folds a fused location of one with no metadata into it: kept as built + return changed ? mlir::Location(mlir::FusedLoc::get(loc.getContext(), nested, fusedLoc.getMetadata())) + : loc; + } + + if (auto callSiteLoc = mlir::dyn_cast(loc)) + { + if (collapseCallSites) + { + return rewrite(callSiteLoc.getCaller(), fn, collapseCallSites); + } + + auto callee = rewrite(callSiteLoc.getCallee(), fn, collapseCallSites); + auto caller = rewrite(callSiteLoc.getCaller(), fn, collapseCallSites); + return callee == callSiteLoc.getCallee() && caller == callSiteLoc.getCaller() + ? loc + : mlir::Location(mlir::CallSiteLoc::get(callee, caller)); + } + + return loc; + } + + static void forEachLocated(mlir::LLVM::LLVMFuncOp funcOp, llvm::function_ref onOp, + llvm::function_ref onArg) + { + funcOp->walk([&](mlir::Block *block) { + for (auto arg : block->getArguments()) + { + onArg(arg); + } + }); + + funcOp->walk([&](mlir::Operation *op) { + if (op != funcOp) + { + onOp(op); + } + }); + } + + // A function of no source: every op of it at line 0 of its file, in no scope but the + // function's own. A call in it still needs a location, and the function keeps its subprogram + // (or gets one from DIScopeForLLVMFuncOpPass); with no line in it, CodeView gives it no line + // table and DWARF debuggers skip line 0 - a function a debugger steps over. + void hideFunction(mlir::LLVM::LLVMFuncOp funcOp) + { + auto *context = funcOp.getContext(); + auto subprogram = subprogramOf(funcOp); + auto funcFileLoc = fileLocOf(funcOp->getLoc()); + + mlir::StringAttr fileName; + if (funcFileLoc) + { + fileName = funcFileLoc.getFilename(); + } + else if (subprogram && subprogram.getFile()) + { + llvm::SmallString<256> path(subprogram.getFile().getDirectory().getValue()); + llvm::sys::path::append(path, subprogram.getFile().getName().getValue()); + fileName = mlir::StringAttr::get(context, path); + } + else if (auto unit = getModule()->getLoc()->findInstanceOf>()) + { + if (auto file = unit.getMetadata().getFile()) + { + llvm::SmallString<256> path(file.getDirectory().getValue()); + llvm::sys::path::append(path, file.getName().getValue()); + fileName = mlir::StringAttr::get(context, path); + } + } + + if (!fileName) + { + return; + } + + // its variables are no one's to watch, and they are in the scope of the subprogram it + // had before + llvm::SmallVector debugOps; + funcOp->walk([&](mlir::Operation *op) { + if (mlir::isa(op)) + { + debugOps.push_back(op); + } + }); + for (auto *op : debugOps) + { + op->erase(); + } + + auto noLine = mlir::FileLineColLoc::get(fileName, 0, 0); + forEachLocated(funcOp, [&](mlir::Operation *op) { op->setLoc(noLine); }, + [&](mlir::BlockArgument arg) { arg.setLoc(noLine); }); + } + + // the line a location is shown at, 0 for none + static unsigned lineOf(mlir::Location loc) + { + auto fileLoc = fileLocOf(loc); + return fileLoc ? fileLoc.getLine() : 0; + } + + static mlir::Location withoutLine(mlir::Location loc) + { + return rewrite( + loc, + [](mlir::FileLineColLoc fileLoc) -> mlir::Location { + return mlir::FileLineColLoc::get(fileLoc.getFilename(), 0, 0); + }, + /*collapseCallSites=*/false); + } + + bool callsHiddenFunction(mlir::Operation *op) + { + if (auto callOp = mlir::dyn_cast(op)) + { + if (auto callee = callOp.getCalleeAttr()) + { + return hiddenNames.contains(callee.getAttr()); + } + } + else if (auto invokeOp = mlir::dyn_cast(op)) + { + if (auto callee = invokeOp.getCalleeAttr()) + { + return hiddenNames.contains(callee.getAttr()); + } + } + + return false; + } + + void stepByStatement(mlir::LLVM::LLVMFuncOp funcOp) + { + auto subprogram = subprogramOf(funcOp); + auto functionLine = subprogram ? subprogram.getLine() : 0; + auto functionFile = fileLocOf(funcOp->getLoc()); + + auto toStatement = [&](mlir::FileLineColLoc fileLoc) -> mlir::Location { + if (auto *statement = statementAt(fileLoc)) + { + return mlir::FileLineColLoc::get(fileLoc.getFilename(), statement->line, + codeView ? 0 : statement->column); + } + + // no statement, and before the function: what the compiler made for it at no place of + // its own (a class's parameter properties at the start of the file) + if (functionFile && fileLoc.getFilename() == functionFile.getFilename() && + fileLoc.getLine() < functionLine) + { + return mlir::FileLineColLoc::get(fileLoc.getFilename(), 0, 0); + } + + return codeView && fileLoc.getColumn() != 0 + ? mlir::FileLineColLoc::get(fileLoc.getFilename(), fileLoc.getLine(), 0) + : mlir::Location(fileLoc); + }; + + // what passes after this one add at the function's own place (the collector started at the + // start of `main`): no column there either + if (codeView) + { + auto funcLoc = funcOp->getLoc(); + auto withoutColumn = rewrite( + funcLoc, + [](mlir::FileLineColLoc fileLoc) -> mlir::Location { + return fileLoc.getColumn() == 0 + ? mlir::Location(fileLoc) + : mlir::FileLineColLoc::get(fileLoc.getFilename(), fileLoc.getLine(), 0); + }, + /*collapseCallSites=*/false); + if (withoutColumn != funcLoc) + { + funcOp->setLoc(withoutColumn); + } + } + + forEachLocated( + funcOp, + [&](mlir::Operation *op) { + auto loc = op->getLoc(); + auto stepped = rewrite(loc, toStatement, /*collapseCallSites=*/!optimized); + if (stepped != loc) + { + op->setLoc(stepped); + } + }, + [&](mlir::BlockArgument arg) { + auto loc = arg.getLoc(); + auto stepped = rewrite(loc, toStatement, /*collapseCallSites=*/!optimized); + if (stepped != loc) + { + arg.setLoc(stepped); + } + }); + + // in straight-line code, no going back: what comes after a later statement in the same + // block and is placed at an earlier one (a variable released at the end of its scope, at + // its declaration) is part of the row before; and a call into compiler glue is no stop + funcOp->walk([&](mlir::Block *block) { + unsigned furthest = 0; + llvm::DenseSet constants; + for (auto &op : *block) + { + // no code of their own where they are: the frame's slots (made at the start of the + // function, at their variables' declarations), what the debugger is told about + // variables, and constants - with what is computed from constants alone (a string's + // address: a constant expression, hoisted to the start of the function) + if (mlir::isa(op)) + { + continue; + } + + if (op.getNumRegions() == 0 && op.getNumResults() > 0 && mlir::isMemoryEffectFree(&op) && + llvm::all_of(op.getOperands(), [&](mlir::Value operand) { return constants.contains(operand); })) + { + for (auto result : op.getResults()) + { + constants.insert(result); + } + + continue; + } + + auto line = lineOf(op.getLoc()); + if (line == 0) + { + continue; + } + + auto sameFile = !functionFile || fileLocOf(op.getLoc()).getFilename() == functionFile.getFilename(); + if (callsHiddenFunction(&op) || (sameFile && line < furthest)) + { + op.setLoc(withoutLine(op.getLoc())); + continue; + } + + if (sameFile) + { + furthest = std::max(furthest, line); + } + } + }); + } +}; +} // end anonymous namespace + +#undef DEBUG_TYPE + +std::unique_ptr mlir_ts::createDebugStepLocationsPass(const CompileOptions &compileOptions, + bool optimized) +{ + auto codeView = !compileOptions.lldbDebugInfo && + llvm::Triple(compileOptions.moduleTargetTriple).isKnownWindowsMSVCEnvironment(); + return std::make_unique(codeView, optimized); +} diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index f034813dc..b699e7285 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -187,6 +187,19 @@ struct ExitOpLowering : public TsPattern rewriter.create(op.getLoc(), retBlock); + // the return block was made with the entry, at the function's opening brace: the way out + // is where the exit is, its closing brace (MLIRGen), which is where a debugger shows it + if (tsContext->compileOptions.generateDebugInfo) + { + for (auto &retOp : *retBlock) + { + if (retOp.getLoc() != op.getLoc()) + { + rewriter.modifyOpInPlace(&retOp, [&]() { retOp.setLoc(op.getLoc()); }); + } + } + } + rewriter.eraseOp(op); return success(); } diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index b7568fc42..966f61f76 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -4879,7 +4879,7 @@ namespace mlirgen { MLIRDebugInfoHelper mdi(builder, debugScope); auto plainLocation = stripMetadata(location); - funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation, /*glue=*/true)); noLocation = locFuseWithScope(plainLocation); } @@ -5056,7 +5056,7 @@ namespace mlirgen { MLIRDebugInfoHelper mdi(builder, debugScope); mlir::Location plainLocation = fileLoc; - funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation, /*glue=*/true)); noLocation = locFuseWithScope(plainLocation); } @@ -5211,7 +5211,7 @@ namespace mlirgen { MLIRDebugInfoHelper mdi(builder, debugScope); mlir::Location plainLocation = fileLoc; - funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation, /*glue=*/true)); noLocation = locFuseWithScope(plainLocation); } diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 6e7fe6f3a..b89964bfe 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -4578,7 +4578,7 @@ genContext); MLIRDebugInfoHelper mdi(builder, debugScope); mlir::Location plainLocation = fileLoc; - funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation, /*glue=*/true)); noLocation = locFuseWithScope(plainLocation); } @@ -4660,7 +4660,7 @@ genContext); { MLIRDebugInfoHelper mdi(builder, debugScope); mlir::Location plainLocation = fileLoc; - funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, thunkName, thunkName, plainLocation, /*glue=*/true)); noLocation = locFuseWithScope(plainLocation); } diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index a3a9e40ce..acbd95668 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -3319,16 +3319,24 @@ namespace mlirgen } } + // the way out of a function is its closing brace, as a debugger shows it (not its opening + // one, where `location` is) + auto exitLocation = location; + if (compileOptions.generateDebugInfo && functionLikeDeclarationBaseAST->body == SyntaxKind::Block) + { + exitLocation = locEnd(functionLikeDeclarationBaseAST->body); + } + // Falling off the end of the body reaches here rather than through a `return`, and the // body block's own exit stops at itself. A `return` inside walks the whole stack outwards // and so has already released these on its own path. - if (failed(mlirGenReleaseOwned(location, DisposeDepth::CurrentScope, {}, &funcGenContext))) + if (failed(mlirGenReleaseOwned(exitLocation, DisposeDepth::CurrentScope, {}, &funcGenContext))) { return mlir::failure(); } // add exit code - if (failed(mlirGenFunctionExit(location, funcGenContext))) + if (failed(mlirGenFunctionExit(exitLocation, funcGenContext))) { return mlir::failure(); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 1f0dc3c3b..73aa30e65 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -311,6 +311,7 @@ class MLIRGenImpl void devirtualizeClosedMethods(); void markFinalClasses(); void markReadonlyFields(); + void markDebugStatements(); bool registerNamespace(llvm::StringRef namePtr, bool isFunctionNamespace = false); @@ -23782,6 +23783,104 @@ class MLIRGenImpl return locFuseWithScope(combine(overwriteLoc, locWithoutScope(loc))); } + // where the node ends: its last character (a block's closing brace) + mlir::Location locEnd(TextRange node) + { + if (!node || node->isTextRangeEmpty() || node->_end <= 0) + { + return loc(node); + } + + auto posLineChar = parser.getLineAndCharacterOfPosition(sourceFile, node->_end - 1); + auto end = mlir::FileLineColLoc::get(builder.getContext(), getStringAttr(mainSourceFileName.str()), + posLineChar.line + 1, posLineChar.character + 1); + return locFuseWithScope(combine(overwriteLoc, end)); + } + + // Is the node one of the current source file's tree? Each file's nodes are collected once. + bool isNodeOfSourceFile(Node node) + { + if (!sourceFile) + { + return false; + } + + auto *file = sourceFile.operator->(); + auto it = sourceFileNodes.find(file); + if (it == sourceFileNodes.end()) + { + auto &nodes = sourceFileNodes[file]; + ts::FuncT<> visitNode; + ts::ArrayFuncT<> visitArray; + visitNode = [&](Node child) -> Node { + if (!child) + { + return undefined; + } + + nodes.insert(child.operator->()); + ts::forEachChild(child, visitNode, visitArray); + return undefined; + }; + visitArray = [&](NodeArray array) -> Node { + for (auto child : array) + { + visitNode(child); + } + + return undefined; + }; + ts::forEachChild(sourceFile.as(), visitNode, visitArray); + it = sourceFileNodes.find(file); + } + + return it->second.contains(static_cast(node.operator->())); + } + + // Under --di, a statement a debugger is to stop at: where it starts and where it ends, in the + // terms the locations of its ops are in (DebugStepLocationsPass) + void recordDebugStatement(Node statement) + { + if (!compileOptions.generateDebugInfo || !statement || statement->isTextRangeEmpty()) + { + return; + } + + // Only a statement of the file being generated: code is made from other files' trees too + // while it is (a default library declaration, a generic instantiated from one), and their + // positions, read in this file, are no place in it - a statement of them took in the way + // out of a function of the program. + if (!isNodeOfSourceFile(statement)) + { + return; + } + + auto start = dyn_cast(locWithoutScope(statement)); + if (!start) + { + return; + } + + auto endLineChar = parser.getLineAndCharacterOfPosition(sourceFile, statement->_end); + auto line = (int32_t)start.getLine(); + auto column = (int32_t)start.getColumn(); + auto endLine = (int32_t)endLineChar.line + 1; + auto endColumn = (int32_t)endLineChar.character + 1; + if (endLine < line || (endLine == line && endColumn <= column)) + { + return; + } + + auto file = start.getFilename().getValue(); + if (!debugStatementsSeen.insert({file.str(), line, column, endLine, endColumn}).second) + { + return; + } + + auto &ranges = debugStatements[file]; + ranges.append({line, column, endLine, endColumn}); + } + // where the node is in the source, without the debug scope and the overwriteLoc loc() adds mlir::Location locWithoutScope(TextRange loc) { @@ -24101,7 +24200,7 @@ class MLIRGenImpl { MLIRDebugInfoHelper mdi(builder, debugScope); auto plainLocation = stripMetadata(location); - funcOp->setLoc(mdi.getSubprogram(plainLocation, name, name, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, name, name, plainLocation, /*glue=*/true)); noLocation = locFuseWithScope(plainLocation); } @@ -25397,6 +25496,12 @@ class MLIRGenImpl // where the innermost statement being generated is (no debug scope: loc() adds the current // one): the location of the nodes the compiler makes for it, which have none of their own mlir::Location generatedNodesAnchor; + // under --di, the statements generated, by file: [line, column, end line, end column]... - + // where a debugger stops (DEBUG_STATEMENTS_ATTR_NAME) + llvm::StringMap> debugStatements; + std::set> debugStatementsSeen; + // the nodes of each source file's tree (isNodeOfSourceFile) + llvm::DenseMap> sourceFileNodes; }; } // namespace mlirgen } // namespace typescript diff --git a/tslang/lib/TypeScript/MLIRGenModule.cpp b/tslang/lib/TypeScript/MLIRGenModule.cpp index 568af88e7..0a5a78db8 100644 --- a/tslang/lib/TypeScript/MLIRGenModule.cpp +++ b/tslang/lib/TypeScript/MLIRGenModule.cpp @@ -1338,6 +1338,7 @@ namespace mlirgen { devirtualizeClosedMethods(); markFinalClasses(); + markDebugStatements(); return theModule; } } @@ -1352,6 +1353,22 @@ namespace mlirgen // or one of its subclasses so - keeps its methods virtual. // The classes whose objects are of that class only, for -mm=own (OWN_FINAL_CLASSES_ATTR_NAME, // TSLANG 84): a @final class, or a declared @cpp one (a C++ object, which holds nothing of ours). + void MLIRGenImpl::markDebugStatements() + { + if (!compileOptions.generateDebugInfo || debugStatements.empty()) + { + return; + } + + llvm::SmallVector files; + for (auto &entry : debugStatements) + { + files.push_back(builder.getNamedAttr(entry.getKey(), builder.getDenseI32ArrayAttr(entry.getValue()))); + } + + theModule->setAttr(DEBUG_STATEMENTS_ATTR_NAME, builder.getDictionaryAttr(files)); + } + void MLIRGenImpl::markFinalClasses() { llvm::SmallVector finals; diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 0457db37e..6fe36b2c4 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -1054,6 +1054,32 @@ namespace mlirgen } auto kind = (SyntaxKind)statementAST; + + // a statement that runs is where a debugger stops; a declaration or a block is not (the + // statements in it are) + switch (kind) + { + case SyntaxKind::ExpressionStatement: + case SyntaxKind::VariableStatement: + case SyntaxKind::IfStatement: + case SyntaxKind::ReturnStatement: + case SyntaxKind::DoStatement: + case SyntaxKind::WhileStatement: + case SyntaxKind::ForStatement: + case SyntaxKind::ForInStatement: + case SyntaxKind::ForOfStatement: + case SyntaxKind::ContinueStatement: + case SyntaxKind::BreakStatement: + case SyntaxKind::SwitchStatement: + case SyntaxKind::ThrowStatement: + case SyntaxKind::TryStatement: + case SyntaxKind::DebuggerStatement: + recordDebugStatement(statementAST); + break; + default: + break; + } + if (kind == SyntaxKind::FunctionDeclaration) { return mlirGen(statementAST.as(), genContext); @@ -3529,7 +3555,7 @@ namespace mlirgen { MLIRDebugInfoHelper mdi(builder, debugScope); auto plainLocation = stripMetadata(location); - funcOp->setLoc(mdi.getSubprogram(plainLocation, name, name, plainLocation)); + funcOp->setLoc(mdi.getSubprogram(plainLocation, name, name, plainLocation, /*glue=*/true)); location = locFuseWithScope(plainLocation); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 5c23a723a..bf8e8ef47 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4539,6 +4539,13 @@ add_test(NAME test-compile-debug-info-opt -DTESTS_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests -P ${CMAKE_CURRENT_SOURCE_DIR}/debug-info-opt.cmake) +# Where a debugger stops in a program built with debug info - see debug-info-steps.cmake. +add_test(NAME test-compile-debug-info-steps + COMMAND ${CMAKE_COMMAND} + -DTSLANG=$ + -DTESTS_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests + -P ${CMAKE_CURRENT_SOURCE_DIR}/debug-info-steps.cmake) + # Debug info without optimisation, for the functions the compiler makes itself - see # debug-info-glue.cmake. add_test(NAME test-compile-debug-info-glue diff --git a/tslang/test/tester/debug-info-steps.cmake b/tslang/test/tester/debug-info-steps.cmake new file mode 100644 index 000000000..ade18a2a2 --- /dev/null +++ b/tslang/test/tester/debug-info-steps.cmake @@ -0,0 +1,122 @@ +# The line table a debugger steps through, for a program built WITH debug info and no optimisation +# (`--di --opt_level=0`, as a debug build compiles), under every memory model: the lines each +# function stops at, in order (DebugStepLocationsPass). +# +# Every op had the place of the expression it was made for, so a debugger stopped at each of them - +# the Visual Studio debugger at every column, a dozen times for one `return` - went back and forth +# over a statement written on two lines, went back to a variable's declaration to release it at the +# end of its scope, returned through the function's first line, and stepped into the compiler's glue +# (a class's `.new`, the reference counting routines) shown at the user's lines. +# +# The rows of a function are the lines of its instructions with a location, in the order they are in +# the IR, without repeats and without line 0 (no stop of its own: CodeView adds no row for it, DWARF +# debuggers skip it). A run, not this, shows where a debugger goes; the IR has the table it goes by. + +if(NOT DEFINED TSLANG OR NOT DEFINED TESTS_DIR) + message(FATAL_ERROR "TSLANG and TESTS_DIR are both required") +endif() + +set(name 00debug_steps.ts) + +# function -> its rows up to its `ret` (the cold paths laid out after it, an allocation that failed, are +# no step); see 00debug_steps.ts. The loop's `v` steps back to the `for` from the loop's head, not from +# the end of its body. Under gc `main` starts the collector first, at the function's own line. +set(expected_sum "12 13 14 15 18 19") +set(expected_Point.len "6 7 9") +set(expected_main "22 23 24 25 26 27 28 29 31") +set(expected_main_gc "21 22 23 24 25 26 27 28 29 31") +set(functions sum Point.len main) + +set(failures "") +foreach(model gc rc none own) + set(ll "${name}.${model}.ll") + execute_process( + COMMAND "${TSLANG}" --emit=llvm --di --opt_level=0 -mm=${model} --no-default-lib + "${TESTS_DIR}/${name}" -o=${ll} + OUTPUT_QUIET + ERROR_VARIABLE diagnostics + RESULT_VARIABLE status) + + if(NOT status EQUAL 0) + string(REGEX MATCH "[^\n]*error:[^\n]*" first_line "${diagnostics}") + list(APPEND failures " -mm=${model}: exit ${status}: ${first_line}") + continue() + endif() + + file(STRINGS "${ll}" ir_lines) + file(REMOVE "${ll}") + + # !N = !DILocation(line: L, ...) -> line_N = L + foreach(ir_line IN LISTS ir_lines) + if(ir_line MATCHES "^!([0-9]+) = !DILocation\\(line: ([0-9]+)") + set(line_${CMAKE_MATCH_1} ${CMAKE_MATCH_2}) + endif() + endforeach() + + set(current "") + set(rows "") + set(last "") + set(returned FALSE) + set(defined "") + foreach(ir_line IN LISTS ir_lines) + if(ir_line MATCHES "^define [^@]*@\"?([^\"( ]+)\"?\\(") + set(current "${CMAKE_MATCH_1}") + list(APPEND defined "${current}") + set(rows "") + set(last "") + set(returned FALSE) + elseif(ir_line STREQUAL "}" AND current) + string(STRIP "${rows}" rows) + set(rows_${current} "${rows}") + set(current "") + # (the alloca test first: a MATCHES that fails clears CMAKE_MATCH_1) + elseif(current AND NOT returned AND NOT ir_line MATCHES " = alloca " + AND ir_line MATCHES "^ [^#].*!dbg !([0-9]+)") + set(row "${line_${CMAKE_MATCH_1}}") + if(NOT row STREQUAL "" AND NOT row STREQUAL "0" AND NOT row STREQUAL last) + string(APPEND rows " ${row}") + set(last "${row}") + endif() + if(ir_line MATCHES "^ ret ") + set(returned TRUE) + endif() + endif() + endforeach() + + foreach(function IN LISTS functions) + set(expected "${expected_${function}}") + if(DEFINED expected_${function}_${model}) + set(expected "${expected_${function}_${model}}") + endif() + if(NOT "${rows_${function}}" STREQUAL "${expected}") + list(APPEND failures " -mm=${model}: ${function} stops at [${rows_${function}}], expected [${expected}]") + endif() + endforeach() + + # the reference counting routines the lowering makes are not stepped into either + foreach(function IN LISTS defined) + if(function MATCHES "^(tsrelv?_|tsretv?_|__tslang_)" AND NOT rows_${function} STREQUAL "") + list(APPEND failures " -mm=${model}: ${function} stops at [${rows_${function}}], expected none") + endif() + unset(rows_${function}) + endforeach() + + # the class's own glue is not stepped into + foreach(glue "Point..new" "Point..instanceOf") + if(DEFINED rows_${glue} AND NOT rows_${glue} STREQUAL "") + list(APPEND failures " -mm=${model}: ${glue} stops at [${rows_${glue}}], expected none") + endif() + unset(rows_${glue}) + endforeach() + + foreach(function IN LISTS functions) + unset(rows_${function}) + endforeach() +endforeach() + +if(failures) + string(REPLACE ";" "\n" report "${failures}") + message(FATAL_ERROR "debug info steps:\n${report}") +endif() + +message(STATUS "debug info steps: each function stops once at each statement") diff --git a/tslang/test/tester/jit-native.cmake b/tslang/test/tester/jit-native.cmake index 37eab813e..fd6e303c0 100644 --- a/tslang/test/tester/jit-native.cmake +++ b/tslang/test/tester/jit-native.cmake @@ -104,9 +104,10 @@ endif() if(DEFINED CDB AND EXISTS "${CDB}") # The DLL linked above, by name: the debugger stops when it loads, loads its PDB, and then stops - # in the imported module's `greeting`, whose frame the PDB places on line 1 of - # greeting_module.ts. A breakpoint on the line itself would be ambiguous - the module's - # initializer is on line 1 too - and optimized, `greeting` has no code on any other. dbgeng + # in the imported module's `greeting`, whose frame the PDB places on one of its lines in + # greeting_module.ts: its `return` (line 2) without optimization, its closing brace (line 3, the + # way out, which is all the optimizer leaves of it) with. A breakpoint on a line would be + # ambiguous - the module's initializer is on line 1. dbgeng # names the module after the file with its dots made underscores. Symbols only from __jit, so # nothing is fetched from a symbol server. `q` ends tslang too. list(GET third 0 dll) @@ -122,8 +123,8 @@ if(DEFINED CDB AND EXISTS "${CDB}") ERROR_VARIABLE err RESULT_VARIABLE status TIMEOUT 120) - if(NOT out MATCHES "Breakpoint 0 hit" OR NOT out MATCHES "${module}!greeting [^\n]*greeting_module\\.ts @ 1") - message(FATAL_ERROR "cdb did not stop in ${module}!greeting at greeting_module.ts line 1:\n${out}\n${err}") + if(NOT out MATCHES "Breakpoint 0 hit" OR NOT out MATCHES "${module}!greeting [^\n]*greeting_module\\.ts @ [1-3]\\]") + message(FATAL_ERROR "cdb did not stop in ${module}!greeting at a line of greeting_module.ts:\n${out}\n${err}") endif() message(STATUS "cdb stops in a function of the imported module, at its source line") endif() diff --git a/tslang/test/tester/tests/00debug_steps.ts b/tslang/test/tester/tests/00debug_steps.ts new file mode 100644 index 000000000..e6231c96d --- /dev/null +++ b/tslang/test/tester/tests/00debug_steps.ts @@ -0,0 +1,31 @@ +// The line table a debugger steps through (debug-info-steps.cmake checks the rows of each function): +// one stop at each statement, the way out at the closing brace, nothing in the compiler's own glue. +class Point { + constructor(public x: number, public y: number) {} + + len() { + return this.x * this.x + + this.y * this.y; + } +} + +function sum(arr: number[]) { + let total = 0; + for (const v of arr) { + total += v; + } + + return total; +} + +function main() { + const p = new Point(3, 4); + const s = "len=" + p.len(); + print(s); + const a = [1, 2, 3]; + const t = sum(a); + print(t); + if (t > 5) { + print("big"); + } +} diff --git a/tslang/tslang/transform.cpp b/tslang/tslang/transform.cpp index 6586eb895..2d70b3aa9 100644 --- a/tslang/tslang/transform.cpp +++ b/tslang/tslang/transform.cpp @@ -290,6 +290,7 @@ int runMLIRPasses(mlir::MLIRContext &context, llvm::SourceMgr &sourceMgr, mlir:: pm.addPass(mlir::typescript::createInlinedLocationPass()); } + pm.addPass(mlir::typescript::createDebugStepLocationsPass(compileOptions, enableOpt)); pm.addPass(mlir::LLVM::createDIScopeForLLVMFuncOpPass()); } From 231e50666bf622ada123044714bc6a2b6f9458a2 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 4 Dec 2026 01:22:30 +0000 Subject: [PATCH 2/5] --di steps: field initializers and callbacks keep their rows; fold only lines already stopped at - A field's initializer is a step of its own (recorded where the field is typed): `class B { v = make() }` had its constructor hidden, and initializers before or after an explicit constructor lost their row or folded the constructor's statements away. - A function's body is a barrier in the statement table: a callback written in a call keeps its own closing brace instead of the call's line. - Code going back in a block, or a call into glue, folds only onto a line already stopped at (the function's own line counts): `noop();` of an empty function keeps its row, and a constructor steps through initializers written after it, then its statements. Inlined ops (--opt) are left alone. - 00debug_steps.ts covers these shapes. Co-Authored-By: Claude Opus 5.5 --- docs/whats-new.md | 2 +- tslang/include/TypeScript/Defines.h | 4 +- .../lib/TypeScript/DebugStepLocationsPass.cpp | 69 ++++++++++++++----- tslang/lib/TypeScript/MLIRGenClasses.cpp | 6 ++ tslang/lib/TypeScript/MLIRGenFunctions.cpp | 6 ++ tslang/lib/TypeScript/MLIRGenImpl.h | 14 ++-- tslang/test/tester/debug-info-steps.cmake | 19 ++++- tslang/test/tester/tests/00debug_steps.ts | 22 ++++++ 8 files changed, 112 insertions(+), 30 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index f4bbd8398..8ddcee07e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,6 +1,6 @@ # What's new -- Stepping through a program built with `--di` stops once at each statement: the line table has one row for a statement where it had one for each expression in it (and a column for each, which the Visual Studio debugger and VS Code's cppvsdbg step through), and a debugger no longer goes back and forth over a statement written on several lines or back to a variable's declaration at the end of its scope, leaves a function at its closing brace (not at its first line), and steps over the compiler's own functions (a class's `.new` and `.instanceOf`, a cast's thunk, the reference counting routines), which have no source line. Under CodeView the line table has no columns, as clang leaves them out for the Microsoft debuggers +- Stepping through a program built with `--di` stops once at each statement: the line table had a row for each expression and a column for each, and now has one row for a statement, so a debugger no longer goes back and forth over a statement written on several lines or back to a variable's declaration to release it at the end of its scope. A function is left at its closing brace (not at its first line), a constructor steps through its fields' initializers before its own statements, a callback written in a call keeps its own lines, and the compiler's own functions (a class's `.new` and `.instanceOf`, a cast's thunk, the reference counting routines) have no source line, so a debugger steps over them. Under CodeView the line table has no columns, as clang leaves them out: the Microsoft debuggers handle start columns without end columns badly. A default library built before this keeps its columns until it is rebuilt - A function of the program named as a function of the default library is the program's own: `function sleep(ms: number): string` beside the library's generic `sleep` compiles and is called (it took the library's type, "can't find return variable"), a program's `__is_any` or a generic function of that name is called instead of the library's, and one named as a function the library declares keeps the signature it is written with. The library's own code, its generics made in the program included (a `Map`'s hashing, `toSpliced`), still calls the library's - **JSX** runs as it is: with no factory named, an element is a call of the default library's `h`, which makes a `JsxElement` (its tag, attributes and children) that prints and turns into a string as HTML (`print(

a < b

)` prints `

a < b

`). A tag that is a function is a component, called with the attributes and the children; `<>...` is a `Fragment`. tsc's default, `React.createElement`, is used only when named. When a statement fails with an error of its own, the "failed statement" error that followed it is no longer printed, and the error of a JSX factory that can't be found is shorter. Needs the default library of the same release - A mixed array literal is typed as tsc types it: an array of the union of its elements' types, `[1, "a"]` a `(s32 | string)[]` and `[3, { a: 4 }]` a `(s32 | { a: s32 })[]` (they were tuples), so it can grow and takes either member. It stays a tuple where the context asks for one: destructured (`const [n, s] = [1, "a"]`, `[x, y] = [y, x]`), given to a tuple parameter or a generic one inferred as a tuple, or pushed into an array of tuples. Code that indexes such a literal as a tuple (`[1, [2, 2]][1][1]`, which tsc refuses too) needs a tuple type (`const t: [number, number[]] = ...`). A union of primitives and object shapes (`number | { a: number }`) can be cast and printed: each member is told apart by its tag, and `print([3, { a: 4 }])` prints `[ 3, { a: 4 } ]` diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 6e9b8f013..81330391a 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -195,8 +195,8 @@ // routine of the base (OwnershipRoutineLogic) compares an object's vtable with each subclass's and // releases the fields of the class it is, not only the base's (rc and own). #define CLASS_BASES_ATTR_NAME "ts.class_bases" -// On the module, under --di: the statements of each file, as {file: [line, column, end line, end column]...} - -// where a debugger stops (DebugStepLocationsPass, which removes it). +// On the module, under --di: the statements of each file, as {file: [line, column, end line, end column, barrier]...} +// - where a debugger stops (DebugStepLocationsPass, which removes it). A barrier is a function's body. #define DEBUG_STATEMENTS_ATTR_NAME "ts.debug_statements" // The classes the module knows (its own and those it imports or declares) whose objects can't say which class they // are: a @cpp class (a C++ vtable), a @value or a static one (no RTTI). A union of classes is stored as the object's diff --git a/tslang/lib/TypeScript/DebugStepLocationsPass.cpp b/tslang/lib/TypeScript/DebugStepLocationsPass.cpp index 486b482e3..66c826af7 100644 --- a/tslang/lib/TypeScript/DebugStepLocationsPass.cpp +++ b/tslang/lib/TypeScript/DebugStepLocationsPass.cpp @@ -31,6 +31,8 @@ struct StatementRange int32_t column; int32_t endLine; int32_t endColumn; + // a function's body: what is in it and in no statement keeps its own line + bool barrier; int parent; bool startsAtOrBefore(int32_t l, int32_t c) const @@ -51,9 +53,9 @@ class FileStatements llvm::SmallVector ranges; public: - void add(int32_t line, int32_t column, int32_t endLine, int32_t endColumn) + void add(int32_t line, int32_t column, int32_t endLine, int32_t endColumn, bool barrier) { - ranges.push_back({line, column, endLine, endColumn, -1}); + ranges.push_back({line, column, endLine, endColumn, barrier, -1}); } void index() @@ -113,11 +115,13 @@ class FileStatements // is in: one stop for each statement, and the column only where the debugger handles columns // (not with CodeView: the Microsoft debuggers want an end column, which is never there - clang // leaves columns out for CodeView too). +// A function's body is a barrier: what is in it and in no statement of its own (its closing +// brace) keeps its line, not that of the statement the function is written in (a callback). // - Ops of no statement that are before the function (what a class's parameter properties make, -// at the start of the file), calls into compiler glue, and code that goes back to a statement -// already passed in the same block (releasing a variable at the end of its scope) get line 0: -// no stop of their own - CodeView adds no row for them, so they belong to the row before; -// DWARF debuggers skip line 0. +// at the start of the file) get line 0, and so does code that goes back, in the same block, to a +// line already stopped at (releasing a variable at the end of its scope, at its declaration), +// and a call into compiler glue at such a line: no stop of their own - CodeView adds no row for +// them, so they belong to the row before; DWARF debuggers skip line 0. // - A function with no statement of the program in it - compiler glue: a thunk, a class's `.new`, // `.instanceOf`, a routine the lowering made - gets line 0 for all its ops: a function with no // source, which a debugger steps over. @@ -188,9 +192,9 @@ class DebugStepLocationsPass : public mlir::PassWrapperwalk([&](mlir::Operation *op) { if (auto fileLoc = fileLocOf(op->getLoc())) { - if (statementAt(fileLoc)) + auto *statement = statementAt(fileLoc); + if (statement && !statement->barrier) { return mlir::WalkResult::interrupt(); } @@ -465,8 +470,16 @@ class DebugStepLocationsPass : public mlir::PassWrapper mlir::Location { if (auto *statement = statementAt(fileLoc)) { - return mlir::FileLineColLoc::get(fileLoc.getFilename(), statement->line, - codeView ? 0 : statement->column); + if (!statement->barrier) + { + return mlir::FileLineColLoc::get(fileLoc.getFilename(), statement->line, + codeView ? 0 : statement->column); + } + + // in a function's body and in no statement of it (its closing brace): where it is + return codeView && fileLoc.getColumn() != 0 + ? mlir::FileLineColLoc::get(fileLoc.getFilename(), fileLoc.getLine(), 0) + : mlir::Location(fileLoc); } // no statement, and before the function: what the compiler made for it at no place of @@ -520,9 +533,20 @@ class DebugStepLocationsPass : public mlir::PassWrapper stoppedAt; + if (functionLine) + { + stoppedAt.insert(functionLine); + } + funcOp->walk([&](mlir::Block *block) { unsigned furthest = 0; llvm::DenseSet constants; @@ -549,6 +573,12 @@ class DebugStepLocationsPass : public mlir::PassWrapperfindInstanceOf()) + { + continue; + } + auto line = lineOf(op.getLoc()); if (line == 0) { @@ -556,16 +586,19 @@ class DebugStepLocationsPass : public mlir::PassWrapper MLIRGenImpl::mlirGenClassDataFieldType(mlir::Location location, PropertyDeclaration propertyDeclaration, const GenContext &genContext) { + // a field's initializer is code of its own in the constructor: a place for a debugger to stop + if (propertyDeclaration->initializer) + { + recordDebugStatement(propertyDeclaration); + } + auto [type, init, typeProvided] = evaluateTypeAndInit(propertyDeclaration, genContext); // the initializer's type is widened (`x = "a"` is a string); a declared one is kept (`type: "bar" = "bar"` // implements an interface's `type: "bar"`), as a parameter property's is diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index acbd95668..74f2e8f6b 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -3072,6 +3072,12 @@ namespace mlirgen // new location withing FunctionScope location = loc(functionLikeDeclarationBaseAST->body); + // its body is a function of its own to a debugger, wherever it is written (a callback in a call) + if (functionLikeDeclarationBaseAST->body == SyntaxKind::Block) + { + recordDebugStatement(functionLikeDeclarationBaseAST->body, /*barrier=*/true); + } + GenContext funcGenContext(genContext); funcGenContext.funcOp = funcOp; // its parameters, for `arguments` (mlirGenArguments) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 73aa30e65..a9df0104e 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -23838,8 +23838,10 @@ class MLIRGenImpl } // Under --di, a statement a debugger is to stop at: where it starts and where it ends, in the - // terms the locations of its ops are in (DebugStepLocationsPass) - void recordDebugStatement(Node statement) + // terms the locations of its ops are in (DebugStepLocationsPass). A function's body is recorded as + // a barrier: what is in it but in no statement of its own (its closing brace) keeps its line, + // not that of the statement around the function (a callback given in a call). + void recordDebugStatement(Node statement, bool barrier = false) { if (!compileOptions.generateDebugInfo || !statement || statement->isTextRangeEmpty()) { @@ -23872,13 +23874,13 @@ class MLIRGenImpl } auto file = start.getFilename().getValue(); - if (!debugStatementsSeen.insert({file.str(), line, column, endLine, endColumn}).second) + if (!debugStatementsSeen.insert({file.str(), line, column, endLine, endColumn, barrier}).second) { return; } auto &ranges = debugStatements[file]; - ranges.append({line, column, endLine, endColumn}); + ranges.append({line, column, endLine, endColumn, barrier ? 1 : 0}); } // where the node is in the source, without the debug scope and the overwriteLoc loc() adds @@ -25496,10 +25498,10 @@ class MLIRGenImpl // where the innermost statement being generated is (no debug scope: loc() adds the current // one): the location of the nodes the compiler makes for it, which have none of their own mlir::Location generatedNodesAnchor; - // under --di, the statements generated, by file: [line, column, end line, end column]... - + // under --di, the statements generated, by file: [line, column, end line, end column, barrier]... - // where a debugger stops (DEBUG_STATEMENTS_ATTR_NAME) llvm::StringMap> debugStatements; - std::set> debugStatementsSeen; + std::set> debugStatementsSeen; // the nodes of each source file's tree (isNodeOfSourceFile) llvm::DenseMap> sourceFileNodes; }; diff --git a/tslang/test/tester/debug-info-steps.cmake b/tslang/test/tester/debug-info-steps.cmake index ade18a2a2..fa97d95b4 100644 --- a/tslang/test/tester/debug-info-steps.cmake +++ b/tslang/test/tester/debug-info-steps.cmake @@ -23,9 +23,14 @@ set(name 00debug_steps.ts) # the end of its body. Under gc `main` starts the collector first, at the function's own line. set(expected_sum "12 13 14 15 18 19") set(expected_Point.len "6 7 9") -set(expected_main "22 23 24 25 26 27 28 29 31") -set(expected_main_gc "21 22 23 24 25 26 27 28 29 31") -set(functions sum Point.len main) +set(expected_make "22 23") +# the constructor's line, its fields' initializers (one written after it too), then its own statements +set(expected_Fields.constructor "30 29 33 31 32") +# `noop();` keeps its row though `noop` has none; the callback's own rows end at its own brace +set(expected_main "37 38 39 40 41 42 43 44 47 50 51 52 53") +set(expected_main_gc "36 37 38 39 40 41 42 43 44 47 50 51 52 53") +set(expected_callback "47 48 49") +set(functions sum Point.len make Fields.constructor main callback) set(failures "") foreach(model gc rc none own) @@ -83,6 +88,14 @@ foreach(model gc rc none own) endif() endforeach() + # the arrow given to forEach, by its generated name + unset(rows_callback) + foreach(function IN LISTS defined) + if(function MATCHES "^\\.f_main\\.\\.af") + set(rows_callback "${rows_${function}}") + endif() + endforeach() + foreach(function IN LISTS functions) set(expected "${expected_${function}}") if(DEFINED expected_${function}_${model}) diff --git a/tslang/test/tester/tests/00debug_steps.ts b/tslang/test/tester/tests/00debug_steps.ts index e6231c96d..ca1153e05 100644 --- a/tslang/test/tester/tests/00debug_steps.ts +++ b/tslang/test/tester/tests/00debug_steps.ts @@ -18,6 +18,21 @@ function sum(arr: number[]) { return total; } +function make() { + return 5; +} + +function noop() {} + +// the initializers run first, the one written after the constructor too +class Fields { + v = make(); + constructor() { + print("ctor"); + } + w = make(); +} + function main() { const p = new Point(3, 4); const s = "len=" + p.len(); @@ -28,4 +43,11 @@ function main() { if (t > 5) { print("big"); } + + a.forEach((x) => { + print(x); + }); + noop(); + const f = new Fields(); + print(f.v + f.w); } From c2462871fe132643fde74f342e9d962f422c5e1d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 4 Dec 2026 02:01:43 +0000 Subject: [PATCH 3/5] --di: a default library's generic is in the library's file, its blocks too; the compiler's own TypeScript is at no line of the program's; functions stepped over have no first line A lexical block took the compile unit's file, so the rows of a default library's generic made in the program (Array.sort's mergeSort) were shown at lines of the program past its end. Code parsed from the compiler's own TypeScript (helper sources, Math.max, inspect) took the program's file and line map; its nodes are now located in a pseudo-file `` that DebugStepLocationsPass gives line 0. A hidden function's subprogram (or the one made for a lowering routine) is at line 0, so CodeView gives it no row at its first line for a step into it to stop at. Co-Authored-By: Claude Opus 5.5 --- docs/whats-new.md | 2 +- tslang/include/TypeScript/Defines.h | 4 + .../MLIRLogic/MLIRDebugInfoHelper.h | 14 +- .../lib/TypeScript/DebugStepLocationsPass.cpp | 47 ++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 40 +++++- tslang/test/tester/debug-info-steps.cmake | 134 +++++++++++++++++- tslang/test/tester/tests/00debug_steps.ts | 5 + 7 files changed, 236 insertions(+), 10 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index 8ddcee07e..e05403cd5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,6 +1,6 @@ # What's new -- Stepping through a program built with `--di` stops once at each statement: the line table had a row for each expression and a column for each, and now has one row for a statement, so a debugger no longer goes back and forth over a statement written on several lines or back to a variable's declaration to release it at the end of its scope. A function is left at its closing brace (not at its first line), a constructor steps through its fields' initializers before its own statements, a callback written in a call keeps its own lines, and the compiler's own functions (a class's `.new` and `.instanceOf`, a cast's thunk, the reference counting routines) have no source line, so a debugger steps over them. Under CodeView the line table has no columns, as clang leaves them out: the Microsoft debuggers handle start columns without end columns badly. A default library built before this keeps its columns until it is rebuilt +- Stepping through a program built with `--di` stops once at each statement: the line table had a row for each expression and a column for each, and now has one row for a statement, so a debugger no longer goes back and forth over a statement written on several lines or back to a variable's declaration to release it at the end of its scope. A function is left at its closing brace (not at its first line), a constructor steps through its fields' initializers before its own statements, a callback written in a call keeps its own lines, and the compiler's own functions (a class's `.new` and `.instanceOf`, a cast's thunk, the reference counting routines) have no source line, so a debugger steps over them. Under CodeView the line table has no columns, as clang leaves them out: the Microsoft debuggers handle start columns without end columns badly. A default library built before this keeps its columns until it is rebuilt. The default library's generics made in the program (`Array.sort`, `join`) are shown in the library's file, not at lines of the program's past its end, and the code the compiler makes from TypeScript of its own (`Math.max`, printing an array, casting from `any`) is at no line of the program's; the functions a debugger steps over have no first line to stop at either - A function of the program named as a function of the default library is the program's own: `function sleep(ms: number): string` beside the library's generic `sleep` compiles and is called (it took the library's type, "can't find return variable"), a program's `__is_any` or a generic function of that name is called instead of the library's, and one named as a function the library declares keeps the signature it is written with. The library's own code, its generics made in the program included (a `Map`'s hashing, `toSpliced`), still calls the library's - **JSX** runs as it is: with no factory named, an element is a call of the default library's `h`, which makes a `JsxElement` (its tag, attributes and children) that prints and turns into a string as HTML (`print(

a < b

)` prints `

a < b

`). A tag that is a function is a component, called with the attributes and the children; `<>...` is a `Fragment`. tsc's default, `React.createElement`, is used only when named. When a statement fails with an error of its own, the "failed statement" error that followed it is no longer printed, and the error of a JSX factory that can't be found is shorter. Needs the default library of the same release - A mixed array literal is typed as tsc types it: an array of the union of its elements' types, `[1, "a"]` a `(s32 | string)[]` and `[3, { a: 4 }]` a `(s32 | { a: s32 })[]` (they were tuples), so it can grow and takes either member. It stays a tuple where the context asks for one: destructured (`const [n, s] = [1, "a"]`, `[x, y] = [y, x]`), given to a tuple parameter or a generic one inferred as a tuple, or pushed into an array of tuples. Code that indexes such a literal as a tuple (`[1, [2, 2]][1][1]`, which tsc refuses too) needs a tuple type (`const t: [number, number[]] = ...`). A union of primitives and object shapes (`number | { a: number }`) can be cast and printed: each member is told apart by its tag, and `print([3, { a: 4 }])` prints `[ 3, { a: 4 } ]` diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 81330391a..c8353c652 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -198,6 +198,10 @@ // On the module, under --di: the statements of each file, as {file: [line, column, end line, end column, barrier]...} // - where a debugger stops (DebugStepLocationsPass, which removes it). A barrier is a function's body. #define DEBUG_STATEMENTS_ATTR_NAME "ts.debug_statements" +// The file the locations of code made from the compiler's own TypeScript (a helper's source, a library's +// printed declarations - parsePartialStatements) are in: their positions are in that text, not in any file. +// No line of it is a debugger's (DebugStepLocationsPass). +#define HELPER_SOURCE_FILE_NAME "" // The classes the module knows (its own and those it imports or declares) whose objects can't say which class they // are: a @cpp class (a C++ vtable), a @value or a static one (no RTTI). A union of classes is stored as the object's // pointer alone, the class asked of the object (`.instanceOf`), unless one of these is among them (user ruling diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h index d071b588e..2cd6ee861 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRDebugInfoHelper.h @@ -222,13 +222,17 @@ class MLIRDebugInfoHelper { if (auto scopeAttr = dyn_cast_or_null(debugScope.lookup(DEBUG_SCOPE))) { - auto [scopeLine, scopeColumn] = LocationHelper::getLineAndColumn(blockLocation); + // the block's own file, as a function's: a default library's generic made in the program is in the + // library's file, and a debugger showed the lines in its blocks as the program's + LocationHelper lh(builder.getContext()); + auto [blockFile, scopeLineAndColumn] = lh.getLineAndColumnAndFile(blockLocation); + auto [scopeLine, scopeColumn] = scopeLineAndColumn; - auto lexicalBlockAttr = + auto lexicalBlockAttr = mlir::LLVM::DILexicalBlockAttr::get( - builder.getContext(), - scopeAttr, - fileAttr, + builder.getContext(), + scopeAttr, + blockFile ? blockFile : fileAttr, scopeLine, scopeColumn); diff --git a/tslang/lib/TypeScript/DebugStepLocationsPass.cpp b/tslang/lib/TypeScript/DebugStepLocationsPass.cpp index 66c826af7..42b299952 100644 --- a/tslang/lib/TypeScript/DebugStepLocationsPass.cpp +++ b/tslang/lib/TypeScript/DebugStepLocationsPass.cpp @@ -11,6 +11,7 @@ #include "mlir/Interfaces/SideEffectInterfaces.h" #include "llvm/ADT/StringMap.h" +#include "llvm/BinaryFormat/Dwarf.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #include "llvm/TargetParser/Triple.h" @@ -422,6 +423,46 @@ class DebugStepLocationsPass : public mlir::PassWrappersetLoc(noLine); }, [&](mlir::BlockArgument arg) { arg.setLoc(noLine); }); + + // nor the function's own line: CodeView gives a function with a prologue a row at its subprogram's + // scope line, where a step into it stopped (a class's `.new` at the class, a helper in ``) + auto funcLoc = withoutLine(funcOp->getLoc()); + if (subprogram && (subprogram.getLine() != 0 || subprogram.getScopeLine() != 0)) + { + auto noLineSubprogram = mlir::LLVM::DISubprogramAttr::get( + context, mlir::DistinctAttr::create(mlir::UnitAttr::get(context)), subprogram.getCompileUnit(), + subprogram.getScope(), subprogram.getName(), subprogram.getLinkageName(), subprogram.getFile(), + /*line=*/0, /*scopeLine=*/0, subprogram.getSubprogramFlags(), subprogram.getType(), + subprogram.getRetainedNodes(), subprogram.getAnnotations()); + + mlir::AttrTypeReplacer replacer; + replacer.addReplacement([&](mlir::LLVM::DISubprogramAttr attr) -> std::optional { + return attr == subprogram ? std::optional(noLineSubprogram) : std::nullopt; + }); + funcLoc = mlir::cast(replacer.replace(funcLoc)); + } + else if (!subprogram) + { + // a routine of the lowering: DIScopeForLLVMFuncOpPass would give it one at line 1 of the program + if (auto unit = + getModule()->getLoc()->findInstanceOf>()) + { + auto compileUnit = unit.getMetadata(); + auto type = mlir::LLVM::DISubroutineTypeAttr::get(context, llvm::dwarf::DW_CC_normal, {}); + llvm::SmallVector retainedNodes; + llvm::SmallVector annotations; + auto noLineSubprogram = mlir::LLVM::DISubprogramAttr::get( + context, mlir::DistinctAttr::create(mlir::UnitAttr::get(context)), compileUnit, + mlir::LLVM::DIScopeAttr(compileUnit), funcOp.getSymNameAttr(), funcOp.getSymNameAttr(), + compileUnit.getFile(), + /*line=*/0, /*scopeLine=*/0, + mlir::LLVM::DISubprogramFlags::Definition | mlir::LLVM::DISubprogramFlags::LocalToUnit, type, + retainedNodes, annotations); + funcLoc = mlir::FusedLoc::get(context, {noLine}, noLineSubprogram); + } + } + + funcOp->setLoc(funcLoc); } // the line a location is shown at, 0 for none @@ -468,6 +509,12 @@ class DebugStepLocationsPass : public mlir::PassWrappergetLoc()); auto toStatement = [&](mlir::FileLineColLoc fileLoc) -> mlir::Location { + // the compiler's own TypeScript: no line of a file a debugger could show + if (fileLoc.getFilename().getValue() == HELPER_SOURCE_FILE_NAME) + { + return mlir::FileLineColLoc::get(fileLoc.getFilename(), 0, 0); + } + if (auto *statement = statementAt(fileLoc)) { if (!statement->barrier) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index a9df0104e..40a9211e5 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -23786,7 +23786,8 @@ class MLIRGenImpl // where the node ends: its last character (a block's closing brace) mlir::Location locEnd(TextRange node) { - if (!node || node->isTextRangeEmpty() || node->_end <= 0) + if (!node || node->isTextRangeEmpty() || node->_end <= 0 || + helperNodeSources.contains(static_cast(node.operator->()))) { return loc(node); } @@ -23887,6 +23888,13 @@ class MLIRGenImpl mlir::Location locWithoutScope(TextRange loc) { auto pos = loc->pos.textPos > 0 ? loc->pos.textPos : loc->pos.pos; + // a node of the compiler's own TypeScript: where it is in that text (parsePartialStatements) + if (auto helper = helperNodeSources.find(static_cast(loc.operator->())); + helper != helperNodeSources.end()) + { + return loc2Fuse(helper->second, HELPER_SOURCE_FILE_NAME, pos, loc->_end - pos); + } + //return loc1(sourceFile, fileName.str(), pos, loc->_end - pos); //return loc2(sourceFile, fileName.str(), pos, loc->_end - pos); return loc2Fuse(sourceFile, mainSourceFileName.str(), pos, loc->_end - pos); @@ -24238,6 +24246,34 @@ class MLIRGenImpl // .d.ts will mark all variables as external (be careful) auto module = parser.parseSourceFile(file_d_ts ? S("partial.d.ts") : S("partial.ts"), src, ScriptTarget::Latest); + // Its nodes' positions are in this text, not in the file being generated: their locations say + // so (locWithoutScope), or a debugger showed a helper's code at lines of the program it does not + // have. Kept by node, as a generic made in it is instantiated later, from the same nodes. + { + ts::FuncT<> visitNode; + ts::ArrayFuncT<> visitArray; + visitNode = [&](Node child) -> Node { + if (!child) + { + return undefined; + } + + TextRange range = child; + helperNodeSources[static_cast(range.operator->())] = module; + ts::forEachChild(child, visitNode, visitArray); + return undefined; + }; + visitArray = [&](NodeArray array) -> Node { + for (auto child : array) + { + visitNode(child); + } + + return undefined; + }; + ts::forEachChild(module.as(), visitNode, visitArray); + } + if (helper) { // `__x` is escaped by the parser as `___x` @@ -25504,6 +25540,8 @@ class MLIRGenImpl std::set> debugStatementsSeen; // the nodes of each source file's tree (isNodeOfSourceFile) llvm::DenseMap> sourceFileNodes; + // the nodes of the compiler's own TypeScript, with the text they were parsed from (parsePartialStatements) + llvm::DenseMap helperNodeSources; }; } // namespace mlirgen } // namespace typescript diff --git a/tslang/test/tester/debug-info-steps.cmake b/tslang/test/tester/debug-info-steps.cmake index fa97d95b4..4f6aaa1fe 100644 --- a/tslang/test/tester/debug-info-steps.cmake +++ b/tslang/test/tester/debug-info-steps.cmake @@ -30,7 +30,14 @@ set(expected_Fields.constructor "30 29 33 31 32") set(expected_main "37 38 39 40 41 42 43 44 47 50 51 52 53") set(expected_main_gc "36 37 38 39 40 41 42 43 44 47 50 51 52 53") set(expected_callback "47 48 49") -set(functions sum Point.len make Fields.constructor main callback) +set(expected_helpers "56 57 58") +set(functions sum Point.len make Fields.constructor main callback helpers) + +# the program's last line: the code made from the compiler's own TypeScript (a helper's source, Math.max's) +# was shown at its lines in that text, as lines of the program, past its end +file(READ "${TESTS_DIR}/${name}" source) +string(REGEX MATCHALL "\n" newlines "${source}") +list(LENGTH newlines last_line) set(failures "") foreach(model gc rc none own) @@ -52,11 +59,54 @@ foreach(model gc rc none own) file(REMOVE "${ll}") # !N = !DILocation(line: L, ...) -> line_N = L + # !N = !DIFile(filename: "00debug_steps.ts", ...): the program's file + set(program_file "") + foreach(ir_line IN LISTS ir_lines) + if(ir_line MATCHES "^(![0-9]+) = !DIFile\\(filename: \"${name}\"") + set(program_file "${CMAKE_MATCH_1}") + endif() + endforeach() + + # a function stepped over has no line of its own either: CodeView gives a function a row at its + # subprogram's scope line, where a step into it stopped + foreach(ir_line IN LISTS ir_lines) + if(ir_line MATCHES "^define [^@]*@\"?(Point\\.\\.new|Point\\.\\.instanceOf|\\.math_[^\"( ]*|\\.inspect_[^\"( ]*|tsrelv?_[0-9]+|tsretv?_[0-9]+|__ts_[^\"( ]*)\"?\\(.* !dbg (![0-9]+)") + set(glue_subprogram_${CMAKE_MATCH_2} "${CMAKE_MATCH_1}") + list(APPEND glue_subprograms "${CMAKE_MATCH_2}") + endif() + endforeach() + foreach(ir_line IN LISTS ir_lines) + if(ir_line MATCHES "^(![0-9]+) = distinct !DISubprogram\\(.*[( ](line|scopeLine): [1-9]") + if(DEFINED glue_subprogram_${CMAKE_MATCH_1}) + list(APPEND failures " -mm=${model}: ${glue_subprogram_${CMAKE_MATCH_1}} has a line") + endif() + endif() + endforeach() + foreach(subprogram IN LISTS glue_subprograms) + unset(glue_subprogram_${subprogram}) + endforeach() + set(glue_subprograms "") + + # the helpers made from the compiler's own TypeScript are not in the program's file + foreach(ir_line IN LISTS ir_lines) + if(program_file AND ir_line MATCHES "!DISubprogram\\(name: \"(\\.(math|inspect)_[^\"]*)\".* file: ${program_file},") + list(APPEND failures " -mm=${model}: ${CMAKE_MATCH_1} is in ${name}") + endif() + endforeach() + + set(past_end "") foreach(ir_line IN LISTS ir_lines) if(ir_line MATCHES "^!([0-9]+) = !DILocation\\(line: ([0-9]+)") set(line_${CMAKE_MATCH_1} ${CMAKE_MATCH_2}) + if(CMAKE_MATCH_2 GREATER last_line) + list(APPEND past_end "${CMAKE_MATCH_2}") + endif() endif() endforeach() + if(past_end) + list(REMOVE_DUPLICATES past_end) + list(APPEND failures " -mm=${model}: rows at lines [${past_end}] past the end of ${name} (${last_line} lines)") + endif() set(current "") set(rows "") @@ -106,9 +156,9 @@ foreach(model gc rc none own) endif() endforeach() - # the reference counting routines the lowering makes are not stepped into either + # the reference counting routines the lowering makes are not stepped into either, nor the helpers foreach(function IN LISTS defined) - if(function MATCHES "^(tsrelv?_|tsretv?_|__tslang_)" AND NOT rows_${function} STREQUAL "") + if(function MATCHES "^(tsrelv?_|tsretv?_|__tslang_|\\.math_|\\.inspect_)" AND NOT rows_${function} STREQUAL "") list(APPEND failures " -mm=${model}: ${function} stops at [${rows_${function}}], expected none") endif() unset(rows_${function}) @@ -127,7 +177,85 @@ foreach(model gc rc none own) endforeach() endforeach() +# A generic of another file made in the program is in that file, its blocks too: the blocks were in the +# program's file, so a debugger showed the generic's lines (a default library's Array.sort) as the +# program's, past its end. +set(work "${CMAKE_CURRENT_BINARY_DIR}/debug_steps_import") +file(MAKE_DIRECTORY "${work}") +file(WRITE "${work}/steps_module.ts" [=[ +export function largest(items: T[], less: (a: T, b: T) => boolean) { + let best = items[0]; + for (const item of items) { + if (less(best, item)) { + best = item; + } + } + + return best; +} +]=]) +file(WRITE "${work}/steps_main.ts" [=[ +import { largest } from "./steps_module"; + +function main() { + print(largest([3, 1, 2], (a, b) => a < b)); +} +]=]) +execute_process( + COMMAND "${TSLANG}" --emit=llvm --di --opt_level=0 --no-default-lib steps_main.ts -o=steps_main.ll + WORKING_DIRECTORY "${work}" + OUTPUT_QUIET + ERROR_VARIABLE diagnostics + RESULT_VARIABLE status) +if(NOT status EQUAL 0) + string(REGEX MATCH "[^\n]*error:[^\n]*" first_line "${diagnostics}") + list(APPEND failures " import: exit ${status}: ${first_line}") +else() + file(STRINGS "${work}/steps_main.ll" ir_lines) + set(blocks "") + set(generic_file "") + foreach(ir_line IN LISTS ir_lines) + if(ir_line MATCHES "^(![0-9]+) = !DIFile\\(filename: \"([^\"]+)\"") + set(file_name_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}") + elseif(ir_line MATCHES "^(![0-9]+) = distinct !DISubprogram\\(name: \"([^\"]*)\".* file: (![0-9]+),") + set(scope_file_${CMAKE_MATCH_1} "${CMAKE_MATCH_3}") + # (kept first: a MATCHES sets CMAKE_MATCH_n again) + set(subprogram_file "${CMAKE_MATCH_3}") + if(CMAKE_MATCH_2 MATCHES "^largest") + set(generic_file "${subprogram_file}") + endif() + elseif(ir_line MATCHES "^(![0-9]+) = distinct !DILexicalBlock\\(scope: (![0-9]+), file: (![0-9]+),") + set(parent_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}") + set(block_file_${CMAKE_MATCH_1} "${CMAKE_MATCH_3}") + list(APPEND blocks "${CMAKE_MATCH_1}") + endif() + endforeach() + + if(NOT generic_file OR NOT file_name_${generic_file} STREQUAL "steps_module.ts") + list(APPEND failures " import: largest is in [${file_name_${generic_file}}], expected steps_module.ts") + endif() + if(NOT blocks) + list(APPEND failures " import: no lexical blocks") + endif() + + # each block is in the file of the function it is in + foreach(block IN LISTS blocks) + set(scope "${parent_${block}}") + foreach(depth RANGE 32) + if(DEFINED scope_file_${scope} OR NOT DEFINED parent_${scope}) + break() + endif() + set(scope "${parent_${scope}}") + endforeach() + if(DEFINED scope_file_${scope} AND NOT block_file_${block} STREQUAL scope_file_${scope}) + list(APPEND failures " import: a block of a function of ${file_name_${scope_file_${scope}}} is in ${file_name_${block_file_${block}}}") + endif() + endforeach() +endif() +file(REMOVE_RECURSE "${work}") + if(failures) + list(REMOVE_DUPLICATES failures) string(REPLACE ";" "\n" report "${failures}") message(FATAL_ERROR "debug info steps:\n${report}") endif() diff --git a/tslang/test/tester/tests/00debug_steps.ts b/tslang/test/tester/tests/00debug_steps.ts index ca1153e05..5e0d3e524 100644 --- a/tslang/test/tester/tests/00debug_steps.ts +++ b/tslang/test/tester/tests/00debug_steps.ts @@ -51,3 +51,8 @@ function main() { const f = new Fields(); print(f.v + f.w); } + +// the compiler's own TypeScript it is made with (Math.max, an array printed) is at no line of this file +function helpers(t: number) { + print(Math.max(t, 1), [t, 2]); +} From 7a8d1aff431e9523900f2cb3ee152f6fdefb6411 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 4 Dec 2026 02:20:54 +0000 Subject: [PATCH 4/5] --di: the helper-node map holds its nodes, so a node taken out of a snippet leaves no address for another Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 40a9211e5..c14318c49 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -23892,7 +23892,7 @@ class MLIRGenImpl if (auto helper = helperNodeSources.find(static_cast(loc.operator->())); helper != helperNodeSources.end()) { - return loc2Fuse(helper->second, HELPER_SOURCE_FILE_NAME, pos, loc->_end - pos); + return loc2Fuse(helper->second.second, HELPER_SOURCE_FILE_NAME, pos, loc->_end - pos); } //return loc1(sourceFile, fileName.str(), pos, loc->_end - pos); @@ -24259,7 +24259,7 @@ class MLIRGenImpl } TextRange range = child; - helperNodeSources[static_cast(range.operator->())] = module; + helperNodeSources[static_cast(range.operator->())] = {child, module}; ts::forEachChild(child, visitNode, visitArray); return undefined; }; @@ -25540,8 +25540,9 @@ class MLIRGenImpl std::set> debugStatementsSeen; // the nodes of each source file's tree (isNodeOfSourceFile) llvm::DenseMap> sourceFileNodes; - // the nodes of the compiler's own TypeScript, with the text they were parsed from (parsePartialStatements) - llvm::DenseMap helperNodeSources; + // the nodes of the compiler's own TypeScript, with the text they were parsed from (parsePartialStatements); + // each node is held, so a node taken out of its tree leaves no address for another to be taken for it + llvm::DenseMap> helperNodeSources; }; } // namespace mlirgen } // namespace typescript From f74c03970c8d2780bef8eaa5466fedaf8da7a9cb Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 4 Dec 2026 08:57:55 +0000 Subject: [PATCH 5/5] Array(n) without new is new Array(n); new Array(n) given to a T[] has T elements `Array(3)` called the default library's static class Array, so `a[0] = 1` failed with "can't resolve property '.index' of class 'Array'". A program's own Array function is still called. `const c: string[] = new Array(2)` made s32[] (the length's type) and failed to cast. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 38 +++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 23 +++++++++++ .../defaultlib/array_call_without_new.ts | 33 ++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 tslang/test/tester/defaultlib/array_call_without_new.ts diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 27da145fd..e3ba368f4 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -2830,6 +2830,22 @@ namespace mlirgen auto callExpr = callExpression->expression.as(); + // `Array(3)`, `Array(3)`, `Array(1, 2)`: `new Array(...)`, as in JavaScript (it was the default + // library's static class Array, of no length and no elements: "can't resolve property '.index' of class + // 'Array'"). A program's own Array function is called as it is. + if (callExpr == SyntaxKind::Identifier && MLIRHelper::getName(callExpr.as()) == "Array" && + !symbolTable.lookup("Array").first && [&]() { + auto calleeType = evaluate(callExpr, genContext); + return !calleeType || !mth.isAnyFunctionType(calleeType, true); + }()) + { + NodeFactory nf(NodeFactoryFlags::None); + auto newArray = nf.createNewExpression(callExpr, callExpression->typeArguments, callExpression->arguments); + newArray->pos = callExpression->pos; + newArray->_end = callExpression->_end; + return mlirGen(newArray, genContext); + } + // gpuMap, gpuFilter, gpuFold, and gpuSort with a compare or values: snippets of arrow kernels that have the // callbacks as their own (mlirGenGpuCallbackBuiltin) if (callExpr == SyntaxKind::Identifier) @@ -4285,6 +4301,28 @@ namespace mlirgen } } + // `const c: string[] = new Array(2)`: a length, and the elements of the type it is given to (they were the + // length's own type: "invalid cast from s32[] to string[]") + if (typeExpression == SyntaxKind::Identifier && MLIRHelper::getName(typeExpression.as()) == "Array" && + newExpression->typeArguments.size() == 0 && newExpression->arguments.size() == 1 && + newExpression->arguments.front() != SyntaxKind::SpreadElement && !symbolTable.lookup("Array").first && + genContext.receiverType) + { + if (auto receiverArray = dyn_cast(mth.stripOptionalType(genContext.receiverType))) + { + auto lengthType = evaluate(newExpression->arguments.front(), genContext); + if (lengthType) + { + lengthType = mth.stripLiteralType(lengthType); + } + + if (lengthType && isa(lengthType)) + { + return NewArray(location, receiverArray, newExpression->arguments, genContext); + } + } + } + auto deferDefaults = newExpression->typeArguments.size() == 0 && (newExpression->arguments.size() > 0 || genContext.receiverType); auto savedErrorMessagesCount = genContext.postponedMessages ? genContext.postponedMessages->size() : 0; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index bf8e8ef47..7313de097 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4849,6 +4849,29 @@ foreach(array_from_mm gc own) endforeach() endforeach() +# `Array(n)` without `new` is `new Array(n)`, and `new Array(n)` given to a `string[]` has its elements, against the +# real default library (whose static class Array the call was). Skipped when that model's default library has not +# been built. +foreach(array_call_mm gc rc own) + foreach(array_call_mode jit compile) + add_test(NAME test-${array_call_mode}-${array_call_mm}-defaultlib-array-call-without-new + COMMAND ${CMAKE_COMMAND} + "-DMODE=${array_call_mode}" + "-DMM=${array_call_mm}" + "-DTSLANG=$" + "-DTSLANG_BIN=${CMAKE_BINARY_DIR}/bin" + "-DTEST=${CMAKE_CURRENT_SOURCE_DIR}/defaultlib/array_call_without_new.ts" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/array-call-without-new-${array_call_mm}-${array_call_mode}" + "-DGC_LIB=${TEST_GC_LIBDIR}" + "-DLLVM_LIB=${defaultlib_collector_llvm_lib}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + "-DOPT=${defaultlib_collector_opt}" + "-DDEFAULT_LIB_CANDIDATES=${PROJECT_SOURCE_DIR}/../TypeScriptCompilerDefaultLib/__build;${PROJECT_SOURCE_DIR}/../../TypeScriptCompilerDefaultLib/__build" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-defaultlib-facts.cmake") + set_tests_properties(test-${array_call_mode}-${array_call_mm}-defaultlib-array-call-without-new PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") + endforeach() +endforeach() + # JSX with no factory named, against the real default library: elements are calls of the library's `h` # (__jsx_h), components, fragments and the HTML an element prints. Skipped when that model's default library # has not been built. (-mm=own refuses the library's factory: 00jsx_typed_factory.tsx is own's.) diff --git a/tslang/test/tester/defaultlib/array_call_without_new.ts b/tslang/test/tester/defaultlib/array_call_without_new.ts new file mode 100644 index 000000000..3b268a990 --- /dev/null +++ b/tslang/test/tester/defaultlib/array_call_without_new.ts @@ -0,0 +1,33 @@ +// `Array(n)` without `new` is `new Array(n)`, as in JavaScript: an array of n elements that can be written to (it was +// the default library's static class Array: "can't resolve property '.index' of class 'Array'"). Against the real +// default library: without it there is no Array to call. +function main() { + const n = 3; + const a = Array(n); + a[0] = 1; + a[2] = 7; + print(a.length, a[0], a[2]); + assert(a.length == 3); + assert(a[0] == 1 && a[2] == 7); + + const b = Array(2); + b[1] = 5; + assert(b.length == 2 && b[1] == 5); + + const c: string[] = Array(2); + c[0] = "x"; + assert(c.length == 2 && c[0] == "x"); + + // the elements of the type it is given to, not of the length's + const e: boolean[] = new Array(2); + e[1] = true; + assert(e.length == 2 && e[1]); + + const d = Array(1, 2, 3); + assert(d.length == 3 && d[2] == 3); + + a.push(9); + assert(a.length == 4 && a[3] == 9); + + print("done."); +}