Skip to content

Commit

Permalink
LLVM optimization: reduce complexity at call site
Browse files Browse the repository at this point in the history
@BlobCodes: I think it would be better to print the bug message in
`Crystal.once` instead of `__crystal_once` to reduce complexity at the
callsite. The previous unreachable method can then be used in the
inlined `__crystal_once` so LLVM also knows it doesn't have to re-run
the method.

It's now even safe because `Crystal.once` would panic if it failed; it
should already be impossible, but let's err on the safe side.
  • Loading branch information
ysbaddaden committed Jan 9, 2025
1 parent 7495855 commit 836a51b
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/crystal/once.cr
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@
{% else %}
once_exec(flag, initializer)
{% end %}

# safety check, and allows to safely call `#once_unreachable` in
# `__crystal_once`
unless flag.value.initialized?
System.print_error "BUG: failed to initialize constant or class variable\n"
LibC._exit(1)
end
end

private def self.once_exec(flag : OnceState*, initializer : Void*) : Nil
Expand All @@ -54,10 +61,10 @@
end
end

@[NoInline]
@[AlwaysInline]
def self.once_unreachable : NoReturn
System.print_error "BUG: failed to initialize constant or class variable\n"
LibC._exit(1)
x = uninitialized NoReturn
x
end
end

Expand All @@ -79,8 +86,9 @@

Crystal.once(flag, initializer)

# make LLVM assume that it musn't call `__crystal_once` anymore for this,
# also doubles as a safety check
# tell LLVM that it can optimize away repeated `__crystal_once` calls for
# this global (e.g. repeated access to constant in a single funtion);
# this is truly unreachable otherwise `Crystal.once` would have panicked
Crystal.once_unreachable unless flag.value.initialized?
end
{% else %}
Expand Down

0 comments on commit 836a51b

Please sign in to comment.