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
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,7 @@ include/daScript/misc/uric.h
include/daScript/misc/lexer_alloc_track.h
include/daScript/misc/env_cfg.h
include/daScript/misc/dep_recorder.h
include/daScript/misc/jobserver.h
src/misc/env_cfg.cpp
src/misc/das_common.cpp
src/misc/gc_node.cpp
Expand All @@ -1073,6 +1074,7 @@ src/misc/string_writer.cpp
src/misc/luau_float2string.cpp
src/misc/memory_model.cpp
src/misc/job_que.cpp
src/misc/jobserver.cpp
src/misc/handle_registry.cpp
src/misc/free_list.cpp
src/misc/alloc_tracker.cpp
Expand Down
2 changes: 1 addition & 1 deletion daslib/rst_comment.das
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ options indenting = 4
options no_aot = true
options strict_smart_pointers = true

module rst_comment shared private
module rst_comment shared private !inscope

//! Documentation comment extractor.
//!
Expand Down
3 changes: 2 additions & 1 deletion doc/reflections/das2rst.das
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,8 @@ def document_module_jobque(_root : string) {
group_by_regex("Internal invocations", mod, %regex~(new_job_invoke|new_thread_invoke|new_thread_loop_invoke|is_thread_loop_capture|new_debugger_thread|set_jobque_fork_pool|get_jobque_fork_pool|get_jobque_fork_skip_init|set_jobque_fork_skip_heap_reset|set_jobque_worker_spin|set_jobque_batch_dispatch|set_jobque_join_spin|set_jobque_team_mode|get_jobque_team_mode|set_jobque_thread_team_mode|get_jobque_thread_team_mode|set_current_thread_priority|get_current_processor|set_current_thread_affinity|set_jobque_threads_cap|set_jobque_threads|get_jobque_threads|set_jobque_affinity|get_jobque_affinity|set_jobque_worker_limit|get_jobque_worker_limit|set_jobque_team_rank_gate|get_jobque_team_rank_gate|set_jobque_team_prof|reset_jobque_team_prof|get_jobque_team_prof|get_jobque_team_prof_counts|get_jobque_team_prof_react|team_parallel_for_invoke|team_parallel_for_indexed_invoke|team_parallel_stages_invoke|flush_jobque_batch|jobque_try_run_one|_builtin_seq_box_publish|_builtin_seq_box_read)$%%),
group_by_regex("Construction", mod, %regex~(with_channel|with_stream|with_job_status|with_job_que|with_lock_box|with_seq_box|create_job_que|destroy_job_que)$%%),
group_by_regex("SeqBox operations", mod, %regex~(clear)$%%),
group_by_regex("Atomic", mod, %regex~(atomic32_create|atomic32_remove|with_atomic32|atomic64_create|atomic64_remove|with_atomic64|get|set|inc|dec)$%%)
group_by_regex("Atomic", mod, %regex~(atomic32_create|atomic32_remove|with_atomic32|atomic64_create|atomic64_remove|with_atomic64|get|set|inc|dec)$%%),
group_by_regex("Jobserver", mod, %regex~(with_jobserver|with_jobserver_token)$%%)
)
document("Jobs and threads", mod, "jobque.rst", groups)
}
Expand Down
3 changes: 3 additions & 0 deletions doc/source/reference/language/modules.rst
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,9 @@ Module can be made visible to all modules in the project via the ``!inscope`` mo

module Foo !inscope

A module that installs a comment reader has to be ``!inscope``: the reader reads the comments of
every module compiled after it, so those modules wait for it.

