diff --git a/tslang/include/TypeScript/TypeScriptPassContext.h b/tslang/include/TypeScript/TypeScriptPassContext.h index 42814e985..20ffb2280 100644 --- a/tslang/include/TypeScript/TypeScriptPassContext.h +++ b/tslang/include/TypeScript/TypeScriptPassContext.h @@ -135,6 +135,11 @@ struct TSContext catchPadIdOf.beginRun(); finallyPadIdOf.beginRun(); inParentTryFinallyPad.beginRun(); + // numbered from 1 in each function: the pass runs over functions on several threads, each copy with a + // context of its own, so a count carried over from the functions a thread lowered before numbered a + // function's pads differently from one compile to the next (nondeterministic IR); only a function's own pads + // name each other (Win32ExceptionPass) + nextCatchPadId = 0; } // options @@ -165,7 +170,7 @@ struct TSContext OpSideTable catchesLeft{"catchesLeft"}; // Windows: the id a try's catch landing pad goes by, so that the pads of a try inside that // catch clause can name it as the funclet they are nested in - see tagPad in TryOpLowering - // and ts.internal.eh_pad in Win32ExceptionPass. Ids are unique within the module. + // and ts.internal.eh_pad in Win32ExceptionPass. Ids are unique within the function (beginRun). OpSideTable catchPadIdOf{"catchPadIdOf"}; // Windows: the same for the pad a try's finally is entered through on the exceptional path, // and whether a try sits in that copy of its parentTryOp's finally - the one copy that runs diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 1336c8098..0858a00f7 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -2911,7 +2911,8 @@ namespace mlirgen } auto viewOp = builder.create(location, declaredType, castValue, loaded); - viewOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getUnitAttr()); + // (naming the field: a reread or a write of the view takes the name from here, weakFieldNameOf) + viewOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getStringAttr(fieldName)); return viewOp; } @@ -2949,21 +2950,24 @@ namespace mlirgen return V(result); } + // The field a @weak field's view reads (weakFieldRead names it on the view): a reread or a write of the view is + // of the same field. It was taken from the checked read found by walking the first operand of what made the + // view's value, which did not always reach it - the field's name was then lost from one compile to the next + // (nondeterministic IR). + static mlir::StringAttr weakFieldNameOf(mlir::Operation *viewOp) + { + return viewOp->getAttrOfType(WEAK_FIELD_VIEW_ATTR_NAME); + } + mlir::Value MLIRGenImpl::weakFieldReread(mlir::Location location, mlir_ts::SafeCastOp viewOp, mlir::Value loaded, const GenContext &genContext) { auto weakRefType = mlir::cast(loaded.getType()); auto derefOp = builder.create(location, weakRefType.getElementType(), loaded); derefOp.setChecked(true); - auto *below = viewOp->getOperand(0).getDefiningOp(); - while (below && !mlir::isa(below)) + if (auto name = weakFieldNameOf(viewOp)) { - below = below->getNumOperands() > 0 ? below->getOperand(0).getDefiningOp() : nullptr; - } - - if (below) - { - derefOp.setWeakFieldAttr(mlir::cast(below).getWeakFieldAttr()); + derefOp.setWeakFieldAttr(name); } auto castValue = weakFieldValue(location, derefOp.getResult(), viewOp.getType(), genContext); @@ -2973,7 +2977,14 @@ namespace mlirgen } auto rereadOp = builder.create(location, viewOp.getType(), castValue, loaded); - rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getUnitAttr()); + if (auto name = weakFieldNameOf(viewOp)) + { + rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, name); + } + else + { + rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getUnitAttr()); + } return rereadOp; } @@ -3134,16 +3145,10 @@ namespace mlirgen return mlir::Value(); } - auto derefOp = viewOp->getOperand(0).getDefiningOp(); - while (derefOp && !mlir::isa(derefOp)) - { - derefOp = derefOp->getNumOperands() > 0 ? derefOp->getOperand(0).getDefiningOp() : nullptr; - } - auto weakRef = builder.create(location, weakRefType, target, mlir::StringAttr()); - if (derefOp) + if (auto name = weakFieldNameOf(viewOp)) { - weakRef.setWeakFieldAttr(mlir::cast(derefOp).getWeakFieldAttr()); + weakRef.setWeakFieldAttr(name); } // born with no weak count: the retain the store adds is the first (as `new WeakRef(x)`) diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 201134b7c..746295f25 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -2705,6 +2705,15 @@ namespace mlirgen GenContext bindingGenContext(genContext); bindingGenContext.bindingParamPatterns = true; + // -mm=rc: a name a destructured parameter binds owns what it reads, as a local does: it borrowed the + // argument's element or field, which the callee may give a new value (`([o]: N[]) => { arr[0] = + // mk(i); o.x }`, `arr` the array given) - the store freed the block `o` read. Listed with the + // parameters' storage when the prologue is done (mlirGenFunctionBody), given back at exit. + SmallVector bindingOwned; + if (compileOptions.memoryModel == MemoryModelRC && !bindingGenContext.ownedVars) + { + bindingGenContext.ownedVars = &bindingOwned; + } if (bindingPattern == SyntaxKind::ArrayBindingPattern) { auto arrayBindingPattern = bindingPattern.as(); @@ -2981,9 +2990,11 @@ namespace mlirgen paramCells->push_back(prologueOp.getResult(0)); } // ...and the slot owning a parameter's default value (processOptionalParam), or, under own, a default in a - // destructured parameter (ownPatternDefaultSlot), given back at exit + // destructured parameter (ownPatternDefaultSlot), or, under rc, a name a destructured parameter binds + // (mlirGenFunctionParamsBindings), given back at exit else if (isa(prologueOp) && - (prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || prologueOp.hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME))) + (prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || prologueOp.hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) || + (compileOptions.memoryModel == MemoryModelRC && prologueOp.hasAttr(OWNED_LOCAL_ATTR_NAME)))) { paramCells->push_back(prologueOp.getResult(0)); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index dd4ed7e10..f9052a3a0 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -6307,6 +6307,109 @@ class MLIRGenImpl return mlir::failure(); } + // `val == null` / `val == undefined` (loose) of a value whose type may be undefined (an optional, a union with + // undefined): the equal side may be either, and is left as it is; the other side is the type without null and + // undefined. Fails for anything else (the strict forms, a type that cannot be undefined), which the null and + // undefined cases narrow as before. + mlir::LogicalResult checkSafeCastLooseNullish(Expression val, Expression nullishVal, bool inverse, ElseSafeCase *elseSafeCase, + const GenContext &genContext) + { + auto expr = stripParentheses(nullishVal); + auto isNullish = expr == SyntaxKind::NullKeyword || + (expr == SyntaxKind::Identifier && expr.as()->escapedText == S(UNDEFINED_NAME)); + if (!isNullish) + { + return mlir::failure(); + } + + auto type = evaluate(val, genContext); + auto mayBeUndefined = [](mlir::Type type) { + if (isa_and_nonnull(type)) + { + return true; + } + + auto unionType = dyn_cast_or_null(type); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type member) { + return isa(member); + }); + }; + if (!mayBeUndefined(type)) + { + return mlir::failure(); + } + + // not undefined: an optional's value, read as `c !== undefined` reads it (a `ts.Value`, which -mm=own sees as a + // view of a borrow; a cast to the type without null too was taken for a store of it, and own refused a + // borrowed `N | null | undefined` narrowed so). A null left in it reads as null, which is all `c.x` needs. + auto present = type; + if (auto optionalType = dyn_cast(present)) + { + present = optionalType.getElementType(); + } + else if (auto unionType = dyn_cast(present)) + { + SmallVector members; + for (auto member : unionType.getTypes()) + { + if (auto optionalMember = dyn_cast(member)) + { + member = optionalMember.getElementType(); + } + + if (!isa(member)) + { + members.push_back(member); + } + } + + if (members.empty()) + { + return mlir::failure(); + } + + present = members.size() == 1 ? members.front() : getUnionType(members); + } + + // `!=`: present where true - and, for a @value record whose null is a niche of its own (`Hit | null | + // undefined`), not null either, narrowed again from the value just read as `c !== null` narrows a union: its + // fields are read so (own refused a borrow of `this` stored in a `Hit` read as `Hit | null`). A class's null + // stays in it, its reads are the same either way, and a second narrowing of a field read (`h.v`) was taken + // for a store of the borrow + if (inverse) + { + if (mlir::failed(addSafeCastStatement(val, present, false, nullptr, genContext))) + { + return mlir::failure(); + } + + if (auto unionType = dyn_cast(present); + unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type member) { return isa(member); }) && + llvm::any_of(unionType.getTypes(), [](mlir::Type member) { return isa(member); })) + { + SmallVector members; + llvm::copy_if(unionType.getTypes(), std::back_inserter(members), + [](mlir::Type member) { return !isa(member); }); + if (!members.empty()) + { + return addSafeCastStatement(val, members.size() == 1 ? members.front() : getUnionType(members), false, + nullptr, genContext); + } + } + + return mlir::success(); + } + + // `==`: present where false + if (elseSafeCase) + { + elseSafeCase->expr = stripParenthesesAndUntangleEquals(val); + elseSafeCase->safeType = present; + } + + return mlir::success(); + } + mlir::LogicalResult checkSafeCastNull(Expression val, Expression nullVal, bool inverse, ElseSafeCase *elseSafeCase, const GenContext &genContext) { auto expr = stripParentheses(nullVal); @@ -6831,6 +6934,22 @@ class MLIRGenImpl auto left = stripParentheses(binExpr->left); auto right = stripParentheses(binExpr->right); + // `c == null`, `c != undefined` - loose - of a value that may be undefined: equal for null and for + // undefined alike, so the equal side is not narrowed to null (a later `c === undefined` in the same + // `&&` chain was false for undefined, `c === null` true); the other side is neither + if (op == SyntaxKind::EqualsEqualsToken || op == SyntaxKind::ExclamationEqualsToken) + { + if (auto result = checkSafeCastLooseNullish(left, right, inverse, elseSafeCase, genContext); mlir::succeeded(result)) + { + return result; + } + + if (auto result = checkSafeCastLooseNullish(right, left, inverse, elseSafeCase, genContext); mlir::succeeded(result)) + { + return result; + } + } + // TODO: refactor it // typeof if (mlir::failed(checkSafeCastTypeOf(left, right, inverse, elseSafeCase, genContext))) diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 5f3f3e160..1ffc5a86f 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -92,13 +92,17 @@ namespace mlirgen mlirGenRetainCaptured(loc(body), mlir::ValueRange{resultValue}, /*atLastUse=*/true); // ...but a slot owning a parameter's default value (-mm=rc, processOptionalParam) is given back - // here, as a return statement's scope exit gives it back: what follows the return is not reached + // here, as a return statement's scope exit gives it back: what follows the return is not reached. + // So are a destructured parameter's default slot (-mm=own, ownPatternDefaultSlot) and the names a + // destructured parameter binds (-mm=rc, mlirGenFunctionParamsBindings): `({ a, b }) => a + b` + // never gave them back (the ownership verifier: "some path out of the function never gives back") if (genContext.ownedVars) { for (auto storage : llvm::reverse(*genContext.ownedVars)) { auto varOp = storage.getDefiningOp(); - if (varOp && varOp->hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME)) + if (varOp && (varOp->hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) || + (compileOptions.memoryModel == MemoryModelRC && varOp->hasAttr(OWNED_LOCAL_ATTR_NAME)))) { builder.create(loc(body), storage) ->setAttr(SCOPE_EXIT_RELEASE_ATTR_NAME, builder.getUnitAttr()); diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 3c2445e86..455625b90 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -169,13 +169,14 @@ class OwnedReturnConsumptionPass } // `new C()` is marked where it is built, so there can be discarded temporaries to give - // back even when no function here is classified as returning owned. + // back even when no function here is classified as returning owned - and conditionals and + // pattern defaults to settle: a module with no such function (no class, no function returning + // a heap value) skipped consumeConditionalResults, and `const xs: number[] = c ? [i] : []` + // under rc kept the branch's count of the new array and the local's own (one leaked every + // evaluation); settleOwnPatternDefaults, under own, never ran there either. if (returnsOwned.empty() && !anyDeclaredRecord) { - ownNewArrayArguments(mth, module); - claimGlobalInitializers(mth, module); - holdReadOnlyNewArrays(mth, module); - releaseDiscardedTemporaries(mth, module); + settleModuleLocalResults(mth, module); return; } @@ -304,6 +305,12 @@ class OwnedReturnConsumptionPass op->erase(); } + settleModuleLocalResults(mth, module); + } + + // What settles results within a function, once calls' results are settled (or none is a call's to settle) + void settleModuleLocalResults(MLIRTypeHelper &mth, mlir::ModuleOp module) + { ownNewArrayArguments(mth, module); settleOwnPatternDefaults(module); @@ -402,13 +409,24 @@ class OwnedReturnConsumptionPass auto anyNew = false; auto allTakenAreLocals = true; + // (`po([undefined])`, `[null]`: elements that are no value at all, so nothing to own or to borrow - such a + // literal given to a call was never given back, own leaked it every call) + auto onlyNoValues = true; for (auto element : arrayOp->getOperands()) { + if (isNoValue(element)) + { + continue; + } + if (!mth.ownsHeapMemory(arrayOp->getLoc(), element.getType()) || isBorrowedText(element)) { + onlyNoValues = onlyNoValues && !isBorrowedText(element); continue; } + onlyNoValues = false; + if (isMovedIn(arrayOp, element) || isNestedLiteral(mth, arrayOp, element)) { anyNew = true; @@ -423,11 +441,37 @@ class OwnedReturnConsumptionPass allTakenAreLocals = allTakenAreLocals && isLocalsOwn(element); } - return anyNew || (allTakenAreLocals && !givenToCall); + return anyNew || onlyNoValues || (allTakenAreLocals && !givenToCall); + } + + // undefined or null, through the casts and the optional that only widen it + static bool isNoValue(mlir::Value value) + { + for (auto *op = value.getDefiningOp(); op; op = op->getNumOperands() == 1 ? op->getOperand(0).getDefiningOp() : nullptr) + { + if (mlir::isa(op)) + { + return true; + } + + if (!mlir::isa(op)) + { + return false; + } + } + + return false; } static bool holdsOnlyMovedInElements(MLIRTypeHelper &mth, mlir::Operation *op, bool givenToCall) { + // `f([])`: an empty array holds nothing (the empty constant array cast to an array is made one first, + // ownNewArrayArguments) + if (mlir::isa_and_nonnull(op)) + { + return true; + } + auto arrayOp = mlir::dyn_cast_or_null(op); return arrayOp && holdsWhatItIsGiven(mth, arrayOp, givenToCall); } @@ -637,6 +681,28 @@ class OwnedReturnConsumptionPass } auto *definingOp = argument.getDefiningOp(); + + // `f([])`: the empty constant array cast to an array - a copy made on the heap there - is the new empty + // array it is (ts.NewEmptyArray), which the inference moves into a callee that keeps it (`new + // Order(-1, [])`, the constructor storing it) and gives back after one that does not (`ln([])`, which + // leaked it). Marked owned as the cast it was, it was given back after a keeping callee as well, which + // then freed it again (DefaultLib worker_objects under -mm=own on wasm: "free" of a freed block) + if (auto castOp = mlir::dyn_cast_or_null(definingOp); + castOp && !castOp->hasAttr(OWNED_RESULT_ATTR_NAME) && mlir::isa(argument.getType()) && + arrayMadeFor(argument, op, false)) + { + auto constArrayType = mlir::dyn_cast(castOp.getIn().getType()); + if (constArrayType && constArrayType.getSize() == 0) + { + mlir::OpBuilder builder(castOp); + auto emptyOp = builder.create(castOp->getLoc(), argument.getType()); + castOp->getResult(0).replaceAllUsesWith(emptyOp.getResult()); + castOp->erase(); + argument = emptyOp.getResult(); + definingOp = emptyOp; + } + } + if (!definingOp || !mlir::isa(argument.getType()) || !seen.insert(argument).second || definingOp->hasAttr(OWNED_RESULT_ATTR_NAME) || !ownsWhatItHolds(mth, definingOp, /*givenToCall=*/true) || !(arrayMadeFor(argument, op, false) || isConvertedArrayFor(argument, op))) @@ -1393,11 +1459,121 @@ class OwnedReturnConsumptionPass llvm::StringMap> assigns; llvm::StringMap> callees; llvm::StringSet<> assignsAny; + // ...and the places each function gives a new value or takes a value out of (rc, readsAliasedPlace), by kind: + // a field by its name ("F:" + name), an element ("E": a store, `pop`, `shift`, `splice`), a captured local's + // cell ("C"), anything else ("*"). Deliberately coarse - a name stands for that field of every class, an + // element for every array - but not the stores that only make an object: a constructor's into `this`, a + // function's into the object it just made, a local record's into its own slot. A function that calls through + // a value may run any function here: it writes what the module writes (moduleKinds). + llvm::StringMap> writtenKinds; + llvm::StringSet<> moduleKinds; + auto fieldKindOf = [](mlir_ts::PropertyRefOp propertyRefOp) -> std::string { + auto type = propertyRefOp->getOperand(0).getType(); + if (auto refType = mlir::dyn_cast(type)) + { + type = refType.getElementType(); + } + + if (auto classType = mlir::dyn_cast(type)) + { + type = classType.getStorageType(); + } + + mlir::Attribute id; + auto position = propertyRefOp.getPosition(); + if (auto storageType = mlir::dyn_cast(type); + storageType && position >= 0 && static_cast(position) < storageType.getFields().size()) + { + id = storageType.getFields()[position].id; + } + else if (auto tupleType = mlir::dyn_cast(type); + tupleType && position >= 0 && static_cast(position) < tupleType.getFields().size()) + { + id = tupleType.getFields()[position].id; + } + + auto name = mlir::dyn_cast_or_null(id); + return name ? ("F:" + name.getValue()).str() : std::string("*"); + }; + // the object a store makes rather than changes: `this` in a constructor, a new object of this function, a + // local record's slot + auto initializes = [](mlir::Value object, mlir_ts::FuncOp funcOp) { + while (auto castOp = object.getDefiningOp()) + { + object = castOp.getIn(); + } + + if (auto argument = mlir::dyn_cast(object)) + { + return argument.getArgNumber() == 0 && argument.getOwner()->isEntryBlock() && + funcOp.getSymName().ends_with(".constructor"); + } + + if (auto loadOp = object.getDefiningOp()) + { + // `this` read out of a constructor's parameter slot; or a new box's contents + if (loadOp.getReference().getDefiningOp()) + { + return true; + } + + auto *slot = loadOp.getReference().getDefiningOp(); + auto initial = mlir::isa_and_nonnull(slot) && slot->getNumOperands() > 0 + ? slot->getOperand(0) + : mlir::Value(); + auto argument = initial ? mlir::dyn_cast(initial) : mlir::BlockArgument(); + return argument && argument.getArgNumber() == 0 && argument.getOwner()->isEntryBlock() && + funcOp.getSymName().ends_with(".constructor"); + } + + return mlir::isa_and_nonnull(object.getDefiningOp()); + }; module.walk([&](mlir_ts::FuncOp funcOp) { auto name = funcOp.getSymName(); funcOp.walk([&](mlir::Operation *op) { + // (`a.length = n` too: a shorter array gives back the elements it drops) + if (mlir::isa(op)) + { + writtenKinds[name].insert("E"); + } + + // `delete`: what it frees takes every place in it along + if (mlir::isa(op)) + { + writtenKinds[name].insert("*"); + } + if (auto storeOp = mlir::dyn_cast(op)) { + auto reference = storeOp.getReference(); + if (auto propertyRefOp = reference.getDefiningOp()) + { + if (!initializes(propertyRefOp->getOperand(0), funcOp)) + { + writtenKinds[name].insert(fieldKindOf(propertyRefOp)); + } + } + else if (auto elementRefOp = reference.getDefiningOp()) + { + if (!initializes(elementRefOp->getOperand(0), funcOp)) + { + writtenKinds[name].insert("E"); + } + } + else if (reference.getDefiningOp()) + { + // a new box's contents (an object literal boxed for an interface): made, not changed + } + else if (own_facts::isPlace(reference)) + { + writtenKinds[name].insert("*"); + } + else if (reference.getDefiningOp()) + { + writtenKinds[name].insert("C"); + } + if (auto global = globalOf(storeOp.getReference(), true); !global.empty()) { assigns[name].insert(global); @@ -1430,6 +1606,7 @@ class OwnedReturnConsumptionPass changed = true; } + if (auto it = assigns.find(callee); it != assigns.end()) { // copied first: `assigns[caller]` may move the entry being read @@ -1448,6 +1625,51 @@ class OwnedReturnConsumptionPass } } + for (auto &entry : writtenKinds) + { + for (auto &kind : entry.getValue()) + { + moduleKinds.insert(kind.getKey()); + } + } + + // a function calling through a value may run any of them + for (auto &entry : assignsAny) + { + for (auto &kind : moduleKinds) + { + writtenKinds[entry.getKey()].insert(kind.getKey()); + } + } + + for (auto changed = true; changed;) + { + changed = false; + for (auto &entry : callees) + { + auto caller = entry.getKey(); + for (auto callee : entry.getValue()) + { + auto it = writtenKinds.find(callee); + if (it == writtenKinds.end()) + { + continue; + } + + llvm::SmallVector kinds; + for (auto &kind : it->getValue()) + { + kinds.push_back(kind.getKey().str()); + } + + for (auto &kind : kinds) + { + changed |= writtenKinds[caller].insert(kind).second; + } + } + } + } + auto mayAssignAnyGlobal = [&](mlir::Operation *op) { auto callee = calleeOf(op); if (callee.empty() || assignsAny.contains(callee)) @@ -1490,6 +1712,200 @@ class OwnedReturnConsumptionPass return false; }; + // the kinds of places a call may write (writtenKinds; through a value: what any function here writes) + auto mayWriteKind = [&](mlir::Operation *op, llvm::StringRef kind) { + auto callee = calleeOf(op); + const llvm::StringSet<> *kinds = &moduleKinds; + if (!callee.empty() && !assignsAny.contains(callee)) + { + // A callee with no body here writes nothing - as for the globals (assigns). That holds because + // the default library's mutating array methods are generic: instantiated in this module, their + // bodies are walked like any function here. A non-generic library function that wrote into an + // array or an object it is given would be missed. + auto it = writtenKinds.find(callee); + if (it == writtenKinds.end()) + { + return false; + } + + kinds = &it->getValue(); + } + + return kinds->contains(kind) || kinds->contains("*"); + }; + + // Is this a read out of a field or an element of an object some other name may reach, which the call may give + // a new value? `f(arr[0])` with `arr` captured by a closure that sets `arr[0]`, also stored in a global whose + // element the callee sets, put into another array, copied to another local that `pop`s it; `f(h.o)` with + // `arrh = [h]` and a closure setting `arrh[0].o`. The callee - or what it calls - frees the block the argument + // read while it still reads its parameter. Two facts together, both needed: + // - some object on the way to the place may be reached by another name: it is not one made here that never + // escapes (read only through its places, its length, a comparison or this very call) - a parameter's + // object, a captured local's, one read out of somewhere else, one stored or passed on; + // - the call may write a place of a kind on that way (writtenKinds: the field's name, an element, a captured + // local's cell), a write that makes an object aside. + // A global's object is the global rule's (globalOf, mayAssign), not this one's. + std::function escapes = [&](mlir::Value value, mlir::Operation *call, int depth) { + if (depth > 6) + { + return true; + } + + for (auto &use : value.getUses()) + { + auto *user = use.getOwner(); + if (user == call || mlir::isa(user)) + { + continue; + } + + // a place in it: reading and writing it is not another name for the object + if (mlir::isa(user) && use.getOperandNumber() == 0) + { + continue; + } + + // a store of something else into it + if (auto storeOp = mlir::dyn_cast(user); storeOp && storeOp.getValue() != value) + { + continue; + } + + if (mlir::isa(user)) + { + if (escapes(user->getResult(0), call, depth + 1)) + { + return true; + } + + continue; + } + + return true; + } + + return false; + }; + auto isFresh = [](mlir::Value value) { + auto *def = value.getDefiningOp(); + return mlir::isa_and_nonnull(def) || + (mlir::isa_and_nonnull(def) && mlir::isa(def->getOperand(0).getType())); + }; + // may another name reach the object a value is? Not one made here that never escapes, nor a local's slot given + // only such values, not captured, nothing read out of it escaping. (`captured`: the object is a captured + // local's, whose cell a closure may give a new value) + auto mayBeAliased = [&](mlir::Value object, mlir::Operation *call, bool &captured) { + while (auto castOp = object.getDefiningOp()) + { + object = castOp.getIn(); + } + + if (auto loadOp = object.getDefiningOp()) + { + auto varOp = loadOp.getReference().getDefiningOp(); + if (!varOp) + { + // a global's, or one read out of another place (whose object is looked at in its turn) + return false; + } + + if (varOp.getCaptured().value_or(false)) + { + captured = true; + return true; + } + + if (!varOp.getInitializer() || !isFresh(varOp.getInitializer())) + { + return true; + } + + for (auto *user : varOp->getUsers()) + { + if (auto storeOp = mlir::dyn_cast(user)) + { + if (storeOp.getReference() == varOp.getResult() && !isFresh(storeOp.getValue())) + { + return true; + } + + continue; + } + + if (auto slotRead = mlir::dyn_cast(user); slotRead && escapes(slotRead.getResult(), call, 0)) + { + return true; + } + } + + return false; + } + + // a parameter's object: its caller's, which other names may reach + if (mlir::isa(object)) + { + return true; + } + + return !isFresh(object) || escapes(object, call, 0); + }; + auto readsAliasedPlace = [&](mlir::Value value, mlir::Operation *call) { + while (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + } + + auto loadOp = value.getDefiningOp(); + if (!loadOp || !own_facts::isPlace(loadOp.getReference())) + { + return false; + } + + // each place on the way, and the object it is in + auto aliased = false; + auto written = false; + auto ref = loadOp.getReference(); + for (auto depth = 0; depth < 16 && ref && own_facts::isPlace(ref); depth++) + { + auto *place = ref.getDefiningOp(); + if (auto propertyRefOp = mlir::dyn_cast(place)) + { + written = written || mayWriteKind(call, fieldKindOf(propertyRefOp)); + } + else if (mlir::isa(place)) + { + written = written || mayWriteKind(call, "E"); + } + else + { + written = true; + } + + auto object = place->getOperand(0); + while (auto castOp = object.getDefiningOp()) + { + object = castOp.getIn(); + } + + // (a field of a local tuple: the place is in the slot itself) + if (mlir::isa_and_nonnull(object.getDefiningOp())) + { + return false; + } + + auto captured = false; + aliased = mayBeAliased(object, call, captured) || aliased; + written = written || (captured && mayWriteKind(call, "C")); + + auto innerLoad = object.getDefiningOp(); + ref = innerLoad ? innerLoad.getReference() : mlir::Value(); + } + + return aliased && written; + }; + auto mayAssign = [&](mlir::Operation *op, mlir::StringRef global) { auto callee = calleeOf(op); if (callee.empty() || assignsAny.contains(callee)) @@ -1640,6 +2056,14 @@ class OwnedReturnConsumptionPass continue; } + // Out of a field or an element of an object another name may reach, to a call that may write that + // place (readsAliasedPlace). Under rc the caller holds it. + if (compileOptions.isRefCounted() && readsAliasedPlace(argument, op)) + { + held.push_back({op, argument}); + continue; + } + auto global = globalOf(argument, false); if (global.empty()) { diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 089cf6869..a44147c5c 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -264,12 +264,87 @@ namespace own_inference { // a read of a place or of a parameter - or of a split `let`'s holder (TSLANG 66) auto root = rootOf(value); + + // ...or a pattern's default over one (`let { p = mk(1) } = r`), lowered to the merge of its two arms: the + // optional's value (a place read) and the read of the pattern-default slot (MLIRGenImpl::optionalValueOrDefault) + // (any other merge is decided below, as before) + if (auto argument = mlir::dyn_cast(root); argument && mergeOfPatternDefault(argument, 0)) + { + return true; + } + auto rootLoad = root.getDefiningOp(); auto slot = rootLoad ? rootLoad.getReference().getDefiningOp() : mlir_ts::VariableOp(); int index = -1; return placeReadOf(root) || (slot && (isParameterSlot(slot, index) || slot->hasAttr(OWN_LET_HOLDER_ATTR_NAME))); } + // A merge (a block argument) of a pattern's default and what it defaults (`let { p = mk(1) } = r`): each + // incoming value a borrow (letBorrows, through `ts.Value` of an optional) or the read of a pattern-default slot, + // and at least one such read. + bool OwnershipInferencePass::mergeOfPatternDefault(mlir::BlockArgument argument, unsigned depth) + { + auto *block = argument.getOwner(); + if (block->isEntryBlock() || block->hasNoPredecessors() || depth > 4) + { + return false; + } + + auto slotRead = false; + for (auto predecessor = block->pred_begin(); predecessor != block->pred_end(); ++predecessor) + { + auto branchOp = mlir::dyn_cast((*predecessor)->getTerminator()); + if (!branchOp) + { + return false; + } + + auto operands = branchOp.getSuccessorOperands(predecessor.getSuccessorIndex()); + if (argument.getArgNumber() < operands.getProducedOperandCount()) + { + return false; + } + + auto incoming = operands[argument.getArgNumber()]; + if (!incoming) + { + return false; + } + + auto value = rootOf(incoming); + if (auto valueOp = value.getDefiningOp()) + { + value = rootOf(valueOp->getOperand(0)); + } + + auto load = value.getDefiningOp(); + auto slot = load ? load.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (slot && slot->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME)) + { + slotRead = true; + continue; + } + + if (auto nested = mlir::dyn_cast(value)) + { + if (!mergeOfPatternDefault(nested, depth + 1)) + { + return false; + } + + slotRead = true; + continue; + } + + if (!letBorrows(value)) + { + return false; + } + } + + return slotRead; + } + bool OwnershipInferencePass::borrowsOnly(mlir_ts::VariableOp varOp) { // `let layout = this.computeLayout; if (fp16) layout = this.computeLayoutFP16;` (TSLANG 56): diff --git a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp index 48ade4726..f4f11484c 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp @@ -95,9 +95,12 @@ namespace own_inference auto *exit = block.empty() ? nullptr : &block.back(); // a thrown value made of the parameter takes it with it: no release there (a leak, // if it does not) + // ...and the end of a cleanup the exception leaves the function from (its own `finally`, no + // landing pad of its own after it): the kept parameter leaked on that way out (final-review M-1) auto leaves = mlir::isa_and_nonnull(exit) || (mlir::isa_and_nonnull(exit) && - !readsSlot(exit->getOperand(0), varOp.getResult())); + !readsSlot(exit->getOperand(0), varOp.getResult())) || + (mlir::isa_and_nonnull(exit) && exit->getNumSuccessors() == 0); if (!leaves) { continue; diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index b907887f8..795e96f2c 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -329,12 +329,16 @@ namespace own_inference } markCountedRetains(); - warnCounted(); - // an error nobody counted, or a failure no counted value's error explains + // an error nobody counted, or a failure no counted value's error explains: the function fails, and is not + // built - its counts are not reported (a "counts this object here" beside an error that stays read as if the + // program were built, counting) if (uncountedErrors > 0 || (failureSignalled && countedErrors.empty())) { PassWrapper::signalPassFailure(); + return; } + + warnCounted(); } void OwnershipInferencePass::signalPassFailure() diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index a54bff4a0..cc89ebcbd 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -464,6 +464,7 @@ class OwnershipInferencePass bool borrowsOnly(mlir_ts::VariableOp varOp); // Is `value` a read a `let` given it only borrows (borrowsOnly)? bool letBorrows(mlir::Value value); + bool mergeOfPatternDefault(mlir::BlockArgument argument, unsigned depth); // The `let` (borrowsOnly) that `user` assigns `value` to - the store itself, or rc's retain right // before it - or null. mlir_ts::VariableOp borrowingAssignmentOf(mlir::Operation *user, mlir::Value value); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 2ab3b18ed..208c3970f 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -200,7 +200,16 @@ namespace own_signature if (!stableFields.empty()) { - module->setAttr(OWN_STABLE_FIELDS_ATTR_NAME, mlir::ArrayAttr::get(&getContext(), stableFields.getArrayRef())); + // in the order of the class names and positions: writtenAfterConstruction is keyed by type pointer, and + // its order changed from one compile to the next (nondeterministic IR) + llvm::SmallVector sorted(stableFields.begin(), stableFields.end()); + auto keyOf = [](mlir::Attribute entry) { + auto pair = mlir::cast(entry); + auto storage = mlir::cast(mlir::cast(pair[0]).getValue()); + return std::make_pair(storage.getName().getAttr().getValue(), mlir::cast(pair[1]).getInt()); + }; + llvm::stable_sort(sorted, [&](mlir::Attribute a, mlir::Attribute b) { return keyOf(a) < keyOf(b); }); + module->setAttr(OWN_STABLE_FIELDS_ATTR_NAME, mlir::ArrayAttr::get(&getContext(), sorted)); } if (auto functionsDropping = module->getAttrOfType(SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME)) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 8cc71ea0e..66fa2bc9e 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4185,6 +4185,27 @@ foreach(defaultlib_collector_mode jit compile) set_tests_properties(test-${defaultlib_collector_mode}-gc-defaultlib-collector PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") endforeach() +# -mm=own --own-fallback=count with the real default library: a counted node held by the library's containers (a +# Map's value, a Set's member, array helpers) beside its two holders prints what gc prints (final-review M-5: no +# test used the flag with the default library). Skipped when no own default library has been built. +foreach(own_defaultlib_mode jit compile) + add_test(NAME test-${own_defaultlib_mode}-own-fallback-defaultlib + COMMAND ${CMAKE_COMMAND} + "-DMODE=${own_defaultlib_mode}" + "-DEXTRA=--own-fallback=count" + "-DTSLANG=$" + "-DTSLANG_BIN=${CMAKE_BINARY_DIR}/bin" + "-DTEST=${CMAKE_CURRENT_SOURCE_DIR}/defaultlib/own_fallback_default_lib.ts" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-fallback-defaultlib-${own_defaultlib_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-${own_defaultlib_mode}-own-fallback-defaultlib PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") +endforeach() + # -mm=own with the real default library: its facts reach the program, under the JIT as for an exe # (see own-defaultlib-facts.cmake). Skipped when no own default library has been built. foreach(own_defaultlib_mode jit compile) @@ -5691,6 +5712,102 @@ foreach(past_end_mm gc rc own) tslang_add_test(NAME test-jit-${past_end_mm}-destructuring-default-past-end COMMAND test-runner -jit -mm=${past_end_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_default_past_end.ts") tslang_add_test(NAME test-compile-${past_end_mm}-destructuring-default-past-end COMMAND test-runner -mm=${past_end_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_default_past_end.ts") endforeach() +# -mm=rc: an argument read out of a field or an element of an object a closure can reach (a captured local's array, a +# const object captured by value), given to a call that may write a place (the closure setting it, pop/shift/splice, +# a new array for the local), is held by the caller across the call; a destructured parameter's names own what they +# read. They read freed memory. gc and none print the same; own refuses these programs. +foreach(arg_place_mm gc rc none) + tslang_add_test(NAME test-jit-${arg_place_mm}-rc-argument-place-overwritten COMMAND test-runner -jit -mm=${arg_place_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_overwritten.ts") + tslang_add_test(NAME test-compile-${arg_place_mm}-rc-argument-place-overwritten COMMAND test-runner -mm=${arg_place_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_overwritten.ts") +endforeach() +# -mm=own: an array literal holding no value at all (`[undefined]`, `[null]`, `[]`) given straight to a call is owned +# and given back after it (it leaked every call); the same program under gc and rc. IR: the literal is an owned result. +foreach(no_values_mm gc rc own) + tslang_add_test(NAME test-jit-${no_values_mm}-own-literal-argument-no-values COMMAND test-runner -jit -mm=${no_values_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_literal_argument_no_values.ts") + tslang_add_test(NAME test-compile-${no_values_mm}-own-literal-argument-no-values COMMAND test-runner -mm=${no_values_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_literal_argument_no_values.ts") +endforeach() +add_test(NAME test-own-literal-argument-no-values-ir + COMMAND $ --emit=mlir --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_literal_argument_no_values.ts") +set_tests_properties(test-own-literal-argument-no-values-ir + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]CreateArray\"[(]%[0-9]+[)] {__owned_result} : [(]!ts[.]optional --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_conditional_array_no_class.ts") +set_tests_properties(test-rc-conditional-array-no-class-ir + PROPERTIES PASS_REGULAR_EXPRESSION "[}][)] {__owned_result, __owned_result_consumed} : [(]!ts[.]boolean[)] -> !ts[.]array" + FAIL_REGULAR_EXPRESSION "error:|Stack dump") +# `c == null` / `c == undefined` (loose) of a value that may be undefined leaves the equal side as it is (it was +# narrowed to null: `c == null && c === undefined` false for undefined); results match node, every model. +foreach(loose_nullish_mm gc rc own none) + tslang_add_test(NAME test-jit-${loose_nullish_mm}-narrow-loose-nullish COMMAND test-runner -jit -mm=${loose_nullish_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish.ts") + tslang_add_test(NAME test-compile-${loose_nullish_mm}-narrow-loose-nullish COMMAND test-runner -mm=${loose_nullish_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish.ts") +endforeach() +# -mm=own: a `let` a pattern binds with a default, given another value later (`let { p = mk(1) } = r; p = mk(3)`), is +# split into a holder as a `let` given a field read is (it was refused); the same program under gc and rc. +foreach(let_default_mm gc rc own) + tslang_add_test(NAME test-jit-${let_default_mm}-own-pattern-default-let-assigned COMMAND test-runner -jit -mm=${let_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_let_assigned.ts") + tslang_add_test(NAME test-compile-${let_default_mm}-own-pattern-default-let-assigned COMMAND test-runner -mm=${let_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_let_assigned.ts") +endforeach() +# -mm=own: a parameter the function keeps on some paths is released at the end of a cleanup the exception leaves +# the function from (its own `finally`), as at its returns and throws (it leaked); the same program under gc and rc. +foreach(kept_finally_mm gc rc own) + tslang_add_test(NAME test-jit-${kept_finally_mm}-own-kept-param-finally-unwind COMMAND test-runner -jit -mm=${kept_finally_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_kept_param_finally_unwind.ts") + tslang_add_test(NAME test-compile-${kept_finally_mm}-own-kept-param-finally-unwind COMMAND test-runner -mm=${kept_finally_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_kept_param_finally_unwind.ts") +endforeach() +# A concise arrow with a destructured parameter gives back what the parameter's names own (rc) and its default's slot +# (own) before it returns (they leaked; the ownership verifier refused it); every model. +foreach(concise_mm gc rc own none) + tslang_add_test(NAME test-jit-${concise_mm}-param-pattern-concise-arrow COMMAND test-runner -jit -mm=${concise_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00param_pattern_concise_arrow.ts") + tslang_add_test(NAME test-compile-${concise_mm}-param-pattern-concise-arrow COMMAND test-runner -mm=${concise_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00param_pattern_concise_arrow.ts") +endforeach() +# ...and a borrowed `N | null | undefined` (an element, a for-of variable, a field) narrowed so is a view of the borrow: +# own accepts it (it refused it after the loose narrowing); every model. +foreach(loose_borrowed_mm gc rc own none) + tslang_add_test(NAME test-jit-${loose_borrowed_mm}-narrow-loose-nullish-borrowed COMMAND test-runner -jit -mm=${loose_borrowed_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish_borrowed.ts") + tslang_add_test(NAME test-compile-${loose_borrowed_mm}-narrow-loose-nullish-borrowed COMMAND test-runner -mm=${loose_borrowed_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish_borrowed.ts") +endforeach() +# -mm=rc: an argument read out of a place of an object another name may reach (a global, another argument's container, +# a second const, a captured array, a parameter's object) is held across a call that may write a place of that kind +# (the reviewer's X01-X21; rc read freed memory). gc and none the same. IR: `gw2(h.o)` after `G = h`, with `gw2` setting +# `G.o`, holds the argument. +foreach(arg_aliased_mm gc rc none) + tslang_add_test(NAME test-jit-${arg_aliased_mm}-rc-argument-place-aliased COMMAND test-runner -jit -mm=${arg_aliased_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_aliased.ts") + tslang_add_test(NAME test-compile-${arg_aliased_mm}-rc-argument-place-aliased COMMAND test-runner -mm=${arg_aliased_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_aliased.ts") +endforeach() +add_test(NAME test-rc-argument-place-aliased-ir + COMMAND $ --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_aliased.ts") +set_tests_properties(test-rc-argument-place-aliased-ir + PROPERTIES PASS_REGULAR_EXPRESSION "identifier = @gw2}>[^\n]*\n[^\n]*\"ts[.]PropertyRef\"[^\n]*\n[^\n]*\"ts[.]Load\"[^\n]*\n *\"ts[.]Retain\"" + FAIL_REGULAR_EXPRESSION "error:|Stack dump") +# ...and an argument read out of an array a callee shortens through another name (`a.length = 0`): an element write. +# IR: the element read is held. +foreach(arg_set_length_mm gc rc none) + tslang_add_test(NAME test-jit-${arg_set_length_mm}-rc-argument-place-set-length COMMAND test-runner -jit -mm=${arg_set_length_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_set_length.ts") + tslang_add_test(NAME test-compile-${arg_set_length_mm}-rc-argument-place-set-length COMMAND test-runner -mm=${arg_set_length_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_set_length.ts") +endforeach() +add_test(NAME test-rc-argument-place-set-length-ir + COMMAND $ --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_set_length.ts") +set_tests_properties(test-rc-argument-place-set-length-ir + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]ElementRef\"[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[^\n]*-> !ts[.]class<@N[^\n]*\n *\"ts[.]Retain\"[(]%[0-9]+[)] : [(]!ts[.]class<@N" + FAIL_REGULAR_EXPRESSION "error:|Stack dump") # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives @@ -6370,6 +6487,17 @@ foreach(fallback_test own/own_fallback_result_borrow_stays_error own/own_err_sha "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/${fallback_test}.ts" -P "${CMAKE_CURRENT_SOURCE_DIR}/own-fallback.cmake") endforeach() +# ...and the fallback reading OwnershipModuleFactsPass's cached analysis (DescriptorObjectsAnalysis): an interface +# parameter given to two fields is counted only when no class here may hold a closure (read without the cache the +# answer is "may hold", and it would be refused), and stays an error when one does +add_test(NAME test-own-fallback-ir-own_fallback_cached_analysis + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ -DMODE=IR -DCOUNTED=2 + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_fallback_cached_analysis.ts" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-fallback.cmake") +add_test(NAME test-own-fallback-ir-own_fallback_cached_analysis_held + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ -DMODE=EXPECT_ERROR + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_fallback_cached_analysis_held.ts" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-fallback.cmake") # ...and a tuple whose kept retains are of a tagged union's type (a `T | null` field): refused at # its place, with own's error add_test(NAME test-own-fallback-ir-own_fallback_tuple_in_union_stays_error @@ -6402,7 +6530,7 @@ foreach(fallback_test own_fallback_second_owner own_fallback_move_overwrite own_ own_fallback_call_second_owner own_fallback_swap own_fallback_global_lent own_fallback_unwind own_fallback_generator own_fallback_kept_lent own_fallback_kept_call_twice own_fallback_kept_twice_one_call own_fallback_string_second_owner own_fallback_weak_target - own_fallback_unwind_kept_param own_fallback_take_out_of_field own_fallback_take_from_result + own_fallback_unwind_kept_param own_fallback_kept_param_finally own_fallback_take_out_of_field own_fallback_take_from_result own_fallback_take_from_result_iface own_fallback_take_through_id own_fallback_not_promoted own_fallback_keeper own_fallback_fuzz_1122184 own_fallback_fuzz_1122290 own_fallback_fuzz_1122304 own_fallback_let_from_counted_local own_fallback_array_counted diff --git a/tslang/test/tester/defaultlib/own_fallback_default_lib.ts b/tslang/test/tester/defaultlib/own_fallback_default_lib.ts new file mode 100644 index 000000000..690a4fd86 --- /dev/null +++ b/tslang/test/tester/defaultlib/own_fallback_default_lib.ts @@ -0,0 +1,46 @@ +// -mm=own --own-fallback=count with the default library (own-defaultlib-facts.cmake, EXTRA): a node own refuses +// to give two owners (`link` stores it in two holders) is counted, and the counted node is then read through the +// library's array helpers (`map`, `find`, `some`, `indexOf`; `filter` of the values it maps to) and its text kept in a Map and a Set (own's +// Map and Set hold values, strings, `any` and Shared), beside its holders. Each owner gives its share back; the +// program prints what gc prints. +class Node { + constructor(public v: number, public s: string) {} +} + +class Holder { + node: Node | null = null; +} + +function link(h: Holder, g: Holder, n: Node) { + h.node = n; + g.node = n; +} + +function main() { + let sum: number = 0; + for (let i = 0; i < 200; i++) { + const h = new Holder(); + const g = new Holder(); + link(h, g, new Node(i, "a" + i)); + + const byName = new Map(); + byName.set(h.node!.s, h.node!.v); + const seen = new Set(); + seen.add(g.node!.s); + const all: Node[] = [new Node(i + 1, "b" + i), new Node(i + 2, "c" + i)]; + const values = all.map((n) => n.v); + const even = values.filter((v) => v % 2 == 0); + const found = all.find((n) => n.v == i + 2); + const any = all.some((n) => n.s == "b" + i); + + sum += byName.get("a" + i)! + (seen.has(h.node!.s) ? 1 : 0) + even.length + values[0] + (found ? found.v : 0) + + (any ? 1 : 0) + all.indexOf(all[1]); + if (h.node!.s != g.node!.s) { + print("bad"); + } + } + + print(sum); + assert(sum == 61100, "sum"); + print("done."); +} diff --git a/tslang/test/tester/own-defaultlib-facts.cmake b/tslang/test/tester/own-defaultlib-facts.cmake index fa8b0e14a..b6998609a 100644 --- a/tslang/test/tester/own-defaultlib-facts.cmake +++ b/tslang/test/tester/own-defaultlib-facts.cmake @@ -5,6 +5,7 @@ # # MODE=jit run it under the JIT # MODE=compile build an exe and run it +# EXTRA more options for tslang (`--own-fallback=count`: the fallback against the library) # # Every test-runner test passes --no-default-lib, so this drives tslang itself. With no default # library built the test prints SKIPPED and CTest reports it skipped. @@ -60,7 +61,7 @@ set(ENV{DEFAULT_LIB_PATH} "") file(REMOVE_RECURSE "${WORK_DIR}") file(MAKE_DIRECTORY "${WORK_DIR}") -set(common ${OPT} -mm=own "--default-lib-path=${default_lib}" "--llvm-lib-path=${LLVM_LIB}" +set(common ${OPT} -mm=own ${EXTRA} "--default-lib-path=${default_lib}" "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" "--gc-lib-path=${GC_LIB}") if(WIN32) @@ -70,13 +71,19 @@ else() endif() if(MODE STREQUAL "jit") - set(command "${TSLANG}" --emit=jit ${common} "--shared-libs=${runtime}" "${TEST}") + # (with EXTRA, compiled each run: a cached object would compile nothing and say nothing) + set(jit_cache) + if(DEFINED EXTRA) + set(jit_cache --jit-cache=false) + endif() + set(command "${TSLANG}" --emit=jit ${jit_cache} ${common} "--shared-libs=${runtime}" "${TEST}") else() execute_process(COMMAND "${TSLANG}" --emit=exe ${common} "${TEST}" -o "${WORK_DIR}/test${exe_suffix}" OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE status) if(NOT status EQUAL 0) message(FATAL_ERROR "--emit=exe -mm=own: exit ${status}\n${out}\n${err}") endif() + set(build_log "${out}${err}") set(command "${WORK_DIR}/test${exe_suffix}") endif() @@ -88,4 +95,12 @@ if(NOT status EQUAL 0 OR NOT out MATCHES "done\.") message(FATAL_ERROR "${MODE} -mm=own: exit ${status}\n${out}\n${err}") endif() +# with --own-fallback=count, the program exercises it: a value is counted +if(EXTRA MATCHES "own-fallback") + string(FIND "${build_log}${out}${err}" "counts this object here" counted) + if(counted EQUAL -1) + message(FATAL_ERROR "${MODE} -mm=own ${EXTRA}: nothing was counted\n${build_log}${out}${err}") + endif() +endif() + message(STATUS "${MODE} -mm=own: done.") diff --git a/tslang/test/tester/own-fallback.cmake b/tslang/test/tester/own-fallback.cmake index ff9ef96a1..0fae7fb56 100644 --- a/tslang/test/tester/own-fallback.cmake +++ b/tslang/test/tester/own-fallback.cmake @@ -11,7 +11,8 @@ # SHARE, also that its LLVM IR under own has a share routine (`tsshr_`), one for # a closure's capture box (`tsshrbox_`), and an atomic `or` setting the shared # bit: Shared.share is not erased under own -# MODE=EXPECT_ERROR still refused with the flag: `error:` (with ERROR_AT, line:column, one there) +# MODE=EXPECT_ERROR still refused with the flag: `error:` (with ERROR_AT, line:column, one there), and no +# "counts this object here" warning beside it: a function that fails is not built # MODE=SAME the other way round: a file own accepts without the flag is accepted with it # too, with no count and no warning, and run with it (JIT) prints what it prints # under -mm=gc, with no error - the flag only ever turns an error into a count @@ -178,6 +179,12 @@ elseif(MODE STREQUAL "EXPECT_ERROR") if(result EQUAL 0 OR error EQUAL -1) message(FATAL_ERROR "compiled with --own-fallback=count, expected an error (${result}):\n${out}") endif() + # a function that fails is not built: it reports no count beside its error + string(FIND "${out}" "counts this object here" countWarning) + if(NOT countWarning EQUAL -1) + message(FATAL_ERROR "refused with --own-fallback=count, yet reports a count: +${out}") + endif() if(DEFINED ERROR_AT) string(FIND "${out}" ":${ERROR_AT}: error:" errorAt) if(errorAt EQUAL -1) diff --git a/tslang/test/tester/own/own_empty_literal_kept_arg.ts b/tslang/test/tester/own/own_empty_literal_kept_arg.ts new file mode 100644 index 000000000..1a4f24d1b --- /dev/null +++ b/tslang/test/tester/own/own_empty_literal_kept_arg.ts @@ -0,0 +1,31 @@ +// -mm=own: an empty array literal given straight to a call (`new Order(i, [])`) is the new empty array it is: moved into +// a callee that keeps it - the constructor storing it in a field - and given back after one that does not (`ln([])`). +// Owned as the constant-array copy it was made from, it was given back after the keeping constructor too, and the +// object freed it again (the DefaultLib test worker_objects, `worker.postMessage(new Order(-1, []))`, failed on wasm +// with a free of a freed block). The same program under gc and rc. +class Order { + constructor(public id: int, public items: string[]) {} +} + +function ln(xs: string[]): number { + return xs.length + 1; +} + +function count(o: Order): number { + return o.items.length; +} + +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) { + const o = new Order(i, []); + o.items.push("a" + i); + t += count(o) + ln([]); + const kept = [new Order(i, []), new Order(i + 1, [])]; + t += kept.length + kept[1].items.length; + } + + print(t); + assert(t == 4000, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/own_fallback_cached_analysis.ts b/tslang/test/tester/own/own_fallback_cached_analysis.ts new file mode 100644 index 000000000..15279641c --- /dev/null +++ b/tslang/test/tester/own/own_fallback_cached_analysis.ts @@ -0,0 +1,23 @@ +// -mm=own --own-fallback=count: an interface-typed parameter given to two `Shape | null` fields (`h.s = s; k.s = +// s`) is counted only when the module's facts say no class here holds a closure field - a fact +// OwnershipModuleFactsPass caches for the inference (DescriptorObjectsAnalysis). Read without the cache the answer +// is "may hold", and the program is refused instead (own_fallback_cached_analysis_held: the same with a class with a +// closure field, which is refused either way). Pins that the cached analysis is present. +interface Shape { v: number; } +class Node { constructor(public v: number) {} } +class Holder { s: Shape | null = null; } +function link(h: Holder, k: Holder, s: Shape) { + h.s = s; + k.s = s; +} +function main() { + let sum: number = 0; + for (let i = 0; i < 100; i++) { + const h = new Holder(); + const k = new Holder(); + link(h, k, new Node(i)); + sum += h.s!.v + k.s!.v; + } + print(sum); + print("done."); +} diff --git a/tslang/test/tester/own/own_fallback_cached_analysis_held.ts b/tslang/test/tester/own/own_fallback_cached_analysis_held.ts new file mode 100644 index 000000000..15e971476 --- /dev/null +++ b/tslang/test/tester/own/own_fallback_cached_analysis_held.ts @@ -0,0 +1,21 @@ +// -mm=own --own-fallback=count: own_fallback_cached_analysis with a class that has a closure field: the module's +// facts say a class here may hold a closure, so the interface-typed parameter is not counted and stays an error. +interface Shape { v: number; } +class Node { constructor(public v: number) {} } +class Holder { s: Shape | null = null; } +function link(h: Holder, k: Holder, s: Shape) { + h.s = s; + k.s = s; +} +function main() { + let sum: number = 0; + for (let i = 0; i < 100; i++) { + const h = new Holder(); + const k = new Holder(); + link(h, k, new Node(i)); + sum += h.s!.v + k.s!.v; + } + print(sum); + print("done."); +} +class Cl { f: () => number = () => 1; } function useCl() { const c = new Cl(); return c.f(); } diff --git a/tslang/test/tester/own/own_fallback_kept_param_finally.ts b/tslang/test/tester/own/own_fallback_kept_param_finally.ts new file mode 100644 index 000000000..2d9e77681 --- /dev/null +++ b/tslang/test/tester/own/own_fallback_kept_param_finally.ts @@ -0,0 +1,35 @@ +// -mm=own --own-fallback=count: a counted parameter the function keeps, with the exception leaving through the +// function's own `finally` (`try { h.node = n; if (c) throw "x"; return 1 } finally { g.node = n }`): its share was +// given back at the returns and the throws, not at the end of that cleanup, and leaked (+9.9 MB per 400 runs; plain +// own the same, own_kept_param_finally_unwind). Prints what gc prints. +class Node { + constructor(public v: number, public s: string) {} +} +class Holder { + node: Node | null = null; +} +function link(h: Holder, g: Holder, n: Node, c: number): number { + try { + h.node = n; + if (c % 7 == 0) throw "x"; + return 1; + } finally { + g.node = n; + } +} +function main() { + let sum: number = 0; + for (let i = 0; i < 4000; i++) { + const h = new Holder(); + const g = new Holder(); + try { + sum += link(h, g, new Node(i, "a" + i), i); + } catch (e) { + sum += 3; + } + if (h.node) { sum += h.node.v; if (h.node.s != "a" + i) print("bad h"); } + if (g.node) { sum += g.node.v; if (g.node.s != "a" + i) print("bad g"); } + } + print(sum); + print("done."); +} diff --git a/tslang/test/tester/own/own_kept_param_finally_unwind.ts b/tslang/test/tester/own/own_kept_param_finally_unwind.ts new file mode 100644 index 000000000..88011396d --- /dev/null +++ b/tslang/test/tester/own/own_kept_param_finally_unwind.ts @@ -0,0 +1,56 @@ +// -mm=own: a parameter the function keeps on some paths (`if (c % 2 == 0) h.node = n`), with the exception leaving +// through the function's own `finally`: the parameter is released at the function's exits on the paths that did not +// keep it, and the end of that cleanup - where the exception leaves the function - was not one of them: it leaked +// (+9.9 MB per 400 runs, final-review M-1). Kept and then thrown past (`mayThrow` after the store) it stays the +// holder's. The same program under gc and rc. +class Node { + constructor(public v: number, public s: string) {} +} +class Holder { + node: Node | null = null; +} +let trace = 0; +function keep(h: Holder, n: Node, c: number): number { + try { + if (c % 7 == 0) throw "x"; + if (c % 2 == 0) h.node = n; + return 1; + } finally { + trace++; + } +} +@noinline function mayThrow(c: number) { if (c % 5 == 0) throw "y"; } +function keep2(h: Holder, n: Node, c: number): number { + try { + if (c % 2 == 0) h.node = n; + mayThrow(c); + if (c % 7 == 0) throw "x"; + return 1; + } finally { + trace++; + } +} +function main() { + let sum: number = 0; + trace = 0; + for (let i = 0; i < 4000; i++) { + const h = new Holder(); + try { + sum += keep(h, new Node(i, "a" + i), i); + } catch (e) { + sum += 3; + } + const h2 = new Holder(); + try { + sum += keep2(h2, new Node(i, "b" + i), i); + } catch (e) { + sum += 3; + } + if (h.node) { sum += h.node.v; if (h.node.s != "a" + i) print("bad h"); } + if (h2.node) { sum += h2.node.v; if (h2.node.s != "b" + i) print("bad h2"); } + } + print(sum + trace); + assert(sum + trace == 7445088, "total"); + print("done."); +} + diff --git a/tslang/test/tester/own/own_pattern_default_let_assigned.ts b/tslang/test/tester/own/own_pattern_default_let_assigned.ts new file mode 100644 index 000000000..96cc2b902 --- /dev/null +++ b/tslang/test/tester/own/own_pattern_default_let_assigned.ts @@ -0,0 +1,63 @@ +// -mm=own: a `let` a pattern binds with a default that makes a new value, then given another value (`let { p = mk(1) } +// = r; p = mk(3)`), was refused ("'p' borrows 'r.p' and cannot be assigned", "merged from several branches"): its +// value is a merge of a borrow of the field and of the pattern-default slot, both borrows, which own did not see +// as one. It is split as a `let` given a field read is: what it is given later goes into a holder of its own, and the +// `let` borrows that. Also `const [a = mk(1), b = mk(2)] = [mk(i)]` (accepted since the array-default slot). The same +// program under gc and rc. A `let` given a destructured element (`const [a] = xs; let z = a; z = new N(6)`), a merge +// that is no pattern default, is split as before (it was refused while every merge was taken for one). +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +class R { + p?: N; +} + +@noinline function mk(i: number): N { + return new N(i); +} + +function f(r: R, i: number): number { + let { p = mk(1) } = r; + let t = p.x + p.s.length; + if (i % 3 == 0) { + p = mk(i + 10); + } + + return t + p.x + p.s.length; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const r = new R(); + if (i % 2 == 0) { + r.p = mk(i); + } + + let { p = mk(1) } = r; + total += p.x; + p = mk(3); + total += p.x + p.s.length; + total += f(r, i); + + const [a = mk(1), b = mk(2)] = [mk(i)]; + total += a.x + b.x; + + const xs: N[] = [mk(i), mk(i + 1)]; + const [e] = xs; + let z = e; + total += z.x; + z = new N(6); + total += z.x; + } + + print(total); + assert(total == 171329, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00narrow_loose_nullish.ts b/tslang/test/tester/tests/00narrow_loose_nullish.ts new file mode 100644 index 000000000..57ea94d80 --- /dev/null +++ b/tslang/test/tester/tests/00narrow_loose_nullish.ts @@ -0,0 +1,38 @@ +// `c == null` / `c == undefined` (loose) is true for null and for undefined alike. Of a value that may be undefined, +// the equal side was narrowed to null: in `c == null && c === undefined` the second test was false for undefined +// (and `c === null` true), as in `if (c == null) { c === undefined ... }`. It is left as it is now; the other side is +// the type without null and undefined. Results match node; every memory model. +class C { + constructor(public x: number) {} +} + +function t1(c: C | undefined): boolean { return c == null && c === undefined; } +function t2(c: C | null | undefined): boolean { return c == null && c === undefined; } +function t3(c: C | null | undefined): boolean { return c == null && c === null; } +function t4(c: C | null | undefined): boolean { return c == undefined && c === null; } +function t5(c: number | undefined): boolean { return c == null && c === undefined; } +function t6(c: string | null | undefined): boolean { return c == null && c !== undefined; } + +function a(c: C | undefined): number { if (c == null) return -1; return c.x; } +function b(c: C | null | undefined): number { return c != null ? c.x : -2; } +function d(c: C | undefined): boolean { return c == null || c.x > 0; } +function e(c: number | undefined): number { if (c != undefined) { return c + 1; } return 0; } +function f(c: string | null | undefined): number { return c == undefined ? -3 : c.length; } +function g(c: C | null | undefined): string { if (c == null) { return c === undefined ? "u" : "n"; } return "c" + c.x; } + +function main() { + let out = ""; + out += `${t1(undefined)} ${t1(new C(1))}|`; + out += `${t2(undefined)} ${t2(null)} ${t2(new C(1))}|`; + out += `${t3(undefined)} ${t3(null)} ${t3(new C(1))}|`; + out += `${t4(undefined)} ${t4(null)} ${t4(new C(1))}|`; + out += `${t5(undefined)} ${t5(1)}|`; + out += `${t6(undefined)} ${t6(null)} ${t6("s")}|`; + out += `${a(undefined)} ${a(new C(4))} ${b(null)} ${b(undefined)} ${b(new C(5))}|`; + out += `${d(undefined)} ${d(new C(1))} ${d(new C(-1))}|`; + out += `${e(undefined)} ${e(3)} ${f(null)} ${f(undefined)} ${f("abc")}|`; + out += `${g(undefined)} ${g(null)} ${g(new C(7))}`; + print(out); + assert(out == "true false|true false false|false true false|false true false|true false|false true false|-1 4 -2 -2 5|true true false|0 4 -3 -3 3|u n c7", "as node"); + print("done."); +} diff --git a/tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts b/tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts new file mode 100644 index 000000000..7f12959fd --- /dev/null +++ b/tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts @@ -0,0 +1,38 @@ +// A borrowed `N | null | undefined` narrowed by a loose `!= null` / `== null` - an element read into a `const`, a +// for-of variable, a field - is read as `c !== undefined` reads it, a view of the borrow: -mm=own accepted these +// before the loose narrowing (00narrow_loose_nullish) and refused them with it ("'c' borrows an element and cannot +// be stored, returned or captured"). Every model; output as node's. +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +class H { + v: N | null | undefined = undefined; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 100; i++) { + const vs: (N | null | undefined)[] = [new N(i), null, undefined]; + const c = vs[0]; + if (c != null) total += c.x; + const d = vs[1]; + if (d == null) total += 1; + for (const e of vs) { + if (e != null) total += e.x; + else if (e === undefined) total += 2; + } + + const h = new H(); + h.v = new N(3); + if (h.v != null) total += h.v.x; + total += h.v == null || h.v.x > 2 ? 1 : 0; + } + + print(total); + assert(total == 10600, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00own_literal_argument_no_values.ts b/tslang/test/tester/tests/00own_literal_argument_no_values.ts new file mode 100644 index 000000000..cf54480de --- /dev/null +++ b/tslang/test/tester/tests/00own_literal_argument_no_values.ts @@ -0,0 +1,37 @@ +// -mm=own: an array literal given straight to a call that holds no value at all - `po([undefined])`, `pn([null])`, +// `ln([])` - was never given back: it neither owned nor borrowed anything, so own left it to nobody (about 50 bytes a +// call; 3M calls: 110-190 MB on main, flat now). It is owned like a literal of new values, and given back after the +// call. The same program under gc and rc. +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +function v(o: N | undefined | null): number { + return o === undefined ? 1 : o === null ? 2 : o.x; +} + +function po([a]: (N | undefined)[], i: number): number { + return v(a) + i; +} + +function pn(xs: (N | null)[]): number { + return v(xs[0]); +} + +function ln(xs: N[]): number { + return xs.length + 1; +} + +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) { + t += po([undefined], i) + pn([null]) + ln([]) + pn([null, null]); + } + + print(t); + assert(t == 505500, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00param_pattern_concise_arrow.ts b/tslang/test/tester/tests/00param_pattern_concise_arrow.ts new file mode 100644 index 000000000..a5989c758 --- /dev/null +++ b/tslang/test/tester/tests/00param_pattern_concise_arrow.ts @@ -0,0 +1,19 @@ +// A concise arrow (`([a = mk(i)]: N[]) => a.x`, `({ s }: N) => s.length`) with a destructured parameter returns +// without a scope exit: the names such a parameter binds (-mm=rc: they own what they read) and its default's slot +// (-mm=own) were never given back - rc +7.2 MB, own +5.4 MB per 400 runs, and the ownership verifier refused the +// body ("some path out of the function never gives back"). Given back before the return now; every model prints the +// same. +class N { x: number; s: string; constructor(x: number) { this.x = x; this.s = "n" + x; } } +@noinline function mk(i: number): N { return new N(i); } +function main() { + let t: number = 0; + const none: N[] = []; + for (let i = 0; i < 300; i++) { + const f = ([a = mk(i)]: N[]) => a.x + a.s.length; + const g = ({ s }: N) => s.length; + t += f(none) + g(mk(i)); + } + print(t); + assert(t == 47030, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00rc_argument_place_aliased.ts b/tslang/test/tester/tests/00rc_argument_place_aliased.ts new file mode 100644 index 000000000..319311eca --- /dev/null +++ b/tslang/test/tester/tests/00rc_argument_place_aliased.ts @@ -0,0 +1,243 @@ +// -mm=rc: an argument read out of a field or an element of an object another name may reach, given to a call that +// may write that place through the other name, is held by the caller across the call. The reviewer's X01-X21: the +// object a closure captures (by reference or by value), also stored in a global (`G = h; gw2(h.o)` with `gw2` setting +// `G.o`), in another argument's container (`aw(bx, arr[0])`, `bx = [arr]`), behind a second const a closure pops +// (`const b2 = arr`), reached through a captured array (`arrh = [h]`, a closure setting `arrh[0].o`), a parameter's +// object, a callback. rc read freed memory (main too); each part now prints what gc prints. The hold needs both: an +// object on the way that may be aliased, and a call that may write a place of that kind (a field's name, an element, +// a captured local's cell) - writes that only make an object (a constructor's) do not count. gc and none print the +// same; own refuses these programs. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +@noinline function ms(i: number): string { + return "s" + i; +} + +@noinline function take(o: N | null): number { + return o ? o.x + o.s.length : 0; +} + +@noinline function takes(s: string | null): number { + return s ? s.length : 0; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} +class H { o: N = mk(0); arr: N[] = [mk(0)]; h2: H | null = null; m(p: N): number { this.o = mk(77); this.arr[0] = mk(78); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } } +let G: H = new H(); +const GA: N[] = [mk(0)]; +function gw(p: N): number { G.o = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function gw2(p: N): number { G.o = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function hw(b: H, p: N): number { b.h2!.o = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function aw(bx: N[][], p: N): number { bx[0][0] = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function gaw(p: N): number { GA[0] = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function gaw2(p: N): number { GA.pop(); GA.push(mk(5)); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function cw(cb: () => void, p: N): number { cb(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function pw(h: H): number { return inner(h, h.o); } function inner(h: H, p: N): number { h.o = mk(9); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function x01(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const f = (p: N) => { arr[0] = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x02(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const f = (p: N) => { h.o = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h.o); + } + return total; +} +function x03(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); total += h.m(h.o); + } + return total; +} +function x04(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.arr[0] = mk(i); total += h.m(h.arr[0]); + } + return total; +} +function x05(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + G.o = mk(i); total += gw(G.o); + } + return total; +} +function x06(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); G = h; total += gw2(h.o); + } + return total; +} +function x07(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const box = new H(); box.h2 = h; total += hw(box, h.o); + } + return total; +} +function x08(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const bx: N[][] = [arr]; total += aw(bx, arr[0]); + } + return total; +} +function x09(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const b2 = arr; const f = (p: N) => { b2.pop(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x10(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const f = (p: N) => { arr.shift(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x11(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i), mk(1)]; const f = (p: N) => { arr.splice(0, 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x12(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + let arr: N[] = [mk(i)]; const f = (p: N) => { arr = [mk(3)]; let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x13(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + GA[0] = mk(i); total += gaw(GA[0]); + } + return total; +} +function x14(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + GA[0] = mk(i); total += gaw2(GA[0]); + } + return total; +} +function x15(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const w = () => { h.o = mk(i + 2); }; const f = (p: N) => { w(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h.o); + } + return total; +} +function x16(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; total += cw(() => { arr[0] = mk(4); }, arr[0]); + } + return total; +} +function x17(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); total += pw(h); + } + return total; +} +function x18(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const arrh: H[] = [h]; const f = (p: N) => { arrh[0].o = mk(3); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h.o); + } + return total; +} +function x19(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const arrh: H[] = [h]; const f = (p: N) => { arrh[0].o = mk(3); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arrh[0].o); + } + return total; +} +function x20(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const f = ([p]: N[]) => { arr[0] = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr); + } + return total; +} +function x21(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const f = ({ o: p }: H) => { h.o = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h); + } + return total; +} +// an array put into another, given with it to a callee that shortens it (`a.length = 0` drops the element) +function f4(p: N, a: N[]): number { a.length = 0; let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function z04(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const al = [arr]; total += f4(arr[0], al[0]); + } + return total; +} +function main() { + G = new H(); + GA.length = 0; + GA.push(mk(0)); + const totals: number[] = []; + totals.push(x01()); + totals.push(x02()); + totals.push(x03()); + totals.push(x04()); + totals.push(x05()); + totals.push(x06()); + totals.push(x07()); + totals.push(x08()); + totals.push(x09()); + totals.push(x10()); + totals.push(x11()); + totals.push(x12()); + totals.push(x13()); + totals.push(x14()); + totals.push(x15()); + totals.push(x16()); + totals.push(x17()); + totals.push(x18()); + totals.push(x19()); + totals.push(x20()); + totals.push(x21()); + totals.push(z04()); + let sum: number = 0; + for (const t of totals) { + sum += t; + } + + print(sum); + assert(sum == 986700, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00rc_argument_place_overwritten.ts b/tslang/test/tester/tests/00rc_argument_place_overwritten.ts new file mode 100644 index 000000000..026f19ad9 --- /dev/null +++ b/tslang/test/tester/tests/00rc_argument_place_overwritten.ts @@ -0,0 +1,43 @@ +// -mm=rc: an argument read out of a field or an element of an object a closure can reach (a captured local's +// array, a `const` object captured by value) is borrowed by the parameter; the callee - the closure - gave that +// place a new value (`arr[0] = mk(i)`, `h.o = mk(i)`), took the element out (`pop`, `shift`, `splice`) or gave the +// captured local a new array, then read its parameter: freed memory (rc printed garbage, main too). The caller now +// holds the argument across the call. A name a destructured parameter binds (`([p]: N[]) => ...`) owns what it reads +// under rc, as a local does. A global's element given to a function that sets it was held already. gc and none +// print the same; own refuses these programs (it cannot prove the borrow outlives the write). +class N { x: number; s: string; constructor(x: number) { this.x = x; this.s = "n" + x; } } +class H { o: N; constructor(o: N) { this.o = o; } } +@noinline function mk(i: number): N { return new N(i); } +function churn() { const junk: N[] = []; for (let i = 0; i < 16; i++) junk.push(new N(100 + i)); } +function v(p: N): number { return p.x + (p.s == "n" + p.x ? 0 : 1000000); } +let G: N[] = [mk(0)]; +function setG(i: number) { G[0] = mk(i); } +function gf(p: N, i: number): number { setG(i); churn(); return v(p); } +function main() { + let t: number = 0; + G = [mk(0)]; + let arr: N[] = [mk(0), mk(1)]; + const h = new H(mk(0)); + for (let i = 0; i < 2000; i++) { + const fe = (p: N) => { arr[0] = mk(i); churn(); return v(p); }; + t += fe(arr[0]); + const ff = (p: N) => { h.o = mk(i); churn(); return v(p); }; + t += ff(h.o); + const fp = (p: N) => { arr.pop(); arr.push(mk(i)); churn(); return v(p); }; + t += fp(arr[arr.length - 1]); + const fs = (p: N) => { arr.shift(); arr.unshift(mk(i)); churn(); return v(p); }; + t += fs(arr[0]); + const fz = (p: N) => { arr.splice(0, 1, mk(i)); churn(); return v(p); }; + t += fz(arr[0]); + const fr = (p: N) => { arr = [mk(i), mk(i)]; churn(); return v(p); }; + t += fr(arr[1]); + t += gf(G[0], i); + const fd = ([p]: N[]) => { arr[0] = mk(i); churn(); return v(p); }; + t += fd(arr); + const fo = ({ o }: H) => { h.o = mk(i); churn(); return v(o); }; + t += fo(h); + } + print(t); + assert(t == 17983005, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00rc_argument_place_set_length.ts b/tslang/test/tester/tests/00rc_argument_place_set_length.ts new file mode 100644 index 000000000..20edf2330 --- /dev/null +++ b/tslang/test/tester/tests/00rc_argument_place_set_length.ts @@ -0,0 +1,45 @@ +// -mm=rc: an argument read out of an array (`f4(arr[0], al[0])`, `al = [arr]`) given to a callee that shortens that +// array through its other name (`a.length = 0` gives back the element it drops) is held by the caller: `a.length = n` +// is an element write (writtenKinds) as `pop`, `shift` and `splice` are. rc read freed memory (3751995 against gc's +// 4498500). Alone in its module, as 00rc_argument_place_aliased's copy of it is held there for another reason. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +@noinline function ms(i: number): string { + return "s" + i; +} + +@noinline function take(o: N | null): number { + return o ? o.x + o.s.length : 0; +} + +@noinline function takes(s: string | null): number { + return s ? s.length : 0; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} +function f4(p: N, a: N[]): number { a.length = 0; let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const al = [arr]; total += f4(arr[0], al[0]); + } + print(total); + assert(total == 44850, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00rc_conditional_array_no_class.ts b/tslang/test/tester/tests/00rc_conditional_array_no_class.ts new file mode 100644 index 000000000..259aebd46 --- /dev/null +++ b/tslang/test/tester/tests/00rc_conditional_array_no_class.ts @@ -0,0 +1,28 @@ +// -mm=rc: a conditional that yields a new array (`const xs: number[] = c ? [i] : []`) in a module with no function +// that returns a heap value - no class, no `new` - leaked the array every evaluation: OwnedReturnConsumptionPass +// skipped consumeConditionalResults there, and the local took a count of its own beside the branch's. A `let`, the +// assignment form, strings and nested arrays too. Every memory model (own and gc were flat already). +function main() { + let total: number = 0; + for (let i = 0; i < 1000; i++) { + const xs: number[] = i % 2 == 0 ? [i] : []; + total += xs.length; + + let ys: number[] = i % 3 == 0 ? [i, i] : []; + total += ys.length; + + let zs: number[] = [i]; + zs = i % 2 == 1 ? [i, i, i] : []; + total += zs.length; + + const ss: string[] = i % 2 == 0 ? ["s" + i] : []; + total += ss.length; + + const nested: number[][] = i % 4 == 0 ? [[i]] : []; + total += nested.length; + } + + print(total); + assert(total == 3418, "total"); + print("done."); +}