Skip to content
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
18 changes: 16 additions & 2 deletions nilassembler/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,19 @@ struct command_line {
bool help = false;
bool version = false;
bool unmanaged = false;
bool freestanding = false;
bool embed_context = false;
};

void print_usage(std::ostream &stream) {
stream
<< "Usage: nilassembler [-o <output.o>] [--unmanaged] [--embed-context] <input.nil>\n"
<< "Usage: nilassembler [-o <output.o>] [--unmanaged] [--freestanding]"
" [--embed-context] <input.nil>\n"
<< "\n"
<< "Options:\n"
<< " -o, --output <path> Write the host relocatable object to <path>\n"
<< " --unmanaged Use manual native memory management\n"
<< " --freestanding Emit the entry as __ny_entry() with no C main wrapper\n"
<< " --embed-context Retain AI annotations in x86_64 ELF/COFF or x86_64/arm64 Mach-O objects\n"
<< " --version Show the nilassembler version\n"
<< " -h, --help Show this help\n";
Expand All @@ -61,6 +64,7 @@ bool parse_command_line(int argc, char **argv, command_line &result,
bool options = true;
bool output_seen = false;
bool unmanaged_seen = false;
bool freestanding_seen = false;
bool embed_context_seen = false;
for (int index = 1; index < argc; ++index) {
const std::string argument = argv[index];
Expand Down Expand Up @@ -93,6 +97,15 @@ bool parse_command_line(int argc, char **argv, command_line &result,
result.unmanaged = true;
continue;
}
if (options && argument == "--freestanding") {
if (freestanding_seen) {
error = "the freestanding option was provided more than once";
return false;
}
freestanding_seen = true;
result.freestanding = true;
continue;
}
if (options && argument == "--embed-context") {
if (embed_context_seen) {
error = "the embed-context option was provided more than once";
Expand Down Expand Up @@ -132,7 +145,7 @@ bool parse_command_line(int argc, char **argv, command_line &result,

if (result.help || result.version) {
if (!result.input.empty() || output_seen || unmanaged_seen ||
embed_context_seen ||
freestanding_seen || embed_context_seen ||
(result.help && result.version)) {
error = "--help and --version must be used without input or output paths";
return false;
Expand Down Expand Up @@ -401,6 +414,7 @@ int run_assembler(const command_line &arguments) {
ny::NativeCodegen native;
native.setMemoryMode(arguments.unmanaged ? ny::MemoryMode::UNSAFE_MANUAL
: ny::MemoryMode::SAFE_GC);
native.setFreestandingEntry(arguments.freestanding);
native.setEmbedContext(arguments.embed_context);
if (!native.initialize()) {
std::cerr << "nilassembler: failed to initialize the LLVM target\n";
Expand Down
64 changes: 42 additions & 22 deletions nilcompiler/src/llvm_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,7 @@ struct NativeCodegen::Impl {

MemoryMode memory_mode = MemoryMode::UNSAFE_MANUAL;
bool embed_context = false;
bool freestanding_entry = false;
llvm::Function *current_function = nullptr;

// State matching generateModule usage
Expand Down Expand Up @@ -1368,6 +1369,10 @@ void NativeCodegen::setEmbedContext(bool enabled) {
impl_->embed_context = enabled;
}

void NativeCodegen::setFreestandingEntry(bool enabled) {
impl_->freestanding_entry = enabled;
}

bool NativeCodegen::initialize() {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
Expand Down Expand Up @@ -8818,32 +8823,47 @@ bool NativeCodegen::generateModule(const nil_module &mod) {

auto *i32_type = llvm::Type::getInt32Ty(ctx);
auto *opaque_pointer_type = llvm::PointerType::getUnqual(ctx);
const bool freestanding = impl_->freestanding_entry;
// Freestanding callers have no argument vector to pass and no C runtime to
// name the entry for them, so the entry takes none and is called
// `__ny_entry`. Everything after this point is the same sequence.
auto *platform_main_type =
llvm::FunctionType::get(i32_type, {i32_type, opaque_pointer_type}, false);
auto *platform_main = llvm::Function::Create(platform_main_type,
llvm::Function::ExternalLinkage,
"main", *impl_->module);
auto argument = platform_main->arg_begin();
llvm::Value *argc_value = &*argument++;
llvm::Value *argv_value = &*argument;
argc_value->setName("argc");
argv_value->setName("argv");

auto *entry = llvm::BasicBlock::Create(ctx, "entry", platform_main);
impl_->builder->SetInsertPoint(entry);
freestanding
? llvm::FunctionType::get(i32_type, {}, false)
: llvm::FunctionType::get(i32_type, {i32_type, opaque_pointer_type},
false);
auto *platform_main = llvm::Function::Create(
platform_main_type, llvm::Function::ExternalLinkage,
freestanding ? "__ny_entry" : "main", *impl_->module);
auto *zero = llvm::ConstantInt::get(i32_type, 0);
auto *one = llvm::ConstantInt::get(i32_type, 1);
auto *null_argv = llvm::ConstantPointerNull::get(opaque_pointer_type);
auto *has_program_name = impl_->builder->CreateAnd(
impl_->builder->CreateICmpSGT(argc_value, zero),
impl_->builder->CreateICmpNE(argv_value, null_argv));
auto *program_argc = impl_->builder->CreateSelect(
has_program_name, impl_->builder->CreateSub(argc_value, one), zero,
"ny.argc");
auto *argv_after_program_name = impl_->builder->CreateGEP(
opaque_pointer_type, argv_value, one, "ny.argv.after_program_name");
auto *program_argv = impl_->builder->CreateSelect(
has_program_name, argv_after_program_name, null_argv, "ny.argv");
llvm::Value *argc_value = zero;
llvm::Value *argv_value = null_argv;
if (!freestanding) {
auto argument = platform_main->arg_begin();
argc_value = &*argument++;
argv_value = &*argument;
argc_value->setName("argc");
argv_value->setName("argv");
}

auto *entry = llvm::BasicBlock::Create(ctx, "entry", platform_main);
impl_->builder->SetInsertPoint(entry);
llvm::Value *program_argc = zero;
llvm::Value *program_argv = null_argv;
if (!freestanding) {
auto *has_program_name = impl_->builder->CreateAnd(
impl_->builder->CreateICmpSGT(argc_value, zero),
impl_->builder->CreateICmpNE(argv_value, null_argv));
program_argc = impl_->builder->CreateSelect(
has_program_name, impl_->builder->CreateSub(argc_value, one), zero,
"ny.argc");
auto *argv_after_program_name = impl_->builder->CreateGEP(
opaque_pointer_type, argv_value, one, "ny.argv.after_program_name");
program_argv = impl_->builder->CreateSelect(
has_program_name, argv_after_program_name, null_argv, "ny.argv");
}

auto begin_context = impl_->module->getOrInsertFunction(
"nyrt_context_begin",
Expand Down
8 changes: 8 additions & 0 deletions nilcompiler/src/llvm_backend.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ class NativeCodegen {
void setMemoryMode(MemoryMode mode);
MemoryMode getMemoryMode() const;

// Emit the entry sequence under the documented freestanding symbol
// `__ny_entry`, with no arguments, instead of the hosted C `main(int,
// char **)`. A target without a C runtime then has one named entry to call
// rather than a wrapper it has to recognise and feed argc/argv. The
// sequence itself -- runtime ABI check, context begin, global
// initialisation, user main, context end -- is unchanged.
void setFreestandingEntry(bool enabled);

// Opt in to a retained, read-only context manifest on supported native
// targets. Annotation contents are embedded verbatim; the default is off.
void setEmbedContext(bool enabled);
Expand Down
45 changes: 36 additions & 9 deletions tests/tools/native_symbol_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def text(table_offset: int, index: int) -> str:
return data[table_offset + index:end].decode('utf-8', 'replace')

undefined: set[str] = set()
exported: set[str] = set()
for index in range(section_count):
header = section(index)
if text(names['offset'], header['name']) != '.symtab':
Expand All @@ -70,20 +71,28 @@ def text(table_offset: int, index: int) -> str:
raise SystemExit('symbol table has no entry size')
for position in range(header['offset'], header['offset'] + header['size'],
header['entry_size']):
name_index, _info, _other, shndx = struct.unpack_from('<IBBH', data, position)
if shndx != 0 or not name_index: # SHN_UNDEF with a name
name_index, info, _other, shndx = struct.unpack_from('<IBBH', data, position)
if not name_index:
continue
undefined.add(text(strings['offset'], name_index))
return undefined
name = text(strings['offset'], name_index)
if shndx == 0: # SHN_UNDEF with a name
undefined.add(name)
elif info >> 4 == 1: # STB_GLOBAL and defined here
exported.add(name)
return undefined, exported


def emit(compiler: Path, assembler: Path, root: Path, name: str, source: str) -> set[str]:
def emit(compiler: Path, assembler: Path, root: Path, name: str, source: str,
freestanding: bool = False):
path = root / f'{name}.ny'
path.write_text(source, newline='\n')
nil = root / f'{name}.nil'
obj = root / f'{name}.o'
assemble = [assembler, '--unmanaged']
if freestanding:
assemble.append('--freestanding')
for command in ([compiler, '--no-stdlib', '--no-bundle', '--unmanaged', '-o', nil, path],
[assembler, '--unmanaged', '-o', obj, nil]):
assemble + ['-o', obj, nil]):
result = subprocess.run(list(map(str, command)), stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=120)
assert result.returncode == 0, (command, result.returncode, result.stdout, result.stderr)
Expand All @@ -102,8 +111,8 @@ def main() -> int:
checks = 0
with tempfile.TemporaryDirectory(prefix='nil-symbol-surface-') as directory:
root = Path(directory)
plain = emit(args.compiler, args.assembler, root, 'plain',
'fn main() -> i64 {\n let total: i64 = 0;\n return total;\n}\n')
trivial = 'fn main() -> i64 {\n let total: i64 = 0;\n return total;\n}\n'
plain, plain_exports = emit(args.compiler, args.assembler, root, 'plain', trivial)
assert plain <= runtime_abi, (
'an object that uses no hosted facility imports only the native runtime ABI; '
f'unexpected: {sorted(plain - runtime_abi)}')
Expand All @@ -115,7 +124,7 @@ def main() -> int:

# The helper still has to exist when a program actually concatenates,
# or the first assertion would pass for the wrong reason.
concat = emit(args.compiler, args.assembler, root, 'concat',
concat, _ = emit(args.compiler, args.assembler, root, 'concat',
'fn main() -> i64 {\n let a: text = "left";\n'
' let b: text = "right";\n let joined: text = a + b;\n'
' return 0;\n}\n')
Expand All @@ -128,6 +137,24 @@ def main() -> int:
f'unexpected: {sorted(concat - runtime_abi - concat_imports)}')
checks += 1

# A hosted object is entered through the C runtime's main; a
# freestanding one is entered through a named symbol instead, because
# a target with no C runtime has nothing to call main for it and
# should not have to recognise a wrapper by its shape.
assert 'main' in plain_exports and '__ny_entry' not in plain_exports, (
f'a hosted object is entered through main; exports: {sorted(plain_exports)}')
checks += 1
free, free_exports = emit(args.compiler, args.assembler, root, 'free',
trivial, freestanding=True)
assert '__ny_entry' in free_exports and 'main' not in free_exports, (
'a freestanding object is entered through __ny_entry and defines no C main; '
f'exports: {sorted(free_exports)}')
checks += 1
assert free <= runtime_abi, (
'the freestanding entry must not widen the import surface; '
f'unexpected: {sorted(free - runtime_abi)}')
checks += 1

print(f'Native symbol surface: {checks} checks passed')
return 0

Expand Down
Loading