diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 16bb9b02..00000000 --- a/.appveyor.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Documentation: https://github.com/JuliaCI/Appveyor.jl -environment: - matrix: - - julia_version: 1.3 - - julia_version: nightly -platform: - - x86 - - x64 -matrix: - allow_failures: - - julia_version: nightly -branches: - only: - - master - - /release-.*/ -notifications: - - provider: Email - on_build_success: false - on_build_failure: false - on_build_status_changed: false -install: - - ps: iex ((new-object net.webclient).DownloadString("https://raw.githubusercontent.com/JuliaCI/Appveyor.jl/version-1/bin/install.ps1")) -build_script: - - echo "%JL_BUILD_SCRIPT%" - - C:\julia\bin\julia -e "%JL_BUILD_SCRIPT%" -test_script: - - echo "%JL_TEST_SCRIPT%" - - C:\julia\bin\julia -e "%JL_TEST_SCRIPT%" -on_success: - - echo "%JL_CODECOV_SCRIPT%" - - C:\julia\bin\julia -e "%JL_CODECOV_SCRIPT%" diff --git a/.github/workflows/CompatHelper.yml b/.github/workflows/CompatHelper.yml index 7c17290f..486adf2b 100644 --- a/.github/workflows/CompatHelper.yml +++ b/.github/workflows/CompatHelper.yml @@ -1,27 +1,16 @@ name: CompatHelper - on: schedule: - - cron: '0 1 * * *' - issues: - types: [opened, reopened] - + - cron: 0 0 * * 0 + workflow_dispatch: jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - julia-version: [1.3.1] - julia-arch: [x64] - os: [ubuntu-latest] + CompatHelper: + runs-on: ubuntu-latest steps: - - uses: julia-actions/setup-julia@latest - with: - version: ${{ matrix.julia-version }} - - name: Install dependencies - run: julia -e 'using Pkg; Pkg.add(Pkg.PackageSpec(name = "CompatHelper", url = "https://github.com/bcbi/CompatHelper.jl.git"))' - - name: CompatHelper.main + - name: Pkg.add("CompatHelper") + run: julia -e 'using Pkg; Pkg.add("CompatHelper")' + - name: CompatHelper.main() env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - JULIA_DEBUG: CompatHelper + COMPATHELPER_PRIV: ${{ secrets.DOCUMENTER_KEY }} run: julia -e 'using CompatHelper; CompatHelper.main()' diff --git a/.github/workflows/TagBot.yml b/.github/workflows/TagBot.yml index d77d3a0c..f49313b6 100644 --- a/.github/workflows/TagBot.yml +++ b/.github/workflows/TagBot.yml @@ -1,11 +1,15 @@ name: TagBot on: - schedule: - - cron: 0 * * * * + issue_comment: + types: + - created + workflow_dispatch: jobs: TagBot: + if: github.event_name == 'workflow_dispatch' || github.actor == 'JuliaTagBot' runs-on: ubuntu-latest steps: - uses: JuliaRegistries/TagBot@v1 with: token: ${{ secrets.GITHUB_TOKEN }} + ssh: ${{ secrets.DOCUMENTER_KEY }} diff --git a/.github/workflows/ci-integration-nightly.yml b/.github/workflows/ci-integration-nightly.yml new file mode 100644 index 00000000..10eba4bd --- /dev/null +++ b/.github/workflows/ci-integration-nightly.yml @@ -0,0 +1,38 @@ +name: CI (Integration nightly) +on: + push: + branches: + - '**' + paths-ignore: + - 'README.md' + pull_request: + branches: + - master + paths-ignore: + - 'README.md' +jobs: + test-integration-nightly: + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + version: + - 'nightly' + - 'pre' + os: + - ubuntu-latest + arch: + - x64 + group: + - Integration + steps: + - uses: actions/checkout@v6 + - uses: julia-actions/setup-julia@latest + with: + version: ${{ matrix.version }} + arch: ${{ matrix.arch }} + - uses: julia-actions/julia-buildpkg@latest + - uses: julia-actions/julia-runtest@latest + env: + GROUP: ${{ matrix.group }} diff --git a/.github/workflows/ci-integration.yml b/.github/workflows/ci-integration.yml new file mode 100644 index 00000000..2fa1e1d3 --- /dev/null +++ b/.github/workflows/ci-integration.yml @@ -0,0 +1,44 @@ +name: CI (Integration) +on: + push: + branches: + - '**' + paths-ignore: + - 'README.md' + pull_request: + branches: + - master + paths-ignore: + - 'README.md' +jobs: + test-integration: + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + version: + - '1.11' + - '1' + os: + - ubuntu-latest + - macOS-latest + - windows-latest + arch: + - x64 + group: + - Integration + steps: + - uses: actions/checkout@v6 + - uses: KyleMayes/install-llvm-action@v2 + with: + version: "17" + if: matrix.os == 'windows-latest' + - uses: julia-actions/setup-julia@latest + with: + version: ${{ matrix.version }} + arch: ${{ matrix.arch }} + - uses: julia-actions/julia-buildpkg@latest + - uses: julia-actions/julia-runtest@latest + env: + GROUP: ${{ matrix.group }} diff --git a/.github/workflows/ci-julia-nightly.yml b/.github/workflows/ci-julia-nightly.yml new file mode 100644 index 00000000..7ad5d2d6 --- /dev/null +++ b/.github/workflows/ci-julia-nightly.yml @@ -0,0 +1,38 @@ +name: CI (Julia nightly) +on: + push: + branches: + - '**' + paths-ignore: + - 'README.md' + pull_request: + branches: + - master + paths-ignore: + - 'README.md' +jobs: + test-julia-nightly: + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + version: + - 'nightly' + - 'pre' + os: + - ubuntu-latest + arch: + - x64 + group: + - Core + steps: + - uses: actions/checkout@v6 + - uses: julia-actions/setup-julia@latest + with: + version: ${{ matrix.version }} + arch: ${{ matrix.arch }} + - uses: julia-actions/julia-buildpkg@latest + - uses: julia-actions/julia-runtest@latest + env: + GROUP: ${{ matrix.group }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb97e170..78ecaba5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,15 @@ name: CI on: - - push - - pull_request + push: + branches: + - '**' + paths-ignore: + - 'README.md' + pull_request: + branches: + - master + paths-ignore: + - 'README.md' jobs: test: name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} @@ -10,19 +18,35 @@ jobs: fail-fast: false matrix: version: - - '1.3' - - 'nightly' + - '1.11' + - '1' os: - ubuntu-latest - # - macOS-latest + - macOS-latest - windows-latest arch: - x64 + group: + - Core + include: + - arch: x86 + version: '1' + os: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 + - uses: KyleMayes/install-llvm-action@v2 + with: + version: "17" + if: matrix.os == 'windows-latest' - uses: julia-actions/setup-julia@latest with: version: ${{ matrix.version }} arch: ${{ matrix.arch }} - uses: julia-actions/julia-buildpkg@latest - uses: julia-actions/julia-runtest@latest + env: + GROUP: ${{ matrix.group }} + - uses: julia-actions/julia-processcoverage@v1 + - uses: codecov/codecov-action@v2 + with: + files: lcov.info diff --git a/.github/workflows/cross-matrix.yml b/.github/workflows/cross-matrix.yml new file mode 100644 index 00000000..e606fe55 --- /dev/null +++ b/.github/workflows/cross-matrix.yml @@ -0,0 +1,82 @@ +name: Cross-compilation matrix +# What can be made from each kind of host, for each target (test/cross/matrix.jl, a table in the summary of each job), and whether what was made runs on a machine of its target (test/cross/run.jl). +# The hosts: Linux (x86-64 and AArch64), macOS (Apple Silicon) and Windows. The targets: Linux, macOS, Windows (MinGW-w64) and WebAssembly. A host makes what Julia's LLVM has the code generator for (its own architecture, +# and WebAssembly), and what it has the libraries for: those of Linux and Windows are fetched (Glibc_jll, Mingw_jll); the SDK of macOS is Xcode's, or one that is downloaded (phracker/MacOSX-SDKs) on a host that is not a Mac (Linux and Windows). +on: + push: + branches: + - cross-target + paths: + - 'src/**' + - 'ext/**' + - 'test/cross/**' + - '.github/workflows/cross-matrix.yml' + workflow_dispatch: +jobs: + build: + name: Make on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - ubuntu-24.04-arm + - macos-latest + - windows-latest + steps: + - uses: actions/checkout@v4 + - uses: julia-actions/setup-julia@v3 + with: + version: '1' + - uses: julia-actions/cache@v2 + - name: An SDK of macOS, for the programs for macOS that are made on Linux and on Windows + if: runner.os != 'macOS' + shell: bash + run: | + curl -fsSL -o sdk.tar.xz https://github.com/phracker/MacOSX-SDKs/releases/download/11.3/MacOSX11.3.sdk.tar.xz + if [ "$RUNNER_OS" = Windows ]; then + # (a program of C needs `usr/lib`, the stubs of `libSystem`: `System` has the frameworks, with symbolic links that Windows does not make; and the path has to be Windows's) + # (the links of `usr/lib` are needed, `libSystem.tbd` is one: MSYS makes real ones, which the runner's administrator may, with `nativestrict`, and not the copies that it does by default, which fail when the target is not yet extracted) + MSYS=winsymlinks:nativestrict tar xJf sdk.tar.xz --exclude='MacOSX11.3.sdk/System' + test -e MacOSX11.3.sdk/usr/lib/libSystem.tbd + echo "SDKROOT=$(pwd -W)/MacOSX11.3.sdk" >> "$GITHUB_ENV" + else + tar xJf sdk.tar.xz + echo "SDKROOT=$PWD/MacOSX11.3.sdk" >> "$GITHUB_ENV" + fi + rm sdk.tar.xz + - name: What is made + run: julia test/cross/matrix.jl made + - uses: actions/upload-artifact@v4 + if: always() + with: + name: made-${{ matrix.os }} + path: made + run: + name: Run on ${{ matrix.os }} + needs: build + # (what a host made is run wherever it was made: a build that failed on one host does not stop what the others made from being run) + if: ${{ !cancelled() }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - ubuntu-24.04-arm + - macos-latest + - macos-15-intel # (the last runner with an Intel CPU: `macos-13` is retired) + - windows-latest + steps: + - uses: actions/checkout@v4 + - uses: julia-actions/setup-julia@v3 + with: + version: '1' + - uses: actions/download-artifact@v4 + with: + pattern: made-* + path: made + merge-multiple: true + - name: Run what was made for this machine + run: julia test/cross/run.jl made diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f1693494..3e97882b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,28 +1,28 @@ name: Documentation - on: push: branches: - - 'master' - - 'release-' + - master tags: '*' + paths-ignore: + - '.github/workflows/cross-matrix.yml' pull_request: - + branches: + - master jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - julia-version: [1.3.1] - julia-arch: [x64] - os: [ubuntu-latest] + docs: + name: Build and deploy + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: read + statuses: write steps: - - uses: actions/checkout@v2 - - uses: julia-actions/setup-julia@latest + - uses: actions/checkout@v4 + - uses: julia-actions/setup-julia@v3 with: - version: ${{ matrix.julia-version }} - - name : Add current package # for unregistered package - run: julia -e 'using Pkg; Pkg.develop(PackageSpec(; path=pwd()));' + version: '1' + - uses: julia-actions/cache@v2 - name: Install dependencies run: julia --project=docs -e 'using Pkg; Pkg.instantiate()' - name: Build and deploy diff --git a/.gitignore b/.gitignore index 2ef6f28f..30c8380e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,14 +2,18 @@ *.jl.cov *.jl.mem .DS_Store -Manifest.toml -!helpers/Manifest.toml /dev/ /test/standalone -/test/Manifest.toml /test/test.* +Manifest.toml +*.wasm +*.dll +*.o +*.so test.o test.so test.bc /standalone/* +/docs/src/index.md +/docs/build/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index d735ad52..00000000 --- a/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -# Documentation: http://docs.travis-ci.com/user/languages/julia/ -language: julia -os: -- linux -- windows -julia: - - 1.3 - - nightly -matrix: - # extra linux test - include: - - os: linux - dist: bionic - - allow_failures: - - julia: nightly - fast_finish: true - -notifications: - email: false - -after_success: - - julia -e 'using Pkg; Pkg.add("Coverage"); using Coverage; Codecov.submit(process_folder())' - - julia -e 'using Pkg; Pkg.add("Coverage"); using Coverage; Coveralls.submit(process_folder())' diff --git a/LICENSE b/LICENSE index acf45480..b4e5ab82 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2019 Tom Short +Copyright (c) 2019-2022 Mason Protter, William Moses, Valentin Churavy, + McCoy R. Becker, Brenhin Keller, Julian Samaroo, + Tom Short, and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Project.toml b/Project.toml index 583ae233..c9c8ffcf 100644 --- a/Project.toml +++ b/Project.toml @@ -1,27 +1,35 @@ name = "StaticCompiler" uuid = "81625895-6c0f-48fc-b932-11a18313743c" -authors = ["Tom Short"] -version = "0.1.0" +authors = ["Tom Short and contributors"] +version = "0.8.0" + [deps] -Cassette = "7057c7e9-c182-5462-911a-8362d720325c" -DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" +Clang_jll = "0ee61d77-7f21-5576-8119-9fcc46b10100" +GPUCompiler = "61eb1bfa-7361-4325-ad38-22787b887f55" +LLD_jll = "d55e3150-da41-5e91-b323-ecfd1eec6109" LLVM = "929cbde3-209d-540e-8aea-75f648917ca0" Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb" -MacroTools = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" -TypedCodeUtils = "687fb87b-adea-59d5-9be9-82253b54685d" +StaticTools = "86c06d3c-3f03-46de-9781-57580aa96d0a" + +[weakdeps] +Glibc_jll = "452aa2e7-e185-58db-8ff9-d3c1fa4bc997" +Mingw_jll = "2d94bacf-4d71-535d-a47c-45e808015115" +Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" + +[extensions] +StaticCompilerGlibcExt = ["Glibc_jll", "Pkg"] +StaticCompilerMingwExt = ["Mingw_jll", "Pkg"] [compat] -DataStructures = "0.17" -Cassette = "0.3" -LLVM = "1.3" -TypedCodeUtils = "0.1" -MacroTools = "0.5" -julia = "1.2" +Clang_jll = "16, 18, 20, 23" +GPUCompiler = "2" +LLVM = "10" +StaticTools = "0.8, 0.9" +julia = "1.11" [extras] -Formatting = "59287772-0a20-5a39-b81b-1366585eb4c0" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Test", "Formatting"] +test = ["Test"] diff --git a/README.md b/README.md index 8b09b28b..6e4598bd 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,147 @@ # StaticCompiler -[![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://tshort.github.io/StaticCompiler.jl/dev) -[![Build Status](https://travis-ci.com/tshort/StaticCompiler.jl.svg?branch=master)](https://travis-ci.com/tshort/StaticCompiler.jl) -[![Build Status](https://ci.appveyor.com/api/projects/status/github/tshort/StaticCompiler.jl?svg=true)](https://ci.appveyor.com/project/tshort/StaticCompiler-jl) -[![Codecov](https://codecov.io/gh/tshort/StaticCompiler.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/tshort/StaticCompiler.jl) -[![Coveralls](https://coveralls.io/repos/github/tshort/StaticCompiler.jl/badge.svg?branch=master)](https://coveralls.io/github/tshort/StaticCompiler.jl?branch=master) +[![Docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://tshort.github.io/StaticRuntime.jl/dev/) +[![CI](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci.yml) +[![CI (Integration)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration.yml/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration.yml) +[![CI (Julia nightly)](https://github.com/tshort/StaticCompiler.jl/workflows/CI%20(Julia%20nightly)/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-julia-nightly.yml) +[![CI (Integration nightly)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration-nightly.yml/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration-nightly.yml) +[![Coverage](https://codecov.io/gh/tshort/StaticCompiler.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/tshort/StaticCompiler.jl) -This is an experimental package to compile Julia code to standalone libraries. A system image is not needed. It is also meant for cross compilation, so Julia code can be compiled for other targets, including WebAssembly and embedded targets. +This is an experimental package to compile Julia code to standalone libraries. A system image is not needed. ## Installation and Usage +Installation via the package manager: ```julia using Pkg -Pkg.add(PackageSpec( url = "https://github.com/tshort/StaticCompiler.jl", rev = "master")) +Pkg.add("StaticCompiler") ``` +or ```julia -using StaticCompiler +] add StaticCompiler ``` -**Documentation**: [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://tshort.github.io/StaticCompiler.jl/dev) -## Approach -This package uses the [LLVM package](https://github.com/maleadt/LLVM.jl) to generate code in the same fashion as [CUDAnative](https://github.com/JuliaGPU/CUDAnative.jl). +### Standalone compilation +StaticCompiler.jl provides the functions `compile_executable` and `compile_shlib` for compiling a Julia function to a native executable or shared library for use from outside of Julia: +```julia +julia> using StaticCompiler, StaticTools -Some of the key details of this approach are: +julia> hello() = println(c"Hello, world!") +hello (generic function with 1 method) -* **ccalls and cglobal** -- When Julia compiles code CUDAnative style, `ccall` and `cglobal` references get compiled to a direct pointer. `StaticCompiler` converts these to symbol references for later linking. For `ccall` with a tuple call to a symbol in a library, `Cassette` is used to convert that to just a symbol reference (no dynamic library loading). +julia> compile_executable(hello, (), "./") +"/Users/user/hello" -* **Global variables** -- A lot of code gets compiled with global variables, and these get compiled to a direct pointer. `StaticCompiler` includes a basic serialize/deserialize approach. Right now, this is fairly basic, and it takes shortcuts for some objects by swapping in wrong types. This can work because many times, the objects are not really used in the code. Finding the global variable can be a little tricky because the pointer is converted to a Julia object with `unsafe_pointer_to_objref`, and that segfaults for some addresses. How to best handle cases like that is still to be determined. +shell> ls -alh hello +-rwxrwxr-x. 1 user user 8.4K Oct 20 20:36 hello -* **Initialization** -- If libjulia is used, some init code needs to be run to set up garbage collection and other things. For this, a basic `blank.ji` file is used to feed `jl_init_with_image`. +shell> ./hello +Hello, world! +``` +This approach comes with substantial limitations compared to regular julia code, as you cannot rely on julia's runtime, `libjulia` (see, e.g., [StaticTools.jl](https://github.com/brenhinkeller/StaticTools.jl) or [StaticRuntime.jl](https://github.com/brenhinkeller/StaticRuntime.jl) for some ways to work around these limitations). -Long term, a better approach may be to use Julia's standard compilation techniques with "tree shaking" to generate a reduced system image (see [here](https://github.com/JuliaLang/julia/issues/33670)). +The low-level function `StaticCompiler.generate_obj` (not exported) generates object files, while `StaticCompiler.generate_ir` generates LLVM IR; either may be used for more control of compilation (e.g., to pass to your own compiler or linker). Which backend is used in the compilation process may be controlled with the `llvm_to_clang` keyword argument, though some targets only support the latter route (i.e. via LLVM IR). -## Example -The API still needs work, but here is the general approach right now: +### Cross-compilation + +For further control of the compilation process, many StaticCompiler functions (including `compile_executable` and `compile_shlib`) accept a `target` as a keyword argument, which allows cross-compilation (i.e., so that a program can be compiled on one system for use on another): ```julia -using StaticCompiler -m = irgen(cos, Tuple{Float64}) -write(m, "cos.bc") -write_object(m, "cos.o") +julia> using StaticCompiler, Glibc_jll, Pkg # (Glibc_jll and Pkg fetch the C library of a Linux target; Mingw_jll does the same for Windows) + +julia> target = StaticTarget("aarch64-unknown-linux-gnu"; retarget = true, toolchain = LLDToolchain(:gnu; sysroot = StaticCompiler.glibc_sysroot("aarch64-unknown-linux-gnu"))); + +julia> compile_executable(hello, (), "./", "hello_aarch64"; target) +``` + +The toolchain can be either a [`CCToolchain`](@ref) specifying a C compiler, or an [`LLDToolchain`](@ref) object specifying an LLVM `lld` to be used. +For an [`LLDToolchain`](@ref), supported target flavors include: +* `:gnu` for Linux +* `:darwin` for macOS +* `:mingw` for Windows +* `:wasm` for WebAssembly +Julia's LLVM contains the code generators for its own architecture and for WebAssembly only. For any other architecture, the IR can be made (`llvm_to_clang = true` / `generate_ir`), and `StaticTarget(...; llc = "/path/to/llc")` makes the object with an `llc` that has the desired backend for the same LLVM version. + +The [`cross-matrix.yml`](.github/workflows/cross-matrix.yml) CI workfoow tests cross-compilation to and from Linux (x86-64 and AArch64), macOS, and Windows. + +### Method overlays + +Sometimes, a julia function you want to statically compile will do things (such as throwing errors) that aren't supported natively by StaticCompiler. One tool provided for working around this is the `@device_override` macro which lets you swap out a method, but only inside of a StaticCompiler.jl compilation context. For example: + +```julia +julia> using Libdl, StaticCompiler + +julia> f(x) = g(x) + 1; + +julia> g(x) = 2x + +julia> @device_override g(x::Int) = x - 10 + +julia> f(1) # Gives the expected answer in regular julia +3 + +julia> dlopen(compile_shlib(f, (Int,), "./")) do lib + fptr = dlsym(lib, "f") + # Now use the compiled version where g(x) = 2x is replaced with g(x) = x - 10 + @ccall $fptr(1::Int)::Int + end +-8 +``` +Typically, errors should be overrided and replaced with `@print_and_throw`, which is StaticCompiler friendly, i.e. +we define overrides such as +``` julia +@device_override @noinline Base.Math.throw_complex_domainerror(f::Symbol, x) = + @print_and_throw c"This operation requires a complex input to return a complex result" ``` -`cos.o` should contain a function called `cos`. From there, you need to convert to link as needed with `libjulia`. +If for some reason, you wish to use a different method table (defined with `Base.Experimental.@MethodTable` and `Base.Experimental.@overlay`) than the default one provided by StaticCompiler.jl, you can provide it to `compile_executable` and `compile_shlib` via a keyword argument `method_table`. + +`StaticCompiler.empty_table` is available as a method table with no overrides at all, if you do not wish to use StaticCompiler's `@device_override`s.Your own overrides can be added to a table of your own, or to this one, with `Base.Experimental.@overlay(StaticCompiler.empty_table, ...)`. + +## Approach +This package uses [GPUCompiler](https://github.com/JuliaGPU/GPUCompiler.jl) to generate code. + +There are two main routes: +1. Compile all the way to object files (`.o`) with GPUCompiler, then link into to a single binary with an external compiler or linker; or +2. Compile only as far as LLVM IR (`.ll` files), then compile the rest of the way with an external LLVM compiler and linker (i.e., `clang` or `lld`). +The former is the default for native compilation on most targets, while the latter is the default for cross-compilation. + +An external compiler amay be specified with a [`CCToolchain`](@ref) passed to [`StaticTarget`](@ref), and must have the ability to compile LLVM IR (e.g., `clang`) if route (2) is intended (i.e., with `llvm_to_clang=true`). Analagously, an external linker may be specified with an [`LLDToolchain`](@ref) passed to [`StaticTarget`](@ref), along with its target flavor and flags. This approach provides the most control, especially for cross compilation, but for convenience one may also pass a compiler and its flags directly to `compile_executable`/`compile_shlib` as keyword arguments. + +## Limitations + +* GC-tracked allocations and global variables do *not* work with `compile_executable` or `compile_shlib` without some replacement for Julia's GC machinery. This has some interesting consequences, including that all functions _within_ the function you want to compile must generally either be inlined or return only native types (otherwise Julia would have to allocate a place to put the results, which will fail). +* Since error handling relies on libjulia, you can only throw errors from standalone-compiled (`compile_executable` / `compile_shlib`) code if an explicit overload has been defined for that particular error with `@device_override` (see [quirks.jl](src/quirks.jl)). +* Type instability. Type-unstable code cannot generally be statically compiled via this package. +* Extra experimental on Windows, though tested in CI. Should work in WSL on Windows 10+. + +## Guide for Package Authors + +To enable code to be statically compiled, consider the following: + +* Use type-stable code. + +* Use Tuples, NamedTuples, StaticArrays, and other types where appropriate. These allocate on the stack and don't use Julia's heap allocation. + +* Avoid Julia's internal allocations. That means don't bake in use of Arrays or Strings or Dicts. Types from StaticTools can help, like StaticStrings and MallocArrays. + +* If need be, manage memory manually, using `malloc` and `free` from StaticTools.jl. This works with `StaticTools.MallocString` and `StaticTools.MallocArray`, or use [Bumper.jl](https://github.com/MasonProtter/Bumper.jl). + +* Don't use global variables that need to be allocated and initialized. Instead of global variables, use context structures that have an initialization function. It is okay to use global Tuples or NamedTuples as the use of these should be baked into compiled code. + +* Use context variables to store program state, inputs, and outputs. Parameterize these typese as needed, so your code can handle normal types (Arrays) and static-friendly types (StaticArrays, MallocArrays, or StrideArrays). The SciML ecosystem does this well ([example](https://github.com/SciML/OrdinaryDiffEq.jl/blob/e7f045950615352ddfcb126d13d92afd2bad05e4/src/integrators/type.jl#L82)). Use of these context variables also enables allocations and initialization to be centralized, so these could be managed by the calling routines in Julia, Python, JavaScript, or other language. -See the `test` directory for more information and types of code that currently run. The most advanced example that works is a call to an ODE solution using modified code from [ODE.jl](https://github.com/JuliaDiffEq/ODE.jl). For information on compiling and linking to an executable, see [test/standalone-exe.jl](./test/standalone-exe.jl). +* Arguments and returned values from `compile_shlib` must be native objects such as `Int`, `Float64`, or `Ptr`. They cannot be things like `Tuple{Int, Int}` because that is not natively sized. Such objects need to be passed by reference instead of by value. -## Known limitations +* If your code needs an array as a workspace, instead of directly creating it, create it as a function argument (where it could default to a standard array creation). That code could be statically compiled if that function argument is changed to a MallocArray or another static-friendly alternative. -* It won't work for recursive code. Jameson's [codegen-norecursion](https://github.com/JuliaLang/julia/tree/jn/codegen-norecursion) should fix that when merged. +## Guide for Statically Compiling Code -* `cfunction` is not supported. +If you're trying to statically compile generic code, you may run into issues if that code uses features not supported by StaticCompiler. One option is to change the code you're calling using the tips above. If that is not easy, you may by able to compile it anyway. One option is to use method overlays to change what methods are called. -* Generic code that uses `jl_apply_generic` does not work. One strategy for this is to use Cassette to swap out known code that uses dynamic calls. Another approach is to write something like `jl_apply_generic` to implement dynamic calls. +[Cthulhu](https://github.com/JuliaDebug/Cthulhu.jl) is a great help in digging into code, finding type instabilities, and finding other sources of code that may break static compilation. -* The use of Cassette makes it more difficult for Julia to infer some things, and only type-stable code can be statically compiled with this approach. +## Foreign Function Interfacing -* It's only been tested on Linux and Windows. +Because Julia objects follow C memory layouts, compiled libraries should be usable from most languages that can interface with C. For example, results should be usable with Python's [CFFI](https://cffi.readthedocs.io/en/latest/) package. -Finally, this whole approach is young and likely brittle. Do not expect it to work for your code. +For WebAssembly, interface helpers are available at [WebAssemblyInterfaces](https://github.com/tshort/WebAssemblyInterfaces.jl), and users should also see [WebAssemblyCompiler](https://github.com/tshort/WebAssemblyCompiler.jl) for a package more focused on compilation of WebAssebly in general. diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 00000000..3ddada3f --- /dev/null +++ b/codecov.yml @@ -0,0 +1,12 @@ +comment: false + +coverage: + status: + project: + default: + threshold: 1% + target: 1% + patch: + default: + threshold: 1% + target: 1% diff --git a/docs/Project.toml b/docs/Project.toml index c96aeff2..d96ab258 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -1,3 +1,9 @@ [deps] Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" -#StaticCompiler = "81625895-6c0f-48fc-b932-11a18313743c" +StaticCompiler = "81625895-6c0f-48fc-b932-11a18313743c" + +[sources] +StaticCompiler = {path = ".."} + +[compat] +Documenter = "1" diff --git a/docs/make.jl b/docs/make.jl index a7bca12f..ece96ce4 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -1,23 +1,32 @@ using StaticCompiler using Documenter +DocMeta.setdocmeta!(StaticCompiler, :DocTestSetup, :(using StaticCompiler); recursive = true) + +# The home page is the README (so that the two are one text), with the links to files of the repository made absolute +readme = read(joinpath(@__DIR__, "..", "README.md"), String) +readme = replace(readme, r"\]\((?!https?://|#|mailto:)([^)\s]+)\)" => s"](https://github.com/tshort/StaticCompiler.jl/blob/master/\1)") +write(joinpath(@__DIR__, "src", "index.md"), readme) + makedocs(; - modules=[StaticCompiler], - authors="Tom Short", - repo="https://github.com/tshort/StaticCompiler.jl/blob/{commit}{path}#L{line}", - sitename="StaticCompiler.jl", - format=Documenter.HTML(; - prettyurls = prettyurls = get(ENV, "CI", nothing) == "true", - # canonical="https://tshort.github.io/StaticCompiler.jl", - # assets=String[], + modules = [StaticCompiler], + authors = "Tom Short and contributors", + repo = Documenter.Remotes.GitHub("tshort", "StaticCompiler.jl"), + sitename = "StaticCompiler.jl", + format = Documenter.HTML(; + prettyurls = get(ENV, "CI", nothing) == "true", + canonical = "https://tshort.github.io/StaticCompiler.jl", + edit_link = "master", ), - pages=[ + pages = [ "Home" => "index.md", - "Backend Syntax Reference" => "backend.md", - "Helpers Syntax Reference" => "helpers.md", + "API reference" => "api.md", ], + # (not every internal function has a docstring, and the README has links that are for GitHub) + warnonly = [:missing_docs, :cross_references, :autodocs_block], ) deploydocs(; - repo="github.com/tshort/StaticCompiler.jl", + repo = "github.com/tshort/StaticCompiler.jl", + devbranch = "master", ) diff --git a/docs/src/api.md b/docs/src/api.md new file mode 100644 index 00000000..5daa40fb --- /dev/null +++ b/docs/src/api.md @@ -0,0 +1,64 @@ +# API reference + +## Compiling + +```@docs +compile_executable +compile_shlib +``` + +## Inspecting the code + +```@docs +static_code_llvm +static_code_typed +static_llvm_module +static_code_native +``` + +## Method overlays + +```@docs +@device_override +@print_and_throw +``` + +## Targets and toolchains + +```@docs +StaticTarget +CCToolchain +LLDToolchain +``` + +## Building blocks + +The steps that `compile_executable` and `compile_shlib` are made of, for tools that need part of them. + +```@docs +StaticCompiler.generate_obj +StaticCompiler.retarget! +StaticCompiler.generate_ir +StaticCompiler.generate_executable +StaticCompiler.generate_shlib +StaticCompiler.generate_shlib_fptr +StaticCompiler.emit_object +StaticCompiler.link +StaticCompiler.output_name +StaticCompiler.add_builtins +StaticCompiler.add_builtins! +``` + +## Toolchains and sysroots + +```@docs +StaticCompiler.Toolchain +StaticCompiler.Machine +StaticCompiler.set_toolchain! +StaticCompiler.set_compiler! +StaticCompiler.set_runtime! +StaticCompiler.glibc_sysroot +StaticCompiler.glibc_version +StaticCompiler.macos_sdk +StaticCompiler.mingw_sysroot +``` diff --git a/docs/src/backend.md b/docs/src/backend.md deleted file mode 100644 index 523901c2..00000000 --- a/docs/src/backend.md +++ /dev/null @@ -1,10 +0,0 @@ -# Backend Syntax Reference -```@index -Modules = [StaticCompiler] -Pages = ["backend.md"] -``` - -```@autodocs -Modules = [StaticCompiler] -Pages = readdir("../src") -``` diff --git a/docs/src/helpers.md b/docs/src/helpers.md deleted file mode 100644 index c07d4df5..00000000 --- a/docs/src/helpers.md +++ /dev/null @@ -1,23 +0,0 @@ -# Helpers -Note that the helpers defined here are used in tests, and they are useful to test out code in the REPL. - -```julia -twox(x) = 2x -# run code in the REPL -@jlrun twox(3) -# compile to an executable in a `standalone` directory -exegen([ (twox, Tuple{Int}, 4) ]) -``` - -These are not meant to be a permanent part of the API. They are just for testing. - - -```@index -Modules = [StaticCompiler] -Pages = ["helpers.md"] -``` - -```@autodocs -Modules = [StaticCompiler] -Pages = readdir("../src/helpers") -``` diff --git a/docs/src/index.md b/docs/src/index.md index 760d5e6e..2e4d8f18 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -1,64 +1,130 @@ -```@meta -CurrentModule = StaticCompiler -``` - # StaticCompiler -[![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://tshort.github.io/StaticCompiler.jl/dev) -[![Build Status](https://travis-ci.com/tshort/StaticCompiler.jl.svg?branch=master)](https://travis-ci.com/tshort/StaticCompiler.jl) -[![Build Status](https://ci.appveyor.com/api/projects/status/github/tshort/StaticCompiler.jl?svg=true)](https://ci.appveyor.com/project/tshort/StaticCompiler-jl) -[![Codecov](https://codecov.io/gh/tshort/StaticCompiler.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/tshort/StaticCompiler.jl) -[![Coveralls](https://coveralls.io/repos/github/tshort/StaticCompiler.jl/badge.svg?branch=master)](https://coveralls.io/github/tshort/StaticCompiler.jl?branch=master) +[![CI](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci.yml) +[![CI (Integration)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration.yml/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration.yml) +[![CI (Julia nightly)](https://github.com/tshort/StaticCompiler.jl/workflows/CI%20(Julia%20nightly)/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-julia-nightly.yml) +[![CI (Integration nightly)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration-nightly.yml/badge.svg)](https://github.com/tshort/StaticCompiler.jl/actions/workflows/ci-integration-nightly.yml) +[![Coverage](https://codecov.io/gh/tshort/StaticCompiler.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/tshort/StaticCompiler.jl) -This is an experimental package to compile Julia code to standalone libraries. A system image is not needed. It is also meant for cross compilation, so Julia code can be compiled for other targets, including WebAssembly and embedded targets. +This is an experimental package to compile Julia code to standalone libraries. A system image is not needed. ## Installation and Usage +Installation is the same as any other registered Julia package ```julia using Pkg -Pkg.add(PackageSpec( url = "https://github.com/tshort/StaticCompiler.jl", rev = "master")) +Pkg.add("StaticCompiler") ``` + +## Approach + +This package uses the [GPUCompiler package](https://github.com/JuliaGPU/GPUCompiler.jl) to generate code. + +### Standalone compilation +StaticCompiler.jl provides the functions `compile_executable` and `compile_shlib` for compiling a Julia function to a native executable or shared library for use from outside of Julia: ```julia -using StaticCompiler +julia> using StaticCompiler, StaticTools + +julia> hello() = println(c"Hello, world!") +hello (generic function with 1 method) + +julia> compile_executable(hello, (), "./") +"/Users/user/hello" + +shell> ls -alh hello +-rwxrwxr-x. 1 user user 8.4K Oct 20 20:36 hello + +shell> ./hello +Hello, world! ``` -**Documentation**: [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://tshort.github.io/StaticCompiler.jl/dev) +This approach comes with substantial limitations compared to regular julia code, as you cannot rely on julia's runtime, `libjulia` (see, e.g., [StaticTools.jl](https://github.com/brenhinkeller/StaticTools.jl) for some ways to work around these limitations). -## Approach -This package uses the [LLVM package](https://github.com/maleadt/LLVM.jl) to generate code in the same fashion as [CUDAnative](https://github.com/JuliaGPU/CUDAnative.jl). +The low-level function `StaticCompiler.generate_obj` (not exported) generates object files. This can be used for more control of compilation. This can be used for example, to cross-compile to other targets. + +### Method overlays + +Sometimes, a julia function you want to statically compile will do things (such as throwing errors) that aren't supported natively by StaticCompiler. One tool provided for working around this is the `@device_override` macro which lets you swap out a method, but only inside of a StaticCompiler.jl compilation context. For example: -Some of the key details of this approach are: +```julia +julia> using Libdl, StaticCompiler + +julia> f(x) = g(x) + 1; -* **ccalls and cglobal** -- When Julia compiles code CUDAnative style, `ccall` and `cglobal` references get compiled to a direct pointer. `StaticCompiler` converts these to symbol references for later linking. For `ccall` with a tuple call to a symbol in a library, `Cassette` is used to convert that to just a symbol reference (no dynamic library loading). +julia> g(x) = 2x -* **Global variables** -- A lot of code gets compiled with global variables, and these get compiled to a direct pointer. `StaticCompiler` includes a basic serialize/deserialize approach. Right now, this is fairly basic, and it takes shortcuts for some objects by swapping in wrong types. This can work because many times, the objects are not really used in the code. Finding the global variable can be a little tricky because the pointer is converted to a Julia object with `unsafe_pointer_to_objref`, and that segfaults for some addresses. How to best handle cases like that is still to be determined. +julia> @device_override g(x::Int) = x - 10 -* **Initialization** -- If libjulia is used, some init code needs to be run to set up garbage collection and other things. For this, a basic `blank.ji` file is used to feed `jl_init_with_image`. +julia> f(1) # Gives the expected answer in regular julia +3 -Long term, a better approach may be to use Julia's standard compilation techniques with "tree shaking" to generate a reduced system image (see [here](https://github.com/JuliaLang/julia/issues/33670)). +julia> dlopen(compile_shlib(f, (Int,), "./")) do lib + fptr = dlsym(lib, "f") + # Now use the compiled version where g(x) = 2x is replaced with g(x) = x - 10 + @ccall $fptr(1::Int)::Int + end +-8 +``` +Typically, errors should be overrided and replaced with `@print_and_throw`, which is StaticCompiler friendly, i.e. +we define overrides such as +``` julia +@device_override @noinline Base.Math.throw_complex_domainerror(f::Symbol, x) = + @print_and_throw c"This operation requires a complex input to return a complex result" +``` -## Example -The API still needs work, but here is the general approach right now: +If for some reason, you wish to use a different method table (defined with `Base.Experimental.@MethodTable` and `Base.Experimental.@overlay`) than the default one provided by StaticCompiler.jl, you can provide it to `compile_executable` and `compile_shlib` via a keyword argument `method_table`. + +`StaticCompiler.empty_table` is available as a method table with no overrides at all, if you do not wish to use StaticCompiler's `@device_override`s.Your own overrides can be added to a table of your own, or to this one, with `Base.Experimental.@overlay(StaticCompiler.empty_table, ...)`. + +### Cross-compilation + +`compile_executable` and `compile_shlib` accept a `target`, so a program can be made on one system for another: ```julia -using StaticCompiler -m = irgen(cos, Tuple{Float64}) -write(m, "cos.bc") -write_object(m, "cos.o") +julia> using StaticCompiler, Glibc_jll, Pkg # (Glibc_jll and Pkg fetch the C library of a Linux target; Mingw_jll does the same for Windows) + +julia> target = StaticTarget("aarch64-unknown-linux-gnu"; retarget = true, toolchain = LLDToolchain(:gnu; sysroot = StaticCompiler.glibc_sysroot("aarch64-unknown-linux-gnu"))); + +julia> compile_executable(hello, (), "./", "hello_aarch64"; target) ``` -`cos.o` should contain a function called `cos`. From there, you need to convert to link as needed with `libjulia`. +The toolchain can be either a [`CCToolchain`](https://github.com/tshort/StaticCompiler.jl/blob/master/@ref) specifying a C compiler, or an [`LLDToolchain`](https://github.com/tshort/StaticCompiler.jl/blob/master/@ref) object specifying an LLVM `lld` to be used (flavors include `:gnu` for Linux, `:darwin` for macOS, `:mingw` for Windows, and `:wasm` for WebAssembly). Julia's LLVM contains the code generators for its own architecture and for WebAssembly only. For any other architecture, the IR can be made (`emit_llvm_only = true`), and `StaticTarget(...; llc = "/path/to/llc")` makes the object with an `llc` that has the desired backend for the same LLVM version. + +The [`cross-matrix.yml`](https://github.com/tshort/StaticCompiler.jl/blob/master/.github/workflows/cross-matrix.yml) CI workfoow tests cross-compilation to and from Linux (x86-64 and AArch64), macOS, and Windows. + +## Limitations + +* GC-tracked allocations and global variables do *not* work with `compile_executable` or `compile_shlib`. This has some interesting consequences, including that all functions _within_ the function you want to compile must either be inlined or return only native types (otherwise Julia would have to allocate a place to put the results, which will fail). +* Since error handling relies on libjulia, you can only throw errors from standalone-compiled (`compile_executable` / `compile_shlib`) code if an explicit overload has been defined for that particular error with `@device_override` (see [quirks.jl](https://github.com/tshort/StaticCompiler.jl/blob/master/src/quirks.jl)). +* Type instability. Type unstable code cannot currently be statically compiled via this package. +* Extra experimental on Windows (PRs welcome if you encounter issues). Should work in WSL on Windows 10+. + +## Guide for Package Authors + +To enable code to be statically compiled, consider the following: + +* Use type-stable code. + +* Use Tuples, NamedTuples, StaticArrays, and other types where appropriate. These allocate on the stack and don't use Julia's heap allocation. + +* Avoid Julia's internal allocations. That means don't bake in use of Arrays or Strings or Dicts. Types from StaticTools can help, like StaticStrings and MallocArrays. + +* If need be, manage memory manually, using `malloc` and `free` from StaticTools.jl. This works with `StaticTools.MallocString` and `StaticTools.MallocArray`, or use [Bumper.jl](https://github.com/MasonProtter/Bumper.jl). + +* Don't use global variables that need to be allocated and initialized. Instead of global variables, use context structures that have an initialization function. It is okay to use global Tuples or NamedTuples as the use of these should be baked into compiled code. + +* Use context variables to store program state, inputs, and outputs. Parameterize these typese as needed, so your code can handle normal types (Arrays) and static-friendly types (StaticArrays, MallocArrays, or StrideArrays). The SciML ecosystem does this well ([example](https://github.com/SciML/OrdinaryDiffEq.jl/blob/e7f045950615352ddfcb126d13d92afd2bad05e4/src/integrators/type.jl#L82)). Use of these context variables also enables allocations and initialization to be centralized, so these could be managed by the calling routines in Julia, Python, JavaScript, or other language. -See the `test` directory for more information and types of code that currently run. The most advanced example that works is a call to an ODE solution using modified code from [ODE.jl](https://github.com/JuliaDiffEq/ODE.jl). For information on compiling and linking to an executable, see [test/standalone-exe.jl](https://github.com/tshort/StaticCompiler.jl/blob/master/test/standalone-exe.jl). +* Arguments and returned values from `compile_shlib` must be native objects such as `Int`, `Float64`, or `Ptr`. They cannot be things like `Tuple{Int, Int}` because that is not natively sized. Such objects need to be passed by reference instead of by value. -## Known limitations +* If your code needs an array as a workspace, instead of directly creating it, create it as a function argument (where it could default to a standard array creation). That code could be statically compiled if that function argument is changed to a MallocArray or another static-friendly alternative. -* It won't work for recursive code. Jameson's [codegen-norecursion](https://github.com/JuliaLang/julia/tree/jn/codegen-norecursion) should fix that when merged. +## Guide for Statically Compiling Code -* `cfunction` is not supported. +If you're trying to statically compile generic code, you may run into issues if that code uses features not supported by StaticCompiler. One option is to change the code you're calling using the tips above. If that is not easy, you may by able to compile it anyway. One option is to use method overlays to change what methods are called. -* Generic code that uses `jl_apply_generic` does not work. One strategy for this is to use Cassette to swap out known code that uses dynamic calls. Another approach is to write something like `jl_apply_generic` to implement dynamic calls. +[Cthulhu](https://github.com/JuliaDebug/Cthulhu.jl) is a great help in digging into code, finding type instabilities, and finding other sources of code that may break static compilation. -* The use of Cassette makes it more difficult for Julia to infer some things, and only type-stable code can be statically compiled with this approach. +## Foreign Function Interfacing -* It's only been tested on Linux and Windows. +Because Julia objects follow C memory layouts, compiled libraries should be usable from most languages that can interface with C. For example, results should be usable with Python's [CFFI](https://cffi.readthedocs.io/en/latest/) package. -Finally, this whole approach is young and likely brittle. Do not expect it to work for your code. +For WebAssembly, interface helpers are available at [WebAssemblyInterfaces](https://github.com/tshort/WebAssemblyInterfaces.jl), and users should also see [WebAssemblyCompiler](https://github.com/tshort/WebAssemblyCompiler.jl) for a package more focused on compilation of WebAssebly in general. diff --git a/ext/StaticCompilerGlibcExt.jl b/ext/StaticCompilerGlibcExt.jl new file mode 100644 index 00000000..bfbdf6bd --- /dev/null +++ b/ext/StaticCompilerGlibcExt.jl @@ -0,0 +1,26 @@ +# The C library of a Linux target, for linking by `LLDToolchain(:gnu; sysroot)`: the artifact of `Glibc_jll` for the platform of the target, fetched for any host. +module StaticCompilerGlibcExt + +using StaticCompiler: StaticCompiler, StaticTarget +using Glibc_jll: Glibc_jll +using Pkg: Pkg +using Base.BinaryPlatforms: Platform, arch + +function StaticCompiler.glibc_sysroot(platform::Platform) + platform = Platform(arch(platform), "linux"; libc = "glibc") # (the one that `Glibc_jll` has: of the architecture) + toml = joinpath(dirname(dirname(pathof(Glibc_jll))), "Artifacts.toml") + meta = Pkg.Artifacts.artifact_meta("Glibc", toml; platform) + meta === nothing && throw(ArgumentError("`Glibc_jll` has no artifact for $platform")) + Pkg.Artifacts.ensure_artifact_installed("Glibc", meta, toml; platform) + return Pkg.Artifacts.artifact_path(Base.SHA1(meta["git-tree-sha1"])) +end + +function StaticCompiler.glibc_sysroot(triple::AbstractString) + platform = tryparse(Platform, triple) + platform === nothing && throw(ArgumentError("`$triple` is not a triple of a platform that has a glibc")) + return StaticCompiler.glibc_sysroot(platform) +end + +StaticCompiler.glibc_sysroot(target::StaticTarget) = StaticCompiler.glibc_sysroot(StaticCompiler.target_triple(target)) + +end diff --git a/ext/StaticCompilerMingwExt.jl b/ext/StaticCompilerMingwExt.jl new file mode 100644 index 00000000..fa2ff785 --- /dev/null +++ b/ext/StaticCompilerMingwExt.jl @@ -0,0 +1,28 @@ +# The libraries of MinGW-w64 for a Windows target, for linking by `LLDToolchain(:mingw; sysroot)`: the artifact of `Mingw_jll` for the architecture of the target, fetched for any host (it is the start files and the +# libraries of the C runtime and of Windows, which are data: the artifact is listed for Windows platforms, and is the same wherever it is fetched). +module StaticCompilerMingwExt + +using StaticCompiler: StaticCompiler, StaticTarget +using Mingw_jll: Mingw_jll +using Pkg: Pkg +using Base.BinaryPlatforms: Platform, arch + +function StaticCompiler.mingw_sysroot(platform::Platform) + platform = Platform(arch(platform), "windows") # (the one that `Mingw_jll` has: of the architecture) + toml = joinpath(dirname(dirname(pathof(Mingw_jll))), "Artifacts.toml") + meta = Pkg.Artifacts.artifact_meta("Mingw", toml; platform) + meta === nothing && throw(ArgumentError("`Mingw_jll` has no artifact for $platform (it has x86_64 and i686)")) + Pkg.Artifacts.ensure_artifact_installed("Mingw", meta, toml; platform) + return Pkg.Artifacts.artifact_path(Base.SHA1(meta["git-tree-sha1"])) +end + +function StaticCompiler.mingw_sysroot(triple::AbstractString) + # (`Platform` parses `x86_64-w64-mingw32`, and not `x86_64-w64-windows-gnu`, the name that LLVM has for it: the architecture is what it is for) + occursin(r"mingw|windows", triple) || throw(ArgumentError("`$triple` is not a triple of a platform of Windows")) + arch = String(first(split(triple, '-'))) # (`Platform` takes a `String`) + return StaticCompiler.mingw_sysroot(Platform(arch == "amd64" ? "x86_64" : arch, "windows")) +end + +StaticCompiler.mingw_sysroot(target::StaticTarget) = StaticCompiler.mingw_sysroot(StaticCompiler.target_triple(target)) + +end diff --git a/src/StaticCompiler.jl b/src/StaticCompiler.jl index 5f16b621..b6d02f58 100644 --- a/src/StaticCompiler.jl +++ b/src/StaticCompiler.jl @@ -1,28 +1,744 @@ module StaticCompiler +using GPUCompiler: GPUCompiler +using LLVM, LLVM.IR, LLVM.Passes +using Libdl: Libdl +using Clang_jll: Clang_jll +using LLD_jll: lld +using StaticTools +using StaticTools: @symbolcall, @c_str, println +using Base: BinaryPlatforms.Platform, BinaryPlatforms.HostPlatform +using Base: BinaryPlatforms.arch, BinaryPlatforms.os_str, BinaryPlatforms.libc_str +export compile_shlib, compile_executable +export static_code_llvm, static_code_typed, static_code_native, static_llvm_module, compiled_names +export @device_override, @print_and_throw +export StaticTarget, CCToolchain, LLDToolchain -export irgen, write_object, @extern +abstract type Toolchain end # (the field of `StaticTarget`; see toolchain.jl) -import Libdl +include("quirks.jl") +include("target.jl") +include("toolchain.jl") +include("builtins.jl") +include("llvm.jl") -using LLVM -using LLVM.Interop -using TypedCodeUtils -import TypedCodeUtils: reflect, lookthrough, canreflect, - DefaultConsumer, Reflection, Callsite, - identify_invoke, identify_call, identify_foreigncall, - process_invoke, process_call -using MacroTools -using DataStructures: MultiDict +fix_name(f::Function) = fix_name(String(nameof(f))) +fix_name(s) = String(GPUCompiler.safe_name(s)) +include("mangling.jl") -include("serialize.jl") -include("utils.jl") -include("ccalls.jl") -include("globals.jl") -include("overdub.jl") -include("irgen.jl") -include("extern.jl") +# Check that `f(types...)` is compilable to a native entry point, returning the tuple type of `types` +function check_signature(f, types; target::StaticTarget=StaticTarget(), kwargs...) + tt = Base.to_tuple_type(types) + isconcretetype(tt) || error("input type signature `$types` is not concrete") -include("helpers/helpers.jl") + rt = last(only(static_code_typed(f, tt; target, kwargs...))) + isconcretetype(rt) || error("`$f$types` did not infer to a concrete type. Got `$rt`") + nativetype = isprimitivetype(rt) || isa(rt, Ptr) + nativetype || @warn "Return type `$rt` of `$f$types` does not appear to be a native type. Consider returning only a single value of a native machine type (i.e., a single float, int/uint, bool, or pointer). \n\nIgnoring this warning may result in Undefined Behavior!" + return tt +end + +""" +```julia +compile_executable(f::Function, tt=(), args...; also_expose::Vector=Tuple[], kwargs...) +compile_executable(funcs::Union{Array,Tuple}, [path::String=pwd()], [filename::String=fix_name(first(first(funcs)))]; + target = StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle = true, # Whether or not function names should be exactly as they are in Julia + llvm_to_clang = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + main_prologue = nothing, # optional hook: adds code that runs first in `main`, into which `f` will then be wrapped + method_table = StaticCompiler.method_table, + kwargs... +) + +``` +Attempt to compile a standalone executable that runs function `f` with a type signature given by the tuple of `types`. +If there are extra methods you would like to expose in the produced binary for any reason, +you can provide them as a vector of tuples of functions and types, i.e. `[(f1, types1), (f2, types2), ...]` + +There are two hooks that may modify the LLVM code in-place, which differ in when they run: +* `llvm_postprocess(mod)` is called on the `LLVM.Module` of each function as soon as it is generated, before its pointers and runtime calls are located, it is retargeted, and the modules are combined. +* `llvm_finalize(mod)` is called once, on the final combined module when it is complete: after the modules are combined and the `main` (see `main_prologue`) and the builtins of the toolchain are added, and just before the code is emitted. + +`main_prologue(builder, mod)` adds code that runs first in the `main` of the program (the object then has its own `main`, also where a C compiler links it). `llvm_finalize` and `main_prologue` work the same for any target +and any toolchain (the host's or another, linked by a C compiler driver or by `lld`). Objects to link with the program can be given in `cflags`. + +Other keywords will be forwarded to `static_job`. This may include `params`, which if given, +is a `GPUCompiler.AbstractCompilerParams` object (default `StaticCompilerParams()`) which +is passed to `GPUCompiler.CompilerConfig`. + +### Examples +```julia +julia> using StaticCompiler + +julia> function puts(s::Ptr{UInt8}) # Can't use Base.println because it allocates. + # Note, this `llvmcall` requires Julia 1.8+ + Base.llvmcall((\"\"\" + ; External declaration of the puts function + declare i32 @puts(i8* nocapture) nounwind + + define i32 @main(i8*) { + entry: + %call = call i32 (i8*) @puts(i8* %0) + ret i32 0 + } + \"\"\", "main"), Int32, Tuple{Ptr{UInt8}}, s) + end +puts (generic function with 1 method) + +julia> function print_args(argc::Int, argv::Ptr{Ptr{UInt8}}) + for i=1:argc + # Get pointer + p = unsafe_load(argv, i) + # Print string at pointer location (which fortunately already exists isn't tracked by the GC) + puts(p) + end + return 0 + end + +julia> compile_executable(print_args, (Int, Ptr{Ptr{UInt8}})) +""/Users/user/print_args"" + +shell> ./print_args 1 2 3 4 Five +./print_args +1 +2 +3 +4 +Five +``` +```julia +julia> using StaticTools # So you don't have to define `puts` and friends every time + +julia> hello() = println(c"Hello, world!") # c"..." makes a stack-allocated StaticString + +julia> compile_executable(hello) +"/Users/cbkeller/hello" + +shell> ls -alh hello +-rwxr-xr-x 1 user staff 33K Mar 20 21:11 hello + +shell> ./hello +Hello, world! +``` +""" +compile_executable(f::Function, tt=(), args...; also_expose::Vector=Tuple[], kwargs...) = compile_executable(vcat([(f, tt)], also_expose), args...; kwargs...) +function compile_executable(funcs::Union{Array,Tuple}, path::String=pwd(), filename::String=fix_name(first(first(funcs))); + target::StaticTarget=StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + main_prologue = nothing, # optional hook: adds code that runs first in `main`, into which `f` will then be wrapped + kwargs... + ) + + (f, types) = first(funcs) + tt = check_signature(f, types; target, kwargs...) + isexecutableargtype = tt == Tuple{} || tt == Tuple{Int, Ptr{Ptr{UInt8}}} + isexecutableargtype || @warn "input type signature $types should be either `()` or `(Int, Ptr{Ptr{UInt8}})` for standard executables" + + generate_executable(funcs, path, filename; target, demangle, cc, cflags, llvm_to_clang, llvm_postprocess, llvm_finalize, main_prologue, kwargs...) +end + +""" +```julia +compile_shlib(f::Function, types::Tuple, [path::String=pwd()], [filename=fix_name(f)]; kwargs...) +compile_shlib(funcs::Union{Array,Tuple}, [path::String=pwd()], [filename::String="lib"]; + target::StaticTarget=StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + kwargs... +) +``` +Attempt to compile a standalone `.dylib`/`.so` shared library, given a function and its argument types, +or a vector of tuples thereof (i.e., `[(f1, types1), (f2, types2), ...]`). + +Arguments and returned values from compiled functions shoul be native objects such as `Int`, `Float64`, or `Ptr`. +They should not be things like `Tuple{Int, Int}` that are not natively sized; +such objects should to be passed by reference instead of by value. + +The `demangle` keyword argument determines what the functions are called in the compiled library: +* `true` (the default) as they are in Julia (`my_add`); +* `false`, "julia_", the name of the function, and the types of its arguments (`julia_my_add_Int64_Int64`, `julia_main`; numbered for any remaining collisions); +* `:itanium`, as a C++ compiler would name them (`_Z6my_addll`, which `c++filt` reads as `my_add(long, long)`), with the C and C++ types of the arguments where applicable (`Int32` is `int`, `Ptr{UInt8}` is `unsigned char*`, `Cstring` is `const char*`) and Julia's own types named as classes in the namespace of their module. +Multiple methods of one function, if compiled together into the same library, require `false` or `:itanium`. + +### Examples +```julia +julia> using StaticCompiler, LoopVectorization + +julia> function test(n) + r = 0.0 + @turbo for i=1:n + r += log(sqrt(i)) + end + return r/n + end +test (generic function with 1 method) + +julia> compile_shlib(test, (Int,)) +"/Users/user/test.dylib" + +julia> test(100_000) +5.2564961094956075 + +julia> ccall(("test", "test.dylib"), Float64, (Int64,), 100_000) +5.2564961094956075 +``` +""" +compile_shlib(f::Function, tt=(), path::String=pwd(), filename=fix_name(f); kwargs...) = compile_shlib(((f, tt),), path, filename; kwargs...) +function compile_shlib(funcs::Union{Array,Tuple}, path::String=pwd(), filename::String="lib"; + target::StaticTarget=StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + kwargs... + ) + for (f, types) in funcs + check_signature(f, types; target, kwargs...) + end + + generate_shlib(funcs, path, filename; target, demangle, cc, cflags, llvm_to_clang, llvm_postprocess, llvm_finalize, kwargs...) +end + + +""" +```julia +generate_shlib_fptr(path::String, name) +``` +Low level interface for obtaining a function pointer by `dlopen`ing a shared +library given the `path` and `name` of a `.so`/`.dylib` already compiled by +`generate_shlib`. + +See also `StaticCompiler.generate_shlib`. + +### Examples +```julia +julia> function test(n) + r = 0.0 + for i=1:n + r += log(sqrt(i)) + end + return r/n + end +test (generic function with 1 method) + +julia> path, name = StaticCompiler.generate_shlib(test, Tuple{Int64}, "./test"); + +julia> test_ptr = StaticCompiler.generate_shlib_fptr(path, name) +Ptr{Nothing} @0x000000015209f600 + +julia> ccall(test_ptr, Float64, (Int64,), 100_000) +5.256496109495593 + +julia> @ccall \$test_ptr(100_000::Int64)::Float64 # Equivalently +5.256496109495593 + +julia> test(100_000) +5.256496109495593 +``` +""" +function generate_shlib_fptr(path::String, name, filename::String=name) + lib_path = joinpath(abspath(path), "$filename.$(Libdl.dlext)") + ptr = Libdl.dlopen(lib_path, Libdl.RTLD_LOCAL) + fptr = Libdl.dlsym(ptr, name) + @assert fptr != C_NULL + fptr +end + +""" +```julia +generate_executable(f::Function, tt=(), args...; also_expose::Vector, kwargs...) +generate_executable(funcs::Union{Array,Tuple}, [path=tempname()], [filename=fix_name(first(first(funcs)))]; + target::StaticTarget = StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + main_prologue = nothing, # optional hook: adds code that runs first in `main`, into which `f` will then be wrapped + kwargs... +) +``` +Lower-level interface for standalone executable compilation. +As [`compile_executable`](@ref), but without argument or return type signature checking. +""" +generate_executable(f::Function, tt=(), args...; also_expose::Vector=Tuple{Function, Tuple{DataType}}[], kwargs...) = generate_executable(vcat([(f, tt)], also_expose), args...; kwargs...) +function generate_executable(funcs::Union{Array,Tuple}, path::String=tempname(), filename::String=fix_name(first(first(funcs))); + target::StaticTarget = StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + main_prologue = nothing, # optional hook: adds code that runs first in `main`, into which `f` will then be wrapped + kwargs... + ) + # How it is linked: what `cc` says, or the toolchain of the target + tc = isnothing(cc) ? toolchain(target) : CCToolchain(cc) + + # Prepare objects or (if llvm_to_clang is set) IR. A linker that is not a compiler driver is given an object that has a `main`, and so is a driver when + # `main_prologue` asks for code to run first, which the `main` of the object has (the driver would be given a `main` of its own, with nothing before the entry point) + fn = first(compiled_names(funcs; demangle, target)) + main_wrapper = !(tc isa CCToolchain) || !isnothing(main_prologue) ? fn : nothing + entry = isnothing(main_wrapper) ? fn : nothing + obj_or_ir_path = if llvm_to_clang + generate_ir(funcs, path, filename; demangle, target, main_wrapper, main_prologue, llvm_postprocess, llvm_finalize, kwargs...) + else + generate_obj(funcs, path, filename; demangle, target, main_wrapper, main_prologue, llvm_postprocess, llvm_finalize, kwargs...) + end + + # Compile and/or link executable! + exec_path = joinpath(path, output_name(tc, target, filename)) + link(tc, target, [obj_or_ir_path], exec_path; entry, cflags, kind = :executable) + + return joinpath(abspath(path), output_name(isnothing(cc) ? toolchain(target) : CCToolchain(cc), target, filename)) +end + + +""" +```julia +generate_shlib(f::Function, types::Tuple, [path::String=tempname()], [filename=fix_name(f)]; kwargs...) +generate_shlib(funcs::Array, [path::String=tempname()], [filename::String = "lib"]; + target::StaticTarget=StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + kwargs... +) +``` +Lower-level interface for compiling a standalone `.dylib`/`.so` shared object. +As [`compile_shlib`](@ref), but without argument or return type signature checking. +``` +""" +generate_shlib(f::Function, tt=(), path::String=tempname(), filename=fix_name(f); kwargs...) = generate_shlib(((f, tt),), path, filename; kwargs...) +function generate_shlib(funcs::Union{Array,Tuple}, path::String=tempname(), filename::String="lib"; + target::StaticTarget=StaticTarget(), # The target for compilation, including OS and architecture as well as other options + demangle::Union{Bool,Symbol} = true, # `true`: names as they are in Julia; `false`: `julia_` and the types of the arguments; `:itanium`: C++ names + llvm_to_clang::Bool = needs_ir(target), # If true, compilation is completed by an external compiler given our LLVM IR + cc = nothing, # Compiler, may specify to override defaults + cflags = ``, # Compiler flags, may specify to override defaults + llvm_postprocess = nothing, # optional hook: called on the each function's module in turn + llvm_finalize = nothing, # optional hook: called on the final combined module when it is complete + kwargs... + ) + # How it is linked: what `cc` says, or the toolchain of the target + tc = isnothing(cc) ? toolchain(target) : CCToolchain(cc) + + # Prepare objects or (if llvm_to_clang is set) IR. The functions of a DLL are exported (before the hook of the caller, which sees the module as it is linked) + finalize = function (mod) + iswindows(target) && add_dllexport!(mod, funcs; demangle, target) + isnothing(llvm_finalize) || llvm_finalize(mod) + end + lib_path = joinpath(path, output_name(tc, target, filename; kind = :shared)) + obj_or_ir_path = if llvm_to_clang + generate_ir(funcs, path, filename; demangle, target, llvm_postprocess, llvm_finalize=finalize, kwargs...) + else + generate_obj(funcs, path, filename; demangle, target, llvm_postprocess, llvm_finalize=finalize, kwargs...) + end + + # Compile and/or link shlib! + link(tc, target, [obj_or_ir_path], lib_path; cflags, kind = :shared) + + return joinpath(abspath(path), output_name(isnothing(cc) ? toolchain(target) : CCToolchain(cc), target, filename; kind = :shared)) +end + +""" +```julia +static_code_llvm(f, types; target::StaticTarget=StaticTarget(), kwargs...) +``` +Print the LLVM IR that `f` compiles to for the argument types `types`, as the compiler makes it for the +`target`: what [`compile_executable`](@ref) and [`compile_shlib`](@ref) would write, before linking +(with the method overlays of this package, and without the code of libraries that the function calls). +""" +function static_code_llvm(@nospecialize(func), @nospecialize(types); target::StaticTarget=StaticTarget(), kwargs...) + job = static_job(func, types; target, kwargs...) + GPUCompiler.code_llvm(stdout, job; libraries=false) +end + +""" +```julia +static_code_typed(f, types; target::StaticTarget=StaticTarget(), kwargs...) +``` +The typed Julia code of `f` for the argument types `types`, as `code_typed` of Julia gives it, but as the +compiler for the `target` sees it, with the method overlays of this package: a vector of +`CodeInfo => return type` pairs. +""" +function static_code_typed(@nospecialize(func), @nospecialize(types); target::StaticTarget=StaticTarget(), kwargs...) + job = static_job(func, types; target, kwargs...) + GPUCompiler.code_typed(job) +end + +""" +```julia +static_code_native(f, tt, fname=fix_name(f); target::StaticTarget=StaticTarget(), kwargs...) +``` +Print the assembly that `f` compiles to for the argument types `tt` for the `target`, as the code +generator of LLVM makes it. +""" +function static_code_native(@nospecialize(f), @nospecialize(tt), name=fix_name(f); target::StaticTarget=StaticTarget(), kwargs...) + job = static_job(f, tt; name, target, kwargs...) + GPUCompiler.code_native(stdout, job; libraries=false) +end + + +""" +```julia +static_llvm_module(f::Function, tt, name=fix_name(f); demangle=true, target::StaticTarget=StaticTarget(), kwargs...) +static_llvm_module(funcs::Union{Array,Tuple}; demangle=true, target::StaticTarget=StaticTarget(), kwargs...) +``` +Compile the method of `f` for the argument types `tt` to an `LLVM.Module`, which the caller +owns. + +The module belongs to the active thread-safe context, so call this function in a +`GPUCompiler.JuliaContext() do ctx ... end` block, and dispose of the module (or hand it to an +operation that consumes it, like `LLVM.link!(dst, mod)`) before the block ends. Without an +active thread-safe context, a new one is created for the module, which is never disposed of +(i.e., every such call leaks a context). +""" +function static_llvm_module(f::Function, tt, name=nothing; demangle=true, target::StaticTarget=StaticTarget(), kwargs...) + with_module_context() do + compile_llvm_module(f, tt, name; demangle, target, kwargs...) + end +end +function static_llvm_module(funcs::Union{Array,Tuple}; demangle=true, target::StaticTarget=StaticTarget(), kwargs...) + with_module_context() do + compile_llvm_module(funcs; demangle, target, kwargs...) + end +end + +# call `f` with the plain context of the active thread-safe context active, or of a new +# thread-safe context that is never disposed of, so that the modules `f` returns stay valid +function with_module_context(f) + ts_ctx = LLVM.ts_context(; throw_error=false) + ts_ctx === nothing || return context!(f, LLVM.context(ts_ctx)) + ts_ctx = GPUCompiler.JuliaContext() # activates it + ret = try + context!(f, LLVM.context(ts_ctx)) + catch + # nothing was returned that could use the context + dispose(ts_ctx) + rethrow() + end + LLVM.deactivate(ts_ctx) + return ret +end + +# compile to a module in the active (Julia) context, which must outlive the module +function compile_llvm_module(funcs::Union{Array,Tuple}; kwargs...) + names = compiled_names(funcs; demangle = get(kwargs, :demangle, true), target = get(kwargs, :target, nothing)) + (f, tt), rest... = funcs + mod = compile_llvm_module(f, tt; kwargs..., symbol = names[1]) + try + for ((f, tt), name) in zip(rest, names[2:end]) + # consumes the module, also when linking fails + link!(mod, compile_llvm_module(f, tt; kwargs..., symbol = name)) + end + run!(MergeFunctionsPass(), mod) + catch + dispose(mod) + rethrow() + end + return mod +end +function compile_llvm_module(f, tt, name=nothing; + target::StaticTarget=StaticTarget(), + demangle=true, + strip=true, + only_entry=false, + validate=false, + libraries=false, + llvm_postprocess=nothing, + symbol=nothing, + kwargs..., + ) + # (`symbol` is the name in the object, which `compiled_names` made; or the name that was given, with `julia_` before it if `demangle` is `false`; or the name that `demangle` says, of the function and its types) + if symbol === nothing + symbol = name === nothing ? only(compiled_names(((f, tt),); demangle, target)) : demangle === false ? "julia_" * name : name + end + name = symbol + job = static_job(f, tt; name, target, strip, only_entry, validate, libraries, kwargs...) + m, _ = GPUCompiler.compile(:llvm, job) + try + isnothing(llvm_postprocess) || llvm_postprocess(m) + locate_pointers_and_runtime_calls(m) + retarget!(m, target) + catch + dispose(m) + rethrow() + end + return m +end + + +""" +```julia +generate_obj(f::Function, tt, path::String, filenamebase::String="obj"; kwargs...) -> obj_path +generate_obj(funcs::Union{Array,Tuple}, path::String, filenamebase::String="obj"; + target::StaticTarget=StaticTarget(), + demangle = true, + main_wrapper = nothing, + main_prologue = nothing, + llvm_postprocess = nothing, + llvm_finalize = nothing, + kwargs... +) -> obj_path +``` +Low level interface for compiling object code (`.o`) for the function `f` given a tuple type `tt` characterizing the types of the arguments for which the function will be compiled, +or for an array of Tuples `(f, tt)` where each function `f` and tuple type `tt` determine the set of methods which will be compiled. +Returns the path of the file that was written. + +`target` is the [`StaticTarget`](@ref) that the code is made for, which can be one that the host cannot run (see its documentation: the code is then made for the host, retargeted, and the object is made by Julia's LLVM +if it has the code generator for the target, and else by the target's `llc`; an error says so if neither can). The default is the native target. + +`demangle` determines what the functions are called in the compiled library: +* `true` (the default) as they are in Julia (`my_add`); +* `false`, "julia_", the name of the function, and the types of its arguments (`julia_my_add_Int64_Int64`, `julia_main`; numbered for any remaining collisions); +* `:itanium`, as a C++ compiler would name them (`_Z6my_addll`, which `c++filt` reads as `my_add(long, long)`), with the C and C++ types of the arguments where applicable (`Int32` is `int`, `Ptr{UInt8}` is `unsigned char*`, `Cstring` is `const char*`) and Julia's own types named as classes in the namespace of their module. +Multiple methods of one function, if compiled together into the same library, require `false` or `:itanium`. + +If `main_wrapper` is the name of one of the functions, the object will be given a `main` that calls it, +possibly preceded by any code added by `main_prologue(builder, mod)`. + +The builtins that the toolchain of the target asks for (e.g., `__udivti3`, ...) are also added to the module (see [`add_builtins!`](@ref)). + +`llvm_postprocess(mod)`, if given, is called on the module of each function as soon as it is generated +(before its pointers and runtime calls are located, it is retargeted, and the modules are combined). +Similarly, `llvm_finalize(mod)` is called once on the whole module, when it is complete +(the modules combined, and the `main` and the builtins added) and just before the code is emitted. + +See also: [`generate_ir`](@ref) + +### Examples +``` +julia> fib(n) = n <= 1 ? n : fib(n - 1) + fib(n - 2) +fib (generic function with 1 method) + +julia> obj_path = StaticCompiler.generate_obj(fib, Tuple{Int64}, "./test") +"./test/obj.o" + +shell> tree \$path +./test +└── obj.o + +0 directories, 1 file +``` +""" +generate_obj(f::Function, tt, filenamebase=fix_name(f); kwargs...) = generate_obj(((f, tt),), filenamebase; kwargs...) +function generate_obj(funcs::Union{Array,Tuple}, path::String=tempname(), filenamebase::String="obj"; + target::StaticTarget=StaticTarget(), + demangle = true, + main_wrapper = nothing, + main_prologue = nothing, + llvm_postprocess = nothing, + llvm_finalize = nothing, + kwargs..., + ) + can_emit_object(target) || throw(ArgumentError("No object files can be made for $(target_triple(target)) here; Julia's LLVM has no code generator for it, and no `llc` is given (`StaticTarget(...; llc)`). Use `llvm_to_clang=true`, or `generate_ir` and give the IR to a compiler that has one.")) + mkpath(path) + f, tt = first(funcs) + # compile and generate code in one context, which the module can't outlive + GPUCompiler.JuliaContext() do context + @dispose mod=compile_llvm_module(funcs; demangle, target, llvm_postprocess, kwargs...) begin + isnothing(main_wrapper) || add_main_wrapper!(mod, main_wrapper, target; prologue = main_prologue) + uses_builtins(target.toolchain) && add_builtins!(mod, target_triple(target)) + isnothing(llvm_finalize) || llvm_finalize(mod) + obj_path = joinpath(path, "$filenamebase.o") + if !is_retargeted(target) + # Create object files using GPUCompiler + fakejob = static_job(f, tt; target, kwargs...) + obj, _ = GPUCompiler.emit_asm(fakejob, mod, LLVM.CodeGenFileType.Object) + else + # Create object files using LLVM.jl, possibly via an external `llc` + obj = emit_object(mod, target) + end + open(obj_path, "w") do io + write(io, obj) + end + return obj_path + end + end +end + +""" +```julia +generate_ir(f, tt, [path], [filenamebase]; kwargs...) +generate_ir(funcs::Union{Array,Tuple}, path::String, filenamebase::String; kwargs...) -> ir_path +generate_ir(funcs::Union{Array,Tuple}; + target::StaticTarget=StaticTarget(), + demangle = true, + main_wrapper = nothing, + main_prologue = nothing, + llvm_postprocess = nothing, + llvm_finalize = nothing, + kwargs... +) -> String +``` +Low level interface for compiling LLVM IR (`.ll`) for the function `f` given a tuple type `tt` characterizing the types of the arguments for which the function will be compiled, +or for an array of Tuples `(f, tt)` where each function `f` and tuple type `tt` determine the set of methods which will be compiled. +Returns the path of the file that was written, or if `path` is not specified, returns the LLVM IR itself as a `String`. +The LLVM module (which cannot outlive its context) is not returned. + +`target` is the [`StaticTarget`](@ref) that the code is made for, which can be one that the host cannot run (see its documentation: the code is then made for the host, retargeted, and the object is made by Julia's LLVM +if it has the code generator for the target, and else by the target's `llc`; an error says so if neither can). The default is the native target. + +`demangle` determines what the functions are called in the compiled library: +* `true` (the default) as they are in Julia (`my_add`); +* `false`, "julia_", the name of the function, and the types of its arguments (`julia_my_add_Int64_Int64`, `julia_main`; numbered for any remaining collisions); +* `:itanium`, as a C++ compiler would name them (`_Z6my_addll`, which `c++filt` reads as `my_add(long, long)`), with the C and C++ types of the arguments where applicable (`Int32` is `int`, `Ptr{UInt8}` is `unsigned char*`, `Cstring` is `const char*`) and Julia's own types named as classes in the namespace of their module. +Multiple methods of one function, if compiled together into the same library, require `false` or `:itanium`. + +If `main_wrapper` is the name of one of the functions, the object will be given a `main` that calls it, +possibly preceded by any code added by `main_prologue(builder, mod)`. + +The builtins that the toolchain of the target asks for (e.g., `__udivti3`, ...) are also added to the module (see [`add_builtins!`](@ref)). + +`llvm_postprocess(mod)`, if given, is called on the module of each function as soon as it is generated +(before its pointers and runtime calls are located, it is retargeted, and the modules are combined). +Similarly, `llvm_finalize(mod)` is called once on the whole module, when it is complete +(the modules combined, and the `main` and the builtins added) and just before the code is emitted. + +See also: [`generate_obj`](@ref) +""" +generate_ir(f::Function, tt, path::String, filenamebase::String=fix_name(f); kwargs...) = generate_ir(((f, tt),), path, filenamebase; kwargs...) # -> ir_path +function generate_ir(funcs::Union{Array,Tuple}, path::String, filenamebase::String="ir"; kwargs...) + mkpath(path) + ir_path = joinpath(path, "$filenamebase.ll") + write(ir_path, generate_ir(funcs; kwargs...)) + return ir_path +end +generate_ir(f::Function, tt; kwargs...) = generate_ir(((f, tt),); kwargs...) # -> String +function generate_ir(funcs::Union{Array,Tuple}; + target::StaticTarget=StaticTarget(), + demangle = true, + main_wrapper = nothing, + main_prologue = nothing, + llvm_postprocess = nothing, + llvm_finalize = nothing, + kwargs... + ) + GPUCompiler.JuliaContext() do context + @dispose mod=compile_llvm_module(funcs; demangle, target, llvm_postprocess, kwargs...) begin + isnothing(main_wrapper) || add_main_wrapper!(mod, main_wrapper, target; prologue = main_prologue) + uses_builtins(target.toolchain) && add_builtins!(mod, target_triple(target)) + isnothing(llvm_finalize) || llvm_finalize(mod) + return string(mod) + end + end +end + + +""" +```julia +link(toolchain, target, inputs::Vector{String}, output::String; entry = nothing, cflags = ``, kind = :executable) -> path +``` + +Link the `inputs` (object files, or LLVM IR files if the toolchain is a `CCToolchain`) +into an executable (`kind = :executable`) or shared library (`kind = :shared`), and return its path. + +If given, `entry` is the name of the function that an executable runs (`int f(int argc, char **argv)`); +with `entry = nothing` the inputs define `main` already, and are linked as they are. +""" +function link(tc::CCToolchain, target::StaticTarget, inputs::Vector{String}, output::String; kind::Symbol = :executable, entry = nothing, cflags = ``) + # Link using a C compiler driver + cc = tc.cc + # (IR, which `clang` compiles itself: it is told what the target is, as it replaces the triple of the IR by the host's) + ir = any(endswith(".ll"), inputs) + ir && (cflags = `-Wno-override-module $(clang_target_flags(target)) $cflags`) + if kind === :shared + run(`$cc -shared $inputs $cflags -o $output`) + elseif isnothing(entry) + run(`$cc $inputs $cflags -o $output`) # (`main` is in the inputs) + elseif isapple(target) && !ir + # Apple no longer uses _start, so we can just specify a custom entry + run(`$cc -e _$entry $inputs $cflags -o $output`) + else + # Write a minimal wrapper to avoid having to specify a custom entry + wrapper_path = joinpath(dirname(output), "wrapper$(rand(UInt)).c") + write(wrapper_path, """int $entry(int argc, char** argv); + void* __stack_chk_guard = (void*) $(rand(UInt) >> 1); + + int main(int argc, char** argv) + { + return $entry(argc, argv); + }""") + try + # (compiling from LLVM IR, or just linking object files, depending on the inputs) + run(`$cc $wrapper_path $inputs $cflags -o $output`) + finally + rm(wrapper_path; force = true) + end + end + return output +end +function link(tc::LLDToolchain, target::StaticTarget, inputs::Vector{String}, output::String; kind::Symbol = :executable, entry = nothing, cflags = ``) + # Link using an LLDToolchain driver + threads = lld_threads() + any(endswith(".ll"), inputs) && throw(ArgumentError("`LLDToolchain` links objects, not LLVM IR: make the objects (the target has to be one that Julia's LLVM has the code generator for)")) + libs = ["-l$l" for l in tc.libs] + if tc.flavor === :gnu + sysroot = tc.sysroot + isnothing(sysroot) && throw(ArgumentError("linking for $(target_triple(target)) needs the C library of the target: give `sysroot = ...` to `LLDToolchain(:gnu; ...)`")) + dir = crt_directory(sysroot) + if kind === :shared + run(`$(lld()) -flavor gnu $threads -shared -o $output $inputs -L$dir $libs $(tc.flags) $cflags`) + else + loader = something(tc.dynamic_linker, default_dynamic_linker(target)) + run(`$(lld()) -flavor gnu $threads -o $output -dynamic-linker $loader $(joinpath(dir, "crt1.o")) $(joinpath(dir, "crti.o")) $inputs -L$dir $libs $(joinpath(dir, "crtn.o")) $(tc.flags) $cflags`) + end + elseif tc.flavor === :darwin + # Mach-O: the SDK has the libraries (as `.tbd` stubs) and the headers; the minimum version of the system is the triple's + sdk = something(tc.sysroot, macos_sdk()) + triple = target_triple(target) + arch = first(split(triple, '-')) + arch = arch in ("aarch64", "arm64") ? "arm64" : arch + m = match(r"macosx?(\d+(?:\.\d+)*)", triple) + minimum = m === nothing ? "11.0.0" : m.captures[1] + shared = kind === :shared ? `-dylib` : `` + run(`$(lld()) -flavor darwin $threads $shared -arch $arch -platform_version macos $minimum $(sdk_version(sdk)) -syslibroot $sdk $inputs $libs -o $output $(tc.flags) $cflags`) + elseif tc.flavor === :mingw + # PE for Windows, with the start files and the libraries of MinGW-w64: the linker of MinGW is `lld` with the machine of PE that the architecture has + sysroot = tc.sysroot + isnothing(sysroot) && throw(ArgumentError("linking for $(target_triple(target)) needs the libraries of MinGW-w64: give `sysroot = ...` to `LLDToolchain(:mingw; ...)` (the directory that has `lib`: `mingw_sysroot(triple)`)")) + dir = mingw_directory(sysroot) + arch = first(split(target_triple(target), '-')) + machine = arch in ("x86_64", "amd64") ? "i386pep" : arch in ("i686", "i386") ? "i386pe" : arch in ("aarch64", "arm64") ? "arm64pe" : throw(ArgumentError("no machine of PE is known for $arch")) + start = kind === :shared ? joinpath(dir, "dllcrt2.o") : joinpath(dir, "crt2.o") + shared = kind === :shared ? `--shared` : `` + run(`$(lld()) -flavor gnu -m $machine $threads $shared -o $output $start $inputs -L$dir $libs $(tc.flags) $cflags`) + else # :wasm + kind === :shared && throw(ArgumentError("a shared library for WebAssembly is not supported")) + bits = startswith(target_triple(target), "wasm64") ? "-mwasm64" : "-mwasm32" + run(`$(lld()) -flavor wasm $threads $bits --no-entry --export=main --export-memory --allow-undefined -o $output $inputs $(tc.flags) $cflags`) + end + return output +end + +# the directory of a sysroot that has the start files of MinGW-w64 (`crt2.o`) +function mingw_directory(sysroot::AbstractString) + for d in ("lib", "x86_64-w64-mingw32/lib", "i686-w64-mingw32/lib", "aarch64-w64-mingw32/lib", "mingw/lib", ".") + isfile(joinpath(sysroot, d, "crt2.o")) && return joinpath(sysroot, d) + end + throw(ArgumentError("`$sysroot` has no `crt2.o`: the `sysroot` of a `:mingw` `LLDToolchain` is a directory that has the `lib` of MinGW-w64 (the `Mingw_jll` artifact for the platform of the target is one)")) +end +lld_threads() = Sys.iswindows() ? `--threads=1` : `` # The available `lld` seems to crash when run multithreaded on Windows, so limit it to one thread end # module diff --git a/src/builtins.jl b/src/builtins.jl new file mode 100644 index 00000000..1e70895e --- /dev/null +++ b/src/builtins.jl @@ -0,0 +1,335 @@ +## Builtins: the LLVM functions that the code generator may calls and that a C runtime library would have supplied + +# When an object is linked by `lld` alone, nothing supplies the functions that codegen calls that the CPU has no instruction for. +# For example, `__udivti3` for the division of `i128`, `__extendhfsf2` for `Float16`. +# They are defined here in IR, `linkonce_odr` and `hidden`: +# a definition of the program's own, or of a library that is linked, wins, and the module has only those that it uses. +# A toolchain asks for them with `builtins = true` (`LLDToolchain` does by default; a `CCToolchain` does not, as the compiler driver links its runtime library). + +# 128-bit division (`__udivti3` and the others of libgcc and compiler-rt, which a Linux program is not linked with): by shifting and subtracting, with instructions of `i128` that are not calls +# (a division of `i128` in them would be a call of themselves). +const LINUX_INT128_BUILTINS = """ +define linkonce_odr hidden i128 @__static_udivmod(i128 %a, i128 %b, i1 %rem) { +entry: + ; (operands of 64 bits, the usual: the instruction of the CPU; a divisor of zero is left to the loop, which does not trap) + %ah = lshr i128 %a, 64 + %bh = lshr i128 %b, 64 + %hi = or i128 %ah, %bh + %nohi = icmp eq i128 %hi, 0 + %bnz = icmp ne i128 %b, 0 + %small = and i1 %nohi, %bnz + br i1 %small, label %fast, label %loop +fast: + %a64 = trunc i128 %a to i64 + %b64 = trunc i128 %b to i64 + %fq = udiv i64 %a64, %b64 + %fr = urem i64 %a64, %b64 + %fqx = zext i64 %fq to i128 + %frx = zext i64 %fr to i128 + %fres = select i1 %rem, i128 %frx, i128 %fqx + ret i128 %fres +loop: + %i = phi i32 [ 127, %entry ], [ %i1, %loop ] + %q = phi i128 [ 0, %entry ], [ %q2, %loop ] + %r = phi i128 [ 0, %entry ], [ %r3, %loop ] + %i128 = zext i32 %i to i128 + %sh = lshr i128 %a, %i128 + %bit = and i128 %sh, 1 + %r1 = shl i128 %r, 1 + %r2 = or i128 %r1, %bit + %ge = icmp uge i128 %r2, %b + %rs = sub i128 %r2, %b + %r3 = select i1 %ge, i128 %rs, i128 %r2 + %one = shl i128 1, %i128 + %qo = or i128 %q, %one + %q2 = select i1 %ge, i128 %qo, i128 %q + %i1 = sub i32 %i, 1 + %done = icmp slt i32 %i1, 0 + br i1 %done, label %exit, label %loop +exit: + %res = select i1 %rem, i128 %r3, i128 %q2 + ret i128 %res +} +define linkonce_odr hidden i128 @__udivti3(i128 %a, i128 %b) { + %r = call i128 @__static_udivmod(i128 %a, i128 %b, i1 false) + ret i128 %r +} +define linkonce_odr hidden i128 @__umodti3(i128 %a, i128 %b) { + %r = call i128 @__static_udivmod(i128 %a, i128 %b, i1 true) + ret i128 %r +} +define linkonce_odr hidden i128 @__divti3(i128 %a, i128 %b) { + %sa = icmp slt i128 %a, 0 + %sb = icmp slt i128 %b, 0 + %na = sub i128 0, %a + %nb = sub i128 0, %b + %ua = select i1 %sa, i128 %na, i128 %a + %ub = select i1 %sb, i128 %nb, i128 %b + %q = call i128 @__static_udivmod(i128 %ua, i128 %ub, i1 false) + %neg = xor i1 %sa, %sb + %nq = sub i128 0, %q + %r = select i1 %neg, i128 %nq, i128 %q + ret i128 %r +} +define linkonce_odr hidden i128 @__modti3(i128 %a, i128 %b) { + %sa = icmp slt i128 %a, 0 + %sb = icmp slt i128 %b, 0 + %na = sub i128 0, %a + %nb = sub i128 0, %b + %ua = select i1 %sa, i128 %na, i128 %a + %ub = select i1 %sb, i128 %nb, i128 %b + %m = call i128 @__static_udivmod(i128 %ua, i128 %ub, i1 true) + %nm = sub i128 0, %m + %r = select i1 %sa, i128 %nm, i128 %m + ret i128 %r +} +""" + +# The same, for the convention of x86-64 Windows: the code generator calls `__udivti3` and the others with the addresses of the two operands (in `rcx` and `rdx`, as the C convention of Windows passes what is larger than a +# register), and reads the result from `xmm0`, as a vector of two integers of 64 bits (as libgcc, which has them, returns what `__int128` is). (Checked with `llc` of LLVM 23.) +function windows_int128_builtins(text::AbstractString) + for name in ("__udivti3", "__umodti3", "__divti3", "__modti3") + from = "define linkonce_odr hidden i128 @$name(i128 %a, i128 %b) {\n" + occursin(from, text) || error("the text of the division of 128 bits has changed: `$from` is not in it") + text = replace(text, from => "define linkonce_odr hidden <2 x i64> @$name(ptr %pa, ptr %pb) {\n %a = load i128, ptr %pa, align 8\n %b = load i128, ptr %pb, align 8\n") + end + returned = " ret i128 %r\n" + count(returned, text) == 4 || error("the text of the division of 128 bits has changed: it has not four functions that return `%r`") + return replace(text, returned => " %v = bitcast i128 %r to <2 x i64>\n ret <2 x i64> %v\n") +end +const WINDOWS_INT128_BUILTINS = windows_int128_builtins(LINUX_INT128_BUILTINS) + +# Conversions between `Float16`, `Float32`, and `Float64` that the code generator calls where the CPU has no instruction for them. +# For example: WebAssembly has none, nor has generic/older x86-64 (F16C is from 2012 on, and Rosetta before macOS 15 does not have it) +# Instead, we make the conversion by integer arithmetic, as compiler-rt definitions +# Rounding is to nearest, ties to even +# These are called with the convention of the *library calls* that the code generator makes, which varies by target. +# (Checked with `llc` of LLVM 23: the caller reads the result of `__truncsfhf2` from `xmm0`, and passes the argument of `__extendhfsf2` there.) +const HALF_BUILTINS = """ +define linkonce_odr hidden float @__extendhfsf2(half %a) { + %h = bitcast half %a to i16 + %hi = zext i16 %h to i32 + %s1 = lshr i32 %hi, 15 + %s2 = shl i32 %s1, 31 + %e1 = lshr i32 %hi, 10 + %e = and i32 %e1, 31 + %m = and i32 %hi, 1023 + %en = add i32 %e, 112 + %en2 = shl i32 %en, 23 + %m13 = shl i32 %m, 13 + %n1 = or i32 %s2, %en2 + %normal = or i32 %n1, %m13 + %i1 = or i32 %s2, 2139095040 + %infnan = or i32 %i1, %m13 + %mf = uitofp i32 %m to float + %sub = fmul float %mf, 0x3E70000000000000 + %subb = bitcast float %sub to i32 + %subs = or i32 %subb, %s2 + %isz = icmp eq i32 %e, 0 + %isi = icmp eq i32 %e, 31 + %r1 = select i1 %isi, i32 %infnan, i32 %normal + %r = select i1 %isz, i32 %subs, i32 %r1 + %f = bitcast i32 %r to float + ret float %f +} +define linkonce_odr hidden half @__truncsfhf2(float %a) { + %x = bitcast float %a to i32 + %s1 = lshr i32 %x, 16 + %sign = and i32 %s1, 32768 + %e1 = lshr i32 %x, 23 + %e = and i32 %e1, 255 + %m = and i32 %x, 8388607 + %ne = sub i32 %e, 112 + ; infinity and NaN + %m13 = lshr i32 %m, 13 + %nanm = or i32 %m13, 512 + %hasm = icmp ne i32 %m, 0 + %nanbits = select i1 %hasm, i32 %nanm, i32 0 + %infnan = or i32 %nanbits, 31744 + ; normal + %ne10 = shl i32 %ne, 10 + %hn = or i32 %ne10, %m13 + %rem = and i32 %m, 8191 + %gt = icmp ugt i32 %rem, 4096 + %eq = icmp eq i32 %rem, 4096 + %odd1 = and i32 %hn, 1 + %odd = icmp ne i32 %odd1, 0 + %tie = and i1 %eq, %odd + %up = or i1 %gt, %tie + %upi = zext i1 %up to i32 + %hn2 = add i32 %hn, %upi + ; subnormal + %mm = or i32 %m, 8388608 + %shift = sub i32 14, %ne + %shiftc = call i32 @llvm.umin.i32(i32 %shift, i32 31) + %hs = lshr i32 %mm, %shiftc + %one = shl i32 1, %shiftc + %mask = sub i32 %one, 1 + %rem2 = and i32 %mm, %mask + %half1 = lshr i32 %one, 1 + %gt2 = icmp ugt i32 %rem2, %half1 + %eq2 = icmp eq i32 %rem2, %half1 + %odd2a = and i32 %hs, 1 + %odd2 = icmp ne i32 %odd2a, 0 + %tie2 = and i1 %eq2, %odd2 + %up2 = or i1 %gt2, %tie2 + %up2i = zext i1 %up2 to i32 + %hs2 = add i32 %hs, %up2i + ; which + %isinf = icmp eq i32 %e, 255 + %ovf = icmp sge i32 %ne, 31 + %isnorm = icmp sge i32 %ne, 1 + %issub = icmp sge i32 %ne, -10 + %r1 = select i1 %issub, i32 %hs2, i32 0 + %r2 = select i1 %isnorm, i32 %hn2, i32 %r1 + %r3 = select i1 %ovf, i32 31744, i32 %r2 + %r4 = select i1 %isinf, i32 %infnan, i32 %r3 + %r5 = or i32 %r4, %sign + %r16 = trunc i32 %r5 to i16 + %h = bitcast i16 %r16 to half + ret half %h +} +declare i32 @llvm.umin.i32(i32, i32) +; double to half: through float with the rounding to odd (inexact results get an odd last bit: the second rounding is then the one of the double), and half to double +define linkonce_odr hidden half @__truncdfhf2(double %a) { + %f = fptrunc double %a to float + %back = fpext float %f to double + %exact = fcmp oeq double %back, %a + %isnan = fcmp uno double %a, %a + %fb = bitcast float %f to i32 + %odd = and i32 %fb, 1 + %isodd = icmp ne i32 %odd, 0 + %nb = fneg double %back + %bneg = fcmp olt double %back, 0.0 + %ab = select i1 %bneg, double %nb, double %back + %na = fneg double %a + %aneg = fcmp olt double %a, 0.0 + %aa = select i1 %aneg, double %na, double %a + %up = fcmp ogt double %ab, %aa + %dec = sub i32 %fb, 1 + %inc = add i32 %fb, 1 + %adj = select i1 %up, i32 %dec, i32 %inc + %isinf = fcmp oeq float %f, 0x7FF0000000000000 + %k1 = or i1 %exact, %isodd + %k2 = or i1 %k1, %isnan + %k3 = or i1 %k2, %isinf + %r = select i1 %k3, i32 %fb, i32 %adj + %rf = bitcast i32 %r to float + %h = call half @__truncsfhf2(float %rf) + ret half %h +} +define linkonce_odr hidden double @__extendhfdf2(half %a) { + %f = call float @__extendhfsf2(half %a) + %d = fpext float %f to double + ret double %d +} +""" + +# The same, for the convention of x86-64 macOS, where the library calls pass a `Float16` as an `i16` in an integer register +# The `half` of the signatures and of the calls is an `i16`, and what is made of it by `bitcast` is the value itself. +# (the argument in `edi`, the result in `ax`). +function macos_x86_half_builtins(text::AbstractString) + replacements = [ + "define linkonce_odr hidden float @__extendhfsf2(half %a) {\n %h = bitcast half %a to i16\n" => "define linkonce_odr hidden float @__extendhfsf2(i16 %h) {\n", + "define linkonce_odr hidden half @__truncsfhf2(float %a) {" => "define linkonce_odr hidden i16 @__truncsfhf2(float %a) {", + " %h = bitcast i16 %r16 to half\n ret half %h" => " ret i16 %r16", + "define linkonce_odr hidden half @__truncdfhf2(double %a) {" => "define linkonce_odr hidden i16 @__truncdfhf2(double %a) {", + " %h = call half @__truncsfhf2(float %rf)\n ret half %h" => " %h = call i16 @__truncsfhf2(float %rf)\n ret i16 %h", + "define linkonce_odr hidden double @__extendhfdf2(half %a) {\n %f = call float @__extendhfsf2(half %a)" => "define linkonce_odr hidden double @__extendhfdf2(i16 %a) {\n %f = call float @__extendhfsf2(i16 %a)", + ] + for (from, to) in replacements + occursin(from, text) || error("the text of the conversions of `Float16` has changed: `$from` is not in it") + text = replace(text, from => to) + end + return text +end +const MACOS_X86_HALF_BUILTINS = macos_x86_half_builtins(HALF_BUILTINS) + +# The probe of the stack for x86-64 Windows (`___chkstk_ms` of libgcc and compiler-rt): the runtime of MinGW-w64 calls it itself (`pseudo-reloc.o`, which every program has), and the libraries that `Mingw_jll` +# has do not have it. It touches each page of the stack that a function of a large frame is about to use, as the system's guard page needs. It is assembly, which the module has as its own (`module asm`). +const MINGW_X64_BUILTINS = raw""" +module asm ".text" +module asm ".globl ___chkstk_ms" +module asm ".def ___chkstk_ms; .scl 2; .type 32; .endef" +module asm "___chkstk_ms:" +module asm " pushq %rcx" +module asm " pushq %rax" +module asm " cmpq $0x1000, %rax" +module asm " leaq 24(%rsp), %rcx" +module asm " jb 2f" +module asm "1:" +module asm " subq $0x1000, %rcx" +module asm " orl $0, (%rcx)" +module asm " subq $0x1000, %rax" +module asm " cmpq $0x1000, %rax" +module asm " ja 1b" +module asm "2:" +module asm " subq %rax, %rcx" +module asm " orl $0, (%rcx)" +module asm " popq %rax" +module asm " popq %rcx" +module asm " ret" +""" + +# The builtins that the IR needs for the target: the names of the constants above. What the IR has that needs them (`Float16`, the division of `i128`) is `has_half` and `has_i128div`; the system and the architecture are the triple's. +function needed_builtins(has_half::Bool, has_i128div::Bool, triple::AbstractString) + family = llvm_family(first(split(triple, '-'))) + needed = Symbol[] + x86_64 = family == "x86" && startswith(triple, "x86_64") + x86_64 && has_half && push!(needed, occursin(r"apple|darwin|macos", triple) ? :MACOS_X86_HALF_BUILTINS : :HALF_BUILTINS) + family == "wasm" && has_half && push!(needed, :HALF_BUILTINS) + occursin("linux", triple) && has_i128div && push!(needed, :LINUX_INT128_BUILTINS) + x86_64 && occursin(r"windows|mingw", triple) && has_i128div && push!(needed, :WINDOWS_INT128_BUILTINS) + # (the runtime of MinGW-w64 needs the probe of the stack whatever the program is) + startswith(triple, "x86_64") && occursin(r"windows|mingw", triple) && push!(needed, :MINGW_X64_BUILTINS) + return needed +end +# (of the text of IR) +needed_builtins(text::AbstractString, triple::AbstractString) = + needed_builtins(occursin(r"\bhalf\b", text), occursin(r"\b(udiv|sdiv|urem|srem) i128\b", text), triple) +# (of a module: by its instructions, without printing it) +function needed_builtins(mod::LLVM.Module, triple::AbstractString) + has_half = has_i128div = false + for f in LLVM.functions(mod), bb in LLVM.blocks(f), inst in LLVM.instructions(bb) + has_half = has_half || mentions_half(LLVM.value_type(inst)) || any(op -> mentions_half(LLVM.value_type(op)), LLVM.operands(inst)) + if !has_i128div && LLVM.opcode(inst) in (LLVM.API.LLVMUDiv, LLVM.API.LLVMSDiv, LLVM.API.LLVMURem, LLVM.API.LLVMSRem) + ty = LLVM.value_type(inst) + has_i128div = ty isa LLVM.IntegerType && LLVM.width(ty) == 128 + end + has_half && has_i128div && break + end + return needed_builtins(has_half, has_i128div, triple) +end +# (a `half`, or a vector of them) +mentions_half(ty::LLVM.LLVMType) = ty isa LLVM.HalfType || (ty isa LLVM.VectorType && LLVM.eltype(ty) isa LLVM.HalfType) + +""" + add_builtins(text::AbstractString, triple::AbstractString) -> String + +The LLVM IR `text` with the definitions of the builtins that it needs for `triple` (see [`add_builtins!`](@ref)). +""" +function add_builtins(text::AbstractString, triple::AbstractString) + for name in needed_builtins(text, triple) + text = string(text, "\n", getfield(@__MODULE__, name)) + end + return text +end + +""" + add_builtins!(mod::LLVM.Module, triple::AbstractString) -> mod + +Define in the module the builtins that it needs for the target `triple`: the functions that the code generator calls for what the CPU has no instruction for, which a C runtime library (libgcc, compiler-rt) has and an object +that is linked by `lld` alone has not. Which are needed is what the module says: `i128` division on Linux, `Float16` conversions on x86-64 and WebAssembly. +""" +function add_builtins!(mod::LLVM.Module, triple::AbstractString) + for name in needed_builtins(mod, triple) + builtins = parse(LLVM.Module, getfield(@__MODULE__, name)) + for f in LLVM.functions(builtins) + LLVM.isdeclaration(f) || LLVM.linkage!(f, LLVM.API.LLVMWeakODRLinkage) + end + LLVM.triple!(builtins, LLVM.triple(mod)) + LLVM.datalayout!(builtins, LLVM.datalayout(mod)) + LLVM.link!(mod, builtins) + end + return mod +end diff --git a/src/ccalls.jl b/src/ccalls.jl deleted file mode 100644 index 4314fab5..00000000 --- a/src/ccalls.jl +++ /dev/null @@ -1,90 +0,0 @@ - -""" - find_ccalls(f, tt) - -Returns a `Dict` mapping function addresses to symbol names for all `ccall`s and -`cglobal`s called from the method. This descends into other invocations -within the method. -""" -find_ccalls(@nospecialize(f), @nospecialize(tt)) = find_ccalls(reflect(f, tt)) - -function find_ccalls(ref::Reflection) - result = Dict{Ptr{Nothing}, Symbol}() - idx = VERSION > v"1.2" ? 5 : 4 - foreigncalls = TypedCodeUtils.filter((c) -> lookthrough((c) -> c.head === :foreigncall && !(c.args[idx] isa QuoteNode && c.args[idx].value == :llvmcall), c), ref.CI.code) - # foreigncalls = TypedCodeUtils.filter((c) -> lookthrough((c) -> c.head === :foreigncall, c), ref.CI.code) - for fc in foreigncalls - sym = getsym(fc[2].args[1]) - address = eval(:(cglobal($(sym)))) - result[address] = Symbol(sym isa Tuple ? sym[1] : sym.value) - end - cglobals = TypedCodeUtils.filter((c) -> lookthrough(c -> c.head === :call && iscglobal(c.args[1]), c), ref.CI.code) - for fc in cglobals - sym = getsym(fc[2].args[2]) - address = eval(:(cglobal($(sym)))) - result[address] = Symbol(sym isa Tuple ? sym[1] : sym.value) - end - invokes = TypedCodeUtils.filter((c) -> lookthrough(identify_invoke, c), ref.CI.code) - invokes = map((arg) -> process_invoke(DefaultConsumer(), ref, arg...), invokes) - for fi in invokes - canreflect(fi) || continue - merge!(result, find_ccalls(reflect(fi))) - end - return result -end - -getsym(x) = x -getsym(x::String) = QuoteNode(Symbol(x)) -getsym(x::QuoteNode) = x -getsym(x::Expr) = eval.((x.args[2], x.args[3])) - -iscglobal(x) = x == cglobal || x isa GlobalRef && x.name == :cglobal - - -""" - fix_ccalls!(mod::LLVM.Module, d) - -Replace function addresses with symbol names in `mod`. The symbol names are -meant to be linked to `libjulia` or other libraries. -`d` is a `Dict` mapping a function address to symbol name for `ccall`s. -""" -function fix_ccalls!(mod::LLVM.Module, d) - for fun in functions(mod), blk in blocks(fun), instr in instructions(blk) - if instr isa LLVM.CallInst - dest = called_value(instr) - if dest isa ConstantExpr && occursin("inttoptr", string(dest)) - # @show instr - # @show dest - argtypes = [llvmtype(op) for op in operands(instr)] - nargs = length(parameters(eltype(argtypes[end]))) - # num_extra_args = 1 + length(collect(eachmatch(r"jl_roots", string(instr)))) - ptr = Ptr{Cvoid}(convert(Int, first(operands(dest)))) - if haskey(d, ptr) - sym = d[ptr] - newdest = LLVM.Function(mod, string(sym), LLVM.FunctionType(llvmtype(instr), argtypes[1:nargs])) - LLVM.linkage!(newdest, LLVM.API.LLVMExternalLinkage) - replace_uses!(dest, newdest) - end - end - elseif instr isa LLVM.LoadInst && occursin("inttoptr", string(instr)) - # dest = called_value(instr) - for op in operands(instr) - lastop = op - if occursin("inttoptr", string(op)) - # @show instr - if occursin("addrspacecast", string(op)) || occursin("getelementptr", string(op)) - op = first(operands(op)) - end - first(operands(op)) isa LLVM.ConstantInt || continue - ptr = Ptr{Cvoid}(convert(Int, first(operands(op)))) - if haskey(d, ptr) - obj = d[ptr] - newdest = GlobalVariable(mod, llvmtype(instr), string(d[ptr])) - LLVM.linkage!(newdest, LLVM.API.LLVMExternalLinkage) - replace_uses!(op, newdest) - end - end - end - end - end -end diff --git a/src/extern.jl b/src/extern.jl deleted file mode 100644 index 6c0424a9..00000000 --- a/src/extern.jl +++ /dev/null @@ -1,16 +0,0 @@ -""" - @extern(fun, returntype, argtypes, args...) - -Creates a call to an external function meant to be included at link time. -Use the same conventions as `ccall`. - -This transforms into the following `ccall`: - - ccall("extern fun", llvmcall, returntype, argtypes, args...) -""" -macro extern(name, rettyp, argtyp, args...) - externfun = string("extern ", name isa AbstractString || name isa Symbol ? name : name.value) - Expr(:call, :ccall, externfun, esc(:llvmcall), esc(rettyp), - Expr(:tuple, esc.(argtyp.args)...), esc.(args)...) -end - diff --git a/src/globals.jl b/src/globals.jl deleted file mode 100644 index e2583388..00000000 --- a/src/globals.jl +++ /dev/null @@ -1,164 +0,0 @@ -struct GlobalsContext - invokes::Set{Any} -end -GlobalsContext() = GlobalsContext(Set()) - - -""" - fix_globals!(mod::LLVM.Module) - -Replace function addresses in `mod` with references to global data structures. -For each global variable, two LLVM global objects are created: - -* `jl.global.data` -- An LLVM 'i8' vector holding a serialized version of the Julia object. -* `jl.global` -- A pointer to the unserialized Julia object. - -The `inttopt` with the function address is replaced by `jl.global`. - -A function `jl_init_globals` is added to `mod`. This function deserializes the data in -`jl.global.data` and updates `jl.global`. -""" - -_opcode(x::LLVM.ConstantExpr) = LLVM.API.LLVMGetConstOpcode(LLVM.ref(x)) - -function fix_globals!(mod::LLVM.Module) - # Create a `jl_init_globals` function. - jl_init_globals_func = LLVM.Function(mod, "jl_init_globals", - LLVM.FunctionType(julia_to_llvm(Cvoid), LLVMType[])) - jl_init_global_entry = BasicBlock(jl_init_globals_func, "entry", context(mod)) - - # Definitions for utility functions - func_type = LLVM.FunctionType(julia_to_llvm(Any), LLVMType[LLVM.PointerType(julia_to_llvm(Int8))]) - deserialize_funs = Dict() - - uint8_t = julia_to_llvm(UInt8) - - ctx = SerializeContext() - es = [] - objs = Set() - gptridx = Dict() - instrs = [] - gptrs = [] - j = 1 # counter for position in gptridx - Builder(context(mod)) do builder - toinstr!(x) = x - function toinstr!(x::LLVM.ConstantExpr) - if _opcode(x) == LLVM.API.LLVMAddrSpaceCast - val = toinstr!(first(operands(x))) - ret = addrspacecast!(builder, val, llvmtype(x)) - return ret - elseif _opcode(x) == LLVM.API.LLVMGetElementPtr - ops = operands(x) - val = toinstr!(first(ops)) - ret = gep!(builder, val, [ops[i] for i in 2:length(ops)]) - return ret - elseif _opcode(x) == LLVM.API.LLVMBitCast - ops = operands(x) - val = toinstr!(first(ops)) - ret = pointercast!(builder, val, llvmtype(x)) - return ret - elseif _opcode(x) == LLVM.API.LLVMIntToPtr - ptr = Ptr{Any}(convert(Int, first(operands(x)))) - obj = unsafe_pointer_to_objref(ptr) - if !in(obj, objs) - push!(es, serialize(ctx, obj)) - push!(objs, obj) - # Create pointers to the data. - gptr = GlobalVariable(mod, julia_to_llvm(Any), "jl.global") - linkage!(gptr, LLVM.API.LLVMInternalLinkage) - LLVM.API.LLVMSetInitializer(LLVM.ref(gptr), LLVM.ref(null(julia_to_llvm(Any)))) - push!(gptrs, gptr) - gptridx[obj] = j - j += 1 - end - gptr = gptrs[gptridx[obj]] - gptr2 = load!(builder, gptr) - ret = pointercast!(builder, gptr2, llvmtype(x)) - return ret - end - return x - end - for fun in functions(mod) - if startswith(LLVM.name(fun), "jfptr") - unsafe_delete!(mod, fun) - continue - end - - for blk in blocks(fun), instr in instructions(blk) - # Set up functions to walk the operands of the instruction - # and convert appropriate ConstantExpr's to instructions. - # Look for `LLVMIntToPtr` expressions. - position!(builder, instr) - ops = operands(instr) - N = opcode(instr) == LLVM.API.LLVMCall ? length(ops) - 1 : length(ops) - if opcode(instr) == LLVM.API.LLVMCall && name(last(operands(instr))) == "jl_type_error" - continue - end - for i in 1:N - try - if opcode(instr) == LLVM.API.LLVMPHI - position!(builder, last(instructions(LLVM.incoming(instr)[i][2]))) - end - ops[i] = toinstr!(ops[i]) - catch x - end - end - end - end - end - nglobals = length(es) - #@show mod - #verify(mod) - for i in 1:nglobals - # Assign the appropriate function argument to the appropriate global. - es[i] = :(unsafe_store!($((Symbol("global", i))), $(es[i]))) - end - # Define the deserializing function. - fune = quote - function _deserialize_globals(Vptr, $((Symbol("global", i) for i in 1:nglobals)...)) - $(ctx.init...) - $(es...) - return - end - end - # @show fune - # Execute the deserializing function. - deser_fun = eval(fune) - v = take!(ctx.io) - gv_typ = LLVM.ArrayType(uint8_t, length(v)) - data = LLVM.GlobalVariable(mod, gv_typ, "jl.global.data") - linkage!(data, LLVM.API.LLVMExternalLinkage) - constant!(data, true) - LLVM.API.LLVMSetInitializer(LLVM.ref(data), - LLVM.API.LLVMConstArray(LLVM.ref(uint8_t), - [LLVM.ref(ConstantInt(uint8_t, x)) for x in v], - UInt32(length(v)))) - Builder(context(mod)) do builder - dataptr = gep!(builder, data, [ConstantInt(0, context(mod)), ConstantInt(0, context(mod))]) - - # Create the Julia object from `data` and include that in `init_fun`. - position!(builder, jl_init_global_entry) - gfunc_type = LLVM.FunctionType(julia_to_llvm(Cvoid), - LLVMType[LLVM.PointerType(julia_to_llvm(Int8)), - Iterators.repeated(LLVM.FunctionType(julia_to_llvm(Any)), nglobals)...]) - deserialize_globals_func = LLVM.Function(mod, "_deserialize_globals", gfunc_type) - LLVM.linkage!(deserialize_globals_func, LLVM.API.LLVMExternalLinkage) - for i in 1:nglobals - # The following fix is to match the argument types which are an integer, not a %jl_value_t**. - gptrs[i] = LLVM.ptrtoint!(builder, gptrs[i], julia_to_llvm(Csize_t)) - end - LLVM.call!(builder, deserialize_globals_func, LLVM.Value[dataptr, gptrs...]) - ret!(builder) - end - tt = Tuple{Ptr{UInt8}, Iterators.repeated(Ptr{Any}, nglobals)...} - deser_mod = irgen(deser_fun, tt, overdub = false, fix_globals = false, optimize_llvm = false) - d = find_ccalls(deser_fun, tt) - fix_ccalls!(deser_mod, d) - # rename deserialization function to "_deserialize_globals" - fun = first(TypedCodeUtils.filter(x -> LLVM.name(x) == "_deserialize_globals", functions(deser_mod)))[2] - # LLVM.name!(fun, "_deserialize_globals") - linkage!(fun, LLVM.API.LLVMExternalLinkage) - # link into the main module - LLVM.link!(mod, deser_mod) - return -end diff --git a/src/helpers/README.md b/src/helpers/README.md deleted file mode 100644 index e443db6a..00000000 --- a/src/helpers/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Helpers -Note that the helpers defined here are used in tests, and they are useful to test out code in the REPL. - -```julia -twox(x) = 2x -# run code in the REPL -@jlrun twox(3) -# compile to an executable in a `standalone` directory -exegen([ (twox, Tuple{Int}, 4) ]) -``` - -These are not meant to be a permanent part of the API. They are just for testing. diff --git a/src/helpers/helpers.jl b/src/helpers/helpers.jl deleted file mode 100644 index 1f041540..00000000 --- a/src/helpers/helpers.jl +++ /dev/null @@ -1,37 +0,0 @@ -""" -Returns shellcmd string for different OS. Optionally, checks for gcc installation. -""" -function _shellcmd(checkInstallation::Bool = false) - - if Sys.isunix() - shellcmd = "gcc" - elseif Sys.iswindows() - shellcmd = ["cmd", "/c", "gcc"] - else - error("run command not defined") - end - - if checkInstallation - # Checking gcc installation - try - run(`$shellcmd -v`) - catch - @warn "Make sure gcc compiler is installed: https://gcc.gnu.org/install/binaries.html and is on the path, othetwise some of the functions will return errors" - return nothing - end - end - - return shellcmd -end - -shellcmd = _shellcmd(true) # is used in @jlrun and exegen() - - -export @jlrun -include("jlrun.jl") - -export ldflags, ldlibs, cflags # are used in exegen -include("juliaconfig.jl") - -export exegen -include("standalone-exe.jl") diff --git a/src/helpers/jlrun.jl b/src/helpers/jlrun.jl deleted file mode 100644 index f2e8e165..00000000 --- a/src/helpers/jlrun.jl +++ /dev/null @@ -1,61 +0,0 @@ -using Libdl, LLVM - -function show_inttoptr(mod) - for fun in LLVM.functions(mod), - blk in LLVM.blocks(fun), - instr in LLVM.instructions(blk) - - s = string(instr) - if occursin("inttoptr", s) && occursin(r"[0-9]{8,30}", s) - println(LLVM.name(fun), " ---------------------------") - @show instr - println() - end - end -end - -""" -Compiles function call provided and calls it with `ccall` using the shared library that was created. -""" -macro jlrun(e) - - fun = e.args[1] - efun = esc(fun) - args = length(e.args) > 1 ? e.args[2:end] : Any[] - libpath = abspath("test.o") - dylibpath = abspath("test.so") - tt = Tuple{(typeof(eval(a)) for a in args)...} - if length(e.args) > 1 - ct = code_typed(Base.eval(__module__, fun), tt) - else - ct = code_typed(Base.eval(__module__, fun)) - end - rettype = ct[1][2] - bindir = joinpath(dirname(Sys.BINDIR), "tools") - libdir = joinpath(dirname(Sys.BINDIR), "lib") - - runCommand = :(run( - $(`$shellcmd -shared -fPIC -o test.so -L$libdir test.o -ljulia`), - wait = true, - )) - - quote - m = irgen($efun, $tt) - # m = irgen($efun, $tt, overdub = false) - LLVM.verify(m) - # show_inttoptr(m) - write(m, "test.bc") - write_object(m, "test.o") - $runCommand - dylib = Libdl.dlopen($dylibpath) - ccall(Libdl.dlsym(dylib, "jl_init_globals"), Cvoid, ()) - res = ccall( - Libdl.dlsym(dylib, $(Meta.quot(fun))), - $rettype, - ($((typeof(eval(a)) for a in args)...),), - $(eval.(args)...), - ) - Libdl.dlclose(dylib) - res - end -end diff --git a/src/helpers/juliaconfig.jl b/src/helpers/juliaconfig.jl deleted file mode 100644 index 039e0905..00000000 --- a/src/helpers/juliaconfig.jl +++ /dev/null @@ -1,63 +0,0 @@ -# from PackageCompilerX: https://github.com/KristofferC/PackageCompilerX.jl/blob/c1a90edfaa28907edf2edbbc734ef8afdeeaca80/src/juliaconfig.jl -# adopted from https://github.com/JuliaLang/julia/blob/release-0.6/contrib/julia-config.jl - -function shell_escape(str) - str = replace(str, "'" => "'\''") - return "'$str'" -end - -function julia_libdir() - return if ccall(:jl_is_debugbuild, Cint, ()) != 0 - dirname(abspath(Libdl.dlpath("libjulia-debug"))) - else - dirname(abspath(Libdl.dlpath("libjulia"))) - end -end - -function julia_private_libdir() - @static if Sys.iswindows() - return julia_libdir() - else - return abspath(Sys.BINDIR, Base.PRIVATE_LIBDIR) - end -end - -julia_includedir() = abspath(Sys.BINDIR, Base.INCLUDEDIR, "julia") - -function ldflags() - fl = "-L$(shell_escape(julia_libdir()))" - if Sys.iswindows() - fl = fl * " -Wl,--stack,8388608" - fl = fl * " -Wl,--export-all-symbols" - elseif Sys.islinux() - fl = fl * " -Wl,--export-dynamic" - end - return fl -end - -# TODO -function ldlibs(relative_path=nothing) - libname = if ccall(:jl_is_debugbuild, Cint, ()) != 0 - "julia-debug" - else - "julia" - end - if Sys.islinux() - return "-Wl,-rpath-link,$(shell_escape(julia_libdir())) -Wl,-rpath-link,$(shell_escape(julia_private_libdir())) -l$libname" - elseif Sys.iswindows() - return "-l$libname -lopenlibm" - else - return "-l$libname" - end -end - -function cflags() - flags = IOBuffer() - print(flags, "-std=gnu99") - include = shell_escape(julia_includedir()) - print(flags, " -I", include) - if Sys.isunix() - print(flags, " -fPIC") - end - return String(take!(flags)) -end diff --git a/src/helpers/standalone-exe.jl b/src/helpers/standalone-exe.jl deleted file mode 100644 index 40d026bb..00000000 --- a/src/helpers/standalone-exe.jl +++ /dev/null @@ -1,148 +0,0 @@ -Ctemplate = """ -#include -#include -extern CRETTYPE FUNNAME(CARGTYPES); -extern void jl_init_with_image(const char *, const char *); -extern void jl_init_globals(void); -int main() -{ - jl_init_with_image(".", "blank.ji"); - jl_init_globals(); - printf("RETFORMAT", FUNNAME(FUNARG)); - jl_atexit_hook(0); - return 0; -} -""" - -# "signed" is removed from signed types -# duplicates will remove automatically -Cmap = Dict( - Cchar => "char", #Int8 - Cuchar => "unsigned char", #UInt8 - Cshort => "short", #Int16 - # Cstring => - Cushort => "unsigned short", #UInt16 - Cint => "int", #Int32 - Cuint => "unsigned int", #UInt32 - Clong => "long", #Int32 - Culong => "unsigned long", #UInt32 - Clonglong => "long long", #Int64 - Culonglong => "unsigned long long", #UInt64 - # Cintmax_t => "intmax_t", #Int64 - # Cuintmax_t => "uintmax_t", #UInt64 - # Csize_t => "size_t", #UInt - # Cssize_t => "ssize_t", #Int - # Cptrdiff_t => "ptrdiff_t", #Int - # Cwchar_t => "wchar_t", #Int32 - # Cwstring => - Cfloat => "float", #Float32 - Cdouble => "double", #Float64 - Nothing => "void", -) - -Cformatmap = Dict( - Cchar => "%c", #Int8 - # Cuchar => "unsigned char", #UInt8 - # Cshort => "short", #Int16 - Cstring => "%s", - # Cushort => "unsigned short", #UInt16 - Cint => "%d", #"i" #Int32 - Cuint => "%u", #UInt32 - Clong => "%ld", #Int32 - # Culong => "unsigned long", #UInt32 - Clonglong => "%lld", #Int64 - # Culonglong => "unsigned long long", #UInt64 - # Cintmax_t => "intmax_t", #Int64 - # Cuintmax_t => "uintmax_t", #UInt64 - # Csize_t => "size_t", #UInt - # Cssize_t => "ssize_t", #Int - # Cptrdiff_t => "ptrdiff_t", #Int - # Cwchar_t => "wchar_t", #Int32 - # Cwstring => - # Cfloat => "%f", #Float32 - Cdouble => "%f", #%e #Float64 -) - -""" -converts to text. returns "" for Nothing and empty Tuple. -""" -totext(x) = string(x) -totext(x::Nothing) = "" -totext(x::Tuple{}) = "" - -""" -Makes standalone executable. -""" -function exegen(funcalls) - - cd(mkpath("standalone")) do - # create `blank.ji` for initialization - julia_path = joinpath(Sys.BINDIR, Base.julia_exename()) - base_dir = dirname(Base.find_source_file("sysimg.jl")) - wd = pwd() - open(println, "blank.jl", "w") - cd(base_dir) do - run(`$(julia_path) --output-ji $(wd)/blank.ji $(wd)/blank.jl`) - end - - dir = pwd() - standalonedir = dir - bindir = string(Sys.BINDIR) - libdir = joinpath(dirname(Sys.BINDIR), "lib") - includedir = joinpath(dirname(Sys.BINDIR), "include", "julia") - if Sys.iswindows() - for fn in readdir(bindir) - if splitext(fn)[end] == ".dll" - cp(joinpath(bindir, fn), fn, force = true) - end - end - end - - flags = join((cflags(), ldflags(), ldlibs()), " ") - flags = Base.shell_split(flags) - wrapper = joinpath(@__DIR__, "embedding_wrapper.c") - if Sys.iswindows() - rpath = `` - elseif Sys.isapple() - rpath = `-Wl,-rpath,'@executable_path' -Wl,-rpath,'@executable_path/../lib'` - else - rpath = `-Wl,-rpath,\$ORIGIN:\$ORIGIN/../lib` - end - - for (func, tt, val) in funcalls - fname = nameof(func) - rettype = Base.return_types(func, tt)[1] - argtype = length(tt.types) > 0 ? tt.types[1] : Nothing - fmt = Cformatmap[rettype] - Ctxt = foldl(replace, - ( - "FUNNAME" => fname, - "CRETTYPE" => Cmap[rettype], - "RETFORMAT" => fmt, - "CARGTYPES" => Cmap[argtype], - "FUNARG" => totext(val), - ), - init = Ctemplate) - write("$fname.c", Ctxt) - m = StaticCompiler.irgen(func, tt) - # StaticCompiler.show_inttoptr(m) - # @show m - dlext = Libdl.dlext - exeext = Sys.iswindows() ? ".exe" : "" - if Sys.isapple() - o_file = `-Wl,-all_load $fname.o` - else - o_file = `-Wl,--whole-archive $fname.o -Wl,--no-whole-archive` - end - extra = Sys.iswindows() ? `-Wl,--export-all-symbols` : `` - write(m, "$fname.bc") - write_object(m, "$fname.o") - - run(`$shellcmd -shared -fpic -L$libdir -o lib$fname.$dlext $o_file -Wl,-rpath,$libdir -ljulia $extra`) - run(`$shellcmd -c -std=gnu99 -I$includedir -DJULIA_ENABLE_THREADING=1 -fPIC $fname.c`) - #run(`$shellcmd -o $fname $fname.o -L$libdir -L$standalonedir -Wl,--unresolved-symbols=ignore-in-object-files -Wl,-rpath,'.' -Wl,-rpath,$libdir -ljulia -l$fname -O2 $rpath $flags`) - run(`$shellcmd -o $fname $fname.o -L$libdir -L$standalonedir -Wl,-rpath,'.' -Wl,-rpath,$libdir -ljulia -l$fname -O2 $rpath $flags`) - end - end - -end diff --git a/src/irgen.jl b/src/irgen.jl deleted file mode 100644 index cc9811c4..00000000 --- a/src/irgen.jl +++ /dev/null @@ -1,300 +0,0 @@ - -struct LLVMNativeCode # thin wrapper - p::Ptr{Cvoid} -end - -function xlinfo(f, tt) - # get the method instance - world = typemax(UInt) - g = (args...) -> Cassette.overdub(ctx, f, args...) - meth = which(g, tt) - sig_tt = Tuple{typeof(g), tt.parameters...} - (ti, env) = ccall(:jl_type_intersection_with_env, Any, - (Any, Any), sig_tt, meth.sig)::Core.SimpleVector - - if VERSION >= v"1.2.0-DEV.320" - meth = Base.func_for_method_checked(meth, ti, env) - else - meth = Base.func_for_method_checked(meth, ti) - end - - return ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, - (Any, Any, Any, UInt), meth, ti, env, world) -end - -""" -Returns an LLVMNativeCode object for the function call `f` with TupleTypes `tt`. -""" -function raise_exception(insblock::BasicBlock, ex::Value) -end - -# const jlctx = Ref{LLVM.Context}() - -# function __init__() -# jlctx[] = LLVM.Context(convert(LLVM.API.LLVMContextRef, -# cglobal(:jl_LLVMContext, Nothing))) -# end - -""" - irgen(func, tt; - optimize = true, - optimize_llvm = true, - fix_globals = true, - overdub = true, - module_setup = (m) -> nothing) - -Generates Julia IR targeted for static compilation. -`ccall` and `cglobal` uses have pointer references changed to symbols -meant to be linked with libjulia and other libraries. - -`optimize` controls Julia-side optimization. `optimize_llvm` controls -optimization on the LLVM side. - -If `overdub == true` (the default), Cassette is used to swap out -`ccall`s with a tuple of library and symbol. - -`module_setup` is an optional function to control setup of modules. It takes an LLVM -module as input. -""" -function irgen(@nospecialize(func), @nospecialize(tt); - optimize = true, - optimize_llvm = true, - fix_globals = true, - overdub = true, - module_setup = (m) -> nothing) - # get the method instance - isa(func, Core.Builtin) && error("function is not a generic function") - world = typemax(UInt) - gfunc = overdub ? (args...) -> Cassette.overdub(ctx, func, args...) : func - meth = which(gfunc, tt) - sig_tt = Tuple{typeof(gfunc), tt.parameters...} - (ti, env) = ccall(:jl_type_intersection_with_env, Any, - (Any, Any), sig_tt, meth.sig)::Core.SimpleVector - - if VERSION >= v"1.2.0-DEV.320" - meth = Base.func_for_method_checked(meth, ti, env) - else - meth = Base.func_for_method_checked(meth, ti) - end - - linfo = ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, - (Any, Any, Any, UInt), meth, ti, env, world) - - current_method = nothing - last_method_instance = nothing - call_stack = Vector{Core.MethodInstance}() - global method_map = Dict{String,Core.MethodInstance}() - global dependencies = MultiDict{Core.MethodInstance,LLVM.Function}() - # set-up the compiler interface - function hook_module_setup(ref::Ptr{Cvoid}) - ref = convert(LLVM.API.LLVMModuleRef, ref) - module_setup(LLVM.Module(ref)) - end - function hook_raise_exception(insblock::Ptr{Cvoid}, ex::Ptr{Cvoid}) - insblock = convert(LLVM.API.LLVMValueRef, insblock) - ex = convert(LLVM.API.LLVMValueRef, ex) - raise_exception(BasicBlock(insblock), Value(ex)) - end - function postprocess(ir) - # get rid of jfptr wrappers - for llvmf in functions(ir) - startswith(LLVM.name(llvmf), "jfptr_") && unsafe_delete!(ir, llvmf) - end - - return - end - function hook_module_activation(ref::Ptr{Cvoid}) - ref = convert(LLVM.API.LLVMModuleRef, ref) - global ir = LLVM.Module(ref) - postprocess(ir) - - # find the function that this module defines - llvmfs = filter(llvmf -> !isdeclaration(llvmf) && - linkage(llvmf) == LLVM.API.LLVMExternalLinkage, - collect(functions(ir))) - llvmf = nothing - if length(llvmfs) == 1 - llvmf = first(llvmfs) - elseif length(llvmfs) > 1 - llvmfs = filter!(llvmf -> startswith(LLVM.name(llvmf), "julia_"), llvmfs) - if length(llvmfs) == 1 - llvmf = first(llvmfs) - end - end - insert!(dependencies, last_method_instance, llvmf) - method_map[name(llvmf)] = current_method - end - function hook_emit_function(method_instance, code, world) - push!(call_stack, method_instance) - end - function hook_emitted_function(method, code, world) - current_method = method - last_method_instance = pop!(call_stack) - # @show code - # dump(method, maxdepth=2) - # global mymeth = method - end - - params = Base.CodegenParams(cached=false, - track_allocations=false, - code_coverage=false, - static_alloc=false, - prefer_specsig=true, - module_setup=hook_module_setup, - module_activation=hook_module_activation, - raise_exception=hook_raise_exception, - emit_function=hook_emit_function, - emitted_function=hook_emitted_function, - ) - - # get the code - mod = let - ref = ccall(:jl_get_llvmf_defn, LLVM.API.LLVMValueRef, - (Any, UInt, Bool, Bool, Base.CodegenParams), - linfo, world, #=wrapper=#false, #=optimize=#false, params) - if ref == C_NULL - # error(jlctx[], "the Julia compiler could not generate LLVM IR") - end - - llvmf = LLVM.Function(ref) - LLVM.parent(llvmf) - end - - # the main module should contain a single jfptr_ function definition, - # e.g. jlcall_kernel_vadd_62977 - - # definitions = filter(f->!isdeclaration(f), functions(mod)) - definitions = Iterators.filter(f->!isdeclaration(f), collect(functions(mod))) - # definitions = collect(functions(mod)) - wrapper = let - fs = collect(Iterators.filter(f->startswith(LLVM.name(f), "jfptr_"), definitions)) - @assert length(fs) == 1 - fs[1] - end - - # the jlcall wrapper function should point us to the actual entry-point, - # e.g. julia_kernel_vadd_62984 - entry_tag = let - m = match(r"jfptr_(.+)_\d+", LLVM.name(wrapper)) - @assert m != nothing - m.captures[1] - end - unsafe_delete!(mod, wrapper) - entry = let - re = Regex("julia_$(entry_tag)_\\d+") - llvmcall_re = Regex("julia_$(entry_tag)_\\d+u\\d+") - fs = collect(Iterators.filter(f->occursin(re, LLVM.name(f)) && - !occursin(llvmcall_re, LLVM.name(f)), definitions)) - if length(fs) != 1 - compiler_error(func, tt, cap, "could not find single entry-point"; - entry=>entry_tag, available=>[LLVM.name.(definitions)]) - end - fs[1] - end - - LLVM.name!(entry, string(nameof(func))) - - # link in dependent modules - cache = Dict{String,String}() - for called_method_instance in keys(dependencies) - llvmfs = dependencies[called_method_instance] - - # link the first module - llvmf = popfirst!(llvmfs) - llvmfn = LLVM.name(llvmf) - link!(mod, LLVM.parent(llvmf)) - # process subsequent duplicate modules - for dup_llvmf in llvmfs - if Base.JLOptions().debug_level >= 2 - # link them too, to ensure accurate backtrace reconstruction - link!(mod, LLVM.parent(dup_llvmf)) - else - # don't link them, but note the called function name in a cache - dup_llvmfn = LLVM.name(dup_llvmf) - cache[dup_llvmfn] = llvmfn - end - end - end - # resolve function declarations with cached entries - for llvmf in filter(isdeclaration, collect(functions(mod))) - llvmfn = LLVM.name(llvmf) - if haskey(cache, llvmfn) - def_llvmfn = cache[llvmfn] - replace_uses!(llvmf, functions(mod)[def_llvmfn]) - unsafe_delete!(LLVM.parent(llvmf), llvmf) - end - end - # rename functions to something easier to decipher - # especially helps with overdubbed functions - for (fname, mi) in method_map - id = split(fname, "_")[end] - basename = mi.def.name - args = join(collect(mi.specTypes.parameters)[2:end], "_") - if basename == :overdub # special handling for Cassette - basename = string(mi.specTypes.parameters[3]) - basename = replace(basename, r"^typeof\(" => "") - basename = replace(basename, r"\)$" => "") - args = join(collect(mi.specTypes.parameters)[4:end], "_") - end - newname = join([basename, args, id], "_") - if haskey(functions(mod), fname) - name!(functions(mod)[fname], newname) - end - end - - d = find_ccalls(gfunc, tt) - fix_ccalls!(mod, d) - if fix_globals - fix_globals!(mod) - end - if optimize_llvm - optimize!(mod) - end - return mod -end - - -""" - optimize!(mod::LLVM.Module) - -Optimize the LLVM module `mod`. Crude for now. -Returns nothing. -""" -function optimize!(mod::LLVM.Module) - for llvmf in functions(mod) - startswith(LLVM.name(llvmf), "jfptr_") && unsafe_delete!(mod, llvmf) - startswith(LLVM.name(llvmf), "julia_") && LLVM.linkage!(llvmf, LLVM.API.LLVMExternalLinkage) - end - # triple = "wasm32-unknown-unknown-wasm" - # triple!(mod, triple) - # datalayout!(mod, "e-m:e-p:32:32-i64:64-n32:64-S128") - # LLVM.API.@apicall(:LLVMInitializeWebAssemblyTarget, Cvoid, ()) - # LLVM.API.@apicall(:LLVMInitializeWebAssemblyTargetMC, Cvoid, ()) - # LLVM.API.@apicall(:LLVMInitializeWebAssemblyTargetInfo, Cvoid, ()) - triple = "i686-pc-linux-gnu" - tm = TargetMachine(Target(triple), triple) - - ModulePassManager() do pm - # add_library_info!(pm, triple(mod)) - add_transform_info!(pm, tm) - ccall(:jl_add_optimization_passes, Cvoid, - (LLVM.API.LLVMPassManagerRef, Cint, Cint), - LLVM.ref(pm), Base.JLOptions().opt_level, 1) - - dead_arg_elimination!(pm) - global_optimizer!(pm) - global_dce!(pm) - strip_dead_prototypes!(pm) - - run!(pm, mod) - end - mod -end - -function write_object(mod::LLVM.Module, path) - host_triple = triple() - host_t = Target(host_triple) - TargetMachine(host_t, host_triple, "", "", LLVM.API.LLVMCodeGenLevelDefault, LLVM.API.LLVMRelocPIC) do tm - emit(tm, mod, LLVM.API.LLVMObjectFile, path) - end -end diff --git a/src/llvm.jl b/src/llvm.jl new file mode 100644 index 00000000..16e92333 --- /dev/null +++ b/src/llvm.jl @@ -0,0 +1,180 @@ +## The LLVM module on its way from Julia's code generation to an object, in order + +function locate_pointers_and_runtime_calls(mod) + for func ∈ mod.functions, bb ∈ func.blocks, inst ∈ bb.instructions + @debug "Inspecting instruction" inst + warned = false + for operand ∈ pointer_operands(inst) + warned |= inspect_pointer(inst, operand) + end + if warned + lines = split(string(func),"\n") + @warn("LLVM function generated warnings due to raw pointers embedded in the code. This will likely cause errors or undefined behaviour.", + func = join(lines[1:min(20, end)], "\n")) # just print the first 20 lines + end + end +end + +# The operands of `inst` that may be pointers to julia data or runtime functions +pointer_operands(inst) = () +pointer_operands(inst::Union{LLVM.LoadInst, LLVM.StoreInst, LLVM.RetInst, LLVM.BitCastInst}) = inst.operands +pointer_operands(inst::LLVM.CallInst) = (inst.called_operand,) + +isinttoptr(x) = x isa LLVM.ConstantExpr && occursin("inttoptr", string(x)) + +# The address embedded in an `inttoptr` constant, or `nothing` if it is not a known constant +function constant_address(x) + op = x.operands[1] + if op isa LLVM.ConstantExpr + op = op.operands[1] + end + op isa LLVM.ConstantInt ? convert(Int, op) : nothing +end + +# Warn if `operand` of `inst` is a raw pointer, returning whether it was +function inspect_pointer(inst, operand) + isinttoptr(operand) || return false + address = constant_address(operand) + if isnothing(address) + @warn("Found pointer reference to an unknown address", "llvm instruction" = inst) + else + frames = ccall(:jl_lookup_code_address, Any, (Ptr{Cvoid}, Cint,), Ptr{Cvoid}(address), 0) + data_warnings(inst, frames) + end + return true +end + +data_warnings(inst, frames) = for frame ∈ frames + fn, file, line, linfo, fromC, inlined = frame + @warn("Found pointer references to julia data", + "llvm instruction" = inst, + name = fn, + file = file, + line = line, + fromC = fromC, + inlined = inlined) +end + +""" + retarget!(mod::LLVM.Module, target::StaticTarget) + +Make the IR of a target that is retargeted (`is_retargeted(target)`: code that was made for the host's machine, for +another) the IR of that target: it gets the triple of the target, no data layout (the code generator that makes +the object has the target's), and no attributes that name the host's CPU and features. IR that has intrinsics of +the host's architecture is refused. +""" +function retarget!(mod::LLVM.Module, target::StaticTarget) + is_retargeted(target) || return mod + triple = target_triple(target) + family = llvm_family(first(split(triple, '-'))) + for f in LLVM.functions(mod) + m = match(r"^llvm\.(aarch64|arm|x86|wasm)\.", LLVM.name(f)) + isnothing(m) || m.captures[1] == family || throw(ArgumentError("the program uses `$(LLVM.name(f))`, an intrinsic of the code generator of the host's architecture: it can not be made for $triple")) + attrs = LLVM.function_attributes(f) + for kind in ("target-cpu", "target-features", "tune-cpu") + delete!(attrs, kind) + end + end + LLVM.triple!(mod, triple) + LLVM.datalayout!(mod, "") + return mod +end + +# `int main(int argc, char **argv)` that calls the function `entry` of the module +# Includes `__stack_chk_guard`, which a C library that expect one needs somewhere. +# A module that has no `entry` is refused. +# `prologue(builder, mod)`, if given, adds to the start of `main`, before the call. +function add_main_wrapper!(mod::LLVM.Module, entry::AbstractString, target::StaticTarget; prologue = nothing) + haskey(LLVM.functions(mod), entry) || throw(ArgumentError("the module has no function `$entry` to be called by `main`")) + f = LLVM.functions(mod)[entry] + i32, ptr = LLVM.IntType(32), LLVM.PointerType() + fty = LLVM.function_type(f) + nparams = length(LLVM.parameters(fty)) + nparams in (0, 2) || throw(ArgumentError("`$entry` takes nothing or an `argc` and an `argv`, not $nparams arguments")) + haskey(LLVM.functions(mod), "main") && throw(ArgumentError("the module has a `main` already")) + main = LLVM.Function(mod, "main", LLVM.FunctionType(i32, [i32, ptr])) + LLVM.@dispose builder = LLVM.IRBuilder() begin + LLVM.position!(builder, LLVM.at_end(LLVM.BasicBlock(main, "entry"))) + isnothing(prologue) || prologue(builder, mod) # (what the program does before its entry point is called) + args = LLVM.Value[] + if nparams == 2 + argc_type, argv_type = LLVM.parameters(fty) + argc, argv = LLVM.parameters(main) + push!(args, LLVM.sext!(builder, argc, argc_type)) # (an `Int`, usually: `argc` is 32 bits) + push!(args, argv) + end + r = LLVM.call!(builder, fty, f, args) + rty = LLVM.return_type(fty) + result = if rty isa LLVM.VoidType + LLVM.ConstantInt(i32, 0) + elseif rty isa LLVM.IntegerType + LLVM.width(rty) > 32 ? LLVM.trunc!(builder, r, i32) : LLVM.width(rty) < 32 ? LLVM.zext!(builder, r, i32) : r + else + LLVM.ConstantInt(i32, 0) # (what is not an integer is not an exit status) + end + LLVM.ret!(builder, result) + end + triple = target_triple(target) + if !(isapple(target) || startswith(triple, "wasm") || iswindows(target)) && !haskey(LLVM.globals(mod), "__stack_chk_guard") + guard = LLVM.GlobalVariable(mod, ptr, "__stack_chk_guard") + LLVM.initializer!(guard, LLVM.const_inttoptr(LLVM.ConstantInt(LLVM.IntType(64), rand(UInt) >> 1), ptr)) + end + return mod +end + +# Export the compiled entry points from a Windows DLL +function add_dllexport!(mod::LLVM.Module, funcs; demangle=true, target=nothing) + for name_f in compiled_names(funcs; demangle, target) + llvmf = get(mod.functions, name_f, nothing) + if llvmf !== nothing && !isdeclaration(llvmf) + llvmf.dllstorage = LLVM.DLLStorageClass.Export + end + end +end + +## Generating object files from LLVM + +""" + emit_object(mod::LLVM.Module, target::StaticTarget) -> Vector{UInt8} + emit_object(ir::AbstractString, target::StaticTarget) -> Vector{UInt8} + +The object file (the bytes) of the IR, which was made for the host and retargeted (see [`StaticTarget`](@ref) and [`retarget!`](@ref)), for the target: by the code generator of Julia's LLVM if it has one for the +triple, and else by the `llc` of the target. The CPU and the features are those of the target's `machine`, and the code is position independent (WebAssembly: static). +""" +function emit_object(mod::LLVM.Module, target::StaticTarget) + check_retargeted(target) + julia_llvm_has(target_triple(target)) || return emit_object_llc(string(mod), target) + m = target.machine + tm = LLVM.TargetMachine(LLVM.Target(; triple = m.triple), m.triple; cpu = m.cpu, features = m.features, opt_level = LLVM.API.LLVMCodeGenLevelDefault, + reloc = startswith(m.triple, "wasm") ? LLVM.API.LLVMRelocStatic : LLVM.API.LLVMRelocPIC) + try + return LLVM.emit(tm, mod, LLVM.API.LLVMObjectFile) + finally + LLVM.dispose(tm) + end +end +function emit_object(ir::AbstractString, target::StaticTarget) + check_retargeted(target) + julia_llvm_has(target_triple(target)) || return emit_object_llc(ir, target) + LLVM.@dispose ctx = LLVM.Context() begin + mod = parse(LLVM.Module, ir) + try + return emit_object(mod, target) + finally + LLVM.dispose(mod) + end + end +end +check_retargeted(target::StaticTarget) = is_retargeted(target) || throw(ArgumentError("only the objects of a target that is made for by retargeting are made by `emit_object` (see `StaticTarget`)")) + +# Emit the object file via `llc`, if it has a code generator that Julia's LLVM has not +function emit_object_llc(ir::AbstractString, target::StaticTarget) + m = target.machine + isnothing(target.llc) && throw(ArgumentError("No object can be made for $(m.triple): Julia's LLVM has no code generator for it, and no `llc` is given (`StaticTarget(...; llc = ...)`) with which to compile LLVM IR")) + mktempdir() do dir + ll, obj = joinpath(dir, "module.ll"), joinpath(dir, "module.o") + write(ll, ir) + run(`$(target.llc) -O2 -filetype=obj -mtriple=$(m.triple) -mcpu=$(isempty(m.cpu) ? "generic" : m.cpu) -mattr=$(m.features) -relocation-model=pic $ll -o $obj`) + return read(obj) + end +end diff --git a/src/mangling.jl b/src/mangling.jl new file mode 100644 index 00000000..b3515b1a --- /dev/null +++ b/src/mangling.jl @@ -0,0 +1,264 @@ +# The names of the entry points in the object, which depends on `demangle`: +# * `true`, the names that Julia has (`fix_name`); +# * `false`, `julia_`, the name of the function, and the types of its arguments (`julia_my_add_Int64_Int64`, `julia_main`); +# * `:itanium`, the names that a C++ compiler makes (`_Z6my_addll`, see below). +# Two entry points of one name would be two functions of the same name in the module, which LLVM refuses (as an error of the linker, which does not say which entry points they are). +function compiled_names(funcs; demangle::Union{Bool,Symbol} = true, target = nothing) + demangle in (true, false, :itanium) || throw(ArgumentError("`demangle` is `true`, `false` or `:itanium`, not `$(repr(demangle))`")) + base = String[fix_name(f) for (f, _) in funcs] + if demangle === :itanium + long64 = !(target isa StaticTarget && iswindows(target)) # (`long` has 32 bits on Windows) + names = String[itanium_name(f, tt; long64) for (f, tt) in funcs] + for name in unique(names) + count(==(name), names) > 1 || continue + throw(ArgumentError("More than one entry point is named `$name` ($(describe_entries([funcs[i] for i in findall(==(name), names)])))")) + end + return names + elseif demangle === true + for name in unique(base) + group = findall(==(name), base) + length(group) > 1 || continue + throw(ArgumentError("More than one entry point is named `$name` ($(describe_entries([funcs[i] for i in group]))). " * + "With `demangle = true` the name of an entry point is the name of its function, regardless of argument types, " * + "so each needs a function of its own (for example `$(name)_int(a, b) = $name(a, b)` and `$(name)_struct(s) = $name(s)`); " * + "with `demangle = false` the names include argument types (e.g., `julia_$(name)_Int64_Int64`) while `demangle = :itanium` follows the Itanium C++ convention")) + end + return base + else + names = String[add_suffix(name, argument_suffix(tt)) for (name, (_, tt)) in zip(base, funcs)] + # (what the types do not tell apart, or what is too long, is numbered: the oldest method first, and in the order that they are given in for those that are as old) + for suffixed in unique(names) + same = findall(==(suffixed), names) + (length(same) > 1 || length(suffixed) > 120) || continue + for (rank, i) in enumerate(sort(same; by = i -> (definition_world(funcs[i]...), i))) + names[i] = string(base[i], "_", rank) + end + end + for name in unique(names) + count(==(name), names) > 1 || continue + throw(ArgumentError("More than one entry point is named `$name` ($(describe_entries([funcs[i] for i in findall(==(name), names)])))")) + end + return "julia_" .* names + end +end + +# the types of the arguments as part of a name: `Int64_Int64`, `Vector_Int64`, `Ptr_Ptr_UInt8`, and nothing for a function that takes none +add_suffix(name, suffix) = isempty(suffix) ? name : string(name, "_", suffix) +function argument_suffix(tt) + types = Base.to_tuple_type(tt).parameters + isempty(types) && return "" + parts = map(types) do T + text = replace(string(T), r"(?:[A-Za-z_]\w*\.)+" => "") # (without the modules: `Main.hello_struct`) + text = replace(fix_name(text), r"_+" => "_") + strip(text, '_') + end + return join(parts, "_") +end + +describe_entries(entries) = join(("$(nameof(f))$(tt isa Tuple ? tt : (tt,))" for (f, tt) in entries), " and ") + +# the world in which the method that is called for these types was defined (later than all that is not a method of Julia code, if there is none) +function definition_world(f, tt) + try + return Base.which(f, Base.to_tuple_type(tt)).primary_world + catch + return typemax(UInt) + end +end + +# Itanium C++ ABI names for entry points (`demangle = :itanium`): `my_add(Int, Int)` is `_Z6my_addll`, which `c++filt` reads as `my_add(long, long)` and a C++ program that declares +# `long my_add(long, long)` links to. https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling +# +# The types are the C and C++ types that the Julia types have, where there are: the numbers (`Int32` is `int`, `UInt8` is `unsigned char`, `Float64` is `double`, `Bool` is `bool`, `Char` is `char32_t`), +# `Ptr{T}` (`T*`, and `Ptr{Cvoid}` is `void*`), `Cstring` (`const char*`) and `Complex` (C99's `_Complex`). Julia's own types (`Vector{Int}`, structs, tuples, ...) are named as C++ classes are, in the namespace of +# their module (`Main` is the global one): `Array` for `Vector{Int}`, and the parameters that are not types are values (`Val{3}` is `Val<3l>`), or names where they have none (`Val{:a}` is `Val`). +# A Julia type is not a C++ type, so these names are for linking by name and for reading, not for a C++ compiler to check the types of. Not done: the operators of C++ for the functions that Julia has them for +# (`+` is `pl`: here `_`), the return types of functions, and the types that C++ has qualifiers for. +# +# Repeated parts are replaced by the substitutions that the ABI has (`S_`, `S0_`, ...), as a compiler does, so that the names are the same as a C++ compiler's for the types that it has. + +# a type, as the ABI writes it +abstract type MType end +struct MBuiltin <: MType; code::String; end +struct MPointer <: MType; to::MType; end +struct MConstant <: MType; of::MType; end +struct MComplex <: MType; of::MType; end +struct MNamed <: MType # `scope::name`, and `` if `args` is not `nothing` + scope::Vector{String} + name::String + args::Union{Nothing,Vector{Any}} # types (`MType`) and values (`MValue`) +end +struct MValue # `LE`, for the parameter that is a number + code::String + text::String +end +struct MPack # `J...E`, the parameters that a template takes any number of (Julia's `Tuple`) + items::Vector{Any} +end + +mangled_length(s::AbstractString) = string(ncodeunits(s), s) +# the parts of a name as a prefix of the ABI: `3Foo3Bar` +prefix_text(parts) = join(mangled_length.(parts)) + +# the key by which the ABI finds a part again (its spelling without the substitutions) +key(t::MBuiltin) = t.code +key(t::MPointer) = "P" * key(t.to) +key(t::MConstant) = "K" * key(t.of) +key(t::MComplex) = "C" * key(t.of) +key(t::MNamed) = prefix_text([t.scope; t.name]) * (t.args === nothing ? "" : template_text(t.args)) +key(v::MValue) = string("L", v.code, v.text, "E") +key(p::MPack) = string("J", join(key.(p.items)), "E") +template_text(args) = string("I", join(key.(args)), "E") + +mutable struct Mangler + substitutions::Vector{String} +end +Mangler() = Mangler(String[]) + +# `S_`, `S0_`, `S1_`, ..., `S9_`, `SA_`, ..., `SZ_`, `S10_`, ... (the first is `S_`, and then the number, written in base 36, of the one before) +substitution(i::Int) = i == 0 ? "S_" : string("S", uppercase(string(i - 1; base = 36)), "_") + +# the substitution that stands for `k`, if it has been seen +function seen(m::Mangler, k::AbstractString) + i = findfirst(==(k), m.substitutions) + return i === nothing ? nothing : substitution(i - 1) +end + +emit!(m::Mangler, t::MBuiltin) = t.code +emit!(m::Mangler, v::MValue) = string("L", v.code, v.text, "E") +emit!(m::Mangler, p::MPack) = string("J", join(emit!(m, a) for a in p.items), "E") +function emit!(m::Mangler, t::MType) + k = key(t) + s = seen(m, k) + s === nothing || return s + out = emit_new!(m, t) + push!(m.substitutions, k) # (after its parts, which are in the name before it) + return out +end +emit_new!(m::Mangler, t::MPointer) = "P" * emit!(m, t.to) +emit_new!(m::Mangler, t::MConstant) = "K" * emit!(m, t.of) +emit_new!(m::Mangler, t::MComplex) = "C" * emit!(m, t.of) + +# the text of a name (`3Foo`, or `N3Foo3BarE` if it has a scope): the longest prefix of the scope that has been seen is a substitution, and the prefixes that have not are registered. The name itself is registered by the caller, except +# a template's, which is before its parameters (`template` is the list of them) +function emit_name!(m::Mangler, parts::Vector{String}; template::Union{Nothing,Vector{Any}} = nothing) + n = length(parts) + out = IOBuffer() + start = 1 + for j in n-1:-1:1 + s = seen(m, prefix_text(parts[1:j])) + if s !== nothing + print(out, s) + start = j + 1 + break + end + end + for j in start:n-1 + print(out, mangled_length(parts[j])) + push!(m.substitutions, prefix_text(parts[1:j])) + end + if template === nothing + print(out, mangled_length(parts[n])) + text = String(take!(out)) + return n == 1 ? text : string("N", text, "E") + end + # (a template that has been seen is `S_I...E`: a substitution is not in `N...E`) + name = seen(m, prefix_text(parts)) + name === nothing || return n == 1 ? string(name, template_arguments!(m, template)) : string("N", name, template_arguments!(m, template), "E") + push!(m.substitutions, prefix_text(parts)) + arguments = template_arguments!(m, template) + text = string(String(take!(out)), mangled_length(parts[n])) + return n == 1 ? string(text, arguments) : string("N", text, arguments, "E") +end + +template_arguments!(m::Mangler, args) = string("I", join(emit!(m, a) for a in args), "E") + +function emit_new!(m::Mangler, t::MNamed) + parts = [t.scope; t.name] + return emit_name!(m, parts; template = t.args) +end + +## Julia types as the types of the ABI + +# the names of the modules that a type or function is in, without `Main` +function module_scope(mod::Module) + names = String[string(s) for s in fullname(mod)] + !isempty(names) && names[1] == "Main" && popfirst!(names) + return String[identifier(n) for n in names] +end + +# a name that C++ has: letters, digits and `_`, and not starting with a digit +function identifier(s::AbstractString) + t = fix_name(String(s)) + isempty(t) && return "_" + return isdigit(first(t)) ? "_" * t : t +end + +# the name of a type or function: that of the function for the type of a function (`typeof(sin)` is `#sin`), without the `#` of the names that Julia makes +type_identifier(T::DataType) = identifier(lstrip(string(T.name.name), '#')) + +function value_argument(p, long64::Bool) + p isa Bool && return MValue("b", p ? "1" : "0") + if p isa Integer + code = builtin_code(typeof(p), long64) + text = p < 0 ? string("n", -BigInt(p)) : string(p) + return MValue(code, text) + end + p isa Char && return MValue("Di", string(UInt32(p))) + p isa Symbol && return MNamed(String[], "Symbol_" * identifier(string(p)), nothing) + return MNamed(String[], "Value_" * identifier(string(p)), nothing) # (a value that has no spelling in C++) +end + +const BUILTIN_CODES = Dict{DataType,String}(Bool => "b", Int8 => "a", UInt8 => "h", Int16 => "s", UInt16 => "t", Int32 => "i", UInt32 => "j", Int128 => "n", UInt128 => "o", + Float16 => "Dh", Float32 => "f", Float64 => "d", Char => "Di") +function builtin_code(T::DataType, long64::Bool) + T === Int64 && return long64 ? "l" : "x" # (`long` is 32 bits on Windows) + T === UInt64 && return long64 ? "m" : "y" + return get(BUILTIN_CODES, T, "") +end + +# a Julia type as a type of the ABI (`long64`: whether `long` is 64 bits, as it is except on Windows) +function mangled_type(@nospecialize(T), long64::Bool) + if T isa DataType + code = builtin_code(T, long64) + isempty(code) || return MBuiltin(code) + T === Cstring && return MPointer(MConstant(MBuiltin("c"))) + T === Cwstring && return MPointer(MConstant(MBuiltin("w"))) + if T <: Ptr && length(T.parameters) == 1 + to = T.parameters[1] + return MPointer(to === Cvoid || to === Nothing ? MBuiltin("v") : mangled_type(to, long64)) + end + if T <: Complex && length(T.parameters) == 1 && haskey(BUILTIN_CODES, T.parameters[1]) && T.parameters[1] <: AbstractFloat + return MComplex(mangled_type(T.parameters[1], long64)) + end + params = T.parameters + items = Any[p isa Type || p isa TypeVar ? mangled_type(p, long64) : value_argument(p, long64) for p in params] + args = T <: Tuple ? Any[MPack(items)] : isempty(params) ? nothing : items + # (a function's type is named by the function, in the module of the function: `typeof(Base.sin)` is `Base::sin`) + scope = module_scope(parentmodule(T)) + return MNamed(scope, type_identifier(T), args) + elseif T isa TypeVar + return MNamed(String[], "TypeVar_" * identifier(string(T.name)), nothing) + elseif T isa UnionAll + return mangled_type(Base.unwrap_unionall(T), long64) + elseif T isa Union + return MNamed(String[], "Union", Any[mangled_type(t, long64) for t in Base.uniontypes(T)]) + end + return MNamed(String[], "Type_" * identifier(string(T)), nothing) +end + +""" + itanium_name(f, types; long64 = true) -> String + +The name of the entry point `f(types...)` in the Itanium C++ ABI: `_Z`, the name of the function (in the namespace of its module), and the types of the arguments (`v` for none). +`long64` says whether `long` has 64 bits (`Int64` is `l`, and `x`, `long long`, if not: Windows). +""" +function itanium_name(f, types; long64::Bool = true) + ts = Base.to_tuple_type(types).parameters + m = Mangler() + parts = [module_scope(parentmodule(typeof(f))); identifier(string(nameof(f)))] + # (the name of a function: its scope is substituted and registered as that of a type is, and the name is not) + name = emit_name!(m, parts) + params = isempty(ts) ? "v" : join(emit!(m, mangled_type(T, long64)) for T in ts) + return string("_Z", name, params) +end diff --git a/src/overdub.jl b/src/overdub.jl deleted file mode 100644 index 9a0015be..00000000 --- a/src/overdub.jl +++ /dev/null @@ -1,33 +0,0 @@ -# Implements contextual dispatch through Cassette.jl - -using Cassette - -## -# Convert two-arg `ccall` to single arg. -## -function transform(ctx, ref) - CI = ref.code_info - ismatch = x -> begin - Base.Meta.isexpr(x, :foreigncall) && - Base.Meta.isexpr(x.args[1], :call) - end - replace = x -> begin - y = Expr(x.head, Any[x.args[1].args[2], x.args[2:end]...]) - Expr(x.head, x.args[1].args[2], x.args[2:end]...) - end - Cassette.replace_match!(replace, ismatch, CI.code) - return CI -end - -const Pass = Cassette.@pass transform - -Cassette.@context Ctx -const ctx = Cassette.disablehooks(Ctx(pass = Pass)) - -### -# Rewrite functions -### - -#@inline Cassette.overdub(ctx::Ctx, ::typeof(+), a::T, b::T) where T<:Union{Float32, Float64} = add_float_contract(a, b) - -contextualize(f::F) where F = (args...) -> Cassette.overdub(ctx, f, args...) diff --git a/src/quirks.jl b/src/quirks.jl new file mode 100644 index 00000000..23d2059e --- /dev/null +++ b/src/quirks.jl @@ -0,0 +1,197 @@ +Base.Experimental.@MethodTable(method_table) +Base.Experimental.@MethodTable(empty_table) # (no overrides: `method_table = StaticCompiler.empty_table` compiles with Julia's own methods) + +""" +```julia +@device_override old_bad_method(arg1::Type1, arg2::Type2) = new_good_method(arg1, arg2) +``` +Override a non-static-compilable method (e.g. `old_bad_method(::Type1, ::Type2)`) +with a more compileable replacement. +### Examples +``` +@device_override @noinline Core.throw_inexacterror(f::Symbol, ::Type{T}, val) where {T} = + @print_and_throw c"Inexact conversion" +``` +""" +macro device_override(ex) + code = quote + $Base.Experimental.@overlay($StaticCompiler.method_table, $ex) + end + return esc(code) +end + +""" + @print_and_throw message + +Print `message` (a C string, `c"..."`) and stop the program with exit status 1: what the replacements of +the methods that throw (see [`@device_override`](@ref)) do where a program has no exception to throw. +""" +macro print_and_throw(err) + quote + println($err) + libcexit(Int32(1)) + end +end +libcexit(x::Int32) = @symbolcall exit(x::Int32)::Nothing + +# error.jl +@device_override @noinline Base.error(::AbstractString) = + @print_and_throw c"error() called" +@device_override @noinline Base.error(::Vararg{Any}) = + @print_and_throw c"error() called" + +# tuple.jl and essentials.jl +@device_override @noinline Base.first(::Tuple{}) = + @print_and_throw c"Tuple must be non-empty" +@device_override @noinline Base.tail(::Tuple{}) = + @print_and_throw c"Cannot call tail on an empty tuple" + +# reduce.jl +@device_override @noinline Base._empty_reduce_error() = + @print_and_throw c"Reducing over an empty collection is not allowed" + +# char.jl +@device_override @noinline Base.throw_code_point_err(u::Integer) = + @print_and_throw c"Invalid Unicode code point" +@device_override @noinline Base.throw_invalid_char(c::AbstractChar) = + @print_and_throw c"Invalid character" + +# math.jl +@device_override @noinline Base.Math.throw_complex_domainerror(f::Symbol, x) = + @print_and_throw c"This operation requires a complex input to return a complex result" +@device_override @noinline Base.Math.throw_exp_domainerror(x) = + @print_and_throw c"Exponentiation yielding a complex result requires a complex argument" +@device_override @noinline Base.Math.throw_complex_domainerror_neg1(f::Symbol, x) = + @print_and_throw c"This operation requires a complex input to return a complex result" + +# intfuncs.jl +@device_override @noinline Base.throw_domerr_powbysq(::Any, p) = + @print_and_throw c"Cannot raise an integer to a negative power" +@device_override @noinline Base.__throw_gcd_overflow(a, b) = + @print_and_throw c"gcd overflow" + +# checked.jl +@device_override @noinline Base.Checked.throw_overflowerr_binaryop(op, x, y) = + @print_and_throw c"Binary operation overflowed" +@device_override @noinline Base.Checked.throw_overflowerr_negation(x) = + @print_and_throw c"Negation overflowed" +@device_override function Base.Checked.checked_abs(x::Base.Checked.SignedInt) + r = ifelse(x < 0, -x, x) + r < 0 && @print_and_throw(c"Checked arithmetic: cannot compute |x|") + r +end + +# boot.jl +@device_override @noinline Core.throw_inexacterror(f::Symbol, ::Type{T}, val) where {T} = + @print_and_throw c"Inexact conversion" + +# float.jl: conversions of floats to integers throw an `InexactError` if out of range or inexact +for Ti in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128), + Tf in (Float16, Float32, Float64) + # the bounds are checked as in Base + if Ti <: Unsigned || sizeof(Ti) < sizeof(Tf) + inrange_round = :($(Tf(typemin(Ti)) - one(Tf)) < x < $(Tf(typemax(Ti)) + one(Tf))) + inrange = :($(Tf(typemin(Ti))) <= x < $(Tf(typemax(Ti)) + one(Tf))) + else + inrange_round = inrange = :($(Tf(typemin(Ti))) <= x < $(Tf(typemax(Ti)))) + end + @eval begin + @device_override function Base.round(::Type{$Ti}, x::$Tf, ::RoundingMode{:ToZero}) + $inrange_round || @print_and_throw c"Inexact conversion" + unsafe_trunc($Ti, x) + end + @device_override function (::Type{$Ti})(x::$Tf) + ($inrange && isinteger(x)) || @print_and_throw c"Inexact conversion" + unsafe_trunc($Ti, x) + end + end +end + +# array shapes +@device_override @noinline Base.Broadcast.throwdm(axdest, axsrc) = + @print_and_throw c"Destination axes are not compatible with source axes" +@device_override @noinline Base.throw_setindex_mismatch(X, I) = + @print_and_throw c"Tried to assign the wrong number of elements" +@device_override @noinline Base.throw_checksize_error(A, sz) = + @print_and_throw c"Output array is the wrong size" +@device_override @noinline Base.throw_eachindex_mismatch_indices(::IndexStyle, inds...) = + @print_and_throw c"All inputs to eachindex must have the same indices" +@device_override @noinline Base._throw_argerror(s) = + @print_and_throw c"Invalid argument" +@device_override @noinline Base.throw_boundserror(A, I) = + @print_and_throw c"Out-of-bounds array access" + +# used by `checkbounds` on recent Julia versions (nightly / 1.15+) +@static if isdefined(Base, :_throw_boundserror_indices) + @device_override @noinline Base._throw_boundserror_indices(A) = + @print_and_throw c"Out-of-bounds array access" + @device_override @noinline Base._throw_boundserror_indices(A, i1, I...) = + @print_and_throw c"Out-of-bounds array access" +end + +# trig.jl +@device_override @noinline Base.Math.sincos_domain_error(x) = + @print_and_throw c"sincos(x) is only defined for finite x." +# the trig domain error helpers differ between Julia versions +for f in (:sin_domain_error, :cos_domain_error, :tan_domain_error, :throw_finite_domainerror) + isdefined(Base.Math, f) && @eval @device_override @noinline Base.Math.$f(x) = + @print_and_throw c"Trigonometric functions are only defined for finite x." +end +for f in (:asin_domain_error, :acos_domain_error, :acosh_domain_error, :atanh_domain_error) + isdefined(Base.Math, f) && @eval @device_override @noinline Base.Math.$f(x) = + @print_and_throw c"Inverse (hyperbolic) trigonometric function called outside of its domain." +end + +# int.jl: the checked integer division intrinsics throw a `DivideError` from the generated +# code, so check the arguments ourselves and use the unchecked intrinsics +@device_override function Base.div(x::T, y::T) where {T<:Base.BitSigned} + y == 0 && @print_and_throw c"Integer division error" + y == -1 && x == typemin(T) && @print_and_throw c"Integer division error" + Core.Intrinsics.sdiv_int(x, y) +end +@device_override function Base.div(x::T, y::T) where {T<:Base.BitUnsigned} + y == 0 && @print_and_throw c"Integer division error" + Core.Intrinsics.udiv_int(x, y) +end +# (`fld` and `cld` of signed integers, with wrapping arithmetic by the intrinsics (`+%` is syntax of Julia 1.14 only): Julia 1.14 has methods that check the arguments and throw themselves, which do not go through `div` above. The same code, with the error that is ours) +@device_override function Base.div(x::T, y::T, ::typeof(RoundDown)) where {T<:Base.BitSigned} + (iszero(y) | ((x == typemin(T)) & (y == -1))) && @print_and_throw c"Integer division error" + k = 8sizeof(T) - 1 + dsign = y >> k + nsign = (x | Core.Intrinsics.add_int(x, dsign)) >> k + return Core.Intrinsics.add_int(Core.Intrinsics.sdiv_int(Core.Intrinsics.add_int(x, dsign - nsign), y), nsign ⊻ dsign) +end +@device_override function Base.div(x::T, y::T, ::typeof(RoundUp)) where {T<:Base.BitSigned} + (iszero(y) | ((x == typemin(T)) & (y == -1))) && @print_and_throw c"Integer division error" + s = ifelse(y < 0, -(x < 0) % T, (x > 0) % T) + return Core.Intrinsics.add_int(Core.Intrinsics.sdiv_int(Core.Intrinsics.sub_int(x, s), y), T(s != 0)) +end +@device_override function Base.rem(x::T, y::T) where {T<:Base.BitSigned} + y == 0 && @print_and_throw c"Integer division error" + y == -1 ? zero(T) : Core.Intrinsics.srem_int(x, y) +end +@device_override function Base.rem(x::T, y::T) where {T<:Base.BitUnsigned} + y == 0 && @print_and_throw c"Integer division error" + Core.Intrinsics.urem_int(x, y) +end + +# rational.jl +@device_override @noinline Base.__throw_rational_argerror_zero(T) = + @print_and_throw c"Invalid rational: zero//zero" +@device_override @noinline Base.__throw_negate_unsigned() = + @print_and_throw c"Cannot negate unsigned number" +@device_override @noinline Base.__throw_rational_numerator_typemin(T) = + @print_and_throw c"Rational numerator is typemin" + + +@static if isdefined(StaticTools, :Bumper) + Bumper = StaticTools.Bumper + @device_override @noinline Bumper.AllocBufferImpl.oom_error() = + @print_and_throw c"alloc: Buffer out of memory. This might be a sign of a memory leak." + @device_override @noinline Bumper.Internals.esc_err() = + @print_and_throw c"Tried to return a PtrArray from a `no_escape` block. If you really want to do this, evaluate Bumper.allow_ptrarray_to_escape() = true" + + # Just to make the compiler's life a little easier, let's not make it fetch and elide the current task + # since tasks don't actually exist on-device. + @device_override Bumper.Internals.get_task() = 0 +end diff --git a/src/serialize.jl b/src/serialize.jl deleted file mode 100644 index 57256501..00000000 --- a/src/serialize.jl +++ /dev/null @@ -1,242 +0,0 @@ - -""" -A context structure for holding state related to serializing Julia -objects. A key component is an `IOBuffer` used to hold the serialized -result. -""" -struct SerializeContext - io::IOBuffer - store::Dict{Any,Any} # Meant to map Julia object to variable name - init::Vector{Any} # Expressions to run initially -end -SerializeContext(io::IOBuffer = IOBuffer()) = SerializeContext(io, Dict(), Vector{Expr}()) - -const _td = IdDict( - Any => :jl_any_type, - Float64 => :jl_float64_type, - Float32 => :jl_float32_type, - Int64 => :jl_int64_type, - Int32 => :jl_int32_type, - Int16 => :jl_int16_type, - Int8 => :jl_int8_type, - UInt64 => :jl_uint64_type, - UInt32 => :jl_uint32_type, - UInt16 => :jl_uint16_type, - UInt8 => :jl_uint8_type, - Cint => :jl_int32_type, - Cvoid => :jl_any_type, - Array => :jl_array_type, - Array{Any,1} => :jl_array_any_type, - Array{Int32,1} => :jl_array_int32_type, - Array{UInt8,1} => :jl_array_uint8_type, - ErrorException => :jl_errorexception_type, - DataType => :jl_datatype_type, - UnionAll => :jl_unionall_type, - Union => :jl_union_type, - Core.TypeofBottom => :jl_typeofbottom_type, - TypeVar => :jl_tvar_type, -) - -const _t = IdDict() - -for (t,s) in _td - _t[t] = :(unsafe_load(cglobal($(QuoteNode(s)), Type))) -end - -const _gd = IdDict( - Core => :jl_core_module, - Main => :jl_main_module, - nothing => :jl_nothing, - () => :jl_emptytuple, - Core.svec() => :jl_emptysvec, - UndefRefError() => :jl_undefref_exception, -) - -const _g = IdDict() - -for (x,s) in _gd - _g[x] = :(unsafe_load(cglobal($(QuoteNode(s)), Any))) -end - -""" - serialize(ctx::SerializeContext, x) - -Serialize `x` into the context object `ctx`. `ctx.io` is the `IOBuffer` where the -serialized results are stored. Get the result with `take!(ctx.io)`. - -This function returns an expression that will deserialize the object. Several `serialize` -methods can be called recursively to build up deserialization code for nested objects. -The expression returned is meant to be `eval`ed into a function that can be called -to do the serialization. - -The deserialization code should be pretty low-level code that can be compiled -relatively easily. It especially shouldn't use global variables. - -Serialization / deserialization code can use `ctx` to hold state information. - -Some simple types like boxed variables do not need to write anything to `ctx.io`. -They can return an expression that directly creates the object. -""" -function serialize(ctx::SerializeContext, @nospecialize(x)) - haskey(_g, x) && return _g[x] - # TODO: fix this major kludge. - if nfields(x) > 0 - return Expr(:tuple, (serialize(ctx, getfield(x,i)) for i in 1:nfields(x))...) - end - return :(unsafe_load(cglobal(:jl_emptytuple, Any))) -end - -function serialize(ctx::SerializeContext, @nospecialize(t::DataType)) - if haskey(_t, t) - return _t[t] - elseif haskey(ctx.store, t) - return ctx.store[t] - else - # primary = unwrap_unionall(t.wrapper) - name = gensym(Symbol(:type, "-", t.name.name)) - ctx.store[t] = name - e = quote - $name = let - local tn = $(serialize(ctx, t.name)) - # names = $(serialize(ctx, t.names)) - local super = $(serialize(ctx, t.super)) - local parameters = $(serialize(ctx, t.parameters)) - local types = $(serialize(ctx, t.types)) - local ndt = ccall(:jl_new_datatype, Any, - (Any, Any, Any, Any, Any, Any, Cint, Cint, Cint), - tn, tn.module, super, parameters, #=names=# unsafe_load(cglobal(:jl_any_type, Any)), types, - $(t.abstract), $(t.mutable), $(t.ninitialized)) - # tn.wrapper = ndt.name.wrapper - # ccall(:jl_set_const, Cvoid, (Any, Any, Any), tn.module, tn.name, tn.wrapper) - ndt - # ty = tn.wrapper - # $(ctx.types[string(t)]) = ndt - # hasinstance = serialize(ctx, ) - # $(if isdefined(primary, :instance) && !isdefined(t, :instance) - # # use setfield! directly to avoid `fieldtype` lowering expecting to see a Singleton object already on ty - # :(Core.setfield!(ty, :instance, ccall(:jl_new_struct, Any, (Any, Any...), ty))) - # end) - end - end - push!(ctx.init, e) - return name - end -end - -function serialize(ctx::SerializeContext, tn::Core.TypeName) - haskey(ctx.store, tn) && return ctx.store[tn] - name = gensym(Symbol(:typename, "-", tn.name)) - ctx.store[tn] = name - e = quote - $name = ccall(:jl_new_typename_in, Ref{Core.TypeName}, (Any, Any), - # $(serialize(ctx, tn.name)), Main #=__deserialized_types__ =# ) - $(serialize(ctx, tn.name)), unsafe_load(cglobal(:jl_main_module, Any)) #=__deserialized_types__ =# ) - end - push!(ctx.init, e) - return name -end - -function serialize(ctx::SerializeContext, mi::Core.MethodInstance) - return :(unsafe_load(cglobal(:jl_emptytuple, Any))) -end - -function serialize(ctx::SerializeContext, x::String) - advance!(ctx.io) - v = Vector{UInt8}(x) - ioptr = ctx.io.ptr - write(ctx.io, v) - quote - unsafe_string(Vptr + $(ioptr - 1), $(length(v))) - end -end - -function serialize(ctx::SerializeContext, x::Symbol) - haskey(ctx.store, x) && return ctx.store[x] - name = gensym(Symbol(:symbol, "-", x)) - ctx.store[x] = name - e = quote - $name = ccall(:jl_symbol_n, Any, (Ptr{UInt8}, Csize_t), $(serialize(ctx, string(x))), $(length(string(x)))) - # ccall(:jl_set_global, Cvoid, (Any, Any, Any), unsafe_load(cglobal(:jl_main_module, Any)), $(QuoteNode(name)), x) - end - push!(ctx.init, e) - return name -end - - - -# Define functions that return an expression. Example: -# serialize(ctx::SerializeContext, x::Int) = :(ccall(:jl_box_int64, Any, (Int,), $x)) -for (fun, type) in (:jl_box_int64 => Int64, :jl_box_int32 => Int32, :jl_box_int8 => Int16, :jl_box_int8 => Int8, - :jl_box_uint64 => UInt64, :jl_box_uint32 => UInt32, :jl_box_uint8 => UInt16, :jl_box_uint8 => UInt8, - :jl_box_voidpointer => Ptr{Cvoid}, - :jl_box_float64 => Float64, :jl_box_float32 => Float32) - @eval serialize(ctx::SerializeContext, x::$type) = Expr(:call, :ccall, QuoteNode($(QuoteNode(fun))), Any, Expr(:tuple, $type), x) -end -serialize(ctx::SerializeContext, x::Char) = :(ccall(:jl_box_char, Any, (UInt32,), $x)) -serialize(ctx::SerializeContext, x::Bool) = :(ccall(:jl_box_bool, Any, (UInt8,), $x)) - -function serialize(ctx::SerializeContext, a::Tuple) - length(a) == 0 && return :(unsafe_load(cglobal(:jl_emptytuple, Any))) - Expr(:tuple, (serialize(ctx, x) for x in a)...) -end - -function serialize(ctx::SerializeContext, a::Core.SimpleVector) - length(a) == 0 && return :(unsafe_load(cglobal(:jl_emptysvec, Any))) - Expr(:call, Expr(:., :Core, QuoteNode(:svec)), (serialize(ctx, x) for x in a)...) -end - -advance!(io) = write(io, repeat('\0', -rem(io.ptr - 1, 8, RoundUp))) # Align data to 8 bytes - -function serialize(ctx::SerializeContext, a::Array{T,N}) where {T,N} - elty = eltype(a) - aty = typeof(a) - dims = size(a) - atys = serialize(ctx, aty) - if isbitstype(elty) - advance!(ctx.io) - ioptr = ctx.io.ptr - write(ctx.io, a) - if N == 1 - advance!(ctx.io) - ioptr = ctx.io.ptr - write(ctx.io, a) - quote - p = Vptr + $ioptr - 1 - ccall(:jl_ptr_to_array_1d, $aty, (Any, Ptr{Cvoid}, Csize_t, Cint), $atys, p, $(length(a)), false) - end - else - dms = serialize(ctx, dims) - advance!(ctx.io) - ioptr = ctx.io.ptr - write(ctx.io, a) - quote - p = Vptr + $ioptr - 1 - ccall(:jl_ptr_to_array, $aty, (Any, Ptr{Cvoid}, Any, Int32), $atys, p, $dms, false) - end - end - else - idx = Int[] - e = Array{Any}(undef, length(a)) - @inbounds for i in eachindex(a) - if isassigned(a, i) - e[i] = serialize(ctx, a[i]) - push!(idx, i) - end - end - aname = gensym() - resulte = [quote - # $aname = Array{$elty, $(length(dims))}(undef, $dims) - $aname = ccall(:jl_new_array, $aty, (Any, Any), $atys, $(serialize(ctx, dims))) - end] - for i in idx - push!(resulte, quote - # unsafe_store!(pointer($aname), $(e[i]), $i) - unsafe_store!(convert(Ptr{Any}, pointer($aname)), $(e[i]), $i) - # unsafe_store!(convert(Ptr{Csize_t}, pointer($aname)), pointer_from_objref($(e[i])), $i) - # @inbounds $aname[$i] = $(e[i]) - end) - end - push!(resulte, :($aname = $aname)) - Expr(:block, resulte...) - end -end diff --git a/src/target.jl b/src/target.jl new file mode 100644 index 00000000..a5f8b06d --- /dev/null +++ b/src/target.jl @@ -0,0 +1,240 @@ +""" + Machine(triple, cpu, features) + +A machine that code is made for: the LLVM `triple`, the `cpu` (`""` for a generic cpu of a given architecture) and the cpu `features` (`"+neon,-sve"`, ...). +""" +struct Machine + triple::String + cpu::String + features::String +end + +""" +```julia + StaticTarget() # Native target + StaticTarget(platform_or_triple) # Specific target with generic CPU (a `Base.BinaryPlatforms.Platform` or a triple string) + StaticTarget(platform_or_triple, cpu::String) # Specific target with specific CPU + StaticTarget(platform_or_triple, cpu::String, features::String) # Specific target with specific CPU and features + StaticTarget(target::StaticTarget; toolchain, llc, julia_runtime, can_throw) # A copy with some of those changed +``` +A target for the compilation: what the program is made for (`machine`, the triple, the CPU and the features), how it is linked (`toolchain`), and what the compiled code may do (`julia_runtime`, `can_throw`). +By default `StaticTarget()` is the native target. The keywords of the constructors are + +* `toolchain`: how the target is linked: a [`CCToolchain`](@ref) (a C compiler: a `String` or a `Cmd` is the compiler of one) or an [`LLDToolchain`](@ref); the default is the host's `clang`. +* `julia_runtime = false`: whether the code may call the runtime of Julia. +* `can_throw = true`: whether the code may throw errors (a function that cannot, is compiled without the machinery for it). +* `retarget = false`, `llc = nothing`: see below. + +Beware that currently the compilation assumes that the code is on the host so platform specific code like: +```julia + Sys.isapple() ... +``` +does not behave as expected. + +**Retargeting.** Julia's code generation makes the IR for the `machine` of the target, unless the target is retargeted. If the target is not the host's (`retarget = true`, or `retarget = host`, a `StaticTarget` whose machine is +the one to make the IR for; and always where Julia's LLVM has no code generator for the target: x86-64 on a build of Julia that has only AArch64 and WebAssembly, say), the IR is made for the host and then given the target's triple, without +the host's CPU or features (see [`retarget!`](@ref)): IR can be made for it (`generate_ir`, `llvm_to_clang = true`), and the object is made by the code generator of Julia's LLVM if it has one for the triple, else by the external `llc` +(a `Cmd` or a path, of the LLVM version that Julia has), or `clang`. + +The fields can be set (`set_compiler!`, `set_toolchain!`, `set_runtime!`), and the copy constructor makes a changed copy, which leaves the original as it was: `StaticTarget(target; toolchain = CCToolchain("/opt/homebrew/bin/aarch64-unknown-linux-gnu-gcc"))`. +""" +mutable struct StaticTarget + machine::Machine # What the program is made for + codegen::Union{Machine,Nothing} # What Julia's code generation makes the IR for if the target is retargeted (see above), and else `nothing`: the IR is made for `machine` + toolchain::Union{Toolchain,Nothing} # How the target is linked, else the default of `default_toolchain` + llc::Union{Cmd,Nothing} # The `llc` that makes the objects of a retargeted target that Julia's LLVM has no code generator for + julia_runtime::Bool + can_throw::Bool +end +StaticTarget() = StaticTarget(HostPlatform(), LLVM.host_cpu_name(), LLVM.host_cpu_features()) + +# The target for a platform or a triple, with the generic CPU of its architecture unless `cpu` and `features` say otherwise. +# `retarget = true` makes the IR for the generic CPU of the host (or `retarget = host_target`, a `StaticTarget` of the host: the machine of that one). +function StaticTarget(target::Union{Platform,AbstractString}, cpu::AbstractString = "", features::AbstractString = ""; + toolchain = nothing, + retarget::Union{Bool,StaticTarget} = false, + llc = nothing, + julia_runtime::Bool = false, + can_throw::Bool = true, + ) + init_llvm_targets() + triple = LLVM.normalize(llvm_triple(target isa Platform ? clean_triple(target) : String(target))) + machine = Machine(triple, cpu, features) + codegen = retarget isa StaticTarget ? retarget.machine : retarget || !julia_llvm_has(triple) ? host_generic_machine() : nothing + return StaticTarget(machine, codegen, as_toolchain(toolchain), as_llc(llc), julia_runtime, can_throw) +end +# A copy with some changes +StaticTarget(target::StaticTarget; toolchain = target.toolchain, llc = target.llc, julia_runtime::Bool = target.julia_runtime, can_throw::Bool = target.can_throw, codegen::Union{Machine,Nothing} = target.codegen) = + StaticTarget(target.machine, codegen, as_toolchain(toolchain), as_llc(llc), julia_runtime, can_throw) + +# Ensure llc is either a Cmd or Nothing +as_llc(::Nothing) = nothing +as_llc(llc::Cmd) = llc +as_llc(llc::AbstractString) = `$llc` + +""" +```julia +set_compiler!(target::StaticTarget, compiler) +``` +Set the C compiler that links the target (a `String` or a `Cmd`): its toolchain becomes a [`CCToolchain`](@ref) of it. For example: +```julia +set_compiler!(StaticTarget("aarch64-unknown-linux-gnu"), "/opt/homebrew/bin/aarch64-unknown-linux-gnu-gcc") +``` +""" +set_compiler!(target::StaticTarget, compiler::Union{AbstractString,Cmd}) = (target.toolchain = CCToolchain(compiler); target) + +""" +```julia +set_toolchain!(target::StaticTarget, toolchain::Toolchain) +``` +Set how the target is linked: a [`CCToolchain`](@ref) (a C compiler) or an [`LLDToolchain`](@ref) (`lld` and the C library of a sysroot). +""" +set_toolchain!(target::StaticTarget, tc::Toolchain) = (target.toolchain = tc; target) + +"Set whether the code of the target may call the runtime of Julia." +set_runtime!(target::StaticTarget, julia_runtime::Bool) = (target.julia_runtime = julia_runtime; target) + +clean_triple(platform::Platform) = arch(platform) * os_str(platform) * libc_str(platform) +# To emit a COFF object, LLVM seems to want `x86_64-w64-windows-gnu` in place of `x86_64-w64-mingw32` +llvm_triple(triple::AbstractString) = replace(String(triple), r"-mingw(?:32|64)$" => "-windows-gnu") + +# The code generators of every target that Julia's LLVM has, which are not all there until they are initialized (GPUCompiler does it when it first compiles, which is after a target is made) +const LLVM_TARGETS_INITIALIZED = Ref(false) +function init_llvm_targets() + LLVM_TARGETS_INITIALIZED[] && return + LLVM.InitializeAllTargetInfos() + LLVM.InitializeAllTargets() + LLVM.InitializeAllTargetMCs() + LLVM.InitializeAllAsmPrinters() + LLVM.InitializeAllAsmParsers() + LLVM_TARGETS_INITIALIZED[] = true + return +end + +# The host's machine without its CPU and its features, which are not those of another architecture's code (and not to be in its IR) +host_generic_machine() = Machine(LLVM.default_triple(), "", "") + +# The triple that the target is for +target_triple(target::StaticTarget) = target.machine.triple + +# Whether the IR is made for another machine (the host's) than the target's, and retargeted (see `retarget!`) +is_retargeted(target::StaticTarget) = !isnothing(target.codegen) + +# The machine that Julia's code generation makes the IR for +codegen_machine(target::StaticTarget) = something(target.codegen, target.machine) + + +# Default to native +struct StaticCompilerTarget{MT} <: GPUCompiler.AbstractCompilerTarget + triple::String + cpu::String + features::String + julia_runtime::Bool + can_throw::Bool + method_table::MT +end + +# Both `opt` and `optlevel` seem to be unused in current GPUCompiler versions, +# so this particular implementation is somewhat vestigial, but could be expanded in the future +struct StaticCompilerParams <: GPUCompiler.AbstractCompilerParams + opt::Bool + optlevel::Int +end +function StaticCompilerParams(; opt=false, + optlevel=Base.JLOptions().opt_level + ) + return StaticCompilerParams(opt, optlevel) +end + +module RuntimeStubs + # the runtime library + signal_exception() = return + malloc(sz) = ccall("extern malloc", llvmcall, Csize_t, (Csize_t,), sz) + report_oom(sz) = return + report_exception(ex) = return + report_exception_name(ex) = return + report_exception_frame(idx, func, file, line) = return +end + + +function GPUCompiler.llvm_machine(target::StaticCompilerTarget) + triple = GPUCompiler.llvm_triple(target) + + t = LLVM.Target(triple=triple) + + tm = LLVM.TargetMachine(t, triple; target.cpu, target.features, reloc=LLVM.RelocMode.PIC) + LLVM.asm_verbosity!(tm, true) + + return tm +end +GPUCompiler.llvm_triple(target::StaticCompilerTarget) = target.triple +GPUCompiler.runtime_module(::GPUCompiler.CompilerJob{<:StaticCompilerTarget}) = RuntimeStubs +GPUCompiler.can_throw(job::GPUCompiler.CompilerJob{<:StaticCompilerTarget}) = job.config.target.can_throw +GPUCompiler.uses_julia_runtime(job::GPUCompiler.CompilerJob{<:StaticCompilerTarget}) = job.config.target.julia_runtime +GPUCompiler.method_table(@nospecialize(job::GPUCompiler.CompilerJob{<:StaticCompilerTarget})) = job.config.target.method_table + + +# The `GPUCompiler.CompilerJob` of `func` for the argument types `types`, +# for the codegen machine of `target`, with its `julia_runtime` and `can_throw`, and the `method_table`. +# Other keywords (`name`, `strip`, `validate`, ...) are those of `GPUCompiler.CompilerConfig`. +# `params` is the `GPUCompiler.AbstractCompilerParams` of the job. Other packages may pass a type of their own, +# to specialize GPUCompiler's functions (`inference_params`, `optimize!`, ...) for their compilations only, +# without adding methods for `StaticCompilerTarget` and `StaticCompilerParams`, which are ours. +# All the methods above are for any `params`. +function static_job(@nospecialize(func), @nospecialize(types); + name = fix_name(func), + kernel::Bool = false, + target::StaticTarget = StaticTarget(), + params::GPUCompiler.AbstractCompilerParams = StaticCompilerParams(), + method_table = method_table, + kwargs... +) + source = GPUCompiler.methodinstance(typeof(func), Base.to_tuple_type(types)) + codegen = codegen_machine(target) + gputarget = StaticCompilerTarget(codegen.triple, codegen.cpu, codegen.features, target.julia_runtime, target.can_throw, method_table) + config = GPUCompiler.CompilerConfig(gputarget, params; name, kernel, kwargs...) + return GPUCompiler.CompilerJob(source, config) +end + +## The target + +# Determine whether or not Julia's LLVM has the code generator for the triple +function julia_llvm_has(triple::AbstractString) + init_llvm_targets() + try + LLVM.Target(; triple = String(triple)) + return true + catch err + # (`ArgumentError`: "No available targets are compatible with triple") + err isa ArgumentError || rethrow() + return false + end +end + +# Whether an object can be made for the target here: always if the code is made for it, and if it is retargeted, if Julia's LLVM or an `llc` has its code generator +can_emit_object(target::StaticTarget) = !is_retargeted(target) || julia_llvm_has(target_triple(target)) || !isnothing(target.llc) + +# Make any OS-specific choices on the basis of the target, not the host +iswindows(target::StaticTarget) = occursin(r"windows|mingw|msvc|cygwin"i, target_triple(target)) +isapple(target::StaticTarget) = occursin(r"apple|darwin|macos"i, target_triple(target)) + +# The shared library extension of the target +dlext(target::StaticTarget) = isapple(target) ? "dylib" : iswindows(target) ? "dll" : "so" + +# Whether the IR has to go through an external compiler (`clang`, `llc`) to be an object: on Windows (always), or where Julia's LLVM has no code generator for the target +# (An `LLDToolchain` links objects, which IR is not: for it an object that cannot be made says so, by `generate_obj`, and does not go on as IR.) +needs_ir(target::StaticTarget) = (iswindows(target) || !can_emit_object(target)) && !(target.toolchain isa LLDToolchain) + +# The architecture and the operating system that a triple says (not by `Platform`, which does not parse every triple that LLVM has: `x86_64-w64-windows-gnu`, `wasm64-unknown-unknown`) +triple_arch(triple::AbstractString) = (arch = String(first(split(triple, '-'))); arch in ("arm64", "aarch64") ? "aarch64" : arch in ("amd64", "x86_64") ? "x86_64" : arch) +triple_os(triple::AbstractString) = occursin(r"windows|mingw|msvc|cygwin"i, triple) ? :windows : occursin(r"apple|darwin|macos"i, triple) ? :apple : occursin("linux", triple) ? :linux : :other + +# `clang` makes code for its own host unless it is told the target (it replaces the triple of the IR, which `-Wno-override-module` hides) +function clang_target_flags(target::StaticTarget) + triple, host = target_triple(target), LLVM.default_triple() + foreign = is_retargeted(target) || triple_arch(triple) != triple_arch(host) || triple_os(triple) != triple_os(host) + return foreign ? `--target=$triple` : `` +end + +# The family that an architecture's intrinsics (`llvm..`) are named by +llvm_family(arch::AbstractString) = startswith(arch, "aarch64") || startswith(arch, "arm64") ? "aarch64" : startswith(arch, "arm") ? "arm" : arch in ("x86_64", "i686", "i386", "x86") ? "x86" : startswith(arch, "wasm") ? "wasm" : arch diff --git a/src/toolchain.jl b/src/toolchain.jl new file mode 100644 index 00000000..97d48cca --- /dev/null +++ b/src/toolchain.jl @@ -0,0 +1,219 @@ +## Linking: how the object code of a target becomes an executable or a shared library + +@doc """ + Toolchain + +How a target is linked. [`link`](@ref) and [`output_name`](@ref) have a method for each type; new targets (another system, another kind of executable) are new types with those two methods. +`CCToolchain` (a C compiler that compiles and links, as before) is the default, [`LLDToolchain`](@ref) links objects by itself (for a Linux or WebAssembly target that the host's compiler can not link for). +Give a target its toolchain by `StaticTarget(...; toolchain = ...)` (or `StaticTarget(target; toolchain = ...)`, a copy that has another). +""" Toolchain + +""" +```julia +CCToolchain(cc::Cmd) +``` + +Compile and/or link using a C compiler (`clang` from `Clang_jll` by default). +This compiler takes what has been output by `generate_obj` or `generate_ir` (whether objects (`.o`) or LLVM IR (`.ll`)), +compiles if needed, and links the result. + +This is the traditional default route for native compilation of executables and shared libraries +(where the target system is the same as the host system), +but provides somewhat more limited possibilities for control of cross-compilation. +""" +struct CCToolchain <: Toolchain + cc::Cmd + builtins::Bool +end +CCToolchain(cc::Cmd; builtins::Bool = false) = CCToolchain(cc, builtins) +CCToolchain(cc::AbstractString; builtins::Bool = false) = CCToolchain(`$cc`; builtins) +Base.:(==)(a::CCToolchain, b::CCToolchain) = a.cc == b.cc && a.builtins == b.builtins + +# the libraries that a flavor of `LLDToolchain` links with, if none are given +const DEFAULT_LLD_LIBS = Dict( + :mingw => ["mingw32", "mingwex", "moldname", "msvcrt", "advapi32", "shell32", "user32", "kernel32"], + :gnu => ["c", "m", "dl", "pthread"], # (`dl` and `pthread` are libraries of their own before glibc 2.34, and empty ones in it) + :darwin => ["System"], + :wasm => String[], +) + +""" +```julia +LLDToolchain(flavor; sysroot = nothing, dynamic_linker = nothing, libs = nothing, flags = ``, builtins = true) +``` + +Link objects with the `lld` that Julia has, without a C compiler or its driver. `flavor` is +* `:gnu`: ELF for Linux. The start files and the libraries of the C library are in `sysroot`, a directory that has the `lib` of a glibc (the `Glibc_jll` artifact provides one). See [`glibc_sysroot`](@ref). +* `:darwin`: Mach-O for macOS. `sysroot` is the path to the SDK (by default that of Xcode `xcrun --show-sdk-path`); where the host has none, an SDK must be given. See [`macos_sdk`](@ref). +* `:mingw`: PE for Windows, with the libraries of MinGW-w64 in `sysroot` (the `Mingw_jll` artifact provides one). See [`mingw_sysroot`](@ref). +* `:wasm`: WebAssembly, a `.wasm` module. + +Keyword arguments include +* `sysroot` - the path to the relevant system library, as a `String`, or `nothing` to defer to defaults +* `dynamic_linker` - the dynamic linker to use, as a `String`, or `nothing` to defer to defaults +* `libs` - the libraries to link against, as a `String`, or `nothing` to defer to defaults +* `flags` - any optional flags to be passed to the linker +* `builtins` - if true, any llvm builtins which the target does not support will be replaced with emulated versions; see [`add_builtins!`](@ref)). +""" +struct LLDToolchain <: Toolchain + flavor::Symbol + sysroot::Union{String,Nothing} + dynamic_linker::Union{String,Nothing} + libs::Vector{String} + flags::Cmd + builtins::Bool +end +function LLDToolchain(flavor::Symbol; sysroot = nothing, dynamic_linker = nothing, libs = nothing, flags = ``, builtins::Bool = true) + flavor in keys(DEFAULT_LLD_LIBS) || throw(ArgumentError("the flavor of `LLDToolchain` is `:gnu`, `:darwin`, `:mingw` or `:wasm`, not `$(repr(flavor))`")) + libs === nothing && (libs = DEFAULT_LLD_LIBS[flavor]) + return LLDToolchain(flavor, isnothing(sysroot) ? nothing : String(sysroot), isnothing(dynamic_linker) ? nothing : String(dynamic_linker), String.(libs), flags isa Cmd ? flags : `$flags`, builtins) +end + +# Ensure toolchain is either a Toolchain or Nothing +as_toolchain(x::Toolchain) = x +as_toolchain(x::Cmd) = CCToolchain(x) +as_toolchain(x::AbstractString) = CCToolchain(x) +as_toolchain(::Nothing) = nothing + + +""" + output_name(toolchain, target, name; kind = :executable) -> String + +The file name of what is made from `name` for the target: `name.exe` for a Windows executable, `name.wasm` for WebAssembly, the shared library extension of the target for `kind = :shared`. +""" +output_name(::Toolchain, target, name::AbstractString; kind::Symbol = :executable) = + kind === :shared ? "$name.$(dlext(target))" : iswindows(target) ? "$name.exe" : String(name) +output_name(tc::LLDToolchain, target, name::AbstractString; kind::Symbol = :executable) = + tc.flavor === :wasm ? "$name.wasm" : + tc.flavor === :darwin ? (kind === :shared ? "$name.dylib" : String(name)) : + tc.flavor === :mingw ? (kind === :shared ? "$name.dll" : "$name.exe") : + kind === :shared ? "$name.so" : String(name) + +# whether the objects that the toolchain links need the builtins in them (`add_builtins!`) +uses_builtins(tc::Union{CCToolchain,LLDToolchain}) = tc.builtins +uses_builtins(::Union{Toolchain,Nothing}) = false + +""" + glibc_sysroot(platform_or_triple_or_target) -> String + +The directory of the C library of a Linux target (for `LLDToolchain(:gnu; sysroot = ...)`): the artifact of `Glibc_jll` for its architecture, which is fetched if it is not there, for any host. Needs `using Glibc_jll, Pkg`. + +**Which glibc** is the version of the `Glibc_jll` of the environment (see [`glibc_version`](@ref)), and a program that is linked with it needs that glibc or a newer one where it runs. The newest, 2.35, which is the default, +makes programs that need glibc 2.34 or newer (Ubuntu 22.04, Debian 12, ...): they do not run on older systems (Ubuntu 20.04, RHEL 8, ...). To make programs that run on older ones, pin an older `Glibc_jll` in the environment +(`Pkg.add(name = "Glibc_jll", version = "2.17")`, or in `[compat]`): 2.17.1 has x86-64, i686 and ppc64le, and 2.19.1 also aarch64, armv7l and armv6l, and programs that are linked with them need only glibc 2.17. +What a newer glibc has is not there to link with: the functions that were added after the pinned version (`posix_spawn_file_actions_addchdir_np` of 2.29, for example) are undefined symbols. +""" +function glibc_sysroot end + +""" + glibc_version(sysroot) -> Union{VersionNumber,Nothing} + +The version of the glibc that a sysroot has (`nothing` if it has none that is known): the version that programs that are linked with it need, or a newer one, where they run. It is read from the banner of its `libc.so.6`. +""" +function glibc_version(sysroot::AbstractString) + libc = try; joinpath(crt_directory(sysroot), "libc.so.6"); catch; return nothing; end + isfile(libc) || return nothing + bytes = read(libc) + marker = Vector{UInt8}("release version ") + i = findfirst(marker, bytes) + i === nothing && return nothing + text = String(bytes[last(i)+1:min(end, last(i) + 16)]) + m = match(r"^(\d+)\.(\d+)", text) + return m === nothing ? nothing : VersionNumber(parse(Int, m.captures[1]), parse(Int, m.captures[2])) +end + +""" + mingw_sysroot(platform_or_triple_or_target) -> String + +The directory of the MinGW-w64 libraries of a Windows target (for `LLDToolchain(:mingw; sysroot = ...)`): the artifact of `Mingw_jll` for its architecture, which is fetched if it is not there, for any host. +Needs `using Mingw_jll, Pkg`. +""" +function mingw_sysroot end + +""" + macos_sdk() -> String + +The SDK of macOS that a program for macOS is linked with (for `LLDToolchain(:darwin; sysroot = ...)`, which uses it when it has no `sysroot`): the environment variable `SDKROOT`, or that of Xcode (`xcrun --show-sdk-path`) on a Mac. +Where the host has neither, the SDK is given to `LLDToolchain` as `sysroot`: Apple's license has it used on Apple hardware, and a copy of one has to be provided (for example `MacOSX11.3.sdk.tar.xz` of +[phracker/MacOSX-SDKs](https://github.com/phracker/MacOSX-SDKs), which BinaryBuilder uses). +""" +function macos_sdk() + haskey(ENV, "SDKROOT") && return ENV["SDKROOT"] + sdk = xcode_sdk() + isnothing(sdk) || return sdk + throw(ArgumentError("no SDK of macOS is known: give `sysroot = ...` to `LLDToolchain(:darwin)` (the directory of an SDK, like `MacOSX11.3.sdk`), or set `SDKROOT`")) +end + +# The SDK of Xcode (`xcrun --show-sdk-path`), or `nothing` where there is none (not a Mac, or no Xcode or Command Line Tools: `xcrun` fails). Asked once: the command takes some milliseconds, +# and a compile asks for it several times (the selected Xcode does not change in a session; `SDKROOT` is read each time, and is not what is remembered). +const XCODE_SDK = Ref{Union{String,Nothing}}() +const XCODE_SDK_KNOWN = Ref(false) +function xcode_sdk() + if !XCODE_SDK_KNOWN[] + XCODE_SDK[] = if Sys.isapple() && !isnothing(Sys.which("xcrun")) + errors = IOBuffer() + try + String(strip(read(pipeline(`xcrun --show-sdk-path`; stderr = errors), String))) + catch err + err isa ProcessFailedException || rethrow() + @warn """`xcrun --show-sdk-path` failed, so the SDK of macOS cannot be found, and programs for macOS cannot be linked with it. + $(strip(String(take!(errors)))) + To fix this, do one of: + * install the Command Line Tools: run `xcode-select --install` in a terminal + * select an installed Xcode: `sudo xcode-select -s /Applications/Xcode.app/Contents/Developer` + * point `SDKROOT` at an SDK, e.g. `ENV["SDKROOT"] = "/path/to/MacOSX11.3.sdk"` (or pass `sysroot = ...` to `LLDToolchain(:darwin)`) + Meanwhile the system `clang` is used, with whatever SDK it finds itself. (This warning is shown once.)""" maxlog = 1 + nothing + end + else + nothing + end + XCODE_SDK_KNOWN[] = true + end + return XCODE_SDK[] +end + +# the version of an SDK, which is in its `SDKSettings.json` (and `plist`) +function sdk_version(sdk::AbstractString) + for file in ("SDKSettings.json", "SDKSettings.plist") + path = joinpath(sdk, file) + isfile(path) || continue + m = match(r"\"Version\"\s*:\s*\"(\d+(?:\.\d+)*)\"|Version\s*(\d+(?:\.\d+)*)", read(path, String)) + m === nothing || return something(m.captures[1], m.captures[2]) + end + return "11.0" +end + +# The toolchain of a target: its own, or the default: the host's C compiler driver +default_toolchain(::StaticTarget) = CCToolchain(clang()) +toolchain(target::StaticTarget) = isnothing(target.toolchain) ? default_toolchain(target) : target.toolchain # (not `something`, which would find the default, and run `xcrun`, whatever the target has) + +# Generally prefer Clang_jll clang (which should probably be at least as new as Julia's LLVM) +# and fall back to the system one on platforms where Clang_jll is not available or not expected to work +function clang() + Clang_jll.is_available() || return `clang` # Fall back to system clang if Clang_jll is not available + cmd = Clang_jll.clang() + # Clang_jll may not know where to find the macOS SDK (e.g. for `-lSystem`) + if Sys.isapple() && !haskey(ENV, "SDKROOT") + sdk = xcode_sdk() + isnothing(sdk) && return `clang` # Fall back to system clang if we can't figure out the SDK path + cmd = addenv(cmd, "SDKROOT" => sdk) + end + return cmd +end + +# the directory of a sysroot that has the start files of the C library +function crt_directory(sysroot::AbstractString) + for d in ("lib", "usr/lib", "lib64", "usr/lib64", "usr/lib/aarch64-linux-gnu", "usr/lib/x86_64-linux-gnu", "lib/aarch64-linux-gnu", "lib/x86_64-linux-gnu") + isfile(joinpath(sysroot, d, "crt1.o")) && return joinpath(sysroot, d) + end + throw(ArgumentError("`$sysroot` has no `crt1.o`: the `sysroot` of a `:gnu` `LLDToolchain` is a directory that has the `lib` of a glibc (the `Glibc_jll` artifact for the platform of the target is one)")) +end + +# the loader that a program of the architecture asks for, where it is on the system that it runs on +function default_dynamic_linker(target::StaticTarget) + a = llvm_family(first(split(target_triple(target), '-'))) + a == "x86" && return "/lib64/ld-linux-x86-64.so.2" + a == "aarch64" && return "/lib/ld-linux-aarch64.so.1" + throw(ArgumentError("no dynamic linker is known for $(target_triple(target)): give `dynamic_linker` to `LLDToolchain`")) +end \ No newline at end of file diff --git a/src/utils.jl b/src/utils.jl deleted file mode 100644 index 0fdf7a7c..00000000 --- a/src/utils.jl +++ /dev/null @@ -1,56 +0,0 @@ - -function julia_to_llvm(@nospecialize x) - isboxed = Ref{UInt8}() - # LLVMType(ccall(:jl_type_to_llvm, LLVM.API.LLVMTypeRef, (Any, Ref{UInt8}), x, isboxed)) # noserialize - LLVMType(ccall(:julia_type_to_llvm, LLVM.API.LLVMTypeRef, (Any, Ref{UInt8}), x, isboxed)) # julia v1.1.1 -end - -const jl_value_t_ptr = julia_to_llvm(Any) -const jl_value_t = eltype(jl_value_t_ptr) -# const jl_value_t_ptr_ptr = LLVM.PointerType(jl_value_t_ptr) -# # cheat on these for now: -# const jl_datatype_t_ptr = jl_value_t_ptr -# const jl_unionall_t_ptr = jl_value_t_ptr -# const jl_typename_t_ptr = jl_value_t_ptr -# const jl_sym_t_ptr = jl_value_t_ptr -# const jl_svec_t_ptr = jl_value_t_ptr -# const jl_module_t_ptr = jl_value_t_ptr -# const jl_array_t_ptr = jl_value_t_ptr -# -# const bool_t = julia_to_llvm(Bool) -# const int8_t = julia_to_llvm(Int8) -# const int16_t = julia_to_llvm(Int16) -# const int32_t = julia_to_llvm(Int32) -# const int64_t = julia_to_llvm(Int64) -# const uint8_t = julia_to_llvm(UInt8) -# const uint16_t = julia_to_llvm(UInt16) -# const uint32_t = julia_to_llvm(UInt32) -# const uint64_t = julia_to_llvm(UInt64) -# const float_t = julia_to_llvm(Float32) -# const double_t = julia_to_llvm(Float64) -# const float32_t = julia_to_llvm(Float32) -# const float64_t = julia_to_llvm(Float64) -# const void_t = julia_to_llvm(Nothing) -# const size_t = julia_to_llvm(Int) -# -# const int8_t_ptr = LLVM.PointerType(int8_t) -# const void_t_ptr = LLVM.PointerType(void_t) - -function module_setup(mod::LLVM.Module) -# triple!(mod, "wasm32-unknown-unknown-wasm") -# datalayout!(mod, "e-m:e-p:32:32-i64:64-n32:64-S128") -end - -llvmmod(native_code) = - LLVM.Module(ccall(:jl_get_llvm_module, LLVM.API.LLVMModuleRef, - (Ptr{Cvoid},), native_code.p)) - -function Base.write(mod::LLVM.Module, path::String) - open(io -> write(io, mod), path, "w") -end - - -walk(f, x) = true -# walk(f, x::Instruction) = foreach(c->walk(f,c), operands(x)) -# walk(f, x::Instruction) = f(x) || foreach(c->walk(f,c), operands(x)) -walk(f, x::ConstantExpr) = f(x) || foreach(c->walk(f,c), operands(x)) diff --git a/test/Project.toml b/test/Project.toml index 6e781cc6..3c809d13 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,6 +1,18 @@ [deps] -Formatting = "59287772-0a20-5a39-b81b-1366585eb4c0" +Bumper = "8ce10254-0962-460f-a3d8-1f77fea1446e" +Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" +Glibc_jll = "452aa2e7-e185-58db-8ff9-d3c1fa4bc997" +LLD_jll = "d55e3150-da41-5e91-b323-ecfd1eec6109" LLVM = "929cbde3-209d-540e-8aea-75f648917ca0" Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +LoopVectorization = "bdcacae8-1622-11e9-2a5c-532679323890" +ManualMemory = "d125e4d3-2237-4719-b19c-fa641b8a4667" +Mingw_jll = "2d94bacf-4d71-535d-a47c-45e808015115" +Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +StaticTools = "86c06d3c-3f03-46de-9781-57580aa96d0a" +StrideArraysCore = "7792a7ef-975c-4747-a70f-980b88e8d1da" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[compat] +Bumper = "0.7" diff --git a/test/ccalls.jl b/test/ccalls.jl deleted file mode 100644 index dd5663c6..00000000 --- a/test/ccalls.jl +++ /dev/null @@ -1,35 +0,0 @@ -# d = find_ccalls(Threads.nthreads, Tuple{}) -# d = find_ccalls(time, Tuple{}) -# d = find_ccalls(muladd, Tuple{Array{Float64,2},Array{Float64,2},Array{Float64,2}}) - -f1() = ccall(:jl_errno, Int, (Int,), 11) -f2() = ccall(:jl_errno, Int, (Int, Int), 21, 22) -f3() = ccall(:jl_errno, Int, (Int, Int, Int), 31, 32, 33) - -@testset "ccalls" begin - m1 = irgen(f1, Tuple{}) - m2 = irgen(f2, Tuple{}) - m3 = irgen(f3, Tuple{}) - LLVM.verify(m1) - LLVM.verify(m2) - LLVM.verify(m3) -end - - -function f() - n = Int(unsafe_load(cglobal(:jl_n_threads, Cint))) - return 2n -end - -@testset "cglobal" begin - m = irgen(f, Tuple{}) - LLVM.verify(m) - @test f() == @jlrun f() -end - -@testset "extern" begin - f() = @extern(:time, Cvoid, (Ptr{Cvoid},), C_NULL) - m = irgen(f, Tuple{}) - LLVM.verify(m) - @test "time" in [name(f) for f in LLVM.functions(m)] -end diff --git a/test/cross/matrix.jl b/test/cross/matrix.jl new file mode 100644 index 00000000..82daf79f --- /dev/null +++ b/test/cross/matrix.jl @@ -0,0 +1,81 @@ +# What can be made from this host, for each target: `julia test/cross/matrix.jl [outdir]`. +# For each target it tries three things: the LLVM IR, an object file, and a linked executable (the program returns `argc + 41`: 42 when it is run with no arguments), and says what each came to. +# The table is printed, and written to `$GITHUB_STEP_SUMMARY` where there is one. With `outdir`, the executables are kept as `outdir///`, for `test/cross/run.jl` to run on a machine of their target. +# It makes an environment of its own, with the extensions of StaticCompiler that fetch the C libraries of the targets (`Glibc_jll`, `Mingw_jll`). +# +# What a host needs for a target: the code generator for it (Julia's LLVM has the host's architecture and WebAssembly; an `llc` of the same version of LLVM has others: `STATIC_COMPILER_LLC`), and for the link the +# libraries of the target: fetched for Linux and Windows, and for macOS an SDK (Xcode's on a Mac, else the directory in `SDKROOT`). + +import Pkg +Pkg.activate(temp = true; io = devnull) +Pkg.develop(path = dirname(dirname(@__DIR__)); io = devnull) +Pkg.add(["Glibc_jll", "Mingw_jll", "LLVM", "Pkg"]; io = devnull) +using StaticCompiler, Glibc_jll, Mingw_jll, LLVM, Pkg +using Base.BinaryPlatforms + +const SC = StaticCompiler +host = string(Sys.ARCH, "-", Sys.KERNEL === :NT ? "windows" : Sys.islinux() ? "linux" : Sys.isapple() ? "macos" : string(Sys.KERNEL)) +outdir = length(ARGS) >= 1 ? abspath(ARGS[1]) : nothing + +matrix_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 41) % Int + +# the targets, and how each is linked (a function that makes the toolchain, which may say that a resource is missing by throwing) +const TARGETS = [ + ("aarch64-unknown-linux-gnu", () -> SC.LLDToolchain(:gnu; sysroot = SC.glibc_sysroot("aarch64-unknown-linux-gnu"))), + ("x86_64-unknown-linux-gnu", () -> SC.LLDToolchain(:gnu; sysroot = SC.glibc_sysroot("x86_64-unknown-linux-gnu"))), + ("aarch64-apple-macosx11.0.0", () -> SC.LLDToolchain(:darwin)), + ("x86_64-apple-macosx11.0.0", () -> SC.LLDToolchain(:darwin)), + ("x86_64-w64-mingw32", () -> SC.LLDToolchain(:mingw; sysroot = SC.mingw_sysroot("x86_64-w64-mingw32"))), + ("wasm64-unknown-unknown", () -> SC.LLDToolchain(:wasm)), +] + +short(e) = first(split(sprint(showerror, e), '\n')) +status(f) = try; f(); "ok"; catch e; "fails: " * first(short(e), 90); end + +rows = NamedTuple[] +for (triple, make_toolchain) in TARGETS + println("\n## ", triple) + llc = get(ENV, "STATIC_COMPILER_LLC", nothing) + target = try; SC.StaticTarget(triple; llc); catch e; nothing; end + if target === nothing + push!(rows, (; triple, ir = "fails", object = "-", link = "-")); continue + end + backend = SC.julia_llvm_has(triple) + # the IR is made for any target (the host's code, retargeted) + ir_target = SC.StaticTarget(triple; retarget = true) + ir = status() do + text = SC.generate_ir(matrix_main, Tuple{Int,Ptr{Ptr{UInt8}}}; target = ir_target, main_wrapper = "matrix_main") + occursin("define i32 @main", text) || error("no `main` in the IR") + end + println(" IR: ", ir) + # the object: by Julia's LLVM if it has the code generator, or by `llc` + object = !SC.can_emit_object(target) ? "no code generator (needs an `llc`)" : status() do + dir = mktempdir() + obj = SC.generate_obj(((matrix_main, Tuple{Int,Ptr{Ptr{UInt8}}}),), dir, "matrix_main"; target, main_wrapper = "matrix_main") + filesize(obj) > 100 || error("the object is empty") + end + println(" object: ", object) + # the executable + link = if !SC.can_emit_object(target) + "no code generator" + else + status() do + linked = SC.StaticTarget(target; toolchain = make_toolchain()) # (a copy that is linked so, and not the target itself) + dir = mktempdir() + exe = compile_executable(matrix_main, (Int, Ptr{Ptr{UInt8}}), dir, "matrix_main"; target = linked) + isfile(exe) || error("no executable") + if outdir !== nothing + kept = joinpath(outdir, host, triple) + mkpath(kept) + cp(exe, joinpath(kept, basename(exe)); force = true) + end + end + end + println(" link: ", link) + push!(rows, (; triple, ir, object, link)) +end + +table = string("| host `", host, "` makes for | IR | object | executable |\n|:--|:--|:--|:--|\n", + join(("| `$(r.triple)` | $(r.ir) | $(r.object) | $(r.link) |" for r in rows), "\n"), "\n") +println("\n", table) +haskey(ENV, "GITHUB_STEP_SUMMARY") && open(io -> println(io, "\n### Compile matrix, host ", host, ", Julia ", VERSION, "\n\n", table), ENV["GITHUB_STEP_SUMMARY"], "a") diff --git a/test/cross/run.jl b/test/cross/run.jl new file mode 100644 index 00000000..68cc8984 --- /dev/null +++ b/test/cross/run.jl @@ -0,0 +1,35 @@ +# Runs the executables that `test/cross/matrix.jl` kept, where they can run: `julia test/cross/run.jl dir`. +# `dir///` was made on `` for ``. The ones that this machine can run (its system and its architecture) are run, and each has to return 42 (the program returns `argc + 41`). +# Exits with a status that is not 0 if one that could be run did not do that. + +host_arch = Sys.ARCH === :x86_64 ? "x86_64" : Sys.ARCH === :aarch64 ? "aarch64" : string(Sys.ARCH) +host_system = Sys.iswindows() ? "windows" : Sys.islinux() ? "linux" : Sys.isapple() ? "macos" : string(Sys.KERNEL) + +# whether a program for the triple runs here: the system, and the architecture (an Apple Silicon Mac runs x86-64 programs of macOS with Rosetta, if it has it) +function runs_here(triple) + arch = first(split(triple, '-')) + arch == "x86_64" || arch == "aarch64" || return false + system = occursin("apple", triple) ? "macos" : occursin("linux", triple) ? "linux" : occursin("mingw", triple) || occursin("windows", triple) ? "windows" : "?" + system == host_system || return false + arch == host_arch && return true + return system == "macos" && host_arch == "aarch64" && arch == "x86_64" && success(pipeline(`arch -x86_64 /usr/bin/true`; stderr = devnull)) +end + +dir = abspath(ARGS[1]) +rows = NamedTuple[] +for made_on in sort(readdir(dir)), triple in sort(readdir(joinpath(dir, made_on))) + runs_here(triple) || continue + for file in readdir(joinpath(dir, made_on, triple)) + exe = joinpath(dir, made_on, triple, file) + Sys.iswindows() || chmod(exe, 0o755) + command = host_system == "macos" && !startswith(triple, host_arch) ? `arch -x86_64 $exe` : `$exe` + p = run(pipeline(ignorestatus(command); stdout = devnull, stderr = devnull)) + push!(rows, (; made_on, triple, result = p.exitcode == 42 ? "ok" : "exit status $(p.exitcode) (42 wanted)")) + end +end + +host = string(host_arch, "-", host_system) +table = string("| made on | for | run on `", host, "` |\n|:--|:--|:--|\n", join(("| $(r.made_on) | `$(r.triple)` | $(r.result) |" for r in rows), "\n"), "\n") +println(table) +haskey(ENV, "GITHUB_STEP_SUMMARY") && open(io -> println(io, "\n### Executables run on ", host, "\n\n", isempty(rows) ? "none of those that were made are for this machine" : table), ENV["GITHUB_STEP_SUMMARY"], "a") +all(r -> r.result == "ok", rows) || exit(1) diff --git a/test/globals.jl b/test/globals.jl deleted file mode 100644 index 43c70e84..00000000 --- a/test/globals.jl +++ /dev/null @@ -1,36 +0,0 @@ -# @testset "serialize" begin -# ctx = StaticCompiler.SerializeContext() -# a = Any["abcdg", ["hi", "bye"], 3333, Int32(44), 314f0, 3.14, (1, 3.3f0), Core.svec(9.9, 9), :sym, :sym, :a] -# e = StaticCompiler.serialize(ctx, a) -# g = eval(:(Vptr -> $e)) -# v = take!(ctx.io) -# GC.enable(false) -# res = g(pointer(v)) -# GC.enable(true) -# @test res == a -# end - - -# const a = ["abcdg", "asdfl", 123, 3.14, ["a", "asdf"], (1, 3.63), [1, 3.63]] -const a = ["abcdg", "asdxf"] -const b = "B" -const x = [1.33, 35.0] -const xi = [3, 5] - -f(x) = @inbounds a[1][3] > b[1] ? 2x : x -g(i) = @inbounds x[1] > x[2] ? 2i : i -h(i) = @inbounds xi[1] == 3 ? i : 2i - -@testset "globals" begin - @test f(3) == @jlrun f(3) - @test g(3) == @jlrun g(3) - @test h(3) == @jlrun h(3) -end - -f() = Complex{Float64} -g(@nospecialize(x)) = isa(x, Number) ? 1 : 0 - -@testset "type" begin - @test string(@jlrun f()) == "Complex{Float64}" - res = g(4.0im) -end diff --git a/test/ode.jl b/test/ode.jl deleted file mode 100644 index b270a544..00000000 --- a/test/ode.jl +++ /dev/null @@ -1,182 +0,0 @@ -# Adapted from: https://github.com/JuliaDiffEq/ODE.jl/blob/8954872f956116e78b6c04690f899fe2db696b4e/src/ODE.jl#L84-L360 -# MIT license -# Copyright (c) 2009-2015: various contributors: https://github.com/JuliaLang/ODE.jl/contributors - -using LinearAlgebra - -function hinit(F, x0, t0::T, tend, p, reltol, abstol) where T - # Returns first step, direction of integration and F evaluated at t0 - tdir = sign(tend-t0) - tdir==0 && error("Zero time span") - tau = max(reltol*norm(x0, Inf), abstol) - d0 = norm(x0, Inf)/tau - f0 = F(t0, x0) - d1 = norm(f0, Inf)/tau - if d0 < 1e-5 || d1 < 1e-5 - h0 = 1e-6 - else - h0 = 0.01*(d0/d1) - end - h0 = convert(T,h0) - # perform Euler step - x1 = x0 + tdir*h0*f0 - f1 = F(t0 + tdir*h0, x1) - # estimate second derivative - d2 = norm(f1 - f0, Inf)/(tau*h0) - if max(d1, d2) <= 1e-15 - h1 = max(T(10)^(-6), T(10)^(-3)*h0) - else - pow = -(2 + log10(max(d1, d2)))/(p + 1) - h1 = 10^pow - end - h1 = convert(T,h1) - return tdir*min(100*h0, h1, tdir*(tend-t0)), tdir, f0 -end - -function fdjacobian(F, x::Number, t) - ftx = F(t, x) - - # The 100 below is heuristic - dx = (x .+ (x==0))./100 - dFdx = (F(t,x+dx)-ftx)./dx - - return dFdx -end - -function fdjacobian(F, x, t) - ftx = F(t, x) - lx = max(length(x),1) - dFdx = zeros(eltype(x), lx, lx) - for j = 1:lx - # The 100 below is heuristic - dx = zeros(eltype(x), lx) - dx[j] = (x[j] .+ (x[j]==0))./100 - dFdx[:,j] = (F(t,x+dx)-ftx)./dx[j] - end - return dFdx -end - -# ODE23S Solve stiff systems based on a modified Rosenbrock triple -# (also used by MATLAB's ODE23s); see Sec. 4.1 in -# -# [SR97] L.F. Shampine and M.W. Reichelt: "The MATLAB ODE Suite," SIAM Journal on Scientific Computing, Vol. 18, 1997, pp. 1–22 -# -# supports keywords: points = :all | :specified (using dense output) -# jacobian = G(t,y)::Function | nothing (FD) -function ode23s(F, y0, tspan; - reltol = 1.0e-5, abstol = 1.0e-8, - jacobian=nothing, - points=:all, - norm=LinearAlgebra.norm, - minstep=abs(tspan[end] - tspan[1])/1e18, - maxstep=abs(tspan[end] - tspan[1])/2.5, - initstep=0.) - - # select method for computing the Jacobian - if typeof(jacobian) == Function - jac = jacobian - else - # fallback finite-difference - jac = (t, y)->fdjacobian(F, y, t) - end - - # constants - d = 1/(2 + sqrt(2)) - e32 = 6 + sqrt(2) - - - # initialization - t = tspan[1] - - tfinal = tspan[end] - - h = initstep - if h == 0. - # initial guess at a step size - h, tdir, F0 = hinit(F, y0, t, tfinal, 3, reltol, abstol) - else - tdir = sign(tfinal - t) - F0 = F(t,y0) - end - h = tdir * min(abs(h), maxstep) - - y = y0 - tout = [t] # first output time - yout = [deepcopy(y)] # first output solution - - J = jac(t,y) # get Jacobian of F wrt y -# Core.print(t, " ", tfinal, " ", minstep, " ", h) - while abs(t - tfinal) > 0 && minstep < abs(h) - if abs(t-tfinal) < abs(h) - h = tfinal - t - end - - if size(J,1) == 1 - W = I - h*d*J - else - # note: if there is a mass matrix M on the lhs of the ODE, i.e., - # M * dy/dt = F(t,y) - # we can simply replace eye(J) by M in the following expression - # (see Sec. 5 in [SR97]) - - W = lu( I - h*d*J ) - end - - # approximate time-derivative of F - T = h*d*(F(t + h/100, y) - F0)/(h/100) - - # modified Rosenbrock formula - k1 = W\(F0 + T) - F1 = F(t + 0.5*h, y + 0.5*h*k1) - k2 = W\(F1 - k1) + k1 - ynew = y + h*k2 - F2 = F(t + h, ynew) - k3 = W\(F2 - e32*(k2 - F1) - 2*(k1 - F0) + T ) - - err = (abs(h)/6)*norm(k1 - 2*k2 + k3) # error estimate - delta = max(reltol*max(norm(y),norm(ynew)), abstol) # allowable error - - # check if new solution is acceptable - if err <= delta - - # # if points==:specified || points==:all - # # only points in tspan are requested - # # -> find relevant points in (t,t+h] - # for toi in tspan[(tspan.>t) .& (tspan.<=t+h)] - # # rescale to (0,1] - # s = (toi-t)/h - - # # use interpolation formula to get solutions at t=toi - # push!(tout, toi) - # push!(yout, y + h*( k1*s*(1-s)/(1-2*d) + k2*s*(s-2*d)/(1-2*d))) - # end - # # Core.print("First\n") - # # end - # if points==:all - if (tout[end]!=t+h) - # # add the intermediate points - push!(tout, t + h) - push!(yout, ynew) - end - - # update solution - t = t + h - y = ynew - - F0 = F2 # use FSAL property - J = jac(t,y) # get Jacobian of F wrt y - # for new solution - end - - # update of the step size - h = tdir*min( maxstep, abs(h)*0.8*(delta/err)^(1/3) ) - end - - return tout, yout -end - - -# fode() = ode23s((t,y)->2.0t^2, 0.0, Float64[0:.001:2;], initstep = 1e-4)[2][end] -# fode() = ode23s((t,y)->2.0t^2, 0.0, [0:.001:2;], initstep = 1e-4)[2][end] - -# @show fode() diff --git a/test/others.jl b/test/others.jl deleted file mode 100644 index 4481e77a..00000000 --- a/test/others.jl +++ /dev/null @@ -1,73 +0,0 @@ -mutable struct AAA - aaa::Int - bbb::Int -end -@noinline ssum(x) = x.aaa + x.bbb -fstruct(x) = ssum(AAA(x, 99)) -@test fstruct(10) == @jlrun fstruct(10) - -module ZZ -mutable struct AAA - aaa::Int - bbb::Int -end -@noinline ssum(x) = x.aaa + x.bbb -fstruct(x) = ssum(AAA(x, 99)) -end # module -ffstruct(x) = ZZ.fstruct(x) -@test ffstruct(10) == @jlrun ffstruct(10) - -const ag = Ref(0x80808080) -jglobal() = ag -@show bg = @jlrun jglobal() -# @test jglobal()[] == bg[] # Something's broken with mutable's - -arraysum(x) = sum([x, 1]) -# @test arraysum(6) == @jlrun arraysum(6) - -fsin(x) = sin(x) -@test fsin(0.5) == @jlrun fsin(0.5) - -fccall() = ccall(:jl_ver_major, Cint, ()) -@test fccall() == @jlrun fccall() - -fcglobal() = cglobal(:jl_n_threads, Cint) -@test fcglobal() == @jlrun fcglobal() - -const sv = Core.svec(1,2,3,4) -fsv() = sv -@test fsv() == @jlrun fsv() - -const arr = [9,9,9,9] -farray() = arr -@show @jlrun farray() -@show farray() -# @test farray() == @jlrun farray() - -@noinline f0(x) = 3x -@noinline fop(f, x) = 2f(x) -funcall(x) = fop(f0, x) -@test funcall(2) == @jlrun funcall(2) - -hi() = print(Core.stdout, 'X') -@jlrun hi() - -hello() = print(Core.stdout, "Hello world...\n") -@jlrun hello() - -function gx(i) - a = 2.0:0.1:10.0 - @inbounds i > 3 ? a[1] : a[5] -end - -@test_skip gx(4) == @jlrun gx(4) - -fsimple() = [0:.001:2;][end] - -@test fsimple() == @jlrun fsimple() - -@noinline function fsym(x; l = :hello, s = :x) - s == :asdf ? x : 2x -end -gsym(x) = fsym(x, l = :hello, s = :asdf) + 1 -@test gsym(3) == @jlrun gsym(3) diff --git a/test/runtests.jl b/test/runtests.jl index 3381a873..8c533cd7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,21 +1,27 @@ -using StaticCompiler using Test -using LLVM +using StaticCompiler using Libdl +using LinearAlgebra +using LoopVectorization +using ManualMemory +using Distributed +using StaticTools +# using StrideArraysCore +using LLD_jll +using LLVM +using Glibc_jll, Mingw_jll, Pkg # (the extensions that have the C libraries of a Linux and a Windows target) +using Bumper -cd(@__DIR__) -@testset "ccalls" begin - include("ccalls.jl") -end +addprocs(1) +@everywhere using StaticCompiler, StrideArraysCore -@testset "globals" begin - include("globals.jl") -end +const GROUP = get(ENV, "GROUP", "All") -@testset "others" begin - include("others.jl") +if GROUP == "Core" || GROUP == "All" + include("testcore.jl") + include("testquirks.jl") end -@testset "standalone" begin - include("standalone-exe.jl") +if GROUP == "Integration" || GROUP == "All" + include("testintegration.jl") end diff --git a/test/scripts/inbounds_matrix.jl b/test/scripts/inbounds_matrix.jl new file mode 100644 index 00000000..efe0aec5 --- /dev/null +++ b/test/scripts/inbounds_matrix.jl @@ -0,0 +1,52 @@ +using StaticCompiler +using StaticTools + +@inline function mul!(C::MallocArray, A::MallocArray, B::MallocArray) + @inbounds for n ∈ axes(C, 2), m ∈ axes(C, 1) + Cmn = zero(eltype(C)) + for k ∈ axes(A, 2) + Cmn += A[m,k] * B[k,n] + end + C[m,n] = Cmn + end + return C +end + +function inbounds_matrix(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + # LHS + A = MallocArray{Float64}(undef, rows, cols) + @inbounds for i ∈ axes(A, 1) + for j ∈ axes(A, 2) + A[i,j] = i*j + end + end + + # RHS + B = MallocArray{Float64}(undef, cols, rows) + @inbounds for i ∈ axes(B, 1) + for j ∈ axes(B, 2) + B[i,j] = i*j + end + end + + # # Matrix multiplication + C = MallocArray{Float64}(undef, cols, cols) + mul!(C, B, A) + + # Print to stdout + printf(C) + # Also print to file + printdlm(c"table.tsv", C, '\t') + fwrite(c"table.b", C) + # Clean up matrices + free(A) + free(B) + free(C) +end + +# Attempt to compile +path = compile_executable(inbounds_matrix, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/inbounds_matrix_stack.jl b/test/scripts/inbounds_matrix_stack.jl new file mode 100644 index 00000000..1acf0c98 --- /dev/null +++ b/test/scripts/inbounds_matrix_stack.jl @@ -0,0 +1,48 @@ +using StaticCompiler +using StaticTools + +@inline function mul!(C::StackArray, A::StackArray, B::StackArray) + @inbounds for n ∈ axes(C, 2), m ∈ axes(C, 1) + Cmn = zero(eltype(C)) + for k ∈ axes(A, 2) + Cmn += A[m,k] * B[k,n] + end + C[m,n] = Cmn + end + return C +end + +function inbounds_matrix_stack() + rows = 10 + cols = 5 + + # LHS + A = StackArray{Float64}(undef, rows, cols) + @inbounds for i ∈ axes(A, 1) + for j ∈ axes(A, 2) + A[i,j] = i*j + end + end + + # RHS + B = StackArray{Float64}(undef, cols, rows) + @inbounds for i ∈ axes(B, 1) + for j ∈ axes(B, 2) + B[i,j] = i*j + end + end + + # # Matrix multiplication + C = StackArray{Float64}(undef, cols, cols) + mul!(C, B, A) + + # Print to stdout + printf(C) + # Also print to file + fp = fopen(c"table.tsv",c"w") + printf(fp, C) + fclose(fp) +end + +# Attempt to compile +path = compile_executable(inbounds_matrix_stack, (), "./") diff --git a/test/scripts/inbounds_product.jl b/test/scripts/inbounds_product.jl new file mode 100644 index 00000000..e80b5403 --- /dev/null +++ b/test/scripts/inbounds_product.jl @@ -0,0 +1,24 @@ +using StaticCompiler +using StaticTools + +function inbounds_product(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + s = 0 + @inbounds for i=1:rows + for j=1:cols + s += i*j + end + end + # Print result to stdout + printf(s) + # Also print to file + fp = fopen(c"product.tsv",c"w") + printf(fp, s) + fclose(fp) +end + +# Attempt to compile +path = compile_executable(inbounds_product, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/interop.jl b/test/scripts/interop.jl new file mode 100644 index 00000000..5729725f --- /dev/null +++ b/test/scripts/interop.jl @@ -0,0 +1,17 @@ +using StaticCompiler +using StaticTools + +function interop(argc, argv) + # On Linux, `libm.so` is typically a linker script (or absent), so use the versioned soname + lib = StaticTools.dlopen(@static(Sys.islinux() ? c"libm.so.6" : c"libm")) + printf(lib) + sin = StaticTools.dlsym(lib, c"sin") + printf(sin) + x = @ptrcall sin(5.0::Float64)::Float64 + printf(x) + newline() + StaticTools.dlclose(lib) +end + +# Attempt to compile +path = compile_executable(interop, (Int64, Ptr{Ptr{UInt8}}), "./", cflags=`-ldl -lm`) diff --git a/test/scripts/iterate.jl b/test/scripts/iterate.jl new file mode 100644 index 00000000..cdc4b9d9 --- /dev/null +++ b/test/scripts/iterate.jl @@ -0,0 +1,13 @@ +using StaticCompiler +using StaticTools + +function iterate() + if startswith(c"foobar", c"foo") + printf(c"We have iterated!\n") + return Int32(0) + end + return Int32(1) +end + +# Attempt to compile +path = compile_executable(iterate, (), "./") diff --git a/test/scripts/loopvec_matrix.jl b/test/scripts/loopvec_matrix.jl new file mode 100644 index 00000000..7b19ce86 --- /dev/null +++ b/test/scripts/loopvec_matrix.jl @@ -0,0 +1,53 @@ +using StaticCompiler +using StaticTools +using LoopVectorization + +@inline function mul!(C::MallocArray, A::MallocArray, B::MallocArray) + @turbo for n ∈ indices((C,B), 2), m ∈ indices((C,A), 1) + Cmn = zero(eltype(C)) + for k ∈ indices((A,B), (2,1)) + Cmn += A[m,k] * B[k,n] + end + C[m,n] = Cmn + end + return C +end + +function loopvec_matrix(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + # LHS + A = MallocArray{Float64}(undef, rows, cols) + @turbo for i ∈ axes(A, 1) + for j ∈ axes(A, 2) + A[i,j] = i*j + end + end + + # RHS + B = MallocArray{Float64}(undef, cols, rows) + @turbo for i ∈ axes(B, 1) + for j ∈ axes(B, 2) + B[i,j] = i*j + end + end + + # # Matrix multiplication + C = MallocArray{Float64}(undef, cols, cols) + mul!(C, B, A) + + # Print to stdout + printf(C) + # Also print to file + printdlm(c"table.tsv", C, '\t') + fwrite(c"table.b", C) + # Clean up matrices + free(A) + free(B) + free(C) +end + +# Attempt to compile +path = compile_executable(loopvec_matrix, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/loopvec_matrix_stack.jl b/test/scripts/loopvec_matrix_stack.jl new file mode 100644 index 00000000..5e0c90d7 --- /dev/null +++ b/test/scripts/loopvec_matrix_stack.jl @@ -0,0 +1,49 @@ +using StaticCompiler +using StaticTools +using LoopVectorization + +@inline function mul!(C::StackArray, A::StackArray, B::StackArray) + @turbo for n ∈ indices((C,B), 2), m ∈ indices((C,A), 1) + Cmn = zero(eltype(C)) + for k ∈ indices((A,B), (2,1)) + Cmn += A[m,k] * B[k,n] + end + C[m,n] = Cmn + end + return C +end + +function loopvec_matrix_stack() + rows = 10 + cols = 5 + + # LHS + A = StackArray{Float64}(undef, rows, cols) + @turbo for i ∈ axes(A, 1) + for j ∈ axes(A, 2) + A[i,j] = i*j + end + end + + # RHS + B = StackArray{Float64}(undef, cols, rows) + @turbo for i ∈ axes(B, 1) + for j ∈ axes(B, 2) + B[i,j] = i*j + end + end + + # # Matrix multiplication + C = StackArray{Float64}(undef, cols, cols) + mul!(C, B, A) + + # Print to stdout + printf(C) + # Also print to file + fp = fopen(c"table.tsv",c"w") + printf(fp, C) + fclose(fp) +end + +# Attempt to compile +path = compile_executable(loopvec_matrix_stack, (), "./") diff --git a/test/scripts/loopvec_product.jl b/test/scripts/loopvec_product.jl new file mode 100644 index 00000000..83424504 --- /dev/null +++ b/test/scripts/loopvec_product.jl @@ -0,0 +1,25 @@ +using StaticCompiler +using StaticTools +using LoopVectorization + +function loopvec_product(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + s = 0 + @turbo for i=1:rows + for j=1:cols + s += i*j + end + end + # Print result to stdout + printf(s) + # Also print to file + fp = fopen(c"product.tsv",c"w") + printf(fp, s) + fclose(fp) +end + +# Attempt to compile +path = compile_executable(loopvec_product, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/matmul.jl b/test/scripts/matmul.jl new file mode 100644 index 00000000..6511bc2c --- /dev/null +++ b/test/scripts/matmul.jl @@ -0,0 +1,38 @@ +using StaticCompiler +using StaticTools + +function matmul(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + A = MallocArray{Float64}(undef, rows, cols) + @inbounds for i ∈ axes(A, 1) + for j ∈ axes(A, 2) + A[i,j] = i*j + end + end + + B = MallocArray{Float64}(undef, cols, rows) + @inbounds for i ∈ axes(B, 1) + for j ∈ axes(B, 2) + B[i,j] = i*j + end + end + + # Matrix multiplication + C = B * A + + # Print to stdout + printf(C) + # Also print to file + printdlm(c"table.tsv", C, '\t') + fwrite(c"table.b", C) + # Clean up matrices + free(A) + free(B) + # free(C) +end + +# Attempt to compile +path = compile_executable(matmul, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/matmul_stack.jl b/test/scripts/matmul_stack.jl new file mode 100644 index 00000000..5fad70a1 --- /dev/null +++ b/test/scripts/matmul_stack.jl @@ -0,0 +1,35 @@ +using StaticCompiler +using StaticTools + +function matmul_stack() + rows = 10 + cols = 5 + + A = szeros(rows, cols) + @inbounds for i ∈ axes(A, 1) + for j ∈ axes(A, 2) + A[i,j] = i*j + end + end + + B = szeros(cols, rows) + @inbounds for i ∈ axes(B, 1) + for j ∈ axes(B, 2) + B[i,j] = i*j + end + end + + # Matrix multiplication + C = B * A + + # Print to stdout + printf(C) + # Also print to file + printdlm(c"table.tsv", C, '\t') + fwrite(c"table.b", C) + + return Int32(0) +end + +# Attempt to compile +path = compile_executable(matmul_stack, (), "./") diff --git a/test/scripts/print_args.jl b/test/scripts/print_args.jl new file mode 100644 index 00000000..c3d05fbf --- /dev/null +++ b/test/scripts/print_args.jl @@ -0,0 +1,33 @@ +using StaticCompiler +using StaticTools + +function print_args(argc::Int, argv::Ptr{Ptr{UInt8}}) + printf(c"Argument count is %d:\n", argc) + for i=1:argc + # iᵗʰ input argument string + pᵢ = unsafe_load(argv, i) # Get pointer + strᵢ = MallocString(pᵢ) # Can wrap to get high-level interface + println(strᵢ) + # No need to `free` since we didn't allocate this memory + end + newline() + println(c"Testing string indexing and substitution") + m = m"Hello world!" + println(m[1:5]) + println(m) + m[7:11] = c"there" + println(m) + free(m) + + s = m"Hello world!" + println(s[1:5]) + println(s) + s[7:11] = c"there" + println(s) + + println(c"That was fun, see you next time!") + return 0 +end + +# Attempt to compile +path = compile_executable(print_args, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/rand_matrix.jl b/test/scripts/rand_matrix.jl new file mode 100644 index 00000000..184eb58a --- /dev/null +++ b/test/scripts/rand_matrix.jl @@ -0,0 +1,23 @@ +using StaticCompiler +using StaticTools + +function rand_matrix(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + # Manually fil matrix + M = MallocArray{Float64}(undef, rows, cols) + rng = static_rng() + @inbounds for i=1:rows + for j=1:cols + M[i,j] = rand(rng) + end + end + printf(M) + free(M) +end + +# Attempt to compile +# cflags=`-lm`: need to explicitly include libm math library on linux (not needed, or available, on Windows) +path = compile_executable(rand_matrix, (Int64, Ptr{Ptr{UInt8}}), "./", cflags=(Sys.iswindows() ? `` : `-lm`)) diff --git a/test/scripts/randn_matrix.jl b/test/scripts/randn_matrix.jl new file mode 100644 index 00000000..b5fa9d24 --- /dev/null +++ b/test/scripts/randn_matrix.jl @@ -0,0 +1,22 @@ +using StaticCompiler +using StaticTools + +function randn_matrix(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + M = MallocArray{Float64}(undef, rows, cols) + rng = MarsagliaPolar(static_rng()) + @inbounds for i=1:rows + for j=1:cols + M[i,j] = randn(rng) + end + end + printf(M) + free(M) +end + +# Attempt to compile +# cflags=`-lm`: need to explicitly include libm math library on linux (not needed, or available, on Windows) +path = compile_executable(randn_matrix, (Int64, Ptr{Ptr{UInt8}}), "./", cflags=(Sys.iswindows() ? `` : `-lm`)) diff --git a/test/scripts/readwrite.jl b/test/scripts/readwrite.jl new file mode 100644 index 00000000..0e3987cb --- /dev/null +++ b/test/scripts/readwrite.jl @@ -0,0 +1,45 @@ +using StaticCompiler +using StaticTools + +function readwrite(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + M = MallocArray{Int64}(undef, rows, cols) + @inbounds for i=1:rows + for j=1:cols + M[i,j] = i*j + end + end + # Print to file + fwrite(c"table.b", M) + printdlm(c"table.tsv", M) + + Mb = read(c"table.b", MallocArray{Int64}) + Mbv = reshape(Mb, (rows, cols)) + printdlm(c"tableb.tsv", Mbv) + printf(Mbv) + + Ms = read(c"table.b", MallocString) + Msv = ArrayView{Int64,2}(pointer(Ms), rows*cols, (rows, cols)) + printdlm(c"tables.tsv", Msv) + printf(Msv) + + Mts = read(c"table.tsv", MallocString) + fwrite(c"tablets.tsv", Mts) + printf(Mts) + + # Mt = parsedlm(Int64, c"table.tsv") + + # match = M == Mb == Mbv == Msv + + # Clean up + free(M), free(Mb), free(Ms), free(Mts) + + # return !match % Int32 + return Int32(0) +end + +# Attempt to compile +path = compile_executable(readwrite, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/stack_times_table.jl b/test/scripts/stack_times_table.jl new file mode 100644 index 00000000..778349e0 --- /dev/null +++ b/test/scripts/stack_times_table.jl @@ -0,0 +1,20 @@ +using StaticCompiler +using StaticTools + +function stack_times_table() + a = StackArray{Int64}(undef, 5, 5) + for i ∈ axes(a,1) + for j ∈ axes(a,2) + a[i,j] = i*j + end + end + print(a) + fwrite(c"table.b", a) + GC.@preserve a printdlm(c"table.tsv", a) + + # Test reinterpreting + println(c"\nThe same array, reinterpreted as Int32:") + GC.@preserve a print(reinterpret(Int32, a)) +end + +path = compile_executable(stack_times_table, (), "./") diff --git a/test/scripts/throw_errors.jl b/test/scripts/throw_errors.jl new file mode 100644 index 00000000..fb823a0d --- /dev/null +++ b/test/scripts/throw_errors.jl @@ -0,0 +1,15 @@ +using StaticCompiler +using StaticTools + +function maybe_throw(argc::Int, argv::Ptr{Ptr{UInt8}}) + printf(c"Argument count is %d:\n", argc) + argc > 1 || return printf(stderrp(), c"Too few command-line arguments\n") + n = argparse(Int64, argv, 2) # First command-line argument + printf((c"Input:\n", n, c"\n")) + printf(c"\nAttempting to represent input as UInt64:\n") + x = UInt64(n) + printf(x) +end + +# Attempt to compile +path = compile_executable(maybe_throw, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/times_table.jl b/test/scripts/times_table.jl new file mode 100644 index 00000000..7d295eb0 --- /dev/null +++ b/test/scripts/times_table.jl @@ -0,0 +1,25 @@ +using StaticCompiler +using StaticTools + +function times_table(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + M = MallocArray{Int64}(undef, rows, cols) + @inbounds for i=1:rows + for j=1:cols + M[i,j] = i*j + end + end + # Print to stdout + printf(M) + # Also print to file + fwrite(c"table.b", M) + printdlm(c"table.tsv", M) + # Clean up matrix + free(M) +end + +# Attempt to compile +path = compile_executable(times_table, (Int64, Ptr{Ptr{UInt8}}), "./") diff --git a/test/scripts/wasm.jl b/test/scripts/wasm.jl new file mode 100644 index 00000000..0172bc5d --- /dev/null +++ b/test/scripts/wasm.jl @@ -0,0 +1,16 @@ +# Test that we can compile an object to wasm +# WebAssemblyCompiler.jl is a better tool for this, but this exercises the cross compilation pipeline + +using StaticCompiler +using LLVM +LLVM.InitializeAllTargets() +LLVM.InitializeAllTargetInfos() +LLVM.InitializeAllAsmPrinters() +LLVM.InitializeAllAsmParsers() +LLVM.InitializeAllTargetMCs() + +fib(n) = n <= 1 ? n : fib(n - 1) + fib(n - 2) + +target=StaticTarget("wasm32","","") + +StaticCompiler.generate_obj(fib, Tuple{Int64}, "./test", target=target) diff --git a/test/scripts/withmallocarray.jl b/test/scripts/withmallocarray.jl new file mode 100644 index 00000000..998d7fde --- /dev/null +++ b/test/scripts/withmallocarray.jl @@ -0,0 +1,31 @@ +using StaticCompiler +using StaticTools + +function withmallocarray(argc::Int, argv::Ptr{Ptr{UInt8}}) + argc == 3 || return printf(stderrp(), c"Incorrect number of command-line arguments\n") + rows = argparse(Int64, argv, 2) # First command-line argument + cols = argparse(Int64, argv, 3) # Second command-line argument + + mzeros(rows, cols) do A + printf(A) + end + mones(Int, rows, cols) do A + printf(A) + end + mfill(3.141592, rows, cols) do A + printf(A) + end + + # Random number generation + rng = MarsagliaPolar() + mrand(rng, rows, cols) do A + printf(A) + end + mrandn(rng, rows, cols) do A + printf(A) + end +end + +# Attempt to compile +# cflags=`-lm`: need to explicitly include libm math library on linux (not needed, or available, on Windows) +path = compile_executable(withmallocarray, (Int64, Ptr{Ptr{UInt8}}), "./", cflags=(Sys.iswindows() ? `` : `-lm`)) diff --git a/test/standalone-exe.jl b/test/standalone-exe.jl deleted file mode 100644 index fb97de52..00000000 --- a/test/standalone-exe.jl +++ /dev/null @@ -1,41 +0,0 @@ -# Definitions of functions to compile -twox(x) = 2x - -const aa = [4, 5] -arrayfun(x) = x + aa[1] + aa[2] - -jsin(x) = sin(x) - -function arridx(i) - a = collect(1.0:0.1:10.0) - @inbounds i > 3 ? a[1] : a[5] -end - -fsimple() = [0:.001:2;][end] - -include("ode.jl") -fode() = ode23s((t,y)->2.0t^2, 0.0, [0:.001:2;], initstep = 1e-4)[2][end] - -# Functions to compile and arguments to pass -funcalls = [ - (twox, Tuple{Int}, 4), - (arrayfun, Tuple{Int}, 4), - (jsin, Tuple{Float64}, 0.5), - (arridx, Tuple{Int}, 4), - (fsimple, Tuple{}, ()), - (fode, Tuple{}, ()), # Broken on Julia v1.2.0; works on Julia v1.3.0-rc3 -] - -StaticCompiler.exegen(funcalls) - -using Formatting -@testset "exegen" begin - cd("standalone") do - for (func, tt, val) in funcalls - fname = nameof(func) - rettype = Base.return_types(func, tt)[1] - fmt = StaticCompiler.Cformatmap[rettype] - @test Formatting.sprintf1(fmt, func(val...)) == read(`./$fname`, String) - end - end -end diff --git a/test/testcore.jl b/test/testcore.jl new file mode 100644 index 00000000..a3cef3cc --- /dev/null +++ b/test/testcore.jl @@ -0,0 +1,573 @@ +workdir = tempdir() + +fib(n) = n <= 1 ? n : fib(n - 1) + fib(n - 2) # This needs to be defined globally due to https://github.com/JuliaLang/julia/issues/40990 + +@testset "Standalone Dylibs" begin + # Test function + # (already defined) + # fib(n) = n <= 1 ? n : fib(n - 1) + fib(n - 2) + + #Compile dylib + name = string(nameof(fib)) # repr(fib) + filepath = compile_shlib(fib, (Int,), workdir, demangle=true) + @test occursin("fib.$(Libdl.dlext)", filepath) + # Open dylib manually + ptr = Libdl.dlopen(filepath, Libdl.RTLD_LOCAL) + fptr = Libdl.dlsym(ptr, name) + @test fptr != C_NULL + @test ccall(fptr, Int, (Int,), 10) == 55 + Libdl.dlclose(ptr) + + # As above, but without demangling + filepath = compile_shlib(fib, (Int,), workdir, demangle=false) + ptr = Libdl.dlopen(filepath, Libdl.RTLD_LOCAL) + fptr = Libdl.dlsym(ptr, "julia_fib_Int64") # (the name of the function and the types of its arguments) + @test fptr != C_NULL + @test ccall(fptr, Int, (Int,), 10) == 55 + Libdl.dlclose(ptr) +end + +@testset "Standalone Executables" begin + # Minimal test with no `llvmcall` + @inline function foo() + v = 0.0 + n = 1000 + for i=1:n + v += sqrt(n) + end + return 0 + end + + filepath = compile_executable(foo, (), workdir, demangle=false) + r = run(`$filepath`); + @test isa(r, Base.Process) + @test r.exitcode == 0 + + filepath = compile_executable(foo, (), workdir, demangle=true) + r = run(`$filepath`); + @test isa(r, Base.Process) + @test r.exitcode == 0 + + filepath = compile_executable(foo, (), workdir, llvm_to_clang=true) + r = run(`$filepath`); + @test isa(r, Base.Process) + @test r.exitcode == 0 + + + @inline function _puts(s::Ptr{UInt8}) + Base.llvmcall((""" + ; External declaration of the puts function + declare i32 @puts(i8* nocapture) nounwind + + define i32 @main(i8* %str) #0 { + entry: + %status = call i32 (i8*) @puts(i8* %str) + ret i32 %status + } + + attributes #0 = { alwaysinline nounwind ssp uwtable } + """, "main"), Int32, Tuple{Ptr{UInt8}}, s) + end + + @inline function print_args(argc::Int, argv::Ptr{Ptr{UInt8}}) + for i=1:argc + # Get pointer + p = unsafe_load(argv, i) + # Print string at pointer location (which fortunately already exists isn't tracked by the GC) + _puts(p) + end + return 0 + end + + filepath = compile_executable(print_args, (Int, Ptr{Ptr{UInt8}}), workdir, demangle=false) + r = run(`$filepath Hello, world!`); + @test isa(r, Base.Process) + @test r.exitcode == 0 + + filepath = compile_executable(print_args, (Int, Ptr{Ptr{UInt8}}), workdir, demangle=true) + r = run(`$filepath Hello, world!`); + @test isa(r, Base.Process) + @test r.exitcode == 0 + + filepath = compile_executable(print_args, (Int, Ptr{Ptr{UInt8}}), workdir, llvm_to_clang=true) + r = run(`$filepath Hello, world!`); + @test isa(r, Base.Process) + @test r.exitcode == 0 + + + # Compile a function that definitely fails + @inline foo_err() = UInt64(-1) + filepath = compile_executable(foo_err, (), workdir, demangle=true) + @test isfile(filepath) + status = -1 + try + status = run(`filepath`) + catch + @info "foo_err: Task failed successfully!" + end + @test status === -1 + +end + +@noinline square(n) = n*n + +function squaresquare(n) + square(square(n)) +end + +function squaresquaresquare(n) + square(squaresquare(n)) +end + +@testset "Multiple Function Dylibs" begin + + funcs = [(squaresquare,(Float64,)), (squaresquaresquare,(Float64,))] + filepath = compile_shlib(funcs, workdir, demangle=true) + + ptr = Libdl.dlopen(filepath, Libdl.RTLD_LOCAL) + + fptr2 = Libdl.dlsym(ptr, "squaresquare") + @test ccall(fptr2, Float64, (Float64,), 10.) == squaresquare(10.) + + fptr = Libdl.dlsym(ptr, "squaresquaresquare") + @test ccall(fptr, Float64, (Float64,), 10.) == squaresquaresquare(10.) + #Compile dylib +end + + +# Overlays + +module SubFoo + +rand(args...) = Base.rand(args...) + +function f() + x = rand() + y = rand() + return x + y +end + +end + +@device_override SubFoo.rand() = 2 + +# Lets test having another method table around +Base.Experimental.@MethodTable AnotherTable +Base.Experimental.@overlay AnotherTable SubFoo.rand() = 3 + +@testset "Overlays" begin + Libdl.dlopen(compile_shlib(SubFoo.f, (), workdir)) do lib + fptr = Libdl.dlsym(lib, "f") + @test @ccall($fptr()::Int) == 4 + end + Libdl.dlopen(compile_shlib(SubFoo.f, (), workdir; method_table=AnotherTable)) do lib + fptr = Libdl.dlsym(lib, "f") + @test @ccall($fptr()::Int) == 6 + end +end + +@testset "The target is not the host" begin + using Base.BinaryPlatforms + # The code is made for the host: only the platform is considered, and not every LLVM has the code generator of each platform + t(p) = StaticCompiler.StaticTarget(p; retarget = true) + # Ensure we are checking the target, no the host + @test StaticCompiler.iswindows(t(Platform("x86_64", "windows"))) && !StaticCompiler.isapple(t(Platform("x86_64", "windows"))) + @test StaticCompiler.isapple(t(Platform("aarch64", "macos"))) && !StaticCompiler.iswindows(t(Platform("aarch64", "macos"))) + @test !StaticCompiler.iswindows(t(Platform("aarch64", "linux"))) && !StaticCompiler.isapple(t(Platform("aarch64", "linux"))) + # A triple that `Platform` does not parse + wasm = StaticCompiler.StaticTarget("wasm32-unknown-unknown", "generic", "") + @test isnothing(tryparse(Platform, "wasm32-unknown-unknown")) && !StaticCompiler.iswindows(wasm) && !StaticCompiler.isapple(wasm) +end + +@testset "LLVM IR as text" begin + ir = StaticCompiler.generate_ir(fib, Tuple{Int}) + @test ir isa String && occursin("define", ir) && occursin("fib", ir) && occursin("target triple", ir) + ir_path = StaticCompiler.generate_ir(((fib, Tuple{Int}),), mktempdir(), "fibir") + @test isfile(ir_path) && occursin("define", read(ir_path, String)) +end + +@testset "A target that Julia's LLVM has no code generator for" begin + triple = "x86_64-unknown-linux-gnu" + ir_target = StaticCompiler.StaticTarget(triple; retarget = true) + @test StaticCompiler.target_triple(ir_target) == triple && StaticCompiler.needs_ir(ir_target) == !StaticCompiler.julia_llvm_has(triple) + @test occursin("--target=$triple", string(StaticCompiler.clang_target_flags(ir_target))) + ir = StaticCompiler.generate_ir(fib, Tuple{Int}; target = ir_target) + @test occursin("target triple = \"$triple\"", ir) && !occursin("target datalayout", ir) && !occursin("target-cpu", ir) && !occursin("target-features", ir) + # (an object is made if Julia's LLVM has the code generator, and is refused if it has not and no `llc` is given) + if StaticCompiler.julia_llvm_has(triple) + obj = StaticCompiler.generate_obj(((fib, Tuple{Int}),), mktempdir(), "fibobj"; target = ir_target) + @test read(obj, 4) == UInt8[0x7f, 0x45, 0x4c, 0x46] # ELF + else + @test_throws ArgumentError StaticCompiler.generate_obj(((fib, Tuple{Int}),), mktempdir(), "fibobj"; target = ir_target) + end + ir_path = StaticCompiler.generate_ir(((fib, Tuple{Int}),), mktempdir(), "fibir"; target = ir_target) + @test occursin("target triple = \"$triple\"", read(ir_path, String)) + # the host's own target is untouched + host = StaticCompiler.StaticTarget() + @test !StaticCompiler.is_retargeted(host) && StaticCompiler.needs_ir(host) == Sys.iswindows() + @test isempty(StaticCompiler.clang_target_flags(host)) + # (what the host is is found from its triple, however it is spelled: `Platform` does not parse the Windows triple that LLVM has) + @test StaticCompiler.triple_os("x86_64-w64-windows-gnu") == StaticCompiler.triple_os("x86_64-pc-windows-msvc") == StaticCompiler.triple_os("x86_64-w64-mingw32") == :windows + @test StaticCompiler.triple_os("arm64-apple-macosx11.0.0") == StaticCompiler.triple_os("aarch64-apple-darwin22.6.0") == :apple && StaticCompiler.triple_os("aarch64-unknown-linux-gnu") == :linux && StaticCompiler.triple_os("wasm64-unknown-unknown") == :other + @test StaticCompiler.triple_arch("arm64-apple-darwin") == StaticCompiler.triple_arch("aarch64-unknown-linux-gnu") == "aarch64" && StaticCompiler.triple_arch("amd64-pc-windows-msvc") == "x86_64" + @test isempty(StaticCompiler.clang_target_flags(StaticCompiler.StaticTarget(LLVM.default_triple()))) + @test !isempty(StaticCompiler.clang_target_flags(StaticCompiler.StaticTarget("wasm64-unknown-unknown"))) + for other in ("x86_64-w64-windows-gnu", "aarch64-unknown-linux-gnu", "x86_64-apple-macosx11.0.0") + t = StaticCompiler.StaticTarget(other; retarget = true) + @test occursin("--target=", string(StaticCompiler.clang_target_flags(t))) + end + # where there is no code generator for the triple, the constructors make such a target + for t in ("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", "riscv64-unknown-linux-gnu") + has_backend = try; LLVM.Target(triple = t); true; catch; false; end + has_backend || @test StaticCompiler.is_retargeted(StaticCompiler.StaticTarget(t, "generic", "")) && StaticCompiler.target_triple(StaticCompiler.StaticTarget(t, "generic", "")) == LLVM.normalize(t) + end +end + +@testset "Toolchains" begin + using Base.BinaryPlatforms + host = StaticCompiler.StaticTarget() + # the default is the host's C compiler driver, and `set_compiler!` is a driver + @test StaticCompiler.toolchain(host) isa StaticCompiler.CCToolchain + t = StaticCompiler.StaticTarget(host; toolchain = "mycc") + @test t.toolchain == StaticCompiler.CCToolchain(`mycc`) && StaticCompiler.toolchain(t).cc == `mycc` + t2 = StaticCompiler.StaticTarget(t; toolchain = `othercc`); @test t2.toolchain.cc == `othercc` && t.toolchain.cc == `mycc` # (a copy: the original is as it was) + t3 = StaticCompiler.StaticTarget(t; toolchain = StaticCompiler.LLDToolchain(:wasm)); @test t3.toolchain isa StaticCompiler.LLDToolchain + # (and the setters change a target in place) + StaticCompiler.set_compiler!(t, "othercc"); @test t.toolchain.cc == `othercc` && t2.toolchain.cc == `othercc` + StaticCompiler.set_toolchain!(t, StaticCompiler.LLDToolchain(:wasm)); @test t.toolchain isa StaticCompiler.LLDToolchain + StaticCompiler.set_runtime!(t, true); @test t.julia_runtime + # what the compiled code may do is the target's, and is passed to the compiler + @test host.can_throw && !host.julia_runtime && !StaticCompiler.StaticTarget(host; can_throw = false).can_throw && StaticCompiler.StaticTarget(host; julia_runtime = true).julia_runtime + job(target) = StaticCompiler.static_job(fib, Tuple{Int}; target) + @test StaticCompiler.GPUCompiler.can_throw(job(host)) && !StaticCompiler.GPUCompiler.can_throw(job(StaticCompiler.StaticTarget(host; can_throw = false))) + @test !StaticCompiler.GPUCompiler.uses_julia_runtime(job(host)) && StaticCompiler.GPUCompiler.uses_julia_runtime(job(StaticCompiler.StaticTarget(host; julia_runtime = true))) + @test_throws ArgumentError StaticCompiler.LLDToolchain(:macho) + # (the names of what is made) + drv = StaticCompiler.CCToolchain(`cc`) + win = StaticCompiler.StaticTarget(Platform("x86_64", "windows"); retarget = true) + @test StaticCompiler.output_name(drv, host, "prog") == (Sys.iswindows() ? "prog.exe" : "prog") + @test StaticCompiler.output_name(drv, win, "prog") == "prog.exe" && StaticCompiler.output_name(drv, win, "lib"; kind = :shared) == "lib.dll" + @test StaticCompiler.output_name(StaticCompiler.LLDToolchain(:wasm), host, "prog") == "prog.wasm" + @test StaticCompiler.output_name(StaticCompiler.LLDToolchain(:gnu), host, "prog") == "prog" && StaticCompiler.output_name(StaticCompiler.LLDToolchain(:gnu), win, "lib"; kind = :shared) == "lib.so" # (ELF, on any host) + # a target made with a toolchain + @test StaticCompiler.StaticTarget("wasm32", "", ""; toolchain = StaticCompiler.LLDToolchain(:wasm)).toolchain isa StaticCompiler.LLDToolchain + + # `main` made in IR: the executable runs without a C wrapper + dir = mktempdir() + hello_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 41) % Int + ir = StaticCompiler.generate_ir(((hello_main, Tuple{Int,Ptr{Ptr{UInt8}}}),); main_wrapper = "hello_main") + @test occursin(r"define i32 @main\(i32", ir) + ir_path = StaticCompiler.generate_ir(((hello_main, Tuple{Int,Ptr{Ptr{UInt8}}}),), dir, "hm"; main_wrapper = "hello_main") + driver = StaticCompiler.toolchain(host) + exe = joinpath(dir, StaticCompiler.output_name(driver, host, "hm_exe")) + StaticCompiler.link(driver, host, [ir_path], exe; entry = nothing) # (`main` is in the object) + @test run(ignorestatus(`$exe`)).exitcode == 42 # (argc is 1) + @test_throws ArgumentError StaticCompiler.generate_ir(((hello_main, Tuple{Int,Ptr{Ptr{UInt8}}}),); main_wrapper = "nothing_here") + + # linking by `lld`: a WebAssembly module (nothing outside of Julia is needed), and the refusals that say what is missing + wasm_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 41) % Int + wasm = StaticCompiler.StaticTarget("wasm64-unknown-unknown"; toolchain = StaticCompiler.LLDToolchain(:wasm)) + wasm_path = compile_executable(wasm_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "wasm_main"; target = wasm) + @test endswith(wasm_path, "wasm_main.wasm") && read(wasm_path, 4) == UInt8[0x00, 0x61, 0x73, 0x6d] + linux = StaticCompiler.StaticTarget("aarch64-unknown-linux-gnu"; toolchain = StaticCompiler.LLDToolchain(:gnu)) + @test_throws ArgumentError compile_executable(wasm_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "no_sysroot"; target = linux) # (the C library is the target's: `sysroot`) + @test_throws ArgumentError StaticCompiler.link(StaticCompiler.LLDToolchain(:gnu; sysroot = mktempdir()), linux, [ir_path], joinpath(dir, "x"); entry = "main") # (a sysroot that has no `crt1.o`) + @test_throws ArgumentError StaticCompiler.link(StaticCompiler.LLDToolchain(:wasm), wasm, [joinpath(dir, "a.ll")], joinpath(dir, "x")) # (`lld` links objects, not IR) +end + +@testset "Builtins and the start of main" begin + # what a program needs that a C runtime library has: found by what the IR says, for the target + i128ir = "define i128 @f(i128 %a, i128 %b) {\n %r = udiv i128 %a, %b\n ret i128 %r\n}\n" + halfir = "define float @g(half %a) {\n %r = fpext half %a to float\n ret float %r\n}\n" + @test StaticCompiler.needed_builtins(i128ir, "aarch64-unknown-linux-gnu") == [:LINUX_INT128_BUILTINS] + @test isempty(StaticCompiler.needed_builtins(i128ir, "aarch64-apple-macosx11.0.0")) # (macOS has them in its C library) + @test StaticCompiler.needed_builtins("", "x86_64-w64-windows-gnu") == [:MINGW_X64_BUILTINS] && StaticCompiler.needed_builtins("", "x86_64-w64-mingw32") == [:MINGW_X64_BUILTINS] # (the runtime of MinGW has to have the probe of the stack) + @test isempty(StaticCompiler.needed_builtins("", "x86_64-unknown-linux-gnu")) && occursin("___chkstk_ms:", StaticCompiler.add_builtins("", "x86_64-w64-windows-gnu")) + @test StaticCompiler.needed_builtins(halfir, "x86_64-unknown-linux-gnu") == [:HALF_BUILTINS] && StaticCompiler.needed_builtins(halfir, "wasm64-unknown-unknown") == [:HALF_BUILTINS] + @test StaticCompiler.needed_builtins(halfir, "x86_64-w64-windows-gnu") == [:HALF_BUILTINS, :MINGW_X64_BUILTINS] # (the convention of `xmm0`: the one of the IR with `half`, as on Linux) + @test StaticCompiler.needed_builtins(halfir, "x86_64-apple-macosx11.0.0") == [:MACOS_X86_HALF_BUILTINS] # (the one of Apple: an `i16` in an integer register) + @test StaticCompiler.needed_builtins(i128ir, "x86_64-w64-windows-gnu") == [:WINDOWS_INT128_BUILTINS, :MINGW_X64_BUILTINS] + # (by integer arithmetic, with no instruction of F16C, which not every machine that runs an x86-64 program has; with the conversions of `Float64` too; and for x86-64 with the `i16` of the + # library calls of its code generator, where WebAssembly has `half`) + soft = StaticCompiler.add_builtins(halfir, "x86_64-apple-macosx11.0.0") + added = soft[length(halfir)+1:end] + @test !occursin("f16c", soft) && !occursin(r"^[^;\n]*\bhalf\b"m, added) # (no `half` outside of the comments) + @test all(occursin(r"define linkonce_odr hidden \S+ @" * f * r"\(", added) for f in ("__extendhfsf2", "__truncsfhf2", "__truncdfhf2", "__extendhfdf2")) + @test occursin("define linkonce_odr hidden i16 @__truncsfhf2(float", added) && occursin("define linkonce_odr hidden float @__extendhfsf2(i16", added) + for triple in ("wasm64-unknown-unknown", "x86_64-unknown-linux-gnu", "x86_64-w64-windows-gnu") + wasm = StaticCompiler.add_builtins(halfir, triple) + @test occursin("define linkonce_odr hidden half @__truncsfhf2(float", wasm) && occursin("define linkonce_odr hidden float @__extendhfsf2(half", wasm) && !occursin("f16c", wasm) + end + # (128-bit division for Windows: the operands by address, and the result a vector of two integers of 64 bits; for Linux the integers themselves) + windows = StaticCompiler.add_builtins(i128ir, "x86_64-w64-windows-gnu") + @test all(occursin("define linkonce_odr hidden <2 x i64> @$f(ptr %pa, ptr %pb)", windows) for f in ("__udivti3", "__umodti3", "__divti3", "__modti3")) + @test occursin("define linkonce_odr hidden i128 @__udivti3(i128 %a, i128 %b)", StaticCompiler.add_builtins(i128ir, "x86_64-unknown-linux-gnu")) + @test isempty(StaticCompiler.needed_builtins(halfir, "aarch64-unknown-linux-gnu")) # (the CPU converts) + # (the same by the instructions of a module, which is not printed to be searched; and a name that says `half` is not a `half`) + namedir = "define i32 @half(i32 %a) {\n %r = add i32 %a, 1\n ret i32 %r\n}\n" + LLVM.@dispose ctx = LLVM.Context() begin + needed(ir, triple) = (mod = parse(LLVM.Module, ir); try; StaticCompiler.needed_builtins(mod, triple); finally; LLVM.dispose(mod); end) + @test needed(i128ir, "aarch64-unknown-linux-gnu") == [:LINUX_INT128_BUILTINS] && isempty(needed(i128ir, "aarch64-apple-macosx11.0.0")) + @test needed(halfir, "x86_64-unknown-linux-gnu") == [:HALF_BUILTINS] && needed(halfir, "wasm64-unknown-unknown") == [:HALF_BUILTINS] && needed(halfir, "x86_64-apple-macosx11.0.0") == [:MACOS_X86_HALF_BUILTINS] + @test isempty(needed(halfir, "aarch64-unknown-linux-gnu")) && isempty(needed(namedir, "wasm64-unknown-unknown")) + @test needed("", "x86_64-w64-windows-gnu") == [:MINGW_X64_BUILTINS] + end + # (a target that has a toolchain of its own is not given the default, which finds `clang` and the SDK) + own = StaticCompiler.LLDToolchain(:gnu; sysroot = "/nonexistent") + @test StaticCompiler.toolchain(StaticCompiler.StaticTarget("aarch64-unknown-linux-gnu"; toolchain = own, retarget = true)) === own + @test occursin("@__udivti3", StaticCompiler.add_builtins(i128ir, "aarch64-unknown-linux-gnu")) && StaticCompiler.add_builtins(halfir, "aarch64-unknown-linux-gnu") == halfir + # a toolchain asks for them: `lld` links nothing else, a compiler driver brings its runtime library + @test StaticCompiler.uses_builtins(StaticCompiler.LLDToolchain(:gnu)) && !StaticCompiler.uses_builtins(StaticCompiler.LLDToolchain(:gnu; builtins = false)) + @test !StaticCompiler.uses_builtins(StaticCompiler.CCToolchain(`cc`)) && StaticCompiler.uses_builtins(StaticCompiler.CCToolchain(`cc`; builtins = true)) + + # the IR of a program for Linux made with them (and with `retarget`: the code is the host's, the target is Linux) + div128(a::Int, b::Int) = (UInt128(a) ÷ UInt128(b)) % Int + tc = StaticCompiler.LLDToolchain(:gnu; sysroot = "/nonexistent") + target = StaticCompiler.StaticTarget("aarch64-unknown-linux-gnu"; toolchain = tc, retarget = true) + @test StaticCompiler.target_triple(target) == "aarch64-unknown-linux-gnu" && StaticCompiler.is_retargeted(target) && target.codegen.cpu in ("", "generic") + ir = StaticCompiler.generate_ir(div128, Tuple{Int,Int}; target) + @test occursin("target triple = \"aarch64-unknown-linux-gnu\"", ir) && occursin(r"define [^\n]*@__udivti3", ir) && !occursin("target datalayout", ir) + # (linked into the module of a target that is not retargeted, which has a data layout: with no warning of different layouts) + arch = String(first(split(LLVM.default_triple(), '-'))) + plain = StaticCompiler.StaticTarget("$arch-unknown-linux-gnu"; toolchain = StaticCompiler.LLDToolchain(:gnu; sysroot = "/nonexistent")) + plain_ir = @test_logs min_level = Base.CoreLogging.Warn StaticCompiler.generate_ir(div128, Tuple{Int,Int}; target = plain) + @test occursin(r"define [^\n]*@__udivti3", plain_ir) && occursin("target datalayout", plain_ir) + ir = StaticCompiler.generate_ir(div128, Tuple{Int,Int}; target = StaticCompiler.StaticTarget("aarch64-unknown-linux-gnu"; toolchain = StaticCompiler.LLDToolchain(:gnu; builtins = false), retarget = true)) + @test !occursin("@__udivti3", ir) + + # what the start of `main` does first (the program of a collector that looks at the stack from its top: `main` stores it) + hello_start(argc::Int, argv::Ptr{Ptr{UInt8}}) = argc % Int + prologue(builder, mod) = (LLVM.call!(builder, LLVM.FunctionType(LLVM.VoidType(), LLVM.LLVMType[]), LLVM.Function(mod, "static_start_mark", LLVM.FunctionType(LLVM.VoidType(), LLVM.LLVMType[]))); nothing) + ir = StaticCompiler.generate_ir(((hello_start, Tuple{Int,Ptr{Ptr{UInt8}}}),); main_wrapper = "hello_start", main_prologue = prologue) + @test occursin(r"define i32 @main\(i32[^\n]*\{\nentry:\n call void @static_start_mark\(\)", ir) # (first in `main`) +end + +@testset "Objects by retargeting" begin + # the object of the code generator of Julia's LLVM, for a triple that is not the host's (the host's architecture, for another system), made from IR that has the host's code + host_triple = "$(first(split(LLVM.default_triple(), '-')))-unknown-linux-gnu" + target = StaticCompiler.StaticTarget(host_triple; retarget = true) + @test StaticCompiler.can_emit_object(target) + obj = StaticCompiler.emit_object(StaticCompiler.generate_ir(fib, Tuple{Int}; target), target) + @test obj[1:4] == UInt8[0x7f, 0x45, 0x4c, 0x46] # ELF (and not the host's format) + + # where Julia's LLVM has no code generator, the `llc` of the target makes the object: here a script that stands for it (the arguments that it is given, and a file that it writes) + if !Sys.iswindows() + dir = mktempdir() + fake = joinpath(dir, "fakellc") + write(fake, "#!/bin/sh\necho \"\$@\" > $(joinpath(dir, "args"))\nout=\nwhile [ \$# -gt 0 ]; do if [ \"\$1\" = -o ]; then out=\$2; fi; shift; done\nprintf OBJECT > \"\$out\"\n") + chmod(fake, 0o755) + noisa = StaticCompiler.StaticTarget("fakearch64-unknown-linux-gnu", "mycpu", "+feat"; llc = fake) + @test !StaticCompiler.julia_llvm_has("fakearch64-unknown-linux-gnu") && StaticCompiler.can_emit_object(noisa) && !StaticCompiler.needs_ir(noisa) + @test String(StaticCompiler.emit_object("define void @f() {\n ret void\n}\n", noisa)) == "OBJECT" + args = read(joinpath(dir, "args"), String) + @test occursin("-mtriple=fakearch64-unknown-linux-gnu", args) && occursin("-mcpu=mycpu", args) && occursin("-mattr=+feat", args) && occursin("-filetype=obj", args) + # (no `llc`: only the IR can be made) + without = StaticCompiler.StaticTarget("fakearch64-unknown-linux-gnu") + @test !StaticCompiler.can_emit_object(without) && StaticCompiler.needs_ir(without) + @test_throws ArgumentError StaticCompiler.emit_object("define void @f() {\n ret void\n}\n", without) + end +end + +@testset "Linking for Linux from any host" begin + # the C library of the target (fetched for any host), and a program for it linked by `lld` alone + # (for the architecture of the host: the code generator for it is in Julia's LLVM wherever it is) + host_arch = String(first(split(LLVM.default_triple(), '-'))) + triple = "$host_arch-unknown-linux-gnu" + sysroot = StaticCompiler.glibc_sysroot(triple) + @test isfile(joinpath(sysroot, "lib", "crt1.o")) || isfile(joinpath(StaticCompiler.crt_directory(sysroot), "crt1.o")) + @test StaticCompiler.glibc_sysroot(Base.BinaryPlatforms.Platform(host_arch, "linux"; libc = "glibc")) == sysroot + # the version of the glibc is the version of the `Glibc_jll` that is in the environment (pinning it chooses the glibc) + v = StaticCompiler.glibc_version(sysroot) + @test v isa VersionNumber && (v.major, v.minor) == (pkgversion(Glibc_jll).major, pkgversion(Glibc_jll).minor) + @test isnothing(StaticCompiler.glibc_version(mktempdir())) # (a directory that has none) + lin_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 41) % Int + target = StaticCompiler.StaticTarget(triple; toolchain = StaticCompiler.LLDToolchain(:gnu; sysroot)) + # An object that cannot be made is refused, before the linker is asked for it + nobackend = StaticCompiler.StaticTarget("fakearch64-unknown-linux-gnu"; toolchain = StaticCompiler.LLDToolchain(:gnu; sysroot)) + @test_throws ArgumentError compile_executable(lin_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "nobackend"; target = nobackend) + div128(a::Int, b::Int) = (UInt128(a) ÷ UInt128(b)) % Int + exe = compile_executable(lin_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "lin_main"; target) + @test read(exe, 4) == UInt8[0x7f, 0x45, 0x4c, 0x46] # ELF + lib = compile_shlib(lin_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "lin_lib"; target) + @test endswith(lib, ".so") && read(lib, 4) == UInt8[0x7f, 0x45, 0x4c, 0x46] + # (and the builtins that an `lld` link has not: a division of `i128` links) + @test isfile(compile_shlib(div128, (Int, Int), mktempdir(), "div128"; target)) +end + +@testset "The finished module" begin + # `llvm_finalize` is called on the module as it is made into an object, or written: after the retargeting and the `main` + fin_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 1) % Int + seen = String[] + finalize(mod) = (push!(seen, string(LLVM.triple(mod), " ", haskey(LLVM.functions(mod), "main"))); LLVM.name!(first(f for f in LLVM.functions(mod) if LLVM.name(f) == "main"), "main2"); nothing) + ir = StaticCompiler.generate_ir(((fin_main, Tuple{Int,Ptr{Ptr{UInt8}}}),); main_wrapper = "fin_main", llvm_finalize = finalize, + target = StaticCompiler.StaticTarget("aarch64-unknown-linux-gnu"; retarget = true)) + @test seen == ["aarch64-unknown-linux-gnu true"] && occursin("@main2", ir) +end + +@testset "Mach-O and PE: LLDToolchain for macOS and Windows" begin + # the flavors, what they link with, and what they make + @test StaticCompiler.LLDToolchain(:darwin).libs == ["System"] && StaticCompiler.LLDToolchain(:gnu).libs == ["c", "m", "dl", "pthread"] && isempty(StaticCompiler.LLDToolchain(:wasm).libs) + @test "kernel32" in StaticCompiler.LLDToolchain(:mingw).libs && "mingw32" in StaticCompiler.LLDToolchain(:mingw).libs && StaticCompiler.LLDToolchain(:mingw; libs = ["a"]).libs == ["a"] + @test_throws ArgumentError StaticCompiler.LLDToolchain(:coff) + host = StaticCompiler.StaticTarget() + out(flavor, name; kind = :executable) = StaticCompiler.output_name(StaticCompiler.LLDToolchain(flavor), host, name; kind) + @test out(:darwin, "p") == "p" && out(:darwin, "l"; kind = :shared) == "l.dylib" # (whatever the host is) + @test out(:mingw, "p") == "p.exe" && out(:mingw, "l"; kind = :shared) == "l.dll" + @test out(:gnu, "p") == "p" && out(:gnu, "l"; kind = :shared) == "l.so" && out(:wasm, "p") == "p.wasm" + + # the SDK of macOS: the environment's, or Xcode's on a Mac, and else it has to be given + withenv("SDKROOT" => "/some/sdk") do + @test StaticCompiler.macos_sdk() == "/some/sdk" + end + withenv("SDKROOT" => nothing) do + if Sys.isapple() && !isnothing(Sys.which("xcrun")) + @test isdir(StaticCompiler.macos_sdk()) + else + @test_throws ArgumentError StaticCompiler.macos_sdk() + end + end + sdk = mktempdir() + @test StaticCompiler.sdk_version(sdk) == "11.0" # (without `SDKSettings.json`) + write(joinpath(sdk, "SDKSettings.json"), """{"CanonicalName":"macosx14.2","Version":"14.2","DisplayName":"macOS 14.2"}""") + @test StaticCompiler.sdk_version(sdk) == "14.2" + + # `mingw_sysroot`: the triples that it takes, and the refusals that come before the artifact (150 MB) is fetched, which `test/cross/matrix.jl` does + @test_throws ArgumentError StaticCompiler.mingw_sysroot("aarch64-w64-mingw32") # (`Mingw_jll` has x86_64 and i686) + @test_throws ArgumentError StaticCompiler.mingw_sysroot("aarch64-w64-windows-gnu") + @test_throws ArgumentError StaticCompiler.mingw_sysroot("x86_64-unknown-linux-gnu") # (not Windows) + @test_throws ArgumentError StaticCompiler.mingw_sysroot(StaticCompiler.StaticTarget("aarch64-w64-mingw32"; retarget = true)) + + # a MinGW-w64 root has the start files in its `lib`, and one without them is refused (what `Mingw_jll`'s artifact is: fetched by the matrix of `test/cross`, which is 150 MB) + root = mktempdir() + mkpath(joinpath(root, "lib")); touch(joinpath(root, "lib", "crt2.o")) + @test StaticCompiler.mingw_directory(root) == joinpath(root, "lib") + @test_throws ArgumentError StaticCompiler.mingw_directory(mktempdir()) + obj = joinpath(mktempdir(), "x.o"); touch(obj) + windows = StaticCompiler.StaticTarget("x86_64-w64-mingw32"; retarget = true) + @test_throws ArgumentError StaticCompiler.link(StaticCompiler.LLDToolchain(:mingw), windows, [obj], joinpath(dirname(obj), "x.exe")) # (no libraries) + @test_throws ArgumentError StaticCompiler.link(StaticCompiler.LLDToolchain(:mingw; sysroot = mktempdir()), windows, [obj], joinpath(dirname(obj), "x.exe")) # (no start files) + @test_throws ArgumentError StaticCompiler.link(StaticCompiler.LLDToolchain(:mingw; sysroot = root), StaticCompiler.StaticTarget("riscv64-w64-mingw32"; retarget = true), [obj], joinpath(dirname(obj), "x.exe")) # (no machine of PE for it) + + # Check that windows target is compiling the correct executable types + arch = String(first(split(LLVM.default_triple(), '-'))) + for triple in ("$arch-w64-mingw32", "$arch-w64-windows-gnu") + t = StaticCompiler.StaticTarget(triple) + @test StaticCompiler.target_triple(t) == "$arch-w64-windows-gnu" && StaticCompiler.iswindows(t) + win_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 41) % Int + obj = StaticCompiler.generate_obj(((win_main, Tuple{Int,Ptr{Ptr{UInt8}}}),), mktempdir(), "o"; target = t, main_wrapper = "win_main") + head = read(obj, 2) + @test head != UInt8[0x7f, 0x45] && head == (arch == "x86_64" ? UInt8[0x64, 0x86] : UInt8[0x64, 0xaa]) + end + @test StaticCompiler.target_triple(StaticCompiler.StaticTarget("$arch-w64-mingw32"; retarget = true)) == "$arch-w64-windows-gnu" + + # a program for macOS made with `lld` alone, and run (on an Apple Silicon Mac: the code generator for its architecture is in Julia's LLVM, and it runs) + if Sys.isapple() && Sys.ARCH === :aarch64 && !isnothing(Sys.which("xcrun")) + mac_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc + 41) % Int + target = StaticCompiler.StaticTarget("aarch64-apple-macosx11.0.0"; toolchain = StaticCompiler.LLDToolchain(:darwin)) + exe = compile_executable(mac_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "mac_main"; target) + @test success(`file $exe`) && occursin("Mach-O 64-bit executable arm64", read(`file $exe`, String)) + @test run(ignorestatus(`$exe`)).exitcode == 42 + @test success(`codesign -v $exe`) # (`lld` signs it: arm64 macOS will not run one that is not signed) + lib = compile_shlib(mac_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "mac_lib"; target) + @test endswith(lib, ".dylib") && occursin("shared library arm64", read(`file $lib`, String)) + end +end + +@testset "Hooks of a package that makes programs by compile_executable: the same for every toolchain" begin + # `main_prologue` is what `main` does first, and `llvm_finalize` is called on the whole module: the program that a C compiler driver links has them as one that `lld` links does (the object has the `main`, and not a wrapper in C) + prologue(builder, mod) = begin + i32 = LLVM.IntType(32) + exit_function = haskey(LLVM.functions(mod), "exit") ? LLVM.functions(mod)["exit"] : LLVM.Function(mod, "exit", LLVM.FunctionType(LLVM.VoidType(), [i32])) + LLVM.call!(builder, LLVM.function_type(exit_function), exit_function, LLVM.Value[LLVM.ConstantInt(i32, 3)]) + end + hook_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = 0 + finalized = Ref(0) + for ir in (false, true) + exe = compile_executable(hook_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "hook_main"; main_prologue = prologue, llvm_finalize = mod -> (finalized[] += 1), llvm_to_clang = ir) + @test run(ignorestatus(`$exe`)).exitcode == 3 + end + @test finalized[] == 2 + # (and without a prologue the program is what it was: the entry point's value is its status) + exe = compile_executable(hook_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "hook_main2") + @test run(ignorestatus(`$exe`)).exitcode == 0 + # objects in `cflags` are linked with the program + dir = mktempdir() + extra_c = joinpath(dir, "extra.c") + write(extra_c, "int static_compiler_extra(void) { return 7; }\n") + extra_o = joinpath(dir, "extra.o") + run(`$(StaticCompiler.clang()) -c $extra_c -o $extra_o`) + extra_main(argc::Int, argv::Ptr{Ptr{UInt8}}) = ccall("extern static_compiler_extra", llvmcall, Int32, ()) % Int + exe = compile_executable(extra_main, (Int, Ptr{Ptr{UInt8}}), mktempdir(), "extra_main"; cflags = `$extra_o`, llvm_to_clang = false) + @test run(ignorestatus(`$exe`)).exitcode == 7 +end + +# two entry points of one name (methods of one function): an error that says so with `demangle = true`, and numbered names, the oldest method first, with `demangle = false` +struct NameClashPair; a::Int; b::Int; end +name_clash(a, b) = a + b +name_clash(s::NameClashPair) = s.a + s.b +name_clash(a, b, c) = a + b + c +name_clash_int(a, b) = name_clash(a, b) +name_clash_pair(s) = name_clash(s) +@testset "Entry points of one name" begin + entries = ((name_clash, Tuple{NameClashPair}), (name_clash, Tuple{Int,Int,Int}), (name_clash, Tuple{Int,Int})) + err = try StaticCompiler.generate_obj(entries, mktempdir(), "clash"; demangle = true); nothing catch e e end + @test err isa ArgumentError && occursin("More than one entry point is named `name_clash`", err.msg) && occursin("demangle = false", err.msg) + # (the names have the types, whatever the order that the methods were defined or are given in) + @test StaticCompiler.compiled_names(entries; demangle = false) == ["julia_name_clash_NameClashPair", "julia_name_clash_Int64_Int64_Int64", "julia_name_clash_Int64_Int64"] + @test StaticCompiler.compiled_names(reverse(entries); demangle = false) == reverse(StaticCompiler.compiled_names(entries; demangle = false)) + @test StaticCompiler.argument_suffix(()) == "" && StaticCompiler.argument_suffix(Tuple{Vector{Int},Ptr{Ptr{UInt8}}}) == "Vector_Int64_Ptr_Ptr_UInt8" + # (what the types do not tell apart is numbered, the oldest method first) + @test StaticCompiler.compiled_names(((name_clash, Tuple{Int,Int}), (name_clash, Tuple{Int,Int})); demangle = false) == ["julia_name_clash_1", "julia_name_clash_2"] + ir = StaticCompiler.generate_ir(entries; demangle = false) + @test occursin(r"define [^\n]*@julia_name_clash_Int64_Int64\(i64[^,\n]*, i64[^,\n)]*\)", ir) # (the method of two numbers) + @test count(r"define [^\n]*@julia_name_clash_\w+\(", ir) == 3 + # a function of its own for each is as good + obj = StaticCompiler.generate_obj(((name_clash_int, Tuple{Int,Int}), (name_clash_pair, Tuple{NameClashPair})), mktempdir(), "noclash") + @test isfile(obj) + # (with `demangle = false` the types are in every name, also of an entry point that is alone: `julia_`, the function, and the types if it has arguments) + @test StaticCompiler.compiled_names(((name_clash_int, Tuple{Int,Int}),); demangle = false) == ["julia_name_clash_int_Int64_Int64"] + @test StaticCompiler.compiled_names(((name_clash_int, ()),); demangle = false) == ["julia_name_clash_int"] # (nothing for a function that takes no arguments) + @test occursin("@julia_name_clash_int_Int64_Int64(", string(StaticCompiler.static_llvm_module(name_clash_int, Tuple{Int,Int}; demangle = false))) + # (one entry point, or names that differ, are as they were) + @test StaticCompiler.compiled_names(((name_clash_int, Tuple{Int,Int}), (name_clash_pair, Tuple{NameClashPair})); demangle = true) == ["name_clash_int", "name_clash_pair"] +end + +# `demangle = :itanium`: the names of the Itanium C++ ABI, which these are (checked with the names that clang makes of the same declarations in C++: `_Z6my_addll`, ...) +module ItaniumNames + module Inner + struct P; a::Int; end + struct Q{T}; a::Int; end + h(a, b, c, d, e, f) = 1 + k(a, b, c, d) = 1 + end +end +struct ItaniumPoint; a::Int; end +itanium_add(a, b) = a + b +itanium_add(s::ItaniumPoint) = s.a +itanium_none() = 1 +itanium_many(a...) = 1 +@testset "Itanium names" begin + en(f, tt; kw...) = only(StaticCompiler.compiled_names(((f, tt),); demangle = :itanium, kw...)) + @test en(itanium_add, (Int, Int)) == "_Z11itanium_addll" + @test en(itanium_add, (ItaniumPoint,)) == "_Z11itanium_add12ItaniumPoint" + @test en(itanium_none, ()) == "_Z12itanium_nonev" + # (`long` has 32 bits on Windows: `long long`, `x`) + @test en(itanium_add, (Int, UInt); target = StaticCompiler.StaticTarget("x86_64-w64-mingw32")) == "_Z11itanium_addxy" + # the numbers, pointers, strings and complex numbers + @test en(itanium_many, (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, Float32, Float64, Char, Bool)) == "_Z12itanium_manyahstijlmnofdDib" + @test en(itanium_many, (Ptr{UInt8}, Ptr{UInt8}, Ptr{Cvoid}, Cstring, ComplexF64)) == "_Z12itanium_manyPhS_PvPKcCd" + # types of Julia as C++ classes in the namespaces of their modules, and repeated parts replaced by substitutions + @test en(itanium_many, (Vector{Int}, Vector{Int}, Tuple{Int,Float64}, Tuple{})) == "_Z12itanium_manyN4Core5ArrayIlLl1EEES1_NS_5TupleIJldEEENS2_IJEEE" + P, Q = ItaniumNames.Inner.P, ItaniumNames.Inner.Q + @test en(ItaniumNames.Inner.h, (Ptr{P}, P, Q{P}, Q{P}, Q{Int}, Q{Q{P}})) == "_ZN12ItaniumNames5Inner1hEPNS0_1PES1_NS0_1QIS1_EES4_NS3_IlEENS3_IS4_EE" + @test en(ItaniumNames.Inner.k, (Array{P,2}, Array{P,2}, Dict{Int,Float64}, Dict{Float64,Float64})) == "_ZN12ItaniumNames5Inner1kEN4Core5ArrayINS0_1PELl2EEES4_N4Base4DictIldEENS6_IddEE" + # the object has them + # (of the host's own target: `long` is 32 bits on Windows, where `Int` is `x`) + entries = ((itanium_add, (Int, Int)), (itanium_add, (ItaniumPoint,))) + expected = StaticCompiler.compiled_names(entries; demangle = :itanium, target = StaticCompiler.StaticTarget()) + @test expected == [Sys.iswindows() ? "_Z11itanium_addxx" : "_Z11itanium_addll", "_Z11itanium_add12ItaniumPoint"] + obj = StaticCompiler.generate_obj(entries, mktempdir(), "itanium"; demangle = :itanium) + bytes = String(read(obj)) + @test all(name -> occursin(name, bytes), expected) + @test_throws ArgumentError StaticCompiler.compiled_names(((itanium_add, (Int, Int)),); demangle = :nope) +end diff --git a/test/testintegration.jl b/test/testintegration.jl new file mode 100644 index 00000000..640255fe --- /dev/null +++ b/test/testintegration.jl @@ -0,0 +1,507 @@ +# Setup +testpath = pwd() +scratch = tempdir() +cd(scratch) + +function bumper_test(N::Int) + buf = AllocBuffer(MallocVector, sizeof(Float64) * N) + s = 0.0 + for i ∈ 1:N + # some excuse to reuse the same memory a bunch of times + @no_escape buf begin + v = @alloc(Float64, N) + v .= i + s += sum(v) + end + end + free(buf) + s +end + +@testset "Bumper.jl integration" begin + path = compile_shlib(bumper_test, (Int,), "./") + ptr = Libdl.dlopen(path, Libdl.RTLD_LOCAL) + + fptr = Libdl.dlsym(ptr, "bumper_test") + + @test bumper_test(8) == @ccall($fptr(8::Int)::Float64) +end + +# To remove output files +cleanup(files...) = foreach(f -> isfile(f) && rm(f), files) + +@testset "Standalone Executable Integration" begin + + jlpath = joinpath(Sys.BINDIR, Base.julia_exename()) # Get path to julia executable + + ## --- Times table, file IO, mallocarray + let + # Attempt to compile + # We have to start a new Julia process to get around the fact that Pkg.test + # disables `@inbounds`, but ironically we can use `--compile=min` to make that + # faster. + cleanup("times_table") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/times_table.jl`) + catch e + @warn "Could not compile $testpath/scripts/times_table.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Attempt to run + cleanup("table.tsv", "table.b") + println("4x4 times table (MallocArray):") + status = -1 + try + status = run(`./times_table 4 4`) + catch e + @warn "Could not run $(scratch)/times_table" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + # Test ascii output + @test parsedlm(Int, c"table.tsv", '\t') == (1:4)*(1:4)' + # Test binary output + @test fread!(szeros(Int, 4,4), c"table.b") == (1:4)*(1:4)' + end + + ## --- As above but with staticarray + + let + # Compile... + cleanup("stack_times_table") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/stack_times_table.jl`) + catch e + @warn "Could not compile $testpath/scripts/stack_times_table.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run.. + cleanup("table.tsv", "table.b") + println("5x5 times table (StackArray):") + status = -1 + try + status = run(`./stack_times_table`) + catch e + @warn "Could not run $(scratch)/stack_times_table" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + # Test ascii output + @test parsedlm(Int, c"table.tsv", '\t') == (1:5)*(1:5)' + # Test binary output + @test fread!(szeros(Int, 5,5), c"table.b") == (1:5)*(1:5)' + end + + + ## --- Reading from written files + + let + # Compile... + cleanup("readwrite") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/readwrite.jl`) + catch e + @warn "Could not compile $testpath/scripts/readwrite.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + cleanup("table.tsv", "table.b", "tableb.tsv", "tables.tsv", "tablets.tsv") + println("5x5 times table, read from file:") + status = -1 + try + status = run(`./readwrite 5 5`) + catch e + @warn "Could not run $(scratch)/readwrite" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + # Test binary output + @test fread!(szeros(Int, 5,5), c"table.b") == (1:5)*(1:5)' + # Test ascii output + @test parsedlm(Int, c"table.tsv", '\t') == (1:5)*(1:5)' + @test parsedlm(Int, c"tableb.tsv", '\t') == (1:5)*(1:5)' + @test parsedlm(Int, c"tables.tsv", '\t') == (1:5)*(1:5)' + @test parsedlm(Int, c"tablets.tsv", '\t') == (1:5)*(1:5)' + + end + + + ## --- "withmallocarray"-type do-block pattern + let + # Compile... + cleanup("withmallocarray") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/withmallocarray.jl`) + catch e + @warn "Could not compile $testpath/scripts/withmallocarray.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + println("3x3 malloc arrays via do-block syntax:") + status = -1 + try + status = run(`./withmallocarray 3 3`) + catch e + @warn "Could not run $(scratch)/withmallocarray" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end + + ## --- Random number generation + let + # Compile... + cleanup("rand_matrix") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/rand_matrix.jl`) + catch e + @warn "Could not compile $testpath/scripts/rand_matrix.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + println("5x5 uniform random matrix:") + status = -1 + try + status = run(`./rand_matrix 5 5`) + catch e + @warn "Could not run $(scratch)/rand_matrix" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end + + let + # Compile... + cleanup("randn_matrix") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/randn_matrix.jl`) + catch e + @warn "Could not compile $testpath/scripts/randn_matrix.jl" + println(e) + end + @static if Sys.isbsd() + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end + + # Run... + println("5x5 Normal random matrix:") + status = -1 + try + status = run(`./randn_matrix 5 5`) + catch e + @warn "Could not run $(scratch)/randn_matrix" + println(e) + end + @static if Sys.isbsd() + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end + end + + ## --- Test matrix multiplication by plain @inbounds loops + let + # Compile... + cleanup("inbounds_product") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/inbounds_product.jl`) + catch e + @warn "Could not compile $testpath/scripts/inbounds_product.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + cleanup("product.tsv") + println("10x10 table sum:") + status = -1 + try + status = run(`./inbounds_product 10 10`) + catch e + @warn "Could not run $(scratch)/inbounds_product" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + @test parsedlm(c"product.tsv",'\t')[] == 3025 + end + + let + # Compile... + cleanup("inbounds_matrix") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/inbounds_matrix.jl`) + catch e + @warn "Could not compile $testpath/scripts/inbounds_matrix.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + cleanup("table.tsv", "table.b") + println("10x5 MallocMatrix product, manual inbounds:") + status = -1 + try + status = run(`./inbounds_matrix 10 5`) + catch e + @warn "Could not run $(scratch)/inbounds_matrix" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + A = (1:10) * (1:5)' + # Check ascii output + @test parsedlm(c"table.tsv",'\t') == A' * A + # Check binary output + @test fread!(szeros(5,5), c"table.b") == A' * A + end + + let + # Compile... + cleanup("inbounds_matrix_stack") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/inbounds_matrix_stack.jl`) + catch e + @warn "Could not compile $testpath/scripts/inbounds_matrix_stack.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + cleanup("table.tsv") + println("10x5 StackMatrix product, manual inbounds:") + status = -1 + try + status = run(`./inbounds_matrix_stack`) + catch e + @warn "Could not run $(scratch)/inbounds_matrix_stack" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + A = (1:10) * (1:5)' + @test parsedlm(c"table.tsv",'\t') == A' * A + end + + ## --- Test built-in matrix multiplication + let + # Compile... + cleanup("matmul") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/matmul.jl`) + catch e + @warn "Could not compile $testpath/scripts/matmul.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + cleanup("table.tsv", "table.b") + println("10x5 MallocMatrix product:") + status = -1 + try + status = run(`./matmul 10 5`) + catch e + @warn "Could not run $(scratch)/matmul" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + A = (1:10) * (1:5)' + # Check ascii output + @test parsedlm(c"table.tsv",'\t') == A' * A + # Check binary output + @test fread!(szeros(5,5), c"table.b") == A' * A + end + + let + # Compile... + cleanup("matmul_stack") + status = -1 + try + status = run(`$jlpath --compile=min $testpath/scripts/matmul_stack.jl`) + catch e + @warn "Could not compile $testpath/scripts/matmul_stack.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + cleanup("table.tsv", "table.b") + println("10x5 StackMatrix product:") + status = -1 + try + status = run(`./matmul_stack`) + catch e + @warn "Could not run $(scratch)/matmul_stack" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + A = (1:10) * (1:5)' + # Check ascii output + @test parsedlm(c"table.tsv",'\t') == A' * A + # Check binary output + @test fread!(szeros(5,5), c"table.b") == A' * A + end + + ## --- Test string handling + + let + # Compile... + cleanup("print_args") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/print_args.jl`) + catch e + @warn "Could not compile $testpath/scripts/print_args.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + println("String indexing and handling:") + status = -1 + try + status = run(`./print_args foo bar`) + catch e + @warn "Could not run $(scratch)/print_args" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end + + ## --- Test string iteration + + let + # Compile... + cleanup("iterate") + status = -1 + try + status = run(`$jlpath --startup=no $testpath/scripts/iterate.jl`) + catch e + @warn "Could not compile $testpath/scripts/iterate.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + println("Iteration:") + status = -1 + try + status = run(`./iterate`) + catch e + @warn "Could not run $(scratch)/iterate" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end + + ## --- Test error throwing + + let + # Compile... + cleanup("maybe_throw") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/throw_errors.jl`) + catch e + @warn "Could not compile $testpath/scripts/throw_errors.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + println("Error handling:") + status = -1 + try + status = run(`./maybe_throw 10`) + catch e + @warn "Could not run $(scratch)/maybe_throw" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + status = -1 + try + status = run(`./maybe_throw -10`) + catch e + @info "maybe_throw: task failed sucessfully!" + end + @test status === -1 + end + + ## --- Test interop + + # (dlopen/dlsym are not available on Windows) + @static if !Sys.iswindows() let + # Compile... + cleanup("interop") + status = -1 + try + status = run(`$jlpath --startup=no --compile=min $testpath/scripts/interop.jl`) + catch e + @warn "Could not compile $testpath/scripts/interop.jl" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + + # Run... + println("Interop:") + status = -1 + try + status = run(`./interop`) + catch e + @warn "Could not run $(scratch)/interop" + println(e) + end + @test isa(status, Base.Process) + @test isa(status, Base.Process) && status.exitcode == 0 + end end + +end + +## --- Clean up + +cd(testpath) diff --git a/test/testquirks.jl b/test/testquirks.jl new file mode 100644 index 00000000..f40277e8 --- /dev/null +++ b/test/testquirks.jl @@ -0,0 +1,104 @@ +# Functions that can throw errors which need the Julia runtime to be thrown, unless StaticCompiler +# overrides them (see src/quirks.jl). These need to be defined globally due to +# https://github.com/JuliaLang/julia/issues/40990 +quirk_div(x::Int, y::Int) = div(x, y) +quirk_rem(x::Int, y::Int) = rem(x, y) +quirk_mod(x::Int, y::Int) = mod(x, y) +quirk_fld(x::Int, y::Int) = fld(x, y) +quirk_cld(x::Int, y::Int) = cld(x, y) +quirk_divrem(x::Int, y::Int) = first(divrem(x, y)) +quirk_udiv(x::UInt, y::UInt) = div(x, y) +quirk_urem(x::UInt, y::UInt) = rem(x, y) +quirk_i32div(x::Int32, y::Int32) = div(x, y) +quirk_i128div(x::Int, y::Int) = div(Int128(x) << 70, Int128(y)) % Int +quirk_i128rem(x::Int, y::Int) = rem(Int128(x) << 70 + 5, Int128(y)) % Int +quirk_u128rem(x::UInt, y::UInt) = rem(UInt128(x) << 70 + 5, UInt128(y)) % UInt +quirk_int(x::Float64) = Int(x) +quirk_trunc(x::Float64) = trunc(Int, x) +quirk_round(x::Float64) = round(Int, x) +quirk_floor(x::Float64) = floor(Int, x) +quirk_ceil(x::Float64) = ceil(Int, x) +quirk_u8(x::Float64) = UInt8(x) +quirk_i32(x::Float32) = Int32(x) +quirk_acos(x::Float64) = acos(x) +quirk_char(x::Int) = Int(Char(x)) +quirk_rational(x::Int, y::Int) = (x // y).num + +# the same, but triggering the error +quirk_divzero(argc::Int, argv::Ptr{Ptr{UInt8}}) = div(argc, argc - 1) +quirk_remzero(argc::Int, argv::Ptr{Ptr{UInt8}}) = rem(argc, argc - 1) +quirk_divovf(argc::Int, argv::Ptr{Ptr{UInt8}}) = div(typemin(Int) + argc - 1, -argc) +quirk_i128zero(argc::Int, argv::Ptr{Ptr{UInt8}}) = div(Int128(argc), Int128(argc - 1)) % Int +quirk_inexact(argc::Int, argv::Ptr{Ptr{UInt8}}) = Int(argc + 0.5) +quirk_acoserr(argc::Int, argv::Ptr{Ptr{UInt8}}) = round(Int, acos(argc + 1.0)) +quirk_emptyfirst(argc::Int, argv::Ptr{Ptr{UInt8}}) = (first(()); 0) +quirk_error(argc::Int, argv::Ptr{Ptr{UInt8}}) = (argc > 0 && error("bad"); 0) + +@testset "Overridden error paths" begin + workdir = mktempdir() + + # The functions link without the Julia runtime and agree with Base when no error is thrown + funcs = [(quirk_div, (Int, Int)), (quirk_rem, (Int, Int)), (quirk_mod, (Int, Int)), + (quirk_fld, (Int, Int)), (quirk_cld, (Int, Int)), (quirk_divrem, (Int, Int)), + (quirk_udiv, (UInt, UInt)), (quirk_urem, (UInt, UInt)), (quirk_i32div, (Int32, Int32)), + (quirk_i128div, (Int, Int)), (quirk_i128rem, (Int, Int)), (quirk_u128rem, (UInt, UInt)), + (quirk_int, (Float64,)), (quirk_trunc, (Float64,)), (quirk_round, (Float64,)), + (quirk_floor, (Float64,)), (quirk_ceil, (Float64,)), (quirk_u8, (Float64,)), + (quirk_i32, (Float32,)), (quirk_acos, (Float64,)), (quirk_char, (Int,)), + (quirk_rational, (Int, Int))] + path = compile_shlib(funcs, workdir, "libquirks") + lib = Libdl.dlopen(path, Libdl.RTLD_LOCAL) + sym(f) = Libdl.dlsym(lib, string(nameof(f))) + + xs = (-7, -1, 0, 1, 5, 123456789, typemax(Int)) + ys = (-3, -1, 1, 2, 7, typemax(Int)) + for f in (quirk_div, quirk_rem, quirk_mod, quirk_fld, quirk_cld, quirk_divrem), + x in xs, y in ys + @test ccall(sym(f), Int, (Int, Int), x, y) == f(x, y) + end + # `rem` and `mod` by -1 are fine even for typemin + @test ccall(sym(quirk_rem), Int, (Int, Int), typemin(Int), -1) == 0 + @test ccall(sym(quirk_mod), Int, (Int, Int), typemin(Int), -1) == 0 + for x in UInt.((0, 1, 7)) ∪ typemax(UInt), y in UInt.((1, 2, 7)) ∪ typemax(UInt) + @test ccall(sym(quirk_udiv), UInt, (UInt, UInt), x, y) == quirk_udiv(x, y) + @test ccall(sym(quirk_urem), UInt, (UInt, UInt), x, y) == quirk_urem(x, y) + end + for f in (quirk_i128div, quirk_i128rem), x in xs, y in ys + @test ccall(sym(f), Int, (Int, Int), x, y) == f(x, y) + end + for x in UInt.((0, 1, 7)) ∪ typemax(UInt), y in UInt.((1, 2, 7)) ∪ typemax(UInt) + @test ccall(sym(quirk_u128rem), UInt, (UInt, UInt), x, y) == quirk_u128rem(x, y) + end + @test ccall(sym(quirk_i32div), Int32, (Int32, Int32), Int32(-9), Int32(2)) == -4 + for x in (-2.5, -1.5, -0.0, 0.0, 0.4, 0.5, 1.5, 2.5, 3.7, -3.7, 1e10, -1e10) + for f in (quirk_trunc, quirk_round, quirk_floor, quirk_ceil) + @test ccall(sym(f), Int, (Float64,), x) == f(x) + end + end + for x in (-3.0, 0.0, 7.0, 1e10) + @test ccall(sym(quirk_int), Int, (Float64,), x) == Int(x) + end + @test ccall(sym(quirk_u8), UInt8, (Float64,), 200.0) == 200 + @test ccall(sym(quirk_i32), Int32, (Float32,), -5f0) == -5 + @test ccall(sym(quirk_acos), Float64, (Float64,), 0.5) == acos(0.5) + @test ccall(sym(quirk_char), Int, (Int,), 0x41) == 0x41 + @test ccall(sym(quirk_rational), Int, (Int, Int), 6, 4) == 3 + Libdl.dlclose(lib) + + # The errors exit with a message instead + function run_quirk(f) + path = compile_executable(f, (Int, Ptr{Ptr{UInt8}}), workdir) + proc = open(ignorestatus(`$path`)) + out = read(proc, String) + wait(proc) + proc.exitcode, out + end + for (f, msg) in ((quirk_divzero, "Integer division error"), (quirk_remzero, "Integer division error"), + (quirk_divovf, "Integer division error"), (quirk_i128zero, "Integer division error"), (quirk_inexact, "Inexact conversion"), + (quirk_acoserr, "domain"), (quirk_emptyfirst, "Tuple must be non-empty"), + (quirk_error, "error() called")) + code, out = run_quirk(f) + @test code == 1 + @test occursin(msg, out) + end +end