---------------
Builtin modules
---------------
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Opens the GNU make jobserver pool the build advertises in ``MAKEFLAGS`` and runs the block with it inside a job queue, as ``with_job_que`` does; at most ``limit`` tokens are held at once when ``limit`` is positive, the process's own free token included.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Runs the block while holding one token of the jobserver, waiting until one is free; the token goes back when the block ends.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The GNU make jobserver pool of a ``with_jobserver`` block.
40 changes: 40 additions & 0 deletions include/daScript/ast/ast_const_visitor.h
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,43 @@ namespace das {
virtual bool canVisitLooksLikeCall ( const ExprLooksLikeCall * expr ) { return true; }
virtual bool canVisitLabel ( const ExprLabel * ) { return true; }
virtual bool canVisitReader ( const ExprReader * ) { return true; }
virtual bool canVisitStructure ( const Structure * ) { return true; }
virtual bool canVisitGlobalVariable ( const Variable * ) { return true; }
virtual bool canVisitFunction ( const Function * ) { return true; }
virtual bool canVisitEnumeration ( const Enumeration * ) { return true; }
virtual bool canVisitStructureFieldInit ( const Structure * ) { return true; }
virtual bool canVisitArgumentInit ( const Function *, const Variable *, const Expression * ) { return true; }
virtual void preVisitProgram ( const Program * ) {}
virtual void visitProgram ( const Program * ) {}
virtual void preVisitModule ( const Module * ) {}
virtual void visitModule ( const Module * ) {}
virtual void preVisitProgramBody ( const Program *, const Module * ) {}
virtual void preVisitGlobalLetBody ( const Program * ) {}
virtual void visitGlobalLetBody ( const Program * ) {}
virtual void preVisitAlias ( const TypeDecl *, const string & ) {}
virtual void visitAlias ( const TypeDecl *, const string & ) {}
virtual void preVisit ( const Enumeration * ) {}
virtual void preVisitEnumerationValue ( const Enumeration *, const string &, const Expression *, bool ) {}
virtual void visitEnumerationValue ( const Enumeration *, const string &, const Expression *, bool ) {}
virtual void visit ( const Enumeration * ) {}
virtual void preVisit ( const Structure * ) {}
virtual void preVisitStructureAlias ( const Structure *, const string &, const TypeDecl * ) {}
virtual void visitStructureAlias ( const Structure *, const string &, const TypeDecl * ) {}
virtual void preVisitStructureField ( const Structure *, const Structure::FieldDeclaration &, bool ) {}
virtual void visitStructureField ( const Structure *, const Structure::FieldDeclaration &, bool ) {}
virtual void visit ( const Structure * ) {}
virtual void preVisit ( const Function * ) {}
virtual void preVisitArgument ( const Function *, const Variable *, bool ) {}
virtual void visitArgument ( const Function *, const Variable *, bool ) {}
virtual void preVisitArgumentInit ( const Function *, const Variable *, const Expression * ) {}
virtual void visitArgumentInit ( const Function *, const Variable *, const Expression * ) {}
virtual void preVisitFunctionBody ( const Function *, const Expression * ) {}
virtual void visitFunctionBody ( const Function *, const Expression * ) {}
virtual void visit ( const Function * ) {}
virtual void preVisitGlobalLet ( const Variable * ) {}
virtual void visitGlobalLet ( const Variable * ) {}
virtual void preVisitGlobalLetInit ( const Variable *, const Expression * ) {}
virtual void visitGlobalLetInit ( const Variable *, const Expression * ) {}
virtual void preVisit ( const TypeDecl * td ) {}
virtual void visit ( const TypeDecl * td ) {}
virtual void preVisitExpression ( const Expression * expr ) {}
Expand Down Expand Up @@ -224,6 +261,9 @@ namespace das {
#pragma clang diagnostic pop
#endif

DAS_API void constVisitFunction ( ConstVisitor & vis, const Function * fn );
DAS_API void constVisitProgram ( ConstVisitor & vis, const Program * prog, bool visitGenerics );

template <typename TT>
void ExprLikeCall<TT>::visit ( ConstVisitor & vis ) const {
vis.preVisit(static_cast<const TT *>(this));
Expand Down
36 changes: 36 additions & 0 deletions include/daScript/misc/jobserver.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#pragma once

#include "daScript/misc/platform.h"

#include <memory>

namespace das {

class JobserverState;

class DAS_API JobserverToken {
public:
JobserverToken ( JobserverToken && other ) noexcept;
JobserverToken & operator = ( JobserverToken && other ) noexcept;
~JobserverToken ();
private:
friend class Jobserver;
JobserverToken ( JobserverState * s, bool i, char b ) : state(s), implicitToken(i), byte(b) {}
JobserverState * state = nullptr;
bool implicitToken = false;
char byte = 0;
};

// src/misc/ARCHITECTURE_JOBSERVER.md#jobserver-client
class DAS_API Jobserver {
public:
explicit Jobserver ( int32_t limit = 0 );
Jobserver ( int32_t limit, const char * makeflags );
~Jobserver ();
Jobserver ( const Jobserver & ) = delete;
Jobserver & operator = ( const Jobserver & ) = delete;
JobserverToken acquire ();
private:
std::unique_ptr<JobserverState> state;
};
}
3 changes: 3 additions & 0 deletions include/daScript/simulate/aot_builtin_jobque.h
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,9 @@ namespace das {
DAS_API bool channelTryPop ( Channel * ch, const TBlock<void,void*> & blk, Context * context, LineInfoArg * at );
DAS_API bool channelPopWithTimeout ( Channel * ch, int32_t timeoutMs, const TBlock<void,void*> & blk, Context * context, LineInfoArg * at );
DAS_API int jobAppend ( JobStatus * ch, int size, Context * context, LineInfoArg * at );
class Jobserver;
DAS_API void withJobserver ( int32_t limit, const TBlock<void,Jobserver *> & blk, Context * context, LineInfoArg * lineinfo );
DAS_API void withJobserverToken ( Jobserver * jobserver, const TBlock<void> & blk, Context * context, LineInfoArg * lineinfo );
DAS_API void withChannel ( const TBlock<void,Channel *> & blk, Context * context, LineInfoArg * lineinfo );
DAS_API void withChannelEx ( int32_t count, const TBlock<void,Channel *> & blk, Context * context, LineInfoArg * lineinfo );
DAS_API Channel* channelCreate( Context * context, LineInfoArg * at);
Expand Down
4 changes: 2 additions & 2 deletions modules/dasLLVM/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ label silently absorbing new sub-steps breaks the contract the same way an untim
Under `--jit-split-modules` (`run_split_codegen` in `llvm_jit_run.das`) the same labels map
differently: **declare** reads ~zero (declaration moves inside the partition loop), **irgen**
covers partitioning plus every partition's declare/irgen/ctor work, **optimize** carries the
`jit_par_emit_run` pool wall - per-job passes AND object emission interleave on the workers -
`run_split_emit` wall - per-job passes AND object emission interleave on the jobque jobs -
plus the post-optimize verifies and the partition teardown, and **emit+link** is the
`link_from_objects` link plus the DLL reopen only. The finer steps print per the contract:
one `LLVM JIT time: job {obj} passes ... emit ...` line per partition (from the pool, under the
one `LLVM JIT time: job {obj} passes ... emit ...` line per partition (from `run_split_emit`, under the
same log option) and the `link ... (N objects)` line under emit+link. With the obj cache on
(`--jit-obj-cache`, default under split), cached partitions skip declare/irgen/optimize
entirely: the key fold and probe cost lands in **irgen**, the `obj cache - K/N partitions
Expand Down
143 changes: 115 additions & 28 deletions modules/dasLLVM/daslib/llvm_jit_run.das
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ require daslib/strings_boost
require daslib/defer

require daslib/fio
require daslib/jobque_boost
require daslib/safe_addr
require math
require daslib/option
require daslib/result
require jit
Expand All @@ -38,7 +41,7 @@ var LINK_WHOLE_LIB = false // when true, standalone exe links against the whole

// Read by tests-cpp/small/test_jit_emitter_pin.cpp: FNV-1a64 of the emitter sources
// (normalized to LF; file list in the test)
let LLVM_JIT_EMITTER_HASH : uint64 = 0xb6ad06f91d81b170ul
let LLVM_JIT_EMITTER_HASH : uint64 = 0x670ce6130f2bcf5eul

[arch(at = "../ARCHITECTURE_FAST_MATH.md#never-fast-math")]
def private apply_fast_math_to_module(m : LLVMOpaqueModule?) {
Expand Down Expand Up @@ -443,13 +446,109 @@ def private remove_split_link_files(objs : array<string>; output_path : string)
remove(split_link_rsp_path(output_path), err)
}

//! the LLVM handles travel as integers: a channel clones the job
//! into the worker's context, and a pointer field would be cloned
//! as a pointer to own
struct private SplitEmitJob {
mod : uint64
tm : uint64
pbo : uint64
pipeline : string
obj : string
}

struct private SplitEmitResult {
obj : string
error : string
passes_usec : int
emit_usec : int
}

def private run_split_emit_job(job : SplitEmitJob implicit) : SplitEmitResult {
var res = SplitEmitResult(obj = job.obj)
let mod = unsafe(reinterpret<LLVMOpaqueModule?>(job.mod))
let tm = unsafe(reinterpret<LLVMTargetMachineRef>(job.tm))
let pbo = unsafe(reinterpret<LLVMOpaquePassBuilderOptions?>(job.pbo))
let t0 = ref_time_ticks()
if (!empty(job.pipeline)) {
let err = LLVMRunPasses(mod, job.pipeline, tm, pbo)
if (err != null) {
let msg = LLVMGetErrorMessage(err)
res.error = "pass run failed: {msg}"
LLVMDisposeErrorMessage(msg)
return <- res
}
}
var verify_msg : string
let verify_action = LLVMVerifierFailureAction.LLVMReturnStatusAction
if (LLVMVerifyModule(mod, verify_action, safe_addr(verify_msg)) != 0) {
res.error = "post-optimize verify failed for {job.obj}: {verify_msg}"
}
LLVMDisposeMessage(verify_msg)
res.passes_usec = get_time_usec(t0)
return <- res if (!empty(res.error) || empty(job.obj))
let t1 = ref_time_ticks()
var emit_msg : string
let file_type = LLVMCodeGenFileType.LLVMObjectFile
if (LLVMTargetMachineEmitToFile(tm, mod, job.obj, file_type, safe_addr(emit_msg)) != 0) {
res.error = "emit failed for {job.obj}: {emit_msg}"
LLVMDisposeMessage(emit_msg)
}
res.emit_usec = get_time_usec(t1)
return <- res
}

def private report_split_emit(res : SplitEmitResult implicit; log_jit_time : bool) : bool {
if (!empty(res.error)) {
to_log(LOG_ERROR, "LLVM JIT: parallel emit: {res.error}\n")
return false
}
if (log_jit_time) {
let passes = double(res.passes_usec) / 1000000.0lf
let emit = double(res.emit_usec) / 1000000.0lf
to_log(LOG_INFO, "LLVM JIT time: job {res.obj} passes {passes} emit {emit}\n")
}
return true
}

//! optimize+emit each job on its own jobque job, at most `threads`
//! at once (<= 0: the job queue decides); results come back through
//! a channel; false on any failure
def private run_split_emit(jobs : array<SplitEmitJob>; threads : int; log_jit_time : bool) : bool {
return true if (empty(jobs))
var ok = true
if (threads == 1 || length(jobs) == 1) {
for (job in jobs) {
ok = report_split_emit(run_split_emit_job(job), log_jit_time) && ok
}
return ok
}
with_jobserver(max(threads, 0)) $(jobserver) {
with_channel(length(jobs)) $(done) {
for (job in jobs) {
new_job() @() {
with_jobserver_token(jobserver) {
done |> push_clone(run_split_emit_job(job))
}
done |> notify_and_release
}
}
done |> for_each_clone() $(res : SplitEmitResult#) {
ok = report_split_emit(res, log_jit_time) && ok
}
}
}
return ok
}

// nolint:STYLE014
// --jit-split-modules driver, three phases. A (serial das): partition `funcs` by owning das-module
// (program order), codegen each partition into its OWN (context, module, engine) emitter state -
// stashed in g_split_parts, the LAST left ambient for the shared install/finalize path. B: the
// jit_par_emit_run C++ pool optimizes + emits every partition on K threads (K=1 = serial bring-up;
// run_split_emit optimizes + emits every partition on K jobque jobs
// (K=1 = serial bring-up;
// one LLVMContext per job is LLVM's threading contract; the SAME LLVMRunPasses/EmitToFile calls as
// the monolith path, entry points resolved through dasbind - libDaScript never links LLVM). C
// the monolith path). C
// (serial das): post-optimize verify per partition, then dispose everything but the ambient state.
[macro_function, arch(at="../ARCHITECTURE_EXE.md#split-exe-lto")]
def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array<FunctionPtr>; // nolint:STYLE037,STYLE038 - the split orchestration is one linear pipeline (the cache probe adds its branches); the phases share the re-pointed g_* state
Expand Down Expand Up @@ -477,7 +576,7 @@ def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array<Fun
to_log(LOG_INFO, "LLVM JIT: split codegen (--jit-split-modules) - {length(order)} das-module partitions, {thrTag} threads -> one {target.gen_exe ? "exe" : "DLL"}\n")
// the dir must exist before the FIRST emit (a missing dir crashes LLVMTargetMachineEmitToFile)
mkdir_rec(dir_name(output_path))
jit_par_emit_begin()
var emit_jobs : array<SplitEmitJob>
g_split_parts |> reserve(length(order))
// empty pipeline = pool skips optimization (the LLVM_ENABLE_OPT_PASS / LLVM_DEBUG_EVERYTHING rail)
let pipeline = LLVM_ENABLE_OPT_PASS ? opt_pipeline_string(opt_level |> uint, size_level |> uint, sanitize) : ""
Expand Down Expand Up @@ -623,47 +722,35 @@ def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array<Fun
}
let hide_run = main_ok && !lto_run && has_solid_part()
if (main_ok) {
emit_jobs |> reserve(length(g_split_parts))
for (p in g_split_parts) {
// optimize only: LTO leaves as bitcode, a hide run emits in round two
jit_par_emit_add(p.mod, p.tm, p.pbo, pipeline, (lto_run || hide_run) ? "" : p.obj)
let obj = (lto_run || hide_run) ? "" : p.obj
emit_jobs |> push(SplitEmitJob(
mod = intptr(p.mod), tm = intptr(p.tm), pbo = intptr(p.pbo),
pipeline = pipeline, obj = obj))
}
}
let tIr = get_time_usec(phase_tm)
phase_tm = ref_time_ticks()
// phase B - per-job walls logged by the pool under log_compile_time; all partitions cached -> zero jobs, skip the pool (and the LLVM symbol resolution) outright
if (main_ok && !empty(g_split_parts)) {
let llvm_lib = __dasbind_get_library("llvm")
if (llvm_lib == null) {
reset_jit_globals_after_failure()
panic("LLVM JIT: split emit - can't resolve the LLVM library handle")
}
// resolve once + validate ALL entry points - a mismatched LLVM.dll names its missing symbol here
let lfn_names = ["LLVMRunPasses", "LLVMVerifyModule", "LLVMTargetMachineEmitToFile",
"LLVMGetErrorMessage", "LLVMDisposeErrorMessage", "LLVMDisposeMessage"]
var lfns : array<void?>
lfns |> reserve(length(lfn_names))
for (nm in lfn_names) {
let p = llvm_lib |> get_function_address(nm)
if (p == null) {
reset_jit_globals_after_failure()
panic("LLVM JIT: split emit - can't resolve {nm} in the LLVM library")
}
lfns |> push(p)
}
var ok = jit_par_emit_run(split_threads, int(LLVMCodeGenFileType.LLVMObjectFile),
lfns[0], lfns[1], lfns[2], lfns[3], lfns[4], lfns[5], log_jit_time)
var ok = run_split_emit(emit_jobs, split_threads, log_jit_time)
if (ok && hide_run) {
emit_jobs |> clear()
emit_jobs |> reserve(length(g_split_parts))
for (p in g_split_parts) {
if (p.solid) {
hide_solid_array_bases(p.mod, p.ctx)
}
if (dump_ir) {
dump_module_ir(dump_to, p.mod)
}
jit_par_emit_add(p.mod, p.tm, p.pbo, "", p.obj)
emit_jobs |> push(SplitEmitJob(
mod = intptr(p.mod), tm = intptr(p.tm), pbo = intptr(p.pbo),
pipeline = "", obj = p.obj))
}
ok = jit_par_emit_run(split_threads, int(LLVMCodeGenFileType.LLVMObjectFile),
lfns[0], lfns[1], lfns[2], lfns[3], lfns[4], lfns[5], log_jit_time)
ok = run_split_emit(emit_jobs, split_threads, log_jit_time)
}
if (!ok) {
reset_jit_globals_after_failure()
Expand Down
4 changes: 4 additions & 0 deletions modules/dasLLVM/daslib/llvm_macro.das
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ def public run_jit_codegen(prog : Program?; var ctx : Context?; var ok : bool?)
*ok = run_jit(prog, ctx).ok
}

//! a jobque or thread clone of this context dies while LLVM is
//! still in use - only the context itself shuts LLVM down
[finalize(late)]
def private shutdown_llvm {
let category = this_context().category
return if (category.job_clone || category.thread_clone)
LLVMShutdown()
}

Expand Down
Loading
Loading