Skip to content

Automatically export runtime when necessary #2383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ export async function main(argv, options) {
opts.stackSize = assemblyscript.DEFAULT_STACK_SIZE;
}
assemblyscript.setStackSize(compilerOptions, opts.stackSize);
assemblyscript.setBindingsHint(compilerOptions, opts.bindings && opts.bindings.length > 0);

// Instrument callback to perform GC
// prepareResult = (original => {
Expand Down
95 changes: 74 additions & 21 deletions src/bindings/js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -941,23 +941,6 @@ export class JSBuilder extends ExportsWalker {
return moduleId;
}

isPlainObject(clazz: Class): bool {
// A plain object does not inherit and does not have a constructor or private properties
if (clazz.base) return false;
var members = clazz.members;
if (members) {
for (let _values = Map_values(members), i = 0, k = _values.length; i < k; ++i) {
let member = _values[i];
if (member.isAny(CommonFlags.PRIVATE | CommonFlags.PROTECTED)) return false;
if (member.is(CommonFlags.CONSTRUCTOR)) {
// a generated constructor is ok
if (member.declaration.range != this.program.nativeRange) return false;
}
}
}
return true;
}

/** Lifts a WebAssembly value to a JavaScript value. */
makeLiftFromValue(name: string, type: Type, sb: string[] = this.sb): void {
if (type.isInternalReference) {
Expand Down Expand Up @@ -996,7 +979,7 @@ export class JSBuilder extends ExportsWalker {
}
sb.push(", ");
this.needsLiftTypedArray = true;
} else if (this.isPlainObject(clazz)) {
} else if (isPlainObject(clazz)) {
sb.push("__liftRecord");
sb.push(clazz.id.toString());
sb.push("(");
Expand Down Expand Up @@ -1076,7 +1059,7 @@ export class JSBuilder extends ExportsWalker {
sb.push(clazz.getArrayValueType().alignLog2.toString());
sb.push(", ");
this.needsLowerTypedArray = true;
} else if (this.isPlainObject(clazz)) {
} else if (isPlainObject(clazz)) {
sb.push("__lowerRecord");
sb.push(clazz.id.toString());
sb.push("(");
Expand Down Expand Up @@ -1237,7 +1220,7 @@ export class JSBuilder extends ExportsWalker {
}

makeLiftRecord(clazz: Class): string {
assert(this.isPlainObject(clazz));
assert(isPlainObject(clazz));
var sb = new Array<string>();
indent(sb, this.indentLevel);
sb.push("function __liftRecord");
Expand Down Expand Up @@ -1275,7 +1258,7 @@ export class JSBuilder extends ExportsWalker {
}

makeLowerRecord(clazz: Class): string {
assert(this.isPlainObject(clazz));
assert(isPlainObject(clazz));
var sb = new Array<string>();
indent(sb, this.indentLevel);
sb.push("function __lowerRecord");
Expand Down Expand Up @@ -1350,6 +1333,23 @@ function isPlainFunction(signature: Signature, mode: Mode): bool {
return true;
}

function isPlainObject(clazz: Class): bool {
// A plain object does not inherit and does not have a constructor or private properties
if (clazz.base) return false;
var members = clazz.members;
if (members) {
for (let _values = Map_values(members), i = 0, k = _values.length; i < k; ++i) {
let member = _values[i];
if (member.isAny(CommonFlags.PRIVATE | CommonFlags.PROTECTED)) return false;
if (member.is(CommonFlags.CONSTRUCTOR)) {
// a generated constructor is ok
if (member.declaration.range != member.program.nativeRange) return false;
}
}
}
return true;
}

function indentText(text: string, indentLevel: i32, sb: string[], butFirst: bool = false): void {
var lineStart = 0;
var length = text.length;
Expand All @@ -1367,3 +1367,56 @@ function indentText(text: string, indentLevel: i32, sb: string[], butFirst: bool
sb.push(text.substring(lineStart));
}
}

export function liftRequiresExportRuntime(type: Type): bool {
if (!type.isInternalReference) return false;
let clazz = type.classReference;
if (!clazz) {
// functions lift as internref using __pin
assert(type.signatureReference);
return true;
}
let program = clazz.program;
// flat collections lift via memory copy
if (
clazz.extends(program.arrayBufferInstance.prototype) ||
clazz.extends(program.stringInstance.prototype) ||
clazz.extends(program.arrayBufferViewInstance.prototype)
) {
return false;
}
// nested collections lift depending on element type
if (
clazz.extends(program.arrayPrototype) ||
clazz.extends(program.staticArrayPrototype)
) {
return liftRequiresExportRuntime(clazz.getArrayValueType());
}
// complex objects lift as internref using __pin. plain objects may or may not
// involve the runtime: assume that they do to avoid potentially costly checks
return true;
}

export function lowerRequiresExportRuntime(type: Type): bool {
if (!type.isInternalReference) return false;
let clazz = type.classReference;
if (!clazz) {
// lowers by reference
assert(type.signatureReference);
return false;
}
// lowers using __new
let program = clazz.program;
if (
clazz.extends(program.arrayBufferInstance.prototype) ||
clazz.extends(program.stringInstance.prototype) ||
clazz.extends(program.arrayBufferViewInstance.prototype) ||
clazz.extends(program.arrayPrototype) ||
clazz.extends(program.staticArrayPrototype)
) {
return true;
}
// complex objects lower via internref by reference,
// while plain objects lower using __new
return isPlainObject(clazz);
}
62 changes: 59 additions & 3 deletions src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,11 @@ import {
ShadowStackPass
} from "./passes/shadowstack";

import {
liftRequiresExportRuntime,
lowerRequiresExportRuntime
} from "./bindings/js";

/** Compiler options. */
export class Options {
constructor() { /* as internref */ }
Expand Down Expand Up @@ -275,6 +280,8 @@ export class Options {
shrinkLevelHint: i32 = 0;
/** Hinted basename. */
basenameHint: string = "output";
/** Hinted bindings generation. */
bindingsHint: bool = false;

/** Tests if the target is WASM64 or, otherwise, WASM32. */
get isWasm64(): bool {
Expand Down Expand Up @@ -410,6 +417,8 @@ export class Compiler extends DiagnosticEmitter {
shadowStack!: ShadowStackPass;
/** Whether the module has custom function exports. */
hasCustomFunctionExports: bool = false;
/** Whether the module would use the exported runtime to lift/lower. */
desiresExportRuntime: bool = false;

/** Compiles a {@link Program} to a {@link Module} using the specified options. */
static compile(program: Program): Module {
Expand Down Expand Up @@ -500,8 +509,8 @@ export class Compiler extends DiagnosticEmitter {
}
}

// compile and export runtime if requested
if (this.options.exportRuntime) {
// compile and export runtime if requested or necessary
if (this.options.exportRuntime || (this.options.bindingsHint && this.desiresExportRuntime)) {
for (let i = 0, k = runtimeFunctions.length; i < k; ++i) {
let name = runtimeFunctions[i];
let instance = program.requireFunction(name);
Expand Down Expand Up @@ -853,9 +862,27 @@ export class Compiler extends DiagnosticEmitter {
if (!module.hasExport(exportName)) {
module.addFunctionExport(functionInstance.internalName, exportName);
this.hasCustomFunctionExports = true;
if (signature.hasManagedOperands) {
let hasManagedOperands = signature.hasManagedOperands;
if (hasManagedOperands) {
this.shadowStack.noteExport(exportName, signature.getManagedOperandIndices());
}
if (!this.desiresExportRuntime) {
let thisType = signature.thisType;
if (
thisType && lowerRequiresExportRuntime(thisType) ||
liftRequiresExportRuntime(signature.returnType)
) {
this.desiresExportRuntime = true;
} else {
let parameterTypes = signature.parameterTypes;
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
if (lowerRequiresExportRuntime(parameterTypes[i])) {
this.desiresExportRuntime = true;
break;
}
}
}
}
}
return;
}
Expand All @@ -877,6 +904,15 @@ export class Compiler extends DiagnosticEmitter {
let exportName = prefix + name;
if (!module.hasExport(exportName)) {
module.addGlobalExport(element.internalName, exportName);
if (!this.desiresExportRuntime) {
let type = global.type;
if (
liftRequiresExportRuntime(type) ||
!global.is(CommonFlags.CONST) && lowerRequiresExportRuntime(type)
) {
this.desiresExportRuntime = true;
}
}
}
return;
}
Expand Down Expand Up @@ -1087,6 +1123,9 @@ export class Compiler extends DiagnosticEmitter {
!isDeclaredConstant
);
pendingElements.delete(global);
if (!this.desiresExportRuntime && lowerRequiresExportRuntime(type)) {
this.desiresExportRuntime = true;
}
return true;
}

Expand Down Expand Up @@ -1441,6 +1480,23 @@ export class Compiler extends DiagnosticEmitter {
signature.resultRefs
);
funcRef = module.getFunction(instance.internalName);
if (!this.desiresExportRuntime) {
let thisType = signature.thisType;
if (
thisType && liftRequiresExportRuntime(thisType) ||
lowerRequiresExportRuntime(signature.returnType)
) {
this.desiresExportRuntime = true;
} else {
let parameterTypes = signature.parameterTypes;
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
if (liftRequiresExportRuntime(parameterTypes[i])) {
this.desiresExportRuntime = true;
break;
}
}
}
}

// abstract or interface function
} else if (instance.is(CommonFlags.ABSTRACT) || instance.parent.kind == ElementKind.INTERFACE) {
Expand Down
5 changes: 5 additions & 0 deletions src/index-wasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,11 @@ export function setBasenameHint(options: Options, basename: string): void {
options.basenameHint = basename;
}

/** Gives the compiler a hint that bindings will be generated. */
export function setBindingsHint(options: Options, bindings: bool): void {
options.bindingsHint = bindings;
}

/** Sets the `pedantic` option. */
export function setPedantic(options: Options, pedantic: bool): void {
options.pedantic = pedantic;
Expand Down
1 change: 0 additions & 1 deletion tests/compiler/bindings/esm.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"asc_flags": [
"--exportRuntime",
"--exportStart _start",
"--bindings esm"
],
Expand Down
82 changes: 82 additions & 0 deletions tests/compiler/bindings/noExportRuntime.debug.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/** Exported memory */
export declare const memory: WebAssembly.Memory;
/** bindings/noExportRuntime/isBasic */
export declare const isBasic: {
/** @type `i32` */
get value(): number;
set value(value: number);
};
/**
* bindings/noExportRuntime/takesReturnsBasic
* @param a `i32`
* @returns `i32`
*/
export declare function takesReturnsBasic(a: number): number;
/** bindings/noExportRuntime/isString */
export declare const isString: {
/** @type `~lib/string/String` */
get value(): string
};
/**
* bindings/noExportRuntime/returnsString
* @returns `~lib/string/String`
*/
export declare function returnsString(): string;
/** bindings/noExportRuntime/isBuffer */
export declare const isBuffer: {
/** @type `~lib/arraybuffer/ArrayBuffer` */
get value(): ArrayBuffer
};
/**
* bindings/noExportRuntime/returnsBuffer
* @returns `~lib/arraybuffer/ArrayBuffer`
*/
export declare function returnsBuffer(): ArrayBuffer;
/** bindings/noExportRuntime/isTypedArray */
export declare const isTypedArray: {
/** @type `~lib/typedarray/Int32Array` */
get value(): Int32Array
};
/**
* bindings/noExportRuntime/returnsTypedArray
* @returns `~lib/typedarray/Int32Array`
*/
export declare function returnsTypedArray(): Int32Array;
/** bindings/noExportRuntime/isArrayOfBasic */
export declare const isArrayOfBasic: {
/** @type `~lib/array/Array<i32>` */
get value(): Array<number>
};
/**
* bindings/noExportRuntime/returnsArrayOfBasic
* @returns `~lib/array/Array<i32>`
*/
export declare function returnsArrayOfBasic(): Array<number>;
/** bindings/noExportRuntime/isArrayOfArray */
export declare const isArrayOfArray: {
/** @type `~lib/array/Array<~lib/array/Array<i32>>` */
get value(): Array<Array<number>>
};
/**
* bindings/noExportRuntime/returnsArrayOfArray
* @returns `~lib/array/Array<~lib/array/Array<i32>>`
*/
export declare function returnsArrayOfArray(): Array<Array<number>>;
/**
* bindings/noExportRuntime/takesNonPlainObject
* @param obj `bindings/noExportRuntime/NonPlainObject`
*/
export declare function takesNonPlainObject(obj: __Internref6): void;
/**
* bindings/noExportRuntime/takesFunction
* @param fn `() => void`
*/
export declare function takesFunction(fn: __Internref7): void;
/** bindings/noExportRuntime/NonPlainObject */
declare class __Internref6 extends Number {
private __nominal6: symbol;
}
/** ~lib/function/Function<%28%29=>void> */
declare class __Internref7 extends Number {
private __nominal7: symbol;
}
Loading