diff --git a/.claude/ci/benchmarks.md b/.claude/ci/benchmarks.md index d7e5328ed6..97248ca0f1 100644 --- a/.claude/ci/benchmarks.md +++ b/.claude/ci/benchmarks.md @@ -17,6 +17,7 @@ | `benchmarks-pr-comment-appsec` | same | Same flow for AppSec, with its own comment header; needs `benchmarks-appsec` | | `benchmarks-pr-comment-profiler` | same | Same flow for the profiler, with its own comment header; needs `benchmarks-profiler` | | `build-benchmark-ci-images` | (built in-repo from `.gitlab/benchmarks/container/`) | Manual job that builds the microbenchmark CI image from `.gitlab/benchmarks/container/`; described in `.gitlab/benchmarks/README.md` § How to rebuild the CI Docker image | +| `build-llvm-bolt-align-image` | (built in-repo from `.gitlab/benchmarks/container/llvm-bolt-align/`) | Manual job that builds the static `llvm-bolt-align` tool image copied into the microbenchmark CI image; described in `.gitlab/benchmarks/README.md` § Rebuilding the `llvm-bolt-align` image | | `macrobenchmarks: [{PHP_VERSION}]` | `486234852809.dkr.ecr.us-east-1.amazonaws.com/ci/benchmarking-platform:php_laravel-realworld` | Runs a Laravel Realworld application under k6 load at three traffic levels; PHP 7.4 and 8.1 | | `check-big-regressions` | `registry.ddbuild.io/images/benchmarking-platform-tools-ubuntu@sha256:b682acae509fa391ac559705b66df07cac876e4c46641d2457077972a1c0bbb8` | Post-benchmark gate: fails if `benchmarks-tracer` results contain a regression above threshold, or if any part's candidate results (or baseline results, when there is a baseline branch) are missing | | `check-slo-breaches` | (benchmarking-platform-tools template) | Post-macrobenchmark gate: evaluates SLO breaches | @@ -27,8 +28,9 @@ Runner: `runner:apm-k8s-tweaked-metal` (microbenchmarks); `runner:apm-k8s-same-c **Trigger rules:** - `benchmarks-tracer` — runs on every push; has an early-exit guard: if none of - `ext/`, `src/`, `components/`, `components-rs/`, - `zend_abstract_interface/`, `tests/Benchmarks/`, `benchmark/`, `tea/` + `ext/`, `tracer/`, `src/`, `components/`, `components-rs/`, + `zend_abstract_interface/`, `tests/Benchmarks/`, `benchmark/`, `tea/`, + `.gitlab/benchmarks/` or `.gitlab/benchmarks.yml` changed relative to `master`, exits 0 and `check-big-regressions` also skips. - `benchmarks-appsec` — auto-runs when `appsec/src/**/*` changed; @@ -61,16 +63,20 @@ dev container. ### Running the benchmarks -The `.gitlab/benchmarks/` directory is only the -CI orchestrator — it calls `make benchmarks` and friends. You do not -need `bp-runner` for local runs. Three approaches, from simplest to -most flexible: +The `.gitlab/benchmarks/` directory is the CI orchestrator: it checks out +the candidate and baseline, builds and BOLT-aligns them, and runs +`benchmark/runall.sh`, which calls `make benchmarks` and friends. You do not +need `bp-runner` to run those targets locally. To run the whole flow, see +"Full CI flow with BOLT alignment" below. Three approaches for the targets, +from simplest to most flexible: -**Approach 1 — `make benchmarks` (CI-like, clean cache)** +**Approach 1 — `make benchmarks` (clean cache)** -This matches what CI does: build + benchmark in one step from a clean -overlay. The default autotools configure includes the Rust sidecar in -the link, so no special handling is needed. +Builds and benchmarks in one step from a clean overlay. The default autotools +configure includes the Rust sidecar in the link, so no special handling is +needed. It builds the default, tracer-only extension, not the combined +tracer + profiler + AppSec extension that CI measures (see "Full CI flow with +BOLT alignment" below), so its numbers are not comparable to CI's. ```bash .claude/ci/dockerh --cache bench-82 --clean-cache --overlayfs --root \ @@ -166,11 +172,67 @@ to run all suites. For OPcache benchmarks use `call_benchmarks_opcache`. Use separate `--cache` names (e.g. `bench-82-baseline` and `bench-82-candidate`) to avoid rebuilding when switching branches. +### Full CI flow with BOLT alignment + +Runs `.gitlab/benchmarks/steps/run-benchmarks.sh` as the CI job does: clones +the candidate and its merge-base with `master` into `/app`, builds both, +aligns them with `llvm-bolt-align`, and runs both. The scripts write `/app`, +`/etc/hosts` and a sysctl, so run them as root in the CI image +(`$MICROBENCHMARKS_CI_IMAGE`, see `.gitlab/benchmarks.yml`) on an amd64 Linux +machine. The registry may be unreachable from the machine you build on; copy +the image over with `docker save | ssh ... docker load`. + +1. The scripts clone from GitHub, so push the branch, or point the clone at a + local checkout: mount it at `/src` with local branches `$BRANCH` and + `master`, and redirect the URL (see `drive.sh` below). +2. `drive.sh`, mounted into the container (`BP_SCENARIO` is `profiler`, + `tracer` or `appsec`; `profiler` is the shortest): + ```bash + set -ex + git config --global --add safe.directory '*' + git config --global url."/src/".insteadOf \ + https://github.com/DataDog/dd-trace-php/ + # Fewer than 48 CPUs: run-revision.sh pins to 34-47; ignore the pinning. + mkdir -p /shim + printf '#!/bin/sh\nif [ "$1" = -c ]; then shift 2; fi\nexec "$@"\n' \ + > /shim/taskset + chmod +x /shim/taskset + export PATH=/shim:$PATH + export CI_COMMIT_REF_NAME=$BRANCH CI_PROJECT_NAME=dd-trace-php + export CI_COMMIT_SHA=$(git -C /src rev-parse "$BRANCH") + export CI_PROJECT_DIR=/out ARTIFACTS_DIR=/out/artifacts + export BP_SCENARIO=profiler BASELINE_BRANCH=master + export COMPOSER_ALLOW_SUPERUSER=1 DD_TRACE_AUTOLOAD_NO_COMPILE=true + mkdir -p "$ARTIFACTS_DIR" + sysctl -w kernel.perf_event_paranoid=2 || true + /src/.gitlab/benchmarks/steps/run-benchmarks.sh + ``` +3. ```bash + docker run --rm --privileged -e BRANCH=my-branch \ + -v /path/to/checkout:/src:ro -v /path/to/out:/out \ + -v $PWD/drive.sh:/drive.sh:ro IMAGE bash /drive.sh + ``` +4. The aligned count is in the log (`BOLT-ALIGN: pinned N functions (100%)`; + anything well below 100% means the two builds name functions differently). + Results are in `/out/artifacts`: `candidate-*`, `baseline-*`, + `bolt-mode.txt` and `bolt/`. With fewer than 48 CPUs the timings only show + that the pipeline works. + +Verified for the `profiler` scenario only. The `tracer` and `appsec` scenarios +also start mysql and redis, and the `bp-runner` form of the job additionally +needs a Datadog agent and API key. + ### Services needed by some benchmarks Some benchmark suites (e.g. `PDOBench`, `PHPRedisBench`) need MySQL -and Redis. The CI image has them pre-installed. Add these to the -`bash -c` script before running benchmarks: +and Redis, and `make composer_tests_update` needs MySQL too: Laravel's +post-install step creates a database on the `mysql-integration` host. + +The `datadog/dd-trace-ci` images used in the approaches above have neither +server, so those commands fail in `composer_tests_update` there. The +microbenchmark CI image (`$MICROBENCHMARKS_CI_IMAGE`) has both installed but +not running. In it, start them before `composer_tests_update` and the +benchmarks, as the job's setup step does: ```bash service mysql start @@ -179,7 +241,8 @@ echo "127.0.0.1 mysql-integration" >> /etc/hosts echo "127.0.0.1 redis-integration" >> /etc/hosts ``` -Or filter them out: +Or skip those two suites when running the benchmarks (this does not help +`composer_tests_update`, which still needs MySQL): `make call_benchmarks FILTER='PDO(*SKIP)(*F)|Redis(*SKIP)(*F)|.'` ## Investigating a Regression @@ -194,7 +257,7 @@ curl -s -H "PRIVATE-TOKEN: $GITLAB_PERSONAL_ACCESS_TOKEN" \ ## Gotchas -- If the job log says "No tracer-related file changes detected — skipping benchmark +- If the job log says "No tracer-related file changes detected - skipping benchmark execution", `check-big-regressions` also skips. This is expected, not a failure. - `macrobenchmarks` has `allow_failure: true` — it will not block the pipeline. diff --git a/.gitlab/benchmarks.yml b/.gitlab/benchmarks.yml index bf8a07ab35..d351ca5667 100644 --- a/.gitlab/benchmarks.yml +++ b/.gitlab/benchmarks.yml @@ -110,7 +110,8 @@ variables: # Microbenchmarks CI image, consumed by the benchmark jobs below. Repin to the # tag pushed by a `build-benchmark-ci-images` run after changing anything in # `.gitlab/benchmarks/container/` (see `.gitlab/benchmarks/README.md`). - MICROBENCHMARKS_CI_IMAGE: registry.ddbuild.io/ci/benchmarking-platform:dd-trace-php-152770667 + # Built here: https://gitlab.ddbuild.io/DataDog/apm-reliability/dd-trace-php/-/jobs/2300686392 + MICROBENCHMARKS_CI_IMAGE: registry.ddbuild.io/ci/benchmarking-platform:dd-trace-php-156499868 # The Dockerfile is located at: .gitlab/benchmarks/container/Dockerfile BASE_CI_IMAGE_SUFFIX: dd-trace-php-${CI_PIPELINE_ID} BASE_CI_IMAGE_CONTAINER_DIR: .gitlab/benchmarks/container @@ -126,6 +127,18 @@ variables: build-benchmark-ci-images: stage: benchmarks +# Static llvm-bolt-align tool image, copied into the image above. Its Dockerfile +# is `.gitlab/benchmarks/container/llvm-bolt-align/Dockerfile`; after a rebuild, +# repin the `FROM` of `.gitlab/benchmarks/container/Dockerfile`. +build-llvm-bolt-align-image: + extends: build-benchmark-ci-images + needs: [] + timeout: 2h + variables: + BASE_CI_IMAGE_SUFFIX: llvm-bolt-align-${CI_PIPELINE_ID} + BASE_CI_IMAGE: registry.ddbuild.io/ci/benchmarking-platform:$BASE_CI_IMAGE_SUFFIX + BASE_CI_IMAGE_CONTAINER_DIR: .gitlab/benchmarks/container/llvm-bolt-align + workflow: auto_cancel: on_new_commit: interruptible @@ -230,7 +243,7 @@ workflow: echo "Could not diff against master - running benchmarks" CHANGED_FILES=benchmark/ fi - if ! echo "$CHANGED_FILES" | grep -q -E "^(ext/|src/|components/|components-rs/|zend_abstract_interface/|tests/Benchmarks/|benchmark/|tea/|\.gitlab/benchmarks\.yml|\.gitlab/benchmarks/)"; then + if ! echo "$CHANGED_FILES" | grep -q -E "^(ext/|tracer/|src/|components/|components-rs/|zend_abstract_interface/|tests/Benchmarks/|benchmark/|tea/|\.gitlab/benchmarks/|\.gitlab/benchmarks\.yml$)"; then echo "No tracer-related file changes detected - skipping benchmark execution" echo "Reports directory created but empty (no benchmarks needed)" > "${ARTIFACTS_DIR}/skip-reason.txt" exit 0 @@ -238,13 +251,14 @@ workflow: echo "Tracer-related file changes detected - proceeding with benchmarks" fi # Keep submodules at the selected candidate and baseline revisions. The - # whole flow (agent, one-time setup, run, analyze, S3) is driven by the - # bp-runner config; baseline resolution is bp-runner's auto lookup. + # whole flow (agent, one-time setup, paired run, analyze, S3) is driven by + # the in-repo bp-runner config and PHP step scripts. - >- GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=submodule.recurse GIT_CONFIG_VALUE_0=true BP_SCENARIO=$SCENARIO bp-runner "${CI_PROJECT_DIR}/.gitlab/benchmarks/bp-runner.yml" --debug -t artifacts: name: "reports" + when: always paths: - reports/ expire_in: 3 months @@ -256,6 +270,9 @@ workflow: UPSTREAM_BRANCH: $CI_COMMIT_REF_NAME UPSTREAM_COMMIT_SHA: $CI_COMMIT_SHA DD_SIDECAR_DISABLE_DIRECT_EXEC: 1 + # Empty selects align for comparisons, plain for candidate-only runs. + # Override with off/plain/align when comparing binary processing modes. + BOLT_MODE: "" # See https://datadoghq.atlassian.net/wiki/spaces/APMINT/pages/7223313012/Flaky+Benchmarks+Monitoring for more details. # Analyzer settings. Every bp-runner step inherits the CI process environment, # so the settings live here instead of the config. diff --git a/.gitlab/benchmarks/README.md b/.gitlab/benchmarks/README.md index 0026930d42..8064ec454d 100644 --- a/.gitlab/benchmarks/README.md +++ b/.gitlab/benchmarks/README.md @@ -12,8 +12,11 @@ This directory holds everything the microbenchmark jobs need: built in-repo via the [`build-ci-images.template.yml`](https://github.com/DataDog/benchmarking-platform-tools/blob/main/images/templates/gitlab/build-ci-images.template.yml) include (see [How to rebuild the CI Docker image](#how-to-rebuild-the-ci-docker-image)). -- **`steps/`**: `update-dd-agent-config.sh`, the config script of the - `datadog_agent` step (bp-runner has no `update_dd_agent_config` step type). +- **`container/llvm-bolt-align/`**: Dockerfile, patch and smoke test for the + static `llvm-bolt-align` tool image that the CI image copies in (see + [Rebuilding the `llvm-bolt-align` image](#rebuilding-the-llvm-bolt-align-image)). +- **`steps/`**: PHP checkout, BOLT preparation and execution scripts, plus + the Datadog agent configuration script. - **`bp-runner.yml`**: [bp-runner](https://github.com/DataDog/benchmarking-platform-tools/tree/main/bp-runner) experiment definition: captures hardware/software info, starts a local Datadog agent, does the one-time setup (ini appends, mysql and redis start, @@ -42,11 +45,15 @@ Execution flow on each PR: 1. Each benchmark job sets `SCENARIO` (`tracer`, `appsec` or `profiler`) and runs `bp-runner .gitlab/benchmarks/bp-runner.yml`: hardware/software info capture, Datadog agent, one-time setup, then the candidate and baseline - runs (the baseline is the PR's merge-target branch, at the merge base, - resolved by bp-runner's auto lookup). `benchmarks-tracer` is a matrix of - three jobs, one per `TRACER_PART` (`phpbench`, `phpbench-opcache`, `tea`), - and `runall.sh` runs only that part. A baseline whose `runall.sh` predates - `TRACER_PART` runs the candidate's copy instead. + runs. The PHP step resolves the PR's merge-target branch with + `github-find-merge-into-branch` (or uses `BASELINE_BRANCH` when set), then + takes its merge base with the exact candidate commit. + Unless `BOLT_MODE=off`, both revisions are compiled and BOLT-processed + (aligned as a pair by default) before either is measured. + `benchmarks-tracer` is a matrix of three jobs, one per `TRACER_PART` + (`phpbench`, `phpbench-opcache`, `tea`), and `runall.sh` runs only that + part. A baseline whose `runall.sh` predates `TRACER_PART` runs the + candidate's copy instead. 2. Each run's `benchmark/` suite results are saved as `reports/$BASELINE_OR_CANDIDATE-.` artifacts; only the AppSec job also uploads the logs, tarred as `candidate.tar.gz`/`baseline.tar.gz`. @@ -62,6 +69,56 @@ Execution flow on each PR: `bp-runner.fail-on-regression.yml`, and `benchmarks-pr-comment*` comments the comparison on the PR. +## Binary layout processing + +All three scenarios measure the combined `ddtrace.so`. For comparisons, +`llvm-bolt-align` rewrites both the baseline and candidate after linking, +placing their common functions at matching offsets. It does not replace +the linker and requires no profile. Both builds retain relocations with +`-Wl,--emit-relocs` and disable GCC's hot/cold block partitioning with +`-fno-reorder-blocks-and-partition`. + +Set the CI variable `BOLT_MODE` to choose the processing step: + +| Value | Processing after linking | +| --- | --- | +| Empty (default) | `align` when a baseline exists; `plain` for a candidate-only run. | +| `align` | Pairwise rewrite with `llvm-bolt-align`; requires a baseline. | +| `plain` | Independently rewrite each module with `llvm-bolt`, without a profile. | +| `off` | Run the normally linked modules without BOLT processing. | + +Explicit alignment fails when no baseline can be found. A failed baseline +lookup also fails the job. The candidate-only default applies when the +lookup succeeds and returns no target branch, as on master runs. +Master runs have no baseline, so they use `plain` processing and their results +are not directly comparable to the aligned comparisons on PRs. +Both source revisions must contain the combined-extension harness from +[#4520](https://github.com/DataDog/dd-trace-php/pull/4520); older harnesses +are rejected because they rebuild separate modules. + +The PHP image copies a static LLVM 23.1.6 build with +[`llvm-bolt-align`](https://github.com/llvm/llvm-project/pull/210634) +from a digest-pinned tool image. `llvm-bolt` and `llvm-bolt-align` use the +same executable, selecting their operation by the invocation name. +The LLVM 16 packages in the PHP image serve the existing compiler/LTO +toolchain; BOLT runs after linking. + +`llvm-bolt-align` pairs functions by symbol name, and Cargo derives the names +of Rust symbols from the absolute path of the libdatadog crates. The step +therefore builds both revisions in the same scratch directory, copies each +module out, and installs the aligned module into its checkout. Building in +`/app/candidate` and `/app/baseline` would leave about 40% of the functions +(all the Rust ones) unmatched and unaligned. + +`DD_TRACE_ASSUME_COMPILED=1` prevents the benchmark harness from rebuilding +the rewritten module. The installed and build-directory modules are +checked against the selected BOLT output after each run. Unsatisfied +alignment constraints or unexpected module replacement fail the job. +`reports/bolt-mode.txt` records the processing mode, and `reports/bolt/` +retains the tool's diagnostic logs. Temporary BOLT outputs are removed when +the step exits. Checkouts remain at `/app/candidate` and `/app/baseline` for +the shared analyzer to read their Git metadata; they are not uploaded. + ## How to add a new microbenchmark Where a benchmark lives depends on the scenario it belongs to: @@ -157,6 +214,15 @@ or updating `sirun`). 5. Push the update. The microbenchmarks now run against the rebuilt image. Verify a green benchmark pipeline before merging. +### Rebuilding the `llvm-bolt-align` image + +The CI image copies `llvm-bolt` and `llvm-bolt-align` from a digest-pinned tool +image (the first `FROM` in `container/Dockerfile`). Its sources are in +`container/llvm-bolt-align/` (see its README). To change it, edit that +directory, push, play the manual `build-llvm-bolt-align-image` job (up to two +hours), repin the `FROM` to the tag and digest it pushed, and then rebuild and +repin the CI image as above. + ## How to run the suite locally The suites themselves live in the tracer repository, so the quick feedback @@ -169,13 +235,12 @@ Benchmarking Platform wrapper: make benchmarks # tracer PHPBench scenarios make benchmarks_opcache # the same scenarios under OPCache make benchmarks_tea # the C++ Google Benchmark suite - # AppSec adds: make install_appsec, then - # BENCHMARK_EXTRA="--group=frameworks" make call_benchmarks + # For the combined-extension AppSec run, use benchmark/runall.sh below. ``` -- profiler: `SCENARIO=profiler ./benchmark/runall.sh` from the repo root - (sirun drives `profiling/benches/timeline.json` and - `profiling/benches/exceptions.json` after a natively compiled profiler; - see `benchmark/run_with_native_profiler.sh`). +- combined-extension suites: from `benchmark/`, run + `SCENARIO=profiler ./runall.sh` (or `tracer` / `appsec`) with + `ARTIFACTS_DIR` set to an absolute output directory. The profiler's sirun + workloads load `tmp/build_combined/modules/ddtrace.so`. To reproduce a full CI run including the baseline comparison, run the job's steps from the repository root with the environment the CI job provides @@ -185,11 +250,19 @@ variables the CI jobs set (`UNCONFIDENCE_THRESHOLD=2.0`, `CI_TYPE=theoretical`, significance threshold of 1.0 and prints the unchanged-results table: ```bash -export ARTIFACTS_DIR="$(pwd)/reports" +export ARTIFACTS_DIR="$(pwd)/reports" CI_PROJECT_DIR="$(pwd)" +export CI_PROJECT_NAME=dd-trace-php CI_COMMIT_REF_NAME="$(git branch --show-current)" CI_COMMIT_SHA="$(git rev-parse HEAD)" export UNCONFIDENCE_THRESHOLD=2.0 CI_TYPE=theoretical MD_REPORT_ONLY_CHANGES=1 SCENARIO=tracer BP_SCENARIO=tracer bp-runner .gitlab/benchmarks/bp-runner.yml --debug -t ``` +The job clones both revisions from GitHub, so the branch and commit must be +pushed. Set `BASELINE_BRANCH` (e.g. `master`) to skip the baseline lookup. + +The steps expect a writable `/app` and root; to run them locally, use the CI +image in a container (see `.claude/ci/benchmarks.md` § Full CI flow with BOLT +alignment). + Note that `bp-runner.yml` starts a real Datadog agent (the API key comes from AWS SSM in CI, set `DD_API_KEY` yourself locally), needs a GitHub token for the baseline lookup, and pins the benchmark CPUs (34-47 on the 48-core CI diff --git a/.gitlab/benchmarks/bp-runner.yml b/.gitlab/benchmarks/bp-runner.yml index e1f9659777..87fa2df6ac 100644 --- a/.gitlab/benchmarks/bp-runner.yml +++ b/.gitlab/benchmarks/bp-runner.yml @@ -18,9 +18,7 @@ experiments: cpus: 24-25 config_sh: .gitlab/benchmarks/steps/update-dd-agent-config.sh - # One-time setup only. run_microbenchmarks executes the run script once - # for the candidate and once for the baseline, so the ini appends, the - # mysql/redis start and the sysctl must NOT live there. + # Configure services once for the paired candidate/baseline run. - name: One-time setup run: shell cpus: 26-47 @@ -55,70 +53,11 @@ experiments: steps: - name: Run benchmarks - run: run_microbenchmarks - repo: DataDog/dd-trace-php + run: shell cpus: 26-47 - # The default fetch does not initialise submodules, and the suites need - # the libdatadog and google-benchmark submodules. The clone follows the - # branch tip, so the submodules must be re-synced after the SHA checkout. - how_to_fetch_release: | - git clone --recurse-submodules --branch $BRANCH https://github.com/DataDog/dd-trace-php/ "$CODE_SRC" - cd "$CODE_SRC" && git checkout $COMMIT_SHA - git submodule update --init --recursive - # Runs once per release: bp-runner sets CODE_SRC, BRANCH, COMMIT_SHA and - # BASELINE_OR_CANDIDATE (candidate first, then the baseline at the merge - # base, with baseline resolution left to bp-runner's auto lookup). - # runall.sh writes fixed, unprefixed names into $ARTIFACTS_DIR; this - # script renames each result to - # $ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-., the layout the - # analyze steps below and the fail-on-regression gate glob, gives the - # OPCache and AppSec subjects their distinguishing suffixes, and tars - # the run's logs. - how_to_run_benchmarks: | - set -e - export SCENARIO=$BP_SCENARIO - unset CI - - GITLAB_ARTIFACTS_PATH="$CI_PROJECT_DIR" - - cd "$CODE_SRC/benchmark/" - rm -rf /tmp/logs/ - mkdir -p /tmp/logs - # A baseline from before TRACER_PART existed would run every part. - if [ -n "${TRACER_PART:-}" ] && ! grep -q TRACER_PART runall.sh; then - cp "$CI_PROJECT_DIR/benchmark/runall.sh" runall.sh - fi - taskset -c 34-47 ./runall.sh - - if [ "$SCENARIO" = "profiler" ]; then - mv "$ARTIFACTS_DIR/sirun_timeline.ndjson" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-sirun_timeline.ndjson" - mv "$ARTIFACTS_DIR/sirun_exceptions.ndjson" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-sirun_exceptions.ndjson" - elif [ "$SCENARIO" = "tracer" ]; then - if [ -z "${TRACER_PART:-}" ] || [ "$TRACER_PART" = phpbench-opcache ]; then - # Give the OPCache subjects an "-opcache" suffix so they don't - # collide with the non-OPCache subjects (third column is the subject). - awk -F ',' -v OFS=',' 'NR == 1 { print } NR > 1 { $3 = $3 "-opcache"; print }' \ - "$ARTIFACTS_DIR/tracer-bench-results-opcache.csv" > "$ARTIFACTS_DIR/tracer-bench-results-opcache.tmp" - mv "$ARTIFACTS_DIR/tracer-bench-results-opcache.tmp" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-tracer-bench-results-opcache.csv" - rm "$ARTIFACTS_DIR/tracer-bench-results-opcache.csv" - fi - if [ -z "${TRACER_PART:-}" ] || [ "$TRACER_PART" = phpbench ]; then - mv "$ARTIFACTS_DIR/tracer-bench-results.csv" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-tracer-bench-results.csv" - fi - if [ -z "${TRACER_PART:-}" ] || [ "$TRACER_PART" = tea ]; then - mv "$ARTIFACTS_DIR/tracer-tea-bench-results.json" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-tracer-tea-bench-results.json" - fi - elif [ "$SCENARIO" = "appsec" ]; then - # Give the AppSec subjects an "-appsec" suffix so they don't collide - # with the tracer subjects (third column is the subject). - awk -F ',' -v OFS=',' 'NR == 1 { print } NR > 1 { $3 = $3 "-appsec"; print }' \ - "$ARTIFACTS_DIR/appsec-bench-results.csv" > "$ARTIFACTS_DIR/appsec-bench-results.tmp" && \ - mv "$ARTIFACTS_DIR/appsec-bench-results.tmp" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-appsec-bench-results.csv" - fi - - # Save all logs as artifacts - tar -zcvf "$GITLAB_ARTIFACTS_PATH/$BASELINE_OR_CANDIDATE.tar.gz" /tmp/logs - rm -rf /tmp/logs + # The generic sequential runner times the candidate before fetching the + # baseline. Paired BOLT processing needs both builds before either run. + script: '"$CI_PROJECT_DIR/.gitlab/benchmarks/steps/run-benchmarks.sh"' # One analyze step per framework; each step no-ops on the scenarios # whose result files its filter doesn't match. diff --git a/.gitlab/benchmarks/container/Dockerfile b/.gitlab/benchmarks/container/Dockerfile index 4ee33dd0ac..20df4d5585 100644 --- a/.gitlab/benchmarks/container/Dockerfile +++ b/.gitlab/benchmarks/container/Dockerfile @@ -1,8 +1,16 @@ +# Static LLVM 23.1.6 build with llvm-bolt-align (llvm-project#210634), built by +# the build-llvm-bolt-align-image job from container/llvm-bolt-align/. +FROM registry.ddbuild.io/ci/benchmarking-platform:llvm-bolt-align-156483907@sha256:800c006534c5182a29fef46d6f963398606485194b924c7d5636fd06d155d7fb AS bolt-align + FROM registry.ddbuild.io/images/benchmarking-platform-tools-ubuntu:latest ARG CI_JOB_TOKEN ARG RUST_VERSION=1.91.1 +COPY --from=bolt-align /usr/local/bin/llvm-bolt /usr/local/bin/llvm-bolt +RUN ln -s llvm-bolt /usr/local/bin/llvm-bolt-align \ + && llvm-bolt-align --version + # Install MySQL & create a test database (User: test, Password: test, Database: test) RUN --mount=type=ssh bp-install mysql && apt-get install --no-install-recommends -y mysql-client diff --git a/.gitlab/benchmarks/container/llvm-bolt-align/Dockerfile b/.gitlab/benchmarks/container/llvm-bolt-align/Dockerfile new file mode 100644 index 0000000000..da9261cd56 --- /dev/null +++ b/.gitlab/benchmarks/container/llvm-bolt-align/Dockerfile @@ -0,0 +1,86 @@ +# musl allows the tool to be copied into images with any C/C++ runtime. +FROM alpine:3.24 AS build + +RUN apk add --no-cache \ + build-base ca-certificates cmake curl git linux-headers lld ninja python3 + +# Latest stable LLVM release on 2026-11-17. Keep version and checksum together. +ARG LLVM_VERSION=23.1.6 +ARG LLVM_SOURCE_SHA256=66b37a51976c46ad86f49a2304c4dfd64be971f858846dfffaa8a32632474bb8 +RUN curl -fL --retry 3 \ + "https://codeload.github.com/llvm/llvm-project/tar.gz/refs/tags/llvmorg-${LLVM_VERSION}" \ + -o /tmp/llvm.tar.gz \ + && echo "${LLVM_SOURCE_SHA256} /tmp/llvm.tar.gz" | sha256sum -c - \ + && mkdir /src \ + && tar -xzf /tmp/llvm.tar.gz --strip-components=1 -C /src \ + "llvm-project-llvmorg-${LLVM_VERSION}/llvm" \ + "llvm-project-llvmorg-${LLVM_VERSION}/bolt" \ + "llvm-project-llvmorg-${LLVM_VERSION}/libc" \ + "llvm-project-llvmorg-${LLVM_VERSION}/cmake" \ + "llvm-project-llvmorg-${LLVM_VERSION}/third-party" \ + && rm /tmp/llvm.tar.gz + +COPY bolt-align.patch /tmp/bolt-align.patch +RUN cd /src && git apply --check /tmp/bolt-align.patch && git apply /tmp/bolt-align.patch + +# CI compiles on native BuildKit workers with 60 GiB (amd64) / 118 GiB (arm64). +# Override BUILD_JOBS for smaller local Linux build machines. +# Each platform image rewrites native binaries; instrumentation is not needed. +ARG BUILD_JOBS=16 +RUN cmake -G Ninja -S /src/llvm -B /build \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_EXE_LINKER_FLAGS=-static \ + -DLLVM_ENABLE_PROJECTS=bolt \ + -DLLVM_TARGETS_TO_BUILD=Native \ + -DBOLT_ENABLE_RUNTIME=OFF \ + -DLLVM_ENABLE_LLD=ON \ + -DLLVM_PARALLEL_LINK_JOBS=1 \ + -DLLVM_BUILD_TOOLS=OFF \ + -DLLVM_INCLUDE_UTILS=OFF \ + -DLLVM_INCLUDE_RUNTIMES=OFF \ + -DLLVM_INCLUDE_EXAMPLES=OFF \ + -DLLVM_INCLUDE_DOCS=OFF \ + -DLLVM_INCLUDE_TESTS=OFF \ + -DLLVM_INCLUDE_BENCHMARKS=OFF \ + -DLLVM_ENABLE_ASSERTIONS=OFF \ + -DLLVM_ENABLE_BINDINGS=OFF \ + -DLLVM_ENABLE_PLUGINS=OFF \ + -DLLVM_ENABLE_PIC=OFF \ + -DLLVM_ENABLE_TELEMETRY=OFF \ + -DLLVM_ENABLE_LIBPFM=OFF \ + -DLLVM_ENABLE_ZLIB=OFF \ + -DLLVM_ENABLE_ZSTD=OFF \ + -DLLVM_ENABLE_LIBXML2=OFF \ + -DLLVM_ENABLE_CURL=OFF \ + -DLLVM_ENABLE_LIBEDIT=OFF \ + && cmake --build /build --target llvm-bolt --parallel "${BUILD_JOBS}" \ + && readelf --program-headers /build/bin/llvm-bolt > /tmp/program-headers.txt \ + && ! grep -q INTERP /tmp/program-headers.txt \ + && readelf --dynamic /build/bin/llvm-bolt > /tmp/dynamic.txt \ + && ! grep -q NEEDED /tmp/dynamic.txt \ + && mkdir -p /out/usr/local/bin /out/tmp /out/work \ + && chmod 1777 /out/tmp \ + && strip -o /out/usr/local/bin/llvm-bolt /build/bin/llvm-bolt \ + && ln -s llvm-bolt /out/usr/local/bin/llvm-bolt-align + +# Test against glibc binaries, independently of the musl build environment. +FROM ubuntu:24.04 AS test + +RUN apt-get update \ + && apt-get install -y --no-install-recommends build-essential \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=build /out/ /out/ +COPY smoke-test.sh /tmp/smoke-test.sh +# Copy only the executable under the public name to verify standalone use. +RUN cp /out/usr/local/bin/llvm-bolt /tmp/llvm-bolt-align \ + && sh /tmp/smoke-test.sh /tmp/llvm-bolt-align + +FROM scratch + +COPY --from=test /out/ / +RUN ["/usr/local/bin/llvm-bolt-align", "--help"] + +WORKDIR /work +ENTRYPOINT ["/usr/local/bin/llvm-bolt-align"] +CMD ["--help"] diff --git a/.gitlab/benchmarks/container/llvm-bolt-align/README.md b/.gitlab/benchmarks/container/llvm-bolt-align/README.md new file mode 100644 index 0000000000..0860e4df5e --- /dev/null +++ b/.gitlab/benchmarks/container/llvm-bolt-align/README.md @@ -0,0 +1,128 @@ +# llvm-bolt-align + +Standalone tool image for aligning the function layouts of two ELF binaries. +Its entrypoint forwards all arguments to `llvm-bolt-align`. + +The executable is fully static, built against musl. It can be copied into any +Linux image of the matching architecture without installing a C or C++ runtime: + +```dockerfile +COPY --from=registry.ddbuild.io/ci/benchmarking-platform:llvm-bolt-align-@sha256: \ + /usr/local/bin/llvm-bolt /usr/local/bin/llvm-bolt-align +``` + +The source is the actual executable; `llvm-bolt-align` in the tool image is a +symlink to it. Copying the executable under either name is supported. Alignment +needs a writable temporary directory. The standalone image uses `scratch` and +provides `/tmp` with mode 1777 and `/work` for bind mounts. + +Build it with the manual `build-llvm-bolt-align-image` GitLab job +(`.gitlab/benchmarks.yml`). It uses the same image builder as the PHP benchmark +image and publishes +`registry.ddbuild.io/ci/benchmarking-platform:llvm-bolt-align-` +for amd64 and arm64. After a rebuild, repin the `FROM` of +`../Dockerfile` to the new tag and digest, then rebuild and repin the PHP image +(see "How to rebuild the CI Docker image" in `../../README.md`). +For a local build on a Linux build machine: + +```sh +docker build --build-arg BUILD_JOBS=16 -t llvm-bolt-align .gitlab/benchmarks/container/llvm-bolt-align +``` + +Run it with both inputs and the output directory mounted into the container: + +```sh +docker run --rm --user "$(id -u):$(id -g)" \ + -v "$PWD:/work" llvm-bolt-align \ + baseline.so candidate.so -o-a=baseline.aligned.so -o-b=candidate.aligned.so +``` + +With no arguments the image prints help. Inputs need their symbol tables and +must be linked with `-Wl,--emit-relocs`. They can be built with stock GCC, +Clang, or Rust; the patched LLVM is only used to build this tool. +For GCC builds, also use `-fno-reorder-blocks-and-partition`, as required by BOLT. + +Each image supports ELF inputs for its own architecture: x86-64 in the amd64 +image, AArch64 in the arm64 image. These are benchmark artifacts: keep the +original binaries and compare each aligned pair together, since its layout +depends on both inputs. + +## Source and patch + +The Dockerfile pins LLVM [23.1.6](https://github.com/llvm/llvm-project/releases/tag/llvmorg-23.1.6) +(tag `llvmorg-23.1.6`, commit `5b10d2d74929eae78912771222c9855af97496f4`), +the latest stable release on 2026-11-17. It verifies the source archive checksum +and applies the checked-in `bolt-align.patch` before building BOLT. LLVM, musl, +and the C++ runtime are linked statically. The build rejects an ELF interpreter +or dynamic-library dependency before producing the runtime image. + +The patch comes from LLVM PR [#210634](https://github.com/llvm/llvm-project/pull/210634), +using its alignment-only changes between commits +`75415f80b26f7c7177283a1680bef44c744c4886` and +`10efaa57f667e51ed10cc4f1464038a98fc22b5c`. The older relocation-order workaround +is excluded. Instead, the patch backports the upstream fix from +[#219447](https://github.com/llvm/llvm-project/pull/219447), commit +`c7d4c008350c6b66112de0278aa74cd72fedc180`, which is absent from LLVM 23.1.6. +This preserves PLT relocation order when rewriting dynamically linked binaries. + +Local adaptations update the CMake source list and extend the existing +`MCOrgFragment` constructor instead of adding an ambiguous overload. Temporary +layout files use the overload of `createTemporaryFile` that closes the file. +The relocation fix uses the release's `raw_fd_ostream::pwrite` API. +Child processes explicitly select normal BOLT mode, allowing a single executable +to be copied under the `llvm-bolt-align` name without its original symlink layout. + +Each image build copies only the executable into an Ubuntu test stage under the +`llvm-bolt-align` name and runs `smoke-test.sh`. It aligns independently compiled +executable and shared-library pairs, checks common function addresses, executes +the rewritten programs, and loads and calls the rewritten shared libraries. +On x86-64, it also verifies PLT relocation order and execution with mixed +`JUMP_SLOT` and `IRELATIVE` relocations to cover the backported fix. +The final `scratch` stage also executes the tool's help command. + +## Build scope + +The build enables only the BOLT project and requests only the `llvm-bolt` target. +It uses the system compiler and linker; it does not build Clang, LLD, or the full +LLVM tool suite. To reduce the build further: + +- `LLVM_TARGETS_TO_BUILD=Native` builds one backend per platform image instead of + compiling both X86 and AArch64 into every image. +- `BOLT_ENABLE_RUNTIME=OFF` skips the instrumentation and huge-page runtimes. + Function alignment does not use them. +- LLVM utilities, runtimes, examples, documentation, tests, benchmarks, bindings, + plugins, telemetry, and optional external libraries are disabled. +- Assertions are disabled; exceptions and RTTI are also off by default. + Release optimization and LLVM threading remain enabled for the rewriting work. + +`LLVM_INCLUDE_TOOLS` must stay enabled because LLVM adds the BOLT project from +its tools directory. `LLVM_BUILD_TOOLS=OFF` excludes ordinary LLVM tools from the +default build; requesting `llvm-bolt` still builds required dependencies such as +TableGen. BOLT also depends on compiler code-generation and debug-information +libraries, so those cannot simply be omitted with CMake switches. + +Only LLVM, BOLT, the shared CMake/third-party directories, and libc are extracted +from the source archive. The libc headers are required by LLVM Support even +though the libc project is disabled. + +Before the static build change, an experiment using Ubuntu 24.04 on `ubuntu-vm` +(Ryzen 9 9950X, 24 build jobs, one link job) compared the same patched LLVM 23.1.6 +source with these feature settings: + +| Configuration | Ninja build steps | Build time | +| --- | ---: | ---: | +| Previous options: X86 and AArch64, BOLT runtime enabled | 2,156 | 252.6 s | +| Previous options with only the native backend | 1,868 | Not timed | +| Reduced LLVM features | 1,860 | 195.8 s | + +These are single measurements of compilation/linking, excluding configuration, +source download, and image export. The reduced build was about 22% faster. +Architecture selection removes most of the compiled work; disabling the BOLT +runtime removes another eight top-level steps. The other exclusions mostly +reduce configuration work, since the explicit `llvm-bolt` target already avoids +building unrelated tools. CI uses 16 compiler jobs per architecture, one linker +job, and a two-hour timeout. Its native BuildKit workers are configured with +60 GiB / 15 CPUs for amd64 and 118 GiB / 30 CPUs for arm64. The image-builder +job's 12 GiB allocation applies to the client container, not these workers. +Override `BUILD_JOBS` on smaller local Linux machines. These timings do not +measure the current musl build or its separate Ubuntu test stage. diff --git a/.gitlab/benchmarks/container/llvm-bolt-align/bolt-align.patch b/.gitlab/benchmarks/container/llvm-bolt-align/bolt-align.patch new file mode 100644 index 0000000000..b8245dbda9 --- /dev/null +++ b/.gitlab/benchmarks/container/llvm-bolt-align/bolt-align.patch @@ -0,0 +1,1413 @@ +diff --git a/bolt/include/bolt/Core/BinaryContext.h b/bolt/include/bolt/Core/BinaryContext.h +index 73ccb911039d..c6a6b9510305 100644 +--- a/bolt/include/bolt/Core/BinaryContext.h ++++ b/bolt/include/bolt/Core/BinaryContext.h +@@ -1408,9 +1408,10 @@ public: + } + + /// Register dynamic relocation at \p Address. +- void addDynamicRelocation(uint64_t Address, MCSymbol *Symbol, uint32_t Type, +- uint64_t Addend, uint64_t Value = 0, +- bool IsRELR = false); ++ void addDynamicRelocation( ++ uint64_t Address, MCSymbol *Symbol, uint32_t Type, uint64_t Addend, ++ uint64_t Value = 0, bool IsRELR = false, ++ uint32_t JmpRelocationIndex = Relocation::NoJmpRelocationIndex); + + /// Return a dynamic relocation registered at a given \p Address, or nullptr + /// if there is no dynamic relocation at such address. +diff --git a/bolt/include/bolt/Core/BinaryFunction.h b/bolt/include/bolt/Core/BinaryFunction.h +index b3af846c4eb5..53479cbdd8b3 100644 +--- a/bolt/include/bolt/Core/BinaryFunction.h ++++ b/bolt/include/bolt/Core/BinaryFunction.h +@@ -271,6 +271,10 @@ private: + /// Maximum number of bytes used for alignment of cold part of the function. + uint16_t MaxColdAlignmentBytes{0}; + ++ /// The desired output offset of the function's main fragment in bytes ++ /// relative to its code section. ++ std::optional DesiredOffset; ++ + const MCSymbol *PersonalityFunction{nullptr}; + uint8_t PersonalityEncoding{dwarf::DW_EH_PE_sdata4 | dwarf::DW_EH_PE_pcrel}; + +@@ -1954,6 +1958,13 @@ public: + + uint16_t getMaxColdAlignmentBytes() const { return MaxColdAlignmentBytes; } + ++ BinaryFunction &setDesiredOffset(uint64_t Offset) { ++ DesiredOffset = Offset; ++ return *this; ++ } ++ ++ std::optional getDesiredOffset() const { return DesiredOffset; } ++ + BinaryFunction &setImageAddress(uint64_t Address) { + getLayout().getMainFragment().setImageAddress(Address); + return *this; +diff --git a/bolt/include/bolt/Core/BinarySection.h b/bolt/include/bolt/Core/BinarySection.h +index 69da629c7395..75744f93d010 100644 +--- a/bolt/include/bolt/Core/BinarySection.h ++++ b/bolt/include/bolt/Core/BinarySection.h +@@ -365,11 +365,12 @@ public: + } + + /// Add a dynamic relocation at the given /p Offset. +- void addDynamicRelocation(uint64_t Offset, MCSymbol *Symbol, uint32_t Type, +- uint64_t Addend, uint64_t Value = 0, +- bool IsRELR = false) { +- addDynamicRelocation( +- Relocation{Offset, Symbol, Type, Addend, Value, IsRELR}); ++ void addDynamicRelocation( ++ uint64_t Offset, MCSymbol *Symbol, uint32_t Type, uint64_t Addend, ++ uint64_t Value = 0, bool IsRELR = false, ++ uint32_t JmpRelocationIndex = Relocation::NoJmpRelocationIndex) { ++ addDynamicRelocation(Relocation{Offset, Symbol, Type, Addend, Value, IsRELR, ++ JmpRelocationIndex}); + } + + void addDynamicRelocation(const Relocation &Reloc) { +diff --git a/bolt/include/bolt/Core/Relocation.h b/bolt/include/bolt/Core/Relocation.h +index 9bc94d6484b7..02d18ff97cf9 100644 +--- a/bolt/include/bolt/Core/Relocation.h ++++ b/bolt/include/bolt/Core/Relocation.h +@@ -37,17 +37,21 @@ namespace bolt { + /// Relocation class. + class Relocation { + public: ++ static constexpr uint32_t NoJmpRelocationIndex = (1u << 30) - 1; ++ + Relocation(uint64_t Offset, MCSymbol *Symbol, uint32_t Type, uint64_t Addend, +- uint64_t Value, bool IsRELR = false) +- : Offset(Offset), Symbol(Symbol), Type(Type), Optional(false), +- IsRELR(IsRELR), Addend(Addend), Value(Value) { ++ uint64_t Value, bool IsRELR = false, ++ uint32_t JmpRelocationIndex = NoJmpRelocationIndex) ++ : Offset(Offset), Symbol(Symbol), Addend(Addend), Value(Value), ++ Type(Type), JmpRelocationIndex(JmpRelocationIndex), Optional(false), ++ IsRELR(IsRELR) { + assert((isRelative() || !isRELR()) && + "Only relative relocations can be relr."); + } + + Relocation() +- : Offset(0), Symbol(0), Type(0), Optional(0), IsRELR(0), Addend(0), +- Value(0) {} ++ : Offset(0), Symbol(0), Addend(0), Value(0), Type(0), ++ JmpRelocationIndex(NoJmpRelocationIndex), Optional(0), IsRELR(0) {} + + static Triple::ArchType Arch; /// set by BinaryContext ctor. + +@@ -57,27 +61,40 @@ public: + /// The symbol this relocation is referring to. + MCSymbol *Symbol; + ++ /// The offset from the \p Symbol base used to compute the final ++ /// value of this relocation. ++ uint64_t Addend; ++ ++ /// The computed relocation value extracted from the binary file. ++ /// Used to validate relocation correctness. ++ uint64_t Value; ++ + /// Relocation type. + uint32_t Type; + + private: ++ /// Original index in DT_JMPREL, or NoJmpRelocationIndex for relocations ++ /// originating from other relocation tables. ++ uint32_t JmpRelocationIndex : 30; ++ + /// Relocations added by optimizations can be optional, meaning they can be + /// omitted under certain circumstances. +- bool Optional = false; ++ uint32_t Optional : 1; + + /// Track which relocations originate from a relr section. Emit these + /// exclusively into the relr section and do not accidentally promote relative + /// rela entries, because that would require growing the relr section. +- bool IsRELR = false; ++ uint32_t IsRELR : 1; + + public: +- /// The offset from the \p Symbol base used to compute the final +- /// value of this relocation. +- uint64_t Addend; ++ bool isJmpRelocation() const { ++ return JmpRelocationIndex != NoJmpRelocationIndex; ++ } + +- /// The computed relocation value extracted from the binary file. +- /// Used to validate relocation correctness. +- uint64_t Value; ++ uint32_t getJmpRelocationIndex() const { ++ assert(isJmpRelocation() && "not a DT_JMPREL relocation"); ++ return JmpRelocationIndex; ++ } + + /// Return size in bytes of the given relocation \p Type. + static size_t getSizeForType(uint32_t Type); +diff --git a/bolt/include/bolt/Passes/AssignDesiredFunctionOffset.h b/bolt/include/bolt/Passes/AssignDesiredFunctionOffset.h +new file mode 100644 +index 000000000000..0950ccd0edc4 +--- /dev/null ++++ b/bolt/include/bolt/Passes/AssignDesiredFunctionOffset.h +@@ -0,0 +1,41 @@ ++//===- bolt/Passes/AssignDesiredFunctionOffset.h ----------------*- C++ -*-===// ++// ++// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. ++// See https://llvm.org/LICENSE.txt for license information. ++// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ++// ++//===----------------------------------------------------------------------===// ++// ++// Pass to assign the desired output offsets from --function-layout-file to the ++// corresponding functions. ++// ++//===----------------------------------------------------------------------===// ++ ++#ifndef BOLT_PASSES_ASSIGNDESIREDFUNCTIONOFFSET_H ++#define BOLT_PASSES_ASSIGNDESIREDFUNCTIONOFFSET_H ++ ++#include "bolt/Passes/BinaryPasses.h" ++#include "llvm/Support/CommandLine.h" ++ ++using namespace llvm; ++ ++namespace opts { ++extern cl::opt FunctionLayoutFile; ++} // namespace opts ++ ++namespace llvm { ++namespace bolt { ++ ++class AssignDesiredFunctionOffset : public BinaryFunctionPass { ++public: ++ explicit AssignDesiredFunctionOffset() : BinaryFunctionPass(false) {} ++ ++ const char *getName() const override { return "apply-function-layout"; } ++ ++ Error runOnFunctions(BinaryContext &BC) override; ++}; ++ ++} // namespace bolt ++} // namespace llvm ++ ++#endif +diff --git a/bolt/include/bolt/Rewrite/MergeFunctionLayouts.h b/bolt/include/bolt/Rewrite/MergeFunctionLayouts.h +new file mode 100644 +index 000000000000..0e902466fabb +--- /dev/null ++++ b/bolt/include/bolt/Rewrite/MergeFunctionLayouts.h +@@ -0,0 +1,29 @@ ++//===- bolt/Rewrite/MergeFunctionLayouts.h ----------------------*- C++ -*-===// ++// ++// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. ++// See https://llvm.org/LICENSE.txt for license information. ++// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ++// ++//===----------------------------------------------------------------------===// ++ ++#ifndef BOLT_REWRITE_MERGEFUNCTIONLAYOUTS_H ++#define BOLT_REWRITE_MERGEFUNCTIONLAYOUTS_H ++ ++#include "llvm/ADT/StringRef.h" ++#include "llvm/Support/Error.h" ++ ++namespace llvm { ++class raw_ostream; ++ ++namespace bolt { ++ ++/// Merge two layout files \p PathA and \p PathB into an aligned layout stored ++/// to \p OutputPath. Only common functions that occur in the same relative ++/// order are included. ++Error mergeFunctionLayouts(StringRef PathA, StringRef PathB, ++ StringRef OutputPath, raw_ostream &Log); ++ ++} // namespace bolt ++} // namespace llvm ++ ++#endif +diff --git a/bolt/include/bolt/Rewrite/RewriteInstance.h b/bolt/include/bolt/Rewrite/RewriteInstance.h +index 2e63ca93c3e5..7af4a4503825 100644 +--- a/bolt/include/bolt/Rewrite/RewriteInstance.h ++++ b/bolt/include/bolt/Rewrite/RewriteInstance.h +@@ -516,8 +516,8 @@ private: + std::optional PLTRelocationsAddress; + uint64_t PLTRelocationsSize{0}; + +- /// True if relocation of specified type came from .rela.plt +- DenseMap IsJmpRelocation; ++ /// Number of relocations read from DT_JMPREL. ++ uint32_t NumJmpRelocations{0}; + + /// Index of specified symbol in the dynamic symbol table. NOTE Currently it + /// is filled and used only with the relocations-related symbols. +diff --git a/bolt/lib/Core/BinaryContext.cpp b/bolt/lib/Core/BinaryContext.cpp +index 130c523bcda5..3ec22329841b 100644 +--- a/bolt/lib/Core/BinaryContext.cpp ++++ b/bolt/lib/Core/BinaryContext.cpp +@@ -2462,11 +2462,12 @@ void BinaryContext::addRelocation(uint64_t Address, MCSymbol *Symbol, + + void BinaryContext::addDynamicRelocation(uint64_t Address, MCSymbol *Symbol, + uint32_t Type, uint64_t Addend, +- uint64_t Value, bool IsRELR) { ++ uint64_t Value, bool IsRELR, ++ uint32_t JmpRelocationIndex) { + ErrorOr Section = getSectionForAddress(Address); + assert(Section && "cannot find section for address"); + Section->addDynamicRelocation(Address - Section->getAddress(), Symbol, Type, +- Addend, Value, IsRELR); ++ Addend, Value, IsRELR, JmpRelocationIndex); + } + + bool BinaryContext::removeRelocationAt(uint64_t Address) { +diff --git a/bolt/lib/Core/BinaryEmitter.cpp b/bolt/lib/Core/BinaryEmitter.cpp +index a555c7185448..d7c37ec1502b 100644 +--- a/bolt/lib/Core/BinaryEmitter.cpp ++++ b/bolt/lib/Core/BinaryEmitter.cpp +@@ -19,6 +19,8 @@ + #include "bolt/Utils/CommandLineOpts.h" + #include "bolt/Utils/Utils.h" + #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h" ++#include "llvm/MC/MCExpr.h" ++#include "llvm/MC/MCObjectStreamer.h" + #include "llvm/MC/MCSection.h" + #include "llvm/MC/MCStreamer.h" + #include "llvm/Support/CommandLine.h" +@@ -309,12 +311,24 @@ bool BinaryEmitter::emitFunction(BinaryFunction &Function, + // tentative layout. + Section->ensureMinAlignment(Align(BC.AlignFunctions)); + +- Streamer.emitCodeAlignment(Function.getMinAlign(), *BC.STI); +- uint16_t MaxAlignBytes = FF.isSplitFragment() +- ? Function.getMaxColdAlignmentBytes() +- : Function.getMaxAlignmentBytes(); +- if (MaxAlignBytes > 0) +- Streamer.emitCodeAlignment(Function.getAlign(), *BC.STI, MaxAlignBytes); ++ std::optional DesiredOffset; ++ if (FF.isMainFragment()) ++ DesiredOffset = Function.getDesiredOffset(); ++ ++ if (DesiredOffset) { ++ const MCExpr *OffsetExpr = ++ MCConstantExpr::create(*DesiredOffset, *BC.Ctx); ++ const unsigned FillValue = BC.Ctx->getAsmInfo().getTextAlignFillValue(); ++ static_cast(Streamer).emitValueToOffset( ++ OffsetExpr, FillValue, SMLoc(), /*AllowOmission=*/true); ++ } else { ++ Streamer.emitCodeAlignment(Function.getMinAlign(), *BC.STI); ++ uint16_t MaxAlignBytes = FF.isSplitFragment() ++ ? Function.getMaxColdAlignmentBytes() ++ : Function.getMaxAlignmentBytes(); ++ if (MaxAlignBytes > 0) ++ Streamer.emitCodeAlignment(Function.getAlign(), *BC.STI, MaxAlignBytes); ++ } + } else { + Streamer.emitCodeAlignment(Function.getAlign(), *BC.STI); + } +diff --git a/bolt/lib/Passes/AssignDesiredFunctionOffset.cpp b/bolt/lib/Passes/AssignDesiredFunctionOffset.cpp +new file mode 100644 +index 000000000000..70e803dc7a0e +--- /dev/null ++++ b/bolt/lib/Passes/AssignDesiredFunctionOffset.cpp +@@ -0,0 +1,131 @@ ++//===- bolt/Passes/AssignDesiredFunctionOffset.cpp ------------------------===// ++// ++// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. ++// See https://llvm.org/LICENSE.txt for license information. ++// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ++// ++//===----------------------------------------------------------------------===// ++// ++// This file implements the AssignDesiredFunctionOffset pass. ++// ++//===----------------------------------------------------------------------===// ++ ++#include "bolt/Passes/AssignDesiredFunctionOffset.h" ++#include "bolt/Core/BinaryContext.h" ++#include "bolt/Core/BinaryData.h" ++#include "bolt/Core/BinaryFunction.h" ++#include "bolt/Utils/CommandLineOpts.h" ++#include "llvm/Support/CommandLine.h" ++#include "llvm/Support/LineIterator.h" ++#include "llvm/Support/MemoryBuffer.h" ++ ++using namespace llvm; ++using namespace bolt; ++ ++namespace opts { ++ ++extern cl::OptionCategory BoltCategory; ++ ++cl::opt FunctionLayoutFile( ++ "function-layout-file", ++ cl::desc("file populating the functions' desired output offset. Requires " ++ "relocation mode."), ++ cl::value_desc("filename"), cl::Hidden, cl::cat(BoltCategory)); ++ ++} // namespace opts ++ ++namespace llvm { ++namespace bolt { ++ ++/// Mirror the lookup in ReorderFunctions. ++static BinaryFunction *lookupFunction(BinaryContext &BC, StringRef Name) { ++ BinaryData *BD = BC.getBinaryDataByName(Name); ++ if (!BD) { ++ for (uint32_t LocalID = 1;; ++LocalID) { ++ BD = BC.getBinaryDataByName((Name + "/" + Twine(LocalID)).str()); ++ if (!BD) ++ break; ++ if (BinaryFunction *BF = BC.getFunctionForSymbol(BD->getSymbol())) ++ return BF; ++ } ++ return nullptr; ++ } ++ return BC.getFunctionForSymbol(BD->getSymbol()); ++} ++ ++Error AssignDesiredFunctionOffset::runOnFunctions(BinaryContext &BC) { ++ if (opts::FunctionLayoutFile.empty()) ++ return Error::success(); ++ ++ if (!BC.HasRelocations) { ++ BC.errs() << "BOLT-ERROR: --function-layout-file is not supported in " ++ "non-relocation mode\n"; ++ exit(1); ++ } ++ ++ ErrorOr> MB = ++ MemoryBuffer::getFile(opts::FunctionLayoutFile); ++ if (std::error_code EC = MB.getError()) ++ return createStringError(EC, Twine("cannot open function layout file '") + ++ opts::FunctionLayoutFile + ++ "': " + EC.message()); ++ ++ uint64_t Applied = 0; ++ uint64_t NotFound = 0; ++ uint64_t Malformed = 0; ++ for (line_iterator LI(*MB.get(), /*SkipBlanks=*/true, /*CommentMarker=*/'#'); ++ !LI.is_at_eof(); ++LI) { ++ StringRef Line = LI->trim(); ++ if (Line.empty()) ++ continue; ++ ++ StringRef Name, OffsetStr; ++ std::tie(Name, OffsetStr) = Line.split(' '); ++ Name = Name.trim(); ++ OffsetStr = OffsetStr.trim(); ++ ++ uint64_t Offset; ++ if (Name.empty() || OffsetStr.empty() || ++ OffsetStr.getAsInteger(/*Radix=*/0, Offset)) { ++ BC.errs() << "BOLT-WARNING: --function-layout-file: malformed entry at " ++ << opts::FunctionLayoutFile << ":" << LI.line_number() << "\n"; ++ ++Malformed; ++ continue; ++ } ++ ++ BinaryFunction *BF = lookupFunction(BC, Name); ++ if (!BF) { ++ if (opts::Verbosity >= 1) ++ BC.errs() << "BOLT-WARNING: --function-layout-file: cannot find " ++ "function '" ++ << Name << "'\n"; ++ ++NotFound; ++ continue; ++ } ++ ++ if (!isAligned(BF->getMinAlign(), Offset)) { ++ BC.errs() << "BOLT-WARNING: --function-layout-file: offset " << Offset ++ << " for function '" << Name ++ << "' is not aligned by the minimum function alignment (" ++ << BF->getMinAlign().value() << "), skipping\n"; ++ ++Malformed; ++ continue; ++ } ++ ++ BF->setDesiredOffset(Offset); ++ ++Applied; ++ } ++ ++ BC.outs() << "BOLT-INFO: --function-layout-file: pinned " << Applied ++ << " functions"; ++ if (NotFound) ++ BC.outs() << ", " << NotFound << " not found"; ++ if (Malformed) ++ BC.outs() << ", " << Malformed << " malformed/skipped"; ++ BC.outs() << "\n"; ++ ++ return Error::success(); ++} ++ ++} // namespace bolt ++} // namespace llvm +diff --git a/bolt/lib/Passes/CMakeLists.txt b/bolt/lib/Passes/CMakeLists.txt +index ec012f05cc49..616b269880d7 100644 +--- a/bolt/lib/Passes/CMakeLists.txt ++++ b/bolt/lib/Passes/CMakeLists.txt +@@ -3,6 +3,7 @@ add_llvm_library(LLVMBOLTPasses + Aligner.cpp + AllocCombiner.cpp + AsmDump.cpp ++ AssignDesiredFunctionOffset.cpp + BinaryPasses.cpp + CMOVConversion.cpp + CacheMetrics.cpp +diff --git a/bolt/lib/Rewrite/BinaryPassManager.cpp b/bolt/lib/Rewrite/BinaryPassManager.cpp +index 6e3022c491a7..c61c404c6736 100644 +--- a/bolt/lib/Rewrite/BinaryPassManager.cpp ++++ b/bolt/lib/Rewrite/BinaryPassManager.cpp +@@ -11,6 +11,7 @@ + #include "bolt/Passes/Aligner.h" + #include "bolt/Passes/AllocCombiner.h" + #include "bolt/Passes/AsmDump.h" ++#include "bolt/Passes/AssignDesiredFunctionOffset.h" + #include "bolt/Passes/CMOVConversion.h" + #include "bolt/Passes/FixRISCVCallsPass.h" + #include "bolt/Passes/FixRelaxationPass.h" +@@ -525,6 +526,8 @@ Error BinaryFunctionPassManager::runAllPasses(BinaryContext &BC) { + + Manager.registerPass(std::make_unique()); + ++ Manager.registerPass(std::make_unique()); ++ + // Perform reordering on data contained in one or more sections using + // memory profiling data. + Manager.registerPass(std::make_unique()); +diff --git a/bolt/lib/Rewrite/CMakeLists.txt b/bolt/lib/Rewrite/CMakeLists.txt +index bc1b2ed3c2e3..a8a22bc6c468 100644 +--- a/bolt/lib/Rewrite/CMakeLists.txt ++++ b/bolt/lib/Rewrite/CMakeLists.txt +@@ -20,6 +20,7 @@ add_llvm_library(LLVMBOLTRewrite + JITLinkLinker.cpp + LinuxKernelRewriter.cpp + MachORewriteInstance.cpp ++ MergeFunctionLayouts.cpp + MetadataManager.cpp + BuildIDRewriter.cpp + PseudoProbeRewriter.cpp +diff --git a/bolt/lib/Rewrite/MergeFunctionLayouts.cpp b/bolt/lib/Rewrite/MergeFunctionLayouts.cpp +new file mode 100644 +index 000000000000..ce7561e5746c +--- /dev/null ++++ b/bolt/lib/Rewrite/MergeFunctionLayouts.cpp +@@ -0,0 +1,195 @@ ++//===- bolt/Rewrite/MergeFunctionLayouts.cpp - Merge two function layouts -===// ++// ++// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. ++// See https://llvm.org/LICENSE.txt for license information. ++// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ++// ++//===----------------------------------------------------------------------===// ++// ++// This file implements mergeFunctionLayouts() for llvm-bolt-align. ++// ++//===----------------------------------------------------------------------===// ++ ++#include "bolt/Rewrite/MergeFunctionLayouts.h" ++#include "bolt/Utils/Utils.h" ++#include "llvm/ADT/StringMap.h" ++#include "llvm/Support/FileSystem.h" ++#include "llvm/Support/LineIterator.h" ++#include "llvm/Support/MathExtras.h" ++#include "llvm/Support/MemoryBuffer.h" ++#include "llvm/Support/raw_ostream.h" ++#include ++#include ++#include ++ ++using namespace llvm; ++using namespace bolt; ++ ++namespace { ++ ++struct Entry { ++ std::string Name; ++ uint64_t Offset; ++}; ++ ++using Match = std::pair; ++ ++/// Keep some spare space between functions. This absorbs small layout changes ++/// in the final rewrite. ++constexpr uint64_t LayoutSlack = 64; ++constexpr uint64_t LayoutAlignment = 64; ++ ++static Expected> parseFile(StringRef Path) { ++ ErrorOr> MB = MemoryBuffer::getFile(Path); ++ if (std::error_code EC = MB.getError()) ++ return createStringError(EC, Twine("cannot open layout file '") + Path + ++ "': " + EC.message()); ++ ++ std::vector Entries; ++ for (line_iterator LI(*MB.get(), /*SkipBlanks=*/true, /*CommentMarker=*/'#'); ++ !LI.is_at_eof(); ++LI) { ++ StringRef Line = LI->trim(); ++ if (Line.empty()) ++ continue; ++ ++ StringRef Name, OffsetStr; ++ std::tie(Name, OffsetStr) = Line.split(' '); ++ Name = Name.trim(); ++ OffsetStr = OffsetStr.trim(); ++ ++ uint64_t Offset; ++ if (Name.empty() || OffsetStr.empty() || ++ OffsetStr.getAsInteger(/*Radix=*/0, Offset)) ++ return createStringError(inconvertibleErrorCode(), ++ Twine("malformed entry at ") + Path + ":" + ++ Twine(LI.line_number())); ++ ++ Entries.push_back({Name.str(), Offset}); ++ } ++ return Entries; ++} ++ ++/// Return all entries in both \p EntriesA and \p EntriesB in A's order. ++static std::vector findMatches(ArrayRef EntriesA, ++ ArrayRef EntriesB) { ++ StringMap ExactB; ++ StringMap CommonB; ++ StringMap CommonCountA; ++ StringMap CommonCountB; ++ ++ for (const Entry &E : EntriesA) ++ if (std::optional Common = getLTOCommonName(E.Name)) ++ ++CommonCountA[*Common]; ++ ++ for (const Entry &E : EntriesB) { ++ ExactB[E.Name] = &E; ++ if (std::optional Common = getLTOCommonName(E.Name)) { ++ ++CommonCountB[*Common]; ++ CommonB[*Common] = &E; ++ } ++ } ++ ++ std::vector Matches; ++ for (const Entry &E : EntriesA) { ++ const Entry *Match = ExactB.lookup(E.Name); ++ if (!Match) { ++ std::optional Common = getLTOCommonName(E.Name); ++ if (Common && CommonCountA.lookup(*Common) == 1 && ++ CommonCountB.lookup(*Common) == 1) ++ Match = CommonB.lookup(*Common); ++ } ++ if (Match) ++ Matches.emplace_back(&E, Match); ++ } ++ return Matches; ++} ++ ++static std::vector ++findLongestIncreasingSubsequence(ArrayRef Matches) { ++ if (Matches.empty()) ++ return {}; ++ ++ const size_t NoIndex = std::numeric_limits::max(); ++ std::vector Tails; ++ std::vector Previous(Matches.size(), NoIndex); ++ ++ for (size_t I = 0; I != Matches.size(); ++I) { ++ const uint64_t Offset = Matches[I].second->Offset; ++ auto It = std::lower_bound(Tails.begin(), Tails.end(), Offset, ++ [&](size_t Index, uint64_t Key) { ++ return Matches[Index].second->Offset < Key; ++ }); ++ if (It != Tails.begin()) ++ Previous[I] = It[-1]; ++ ++ if (It == Tails.end()) ++ Tails.push_back(I); ++ else ++ *It = I; ++ } ++ ++ std::vector Result; ++ for (size_t I = Tails.back(); I != NoIndex; I = Previous[I]) ++ Result.push_back(Matches[I]); ++ std::reverse(Result.begin(), Result.end()); ++ return Result; ++} ++ ++} // namespace ++ ++Error bolt::mergeFunctionLayouts(StringRef PathA, StringRef PathB, ++ StringRef OutputPath, raw_ostream &Log) { ++ Expected> EntriesA = parseFile(PathA); ++ if (!EntriesA) ++ return EntriesA.takeError(); ++ ++ Expected> EntriesB = parseFile(PathB); ++ if (!EntriesB) ++ return EntriesB.takeError(); ++ ++ const std::vector Matches = ++ findLongestIncreasingSubsequence(findMatches(*EntriesA, *EntriesB)); ++ ++ std::error_code EC; ++ raw_fd_ostream OS(OutputPath, EC, sys::fs::OpenFlags::OF_None); ++ if (EC) ++ return createStringError(EC, Twine("cannot open output layout file '") + ++ OutputPath + "': " + EC.message()); ++ ++ uint64_t Matched = 0; ++ bool First = true; ++ uint64_t PrevMergedOff = 0, PrevAOff = 0, PrevBOff = 0; ++ for (const Match &MatchPair : Matches) { ++ const Entry &A = *MatchPair.first; ++ const Entry &B = *MatchPair.second; ++ const uint64_t AOff = A.Offset; ++ const uint64_t BOff = B.Offset; ++ ++ uint64_t MergedOff; ++ if (First) { ++ MergedOff = alignTo(std::max(AOff, BOff), LayoutAlignment); ++ } else { ++ const uint64_t RequiredGap = std::max(AOff - PrevAOff, BOff - PrevBOff); ++ MergedOff = ++ alignTo(PrevMergedOff + RequiredGap + LayoutSlack, LayoutAlignment); ++ } ++ ++ OS << A.Name << " 0x" << Twine::utohexstr(MergedOff) << "\n"; ++ if (B.Name != A.Name) ++ OS << B.Name << " 0x" << Twine::utohexstr(MergedOff) << "\n"; ++ ++ ++Matched; ++ PrevMergedOff = MergedOff; ++ PrevAOff = AOff; ++ PrevBOff = BOff; ++ First = false; ++ } ++ ++ const uint64_t PossibleMatches = std::min(EntriesA->size(), EntriesB->size()); ++ const uint64_t MatchedPercent = ++ PossibleMatches ? Matched * 100 / PossibleMatches : 0; ++ Log << "BOLT-ALIGN: pinned " << Matched << " functions (" << MatchedPercent ++ << "%)\n"; ++ ++ return Error::success(); ++} +diff --git a/bolt/lib/Rewrite/RewriteInstance.cpp b/bolt/lib/Rewrite/RewriteInstance.cpp +index a12b83859669..1bfed17372c9 100644 +--- a/bolt/lib/Rewrite/RewriteInstance.cpp ++++ b/bolt/lib/Rewrite/RewriteInstance.cpp +@@ -17,6 +17,7 @@ + #include "bolt/Core/MCPlusBuilder.h" + #include "bolt/Core/ParallelUtilities.h" + #include "bolt/Core/Relocation.h" ++#include "bolt/Passes/AssignDesiredFunctionOffset.h" + #include "bolt/Passes/BinaryPasses.h" + #include "bolt/Passes/CacheMetrics.h" + #include "bolt/Passes/IdenticalCodeFolding.h" +@@ -173,6 +174,12 @@ static cl::opt FunctionNamesFileNR( + cl::desc("file with list of functions to optimize (non-regex)"), cl::Hidden, + cl::cat(BoltCategory)); + ++static cl::opt GenerateFunctionLayoutFile( ++ "generate-function-layout-file", ++ cl::desc("write a file mapping each emitted function to its finalized byte " ++ "offset within its output code section."), ++ cl::value_desc("filename"), cl::Hidden, cl::cat(BoltCategory)); ++ + cl::opt + KeepTmp("keep-tmp", + cl::desc("preserve intermediate .o file"), +@@ -2771,6 +2778,13 @@ void RewriteInstance::readDynamicRelocations(const SectionRef &Section, + }); + + for (const RelocationRef &Rel : Section.relocations()) { ++ uint32_t JmpRelocationIndex = Relocation::NoJmpRelocationIndex; ++ if (IsJmpRel) { ++ assert(NumJmpRelocations < Relocation::NoJmpRelocationIndex && ++ "too many DT_JMPREL relocations"); ++ JmpRelocationIndex = NumJmpRelocations++; ++ } ++ + const uint32_t RType = Relocation::getType(Rel); + if (Relocation::isNone(RType)) + continue; +@@ -2790,17 +2804,13 @@ void RewriteInstance::readDynamicRelocations(const SectionRef &Section, + (void)SymbolAddress; + } + +- LLVM_DEBUG( +- SmallString<16> TypeName; +- Rel.getTypeName(TypeName); +- dbgs() << "BOLT-DEBUG: dynamic relocation at 0x" +- << Twine::utohexstr(Rel.getOffset()) << " : " << TypeName +- << " : " << SymbolName << " : " << Twine::utohexstr(SymbolAddress) +- << " : + 0x" << Twine::utohexstr(Addend) << '\n' +- ); +- +- if (IsJmpRel) +- IsJmpRelocation[RType] = true; ++ const uint64_t RelOffset = Rel.getOffset(); ++ LLVM_DEBUG(SmallString<16> TypeName; Rel.getTypeName(TypeName); ++ dbgs() << "BOLT-DEBUG: dynamic relocation at 0x" ++ << Twine::utohexstr(RelOffset) << " : " << TypeName ++ << " : " << SymbolName << " : " ++ << Twine::utohexstr(SymbolAddress) << " : + 0x" ++ << Twine::utohexstr(Addend) << '\n'); + + if (Symbol) + SymbolIndex[Symbol] = getRelocationSymbol(InputFile, Rel); +@@ -2814,10 +2824,11 @@ void RewriteInstance::readDynamicRelocations(const SectionRef &Section, + "relocation type\n"; + exit(1); + } +- handleRelativeDynamicRelocation(Rel.getOffset(), ReferencedAddress); ++ handleRelativeDynamicRelocation(RelOffset, ReferencedAddress); + } + +- BC->addDynamicRelocation(Rel.getOffset(), Symbol, RType, Addend); ++ BC->addDynamicRelocation(RelOffset, Symbol, RType, Addend, ++ /*Value=*/0, /*IsRELR=*/false, JmpRelocationIndex); + } + } + +@@ -4003,6 +4014,76 @@ void RewriteInstance::preregisterSections() { + ELF::SHT_PROGBITS, ROFlags); + } + ++static void printFunctionLayoutStats(BinaryContext &BC) { ++ uint64_t LayoutConstraints = 0; ++ uint64_t SatisfiedLayoutConstraints = 0; ++ for (const BinaryFunction *Function : BC.getAllBinaryFunctions()) { ++ const std::optional DesiredOffset = Function->getDesiredOffset(); ++ ++ if (!DesiredOffset || !Function->isEmitted()) ++ continue; ++ ++ ErrorOr Section = Function->getCodeSection(); ++ if (!Section) ++ continue; ++ ++ ++LayoutConstraints; ++ ++ const uint64_t ActualOffset = ++ Function->getOutputAddress() - Section->getOutputAddress(); ++ if (ActualOffset == *DesiredOffset) { ++ ++SatisfiedLayoutConstraints; ++ continue; ++ } ++ ++ BC.errs() << "BOLT-WARNING: --function-layout-file: missed offset 0x" ++ << Twine::utohexstr(*DesiredOffset) << " for function '" ++ << Function->getOneName() << "' (emitted at 0x" ++ << Twine::utohexstr(ActualOffset) << ")\n"; ++ } ++ if (LayoutConstraints) ++ BC.outs() << "BOLT-INFO: --function-layout-file: satisfied " ++ << SatisfiedLayoutConstraints << " of " << LayoutConstraints ++ << " layout constraints\n"; ++} ++ ++static void generateFunctionLayoutFile(BinaryContext &BC) { ++ std::error_code EC; ++ raw_fd_ostream OS(opts::GenerateFunctionLayoutFile, EC, ++ sys::fs::OpenFlags::OF_None); ++ if (EC) { ++ BC.errs() << "BOLT-ERROR: cannot open --generate-function-layout-file '" ++ << opts::GenerateFunctionLayoutFile << "': " << EC.message() ++ << "\n"; ++ exit(1); ++ } ++ ++ std::vector> Functions; ++ for (const BinaryFunction *Function : BC.getAllBinaryFunctions()) { ++ if (!Function->isEmitted()) ++ continue; ++ ErrorOr Section = Function->getCodeSection(); ++ if (!Section) ++ continue; ++ Functions.emplace_back(Function->getOutputAddress(), Function); ++ } ++ ++ llvm::sort(Functions, llvm::less_first()); ++ ++ for (const auto &[OutputAddress, Function] : Functions) { ++ const uint64_t SectionAddress = ++ Function->getCodeSection()->getOutputAddress(); ++ assert(OutputAddress >= SectionAddress && ++ "function output address precedes its section"); ++ const uint64_t Offset = OutputAddress - SectionAddress; ++ OS << Function->getOneName() << " 0x" << Twine::utohexstr(Offset) << "\n"; ++ } ++ ++ BC.outs() << "BOLT-INFO: --generate-function-layout-file: wrote " ++ << Functions.size() << " functions to " ++ << opts::GenerateFunctionLayoutFile << "\n"; ++} ++ + void RewriteInstance::emitAndLink() { + NamedRegionTimer T("emitAndLink", "emit and link", TimerGroupName, + TimerGroupDesc, opts::TimeRewrite); +@@ -4073,6 +4154,12 @@ void RewriteInstance::emitAndLink() { + // layout. Only do this for the object created by ourselves. + updateOutputValues(*Linker); + ++ if (!opts::FunctionLayoutFile.empty()) ++ printFunctionLayoutStats(*BC); ++ ++ if (!opts::GenerateFunctionLayoutFile.empty()) ++ generateFunctionLayoutFile(*BC); ++ + if (opts::UpdateDebugSections) { + DebugInfoRewriter->updateLineTableOffsets( + static_cast(*Streamer).getAssembler()); +@@ -5893,72 +5980,75 @@ RewriteInstance::patchELFAllocatableRelaSections(ELFObjectFile *File) { + + DynamicRelativeRelocationsCount = 0; + +- auto writeRela = [&OS](const Elf_Rela *RelA, uint64_t &Offset) { ++ auto writeRela = [&OS](const Elf_Rela *RelA, uint64_t Offset) { + OS.pwrite(reinterpret_cast(RelA), sizeof(*RelA), Offset); +- Offset += sizeof(*RelA); + }; + +- auto writeRelocations = [&](bool PatchRelative) { +- for (BinarySection &Section : BC->allocatableSections()) { +- const uint64_t SectionInputAddress = Section.getAddress(); +- uint64_t SectionAddress = Section.getOutputAddress(); +- if (!SectionAddress) +- SectionAddress = SectionInputAddress; ++ auto writeRelocation = [&](BinarySection &Section, const Relocation &Rel, ++ uint64_t Offset, uint64_t EndOffset) { ++ const uint64_t SectionInputAddress = Section.getAddress(); ++ uint64_t SectionAddress = Section.getOutputAddress(); ++ if (!SectionAddress) ++ SectionAddress = SectionInputAddress; + +- for (const Relocation &Rel : Section.dynamicRelocations()) { +- const bool IsRelative = Rel.isRelative(); +- if (PatchRelative != IsRelative || Rel.isRELR()) +- continue; ++ Elf_Rela NewRelA; ++ MCSymbol *Symbol = Rel.Symbol; ++ uint32_t SymbolIdx = 0; ++ uint64_t Addend = Rel.Addend; ++ uint64_t RelOffset = ++ getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset); + +- if (IsRelative) +- ++DynamicRelativeRelocationsCount; ++ RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset; ++ if (Rel.Symbol) { ++ SymbolIdx = getOutputDynamicSymbolIndex(Symbol); ++ } else { ++ // Usually this case is used for R_*_(I)RELATIVE relocations ++ const uint64_t Address = getNewFunctionOrDataAddress(Addend); ++ if (Address) ++ Addend = Address; ++ } + +- Elf_Rela NewRelA; +- MCSymbol *Symbol = Rel.Symbol; +- uint32_t SymbolIdx = 0; +- uint64_t Addend = Rel.Addend; +- uint64_t RelOffset = +- getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset); ++ NewRelA.setSymbolAndType(SymbolIdx, Rel.Type, EF.isMips64EL()); ++ NewRelA.r_offset = RelOffset; ++ NewRelA.r_addend = Addend; + +- RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset; +- if (Rel.Symbol) { +- SymbolIdx = getOutputDynamicSymbolIndex(Symbol); +- } else { +- // Usually this case is used for R_*_(I)RELATIVE relocations +- const uint64_t Address = getNewFunctionOrDataAddress(Addend); +- if (Address) +- Addend = Address; +- } ++ if (!Offset || !EndOffset) { ++ BC->errs() << "BOLT-ERROR: Invalid offsets for dynamic relocation\n"; ++ exit(1); ++ } + +- NewRelA.setSymbolAndType(SymbolIdx, Rel.Type, EF.isMips64EL()); +- NewRelA.r_offset = RelOffset; +- NewRelA.r_addend = Addend; ++ if (Offset > EndOffset || EndOffset - Offset < sizeof(NewRelA)) { ++ BC->errs() << "BOLT-ERROR: Offset overflow for dynamic relocation\n"; ++ exit(1); ++ } + +- const bool IsJmpRel = IsJmpRelocation.contains(Rel.Type); +- uint64_t &Offset = IsJmpRel ? RelPltOffset : RelDynOffset; +- const uint64_t &EndOffset = +- IsJmpRel ? RelPltEndOffset : RelDynEndOffset; +- if (!Offset || !EndOffset) { +- BC->errs() << "BOLT-ERROR: Invalid offsets for dynamic relocation\n"; +- exit(1); +- } ++ writeRela(&NewRelA, Offset); ++ }; + +- if (Offset + sizeof(NewRelA) > EndOffset) { +- BC->errs() << "BOLT-ERROR: Offset overflow for dynamic relocation\n"; +- exit(1); +- } ++ auto writeDynRelocations = [&](bool PatchRelative) { ++ for (BinarySection &Section : BC->allocatableSections()) { ++ for (const Relocation &Rel : Section.dynamicRelocations()) { ++ if (Rel.isJmpRelocation()) ++ continue; ++ ++ const bool IsRelative = Rel.isRelative(); ++ if (PatchRelative != IsRelative || Rel.isRELR()) ++ continue; + +- writeRela(&NewRelA, Offset); ++ if (IsRelative) ++ ++DynamicRelativeRelocationsCount; ++ writeRelocation(Section, Rel, RelDynOffset, RelDynEndOffset); ++ RelDynOffset += sizeof(Elf_Rela); + } + } + }; + + // The dynamic linker expects all R_*_RELATIVE relocations in RELA + // to be emitted first. +- writeRelocations(/* PatchRelative */ true); +- writeRelocations(/* PatchRelative */ false); ++ writeDynRelocations(/* PatchRelative */ true); ++ writeDynRelocations(/* PatchRelative */ false); + +- auto fillNone = [&](uint64_t &Offset, uint64_t EndOffset) { ++ auto fillNone = [&](uint64_t Offset, uint64_t EndOffset) { + if (!Offset) + return; + +@@ -5966,15 +6056,32 @@ RewriteInstance::patchELFAllocatableRelaSections(ELFObjectFile *File) { + RelA.setSymbolAndType(0, Relocation::getNone(), EF.isMips64EL()); + RelA.r_offset = 0; + RelA.r_addend = 0; +- while (Offset < EndOffset) ++ while (Offset < EndOffset) { + writeRela(&RelA, Offset); ++ Offset += sizeof(Elf_Rela); ++ } + + assert(Offset == EndOffset && "Unexpected section overflow"); + }; + +- // Fill the rest of the sections with R_*_NONE relocations + fillNone(RelDynOffset, RelDynEndOffset); ++ ++ // Start with an empty DT_JMPREL table and patch relocations ++ // back into their original slots. + fillNone(RelPltOffset, RelPltEndOffset); ++ ++ for (BinarySection &Section : BC->allocatableSections()) { ++ for (const Relocation &Rel : Section.dynamicRelocations()) { ++ if (!Rel.isJmpRelocation()) ++ continue; ++ assert(!Rel.isRELR() && "RELR relocation cannot belong to DT_JMPREL"); ++ ++ const uint64_t Offset = ++ RelPltOffset + Rel.getJmpRelocationIndex() * sizeof(Elf_Rela); ++ ++ writeRelocation(Section, Rel, Offset, RelPltEndOffset); ++ } ++ } + } + + template +diff --git a/bolt/test/X86/llvm-bolt-align.s b/bolt/test/X86/llvm-bolt-align.s +new file mode 100644 +index 000000000000..abca06d59e10 +--- /dev/null ++++ b/bolt/test/X86/llvm-bolt-align.s +@@ -0,0 +1,85 @@ ++# RUN: llvm-mc -filetype=obj -triple x86_64-unknown-unknown \ ++# RUN: --defsym VARIATION=0 %s -o %t.a.o ++# RUN: llvm-mc -filetype=obj -triple x86_64-unknown-unknown \ ++# RUN: --defsym VARIATION=1 %s -o %t.b.o ++# RUN: %clang %cflags %t.a.o -o %t.a.exe -Wl,-q ++# RUN: %clang %cflags %t.b.o -o %t.b.exe -Wl,-q ++# RUN: llvm-bolt-align %t.a.exe %t.b.exe -o-a=%t.a -o-b=%t.b 2>&1 | FileCheck %s ++# RUN: llvm-nm -n --defined-only %t.a \ ++# RUN: | awk '$3 ~ /^(main|funcb|funce)$/ { print $1, $3 }' > %t.a.nm ++# RUN: llvm-nm -n --defined-only %t.b \ ++# RUN: | awk '$3 ~ /^(main|funcb|funce)$/ { print $1, $3 }' > %t.b.nm ++# RUN: diff -u %t.a.nm %t.b.nm ++ ++# CHECK: BOLT-ALIGN: pinned 3 functions (60%) ++# CHECK: BOLT-ALIGN: wrote aligned binaries ++ ++ .macro emit_main ++ .globl main ++ .type main, %function ++main: ++ callq funca ++ callq funcb ++ callq funce ++ retq ++.size main, .-main ++ .endm ++ ++ .macro emit_funca ++ .globl funca ++ .type funca, %function ++funca: ++.if VARIATION==1 ++ .rept 32 ++ nop ++ .endr ++.endif ++ retq ++.size funca, .-funca ++ .endm ++ ++ .macro emit_funcb ++ .globl funcb ++ .type funcb, %function ++funcb: ++ retq ++.size funcb, .-funcb ++ .endm ++ ++ .macro emit_funcc ++ .globl funcc ++ .type funcc, %function ++funcc: ++ retq ++.size funcc, .-funcc ++ .endm ++ ++ .macro emit_funcd ++ .globl funcd ++ .type funcd, %function ++funcd: ++ retq ++.size funcd, .-funcd ++ .endm ++ ++ .macro emit_funce ++ .globl funce ++ .type funce, %function ++funce: ++ retq ++.size funce, .-funce ++ .endm ++ ++.if VARIATION==0 ++ emit_main ++ emit_funca ++ emit_funcb ++ emit_funcc ++ emit_funce ++.else ++ emit_main ++ emit_funcb ++ emit_funca ++ emit_funcd ++ emit_funce ++.endif +diff --git a/bolt/test/runtime/X86/rela-plt-order.c b/bolt/test/runtime/X86/rela-plt-order.c +new file mode 100644 +index 000000000000..4a894ba8f6f6 +--- /dev/null ++++ b/bolt/test/runtime/X86/rela-plt-order.c +@@ -0,0 +1,37 @@ ++// REQUIRES: x86_64-linux, gnu_ld ++// ++// RUN: split-file %s %t ++// RUN: %clang %cflags -fPIC -shared -o %t/libexample.so \ ++// RUN: %t/example.c ++// RUN: %clang %cflags -fno-pie -no-pie -fuse-ld=bfd \ ++// RUN: -Wl,--emit-relocs -Wl,-rpath,\$ORIGIN -o %t/main %t/main.c \ ++// RUN: -L%t -lexample ++// RUN: llvm-readelf --dyn-relocations %t/main | \ ++// RUN: sed -n "/'PLT' relocation section/,/^$/p" | \ ++// RUN: awk '/^0/ { print $3, $5 }' > %t/main.plt ++// RUN: FileCheck %s --check-prefix=PLT-KINDS < %t/main.plt ++// RUN: llvm-bolt %t/main -o %t/main.bolt ++// RUN: llvm-readelf --dyn-relocations %t/main.bolt | \ ++// RUN: sed -n "/'PLT' relocation section/,/^$/p" | \ ++// RUN: awk '/^0/ { print $3, $5 }' > %t/main.bolt.plt ++// RUN: diff %t/main.plt %t/main.bolt.plt ++// RUN: %t/main.bolt ++ ++// PLT-KINDS-DAG: R_X86_64_JUMP_SLOT long_name ++// PLT-KINDS-DAG: R_X86_64_IRELATIVE ++ ++//--- main.c ++extern int long_name(void); ++ ++__attribute__((target_clones("default,avx2"))) int foo(int x) { return x + 1; } ++ ++int main(void) { ++ if (foo(1) != 2) ++ return 1; ++ if (long_name() != 0) ++ return 1; ++ return 0; ++} ++ ++//--- example.c ++int long_name(void) { return 0; } +diff --git a/bolt/tools/driver/CMakeLists.txt b/bolt/tools/driver/CMakeLists.txt +index 4b3c7416de97..7505a1da5f3b 100644 +--- a/bolt/tools/driver/CMakeLists.txt ++++ b/bolt/tools/driver/CMakeLists.txt +@@ -29,6 +29,7 @@ target_link_libraries(llvm-bolt + + add_bolt_tool_symlink(perf2bolt llvm-bolt) + add_bolt_tool_symlink(llvm-boltdiff llvm-bolt) ++add_bolt_tool_symlink(llvm-bolt-align llvm-bolt) + + add_dependencies(bolt llvm-bolt) + +diff --git a/bolt/tools/driver/llvm-bolt.cpp b/bolt/tools/driver/llvm-bolt.cpp +index cc8e6d70001e..7f606dd07a28 100644 +--- a/bolt/tools/driver/llvm-bolt.cpp ++++ b/bolt/tools/driver/llvm-bolt.cpp +@@ -14,6 +14,7 @@ + + #include "bolt/Profile/DataAggregator.h" + #include "bolt/Rewrite/MachORewriteInstance.h" ++#include "bolt/Rewrite/MergeFunctionLayouts.h" + #include "bolt/Rewrite/RewriteInstance.h" + #include "bolt/Utils/CommandLineOpts.h" + #include "llvm/MC/TargetRegistry.h" +@@ -21,14 +22,23 @@ + #include "llvm/Support/CommandLine.h" + #include "llvm/Support/Errc.h" + #include "llvm/Support/Error.h" ++#include "llvm/Support/FileUtilities.h" + #include "llvm/Support/ManagedStatic.h" + #include "llvm/Support/Path.h" + #include "llvm/Support/PrettyStackTrace.h" ++#include "llvm/Support/Program.h" + #include "llvm/Support/Signals.h" + #include "llvm/Support/TargetSelect.h" + + #define DEBUG_TYPE "bolt" + ++// FIXME: Is this portable enough? ++#if defined(_WIN32) || defined(_WIN64) ++#define NULL_FILE "nul" ++#else ++#define NULL_FILE "/dev/null" ++#endif ++ + using namespace llvm; + using namespace object; + using namespace bolt; +@@ -81,6 +91,18 @@ InputFilename2( + cl::Optional, + cl::cat(BoltDiffCategory)); + ++static cl::OptionCategory BoltAlignCategory("BOLT align options"); ++ ++static cl::OptionCategory *BoltAlignCategories[] = {&BoltAlignCategory}; ++ ++static cl::opt ++ AlignOutputA("o-a", cl::desc("output path for aligned binary A"), ++ cl::value_desc("filename"), cl::cat(BoltAlignCategory)); ++ ++static cl::opt ++ AlignOutputB("o-b", cl::desc("output path for aligned binary B"), ++ cl::value_desc("filename"), cl::cat(BoltAlignCategory)); ++ + } // namespace opts + + static StringRef ToolName; +@@ -147,6 +169,111 @@ void boltDiffMode(int argc, char **argv) { + opts::DiffOnly = true; + } + ++static Error runBoltAlignCommand(StringRef ToolPath, StringRef Input, ++ StringRef Output, StringRef LayoutOption) { ++ std::string OutputArg = (Twine("-o=") + Output).str(); ++ SmallVector Args; ++ // Select normal BOLT mode even when the binary was copied as llvm-bolt-align. ++ Args.push_back("llvm-bolt"); ++ Args.push_back(Input); ++ Args.push_back(OutputArg); ++ Args.push_back(LayoutOption); ++ ++ outs().flush(); ++ errs().flush(); ++ std::string ErrMsg; ++ const int Result = ++ sys::ExecuteAndWait(ToolPath, Args, std::nullopt, {}, 0, 0, &ErrMsg); ++ if (Result < 0) ++ return createStringError(inconvertibleErrorCode(), ++ Twine("failed to execute llvm-bolt-align: ") + ++ ErrMsg); ++ if (Result != 0) ++ return createStringError(inconvertibleErrorCode(), ++ Twine("llvm-bolt-align exited with status ") + ++ Twine(Result)); ++ return Error::success(); ++} ++ ++static Expected createAlignTempFile(StringRef Label) { ++ SmallString<128> Path; ++ if (std::error_code EC = sys::fs::createTemporaryFile( ++ Twine("llvm-bolt-align-") + Label, "layout", Path)) ++ return createStringError(EC, "cannot create temporary layout file"); ++ ++ return Path.str().str(); ++} ++ ++static int boltAlignMode(int argc, char **argv, StringRef ToolPath) { ++ cl::HideUnrelatedOptions(ArrayRef(opts::BoltAlignCategories)); ++ cl::AddExtraVersionPrinter(printBoltRevision); ++ cl::ParseCommandLineOptions( ++ argc, argv, ++ "llvm-bolt-align - align the function layouts of two binaries\n" ++ "\nEXAMPLE: llvm-bolt-align a.out b.out -o-a=a.aligned -o-b=b.aligned\n"); ++ if (opts::InputFilename2.empty()) { ++ errs() << ToolName << ": expected two input binaries.\n"; ++ return EXIT_FAILURE; ++ } ++ if (opts::AlignOutputA.empty() || opts::AlignOutputB.empty()) { ++ errs() << ToolName << ": expected -o-a= and -o-b=.\n"; ++ return EXIT_FAILURE; ++ } ++ ++ Expected NaturalLayoutAOrErr = createAlignTempFile("natural-a"); ++ if (!NaturalLayoutAOrErr) ++ report_error("llvm-bolt-align", NaturalLayoutAOrErr.takeError()); ++ const std::string NaturalLayoutA = std::move(*NaturalLayoutAOrErr); ++ FileRemover RemoveNaturalLayoutA(NaturalLayoutA); ++ ++ Expected NaturalLayoutBOrErr = createAlignTempFile("natural-b"); ++ if (!NaturalLayoutBOrErr) ++ report_error("llvm-bolt-align", NaturalLayoutBOrErr.takeError()); ++ const std::string NaturalLayoutB = std::move(*NaturalLayoutBOrErr); ++ FileRemover RemoveNaturalLayoutB(NaturalLayoutB); ++ ++ Expected MergedOrErr = createAlignTempFile("merged"); ++ if (!MergedOrErr) ++ report_error("llvm-bolt-align", MergedOrErr.takeError()); ++ const std::string Merged = std::move(*MergedOrErr); ++ FileRemover RemoveMerged(Merged); ++ ++ // FIXME: The FileRemovers will not run on exit(1). ++ ++ outs() << "BOLT-ALIGN: measuring natural binary A layout\n"; ++ if (Error E = runBoltAlignCommand( ++ ToolPath, opts::InputFilename, NULL_FILE, ++ (Twine("--generate-function-layout-file=") + NaturalLayoutA).str())) ++ report_error(opts::InputFilename, std::move(E)); ++ ++ outs() << "BOLT-ALIGN: measuring natural binary B layout\n"; ++ if (Error E = runBoltAlignCommand( ++ ToolPath, opts::InputFilename2, NULL_FILE, ++ (Twine("--generate-function-layout-file=") + NaturalLayoutB).str())) ++ report_error(opts::InputFilename2, std::move(E)); ++ ++ if (Error E = bolt::mergeFunctionLayouts(NaturalLayoutA, NaturalLayoutB, ++ Merged, outs())) ++ report_error("llvm-bolt-align", std::move(E)); ++ ++ outs() << "BOLT-ALIGN: rewriting binary A\n"; ++ if (Error E = runBoltAlignCommand( ++ ToolPath, opts::InputFilename, opts::AlignOutputA, ++ (Twine("--function-layout-file=") + Merged).str())) ++ report_error(opts::InputFilename, std::move(E)); ++ ++ outs() << "BOLT-ALIGN: rewriting binary B\n"; ++ if (Error E = runBoltAlignCommand( ++ ToolPath, opts::InputFilename2, opts::AlignOutputB, ++ (Twine("--function-layout-file=") + Merged).str())) ++ report_error(opts::InputFilename2, std::move(E)); ++ ++ outs() << "BOLT-ALIGN: wrote aligned binaries to " << opts::AlignOutputA ++ << " and " << opts::AlignOutputB << "\n"; ++ ++ return EXIT_SUCCESS; ++} ++ + void boltMode(int argc, char **argv) { + cl::HideUnrelatedOptions(ArrayRef(opts::BoltCategories)); + // Register the target printer for --version. +@@ -188,6 +315,8 @@ int main(int argc, char **argv) { + perf2boltMode(argc, argv); + else if (llvm::sys::path::filename(ToolName).starts_with("llvm-boltdiff")) + boltDiffMode(argc, argv); ++ else if (llvm::sys::path::filename(ToolName).starts_with("llvm-bolt-align")) ++ return boltAlignMode(argc, argv, ToolPath); + else + boltMode(argc, argv); + +diff --git a/llvm/include/llvm/MC/MCObjectStreamer.h b/llvm/include/llvm/MC/MCObjectStreamer.h +index 003f6106d15b..3a5961581f40 100644 +--- a/llvm/include/llvm/MC/MCObjectStreamer.h ++++ b/llvm/include/llvm/MC/MCObjectStreamer.h +@@ -143,6 +143,8 @@ public: + uint8_t Fill, const MCSubtargetInfo &STI) override; + void emitValueToOffset(const MCExpr *Offset, unsigned char Value, + SMLoc Loc) override; ++ void emitValueToOffset(const MCExpr *Offset, unsigned char Value, SMLoc Loc, ++ bool AllowOmission); + void emitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, + unsigned Flags, unsigned Isa, + unsigned Discriminator, StringRef FileName, +diff --git a/llvm/include/llvm/MC/MCSection.h b/llvm/include/llvm/MC/MCSection.h +index 239a9654a410..76b4731f70b7 100644 +--- a/llvm/include/llvm/MC/MCSection.h ++++ b/llvm/include/llvm/MC/MCSection.h +@@ -449,14 +449,20 @@ class MCOrgFragment : public MCFragment { + /// Source location of the directive that this fragment was created for. + SMLoc Loc; + ++ /// Whether the fragment may be omitted if we missed the target offset. ++ bool AllowOmission = false; ++ + public: +- MCOrgFragment(const MCExpr &Offset, int8_t Value, SMLoc Loc) +- : MCFragment(FT_Org), Value(Value), Offset(&Offset), Loc(Loc) {} ++ MCOrgFragment(const MCExpr &Offset, int8_t Value, SMLoc Loc, ++ bool AllowOmission = false) ++ : MCFragment(FT_Org), Value(Value), Offset(&Offset), Loc(Loc), ++ AllowOmission(AllowOmission) {} + + const MCExpr &getOffset() const { return *Offset; } + uint8_t getValue() const { return Value; } + + SMLoc getLoc() const { return Loc; } ++ bool getAllowOmission() const { return AllowOmission; } + + static bool classof(const MCFragment *F) { + return F->getKind() == MCFragment::FT_Org; +diff --git a/llvm/lib/MC/MCAssembler.cpp b/llvm/lib/MC/MCAssembler.cpp +index 85463fc2d56e..c5f26f15cc4a 100644 +--- a/llvm/lib/MC/MCAssembler.cpp ++++ b/llvm/lib/MC/MCAssembler.cpp +@@ -263,6 +263,8 @@ uint64_t MCAssembler::computeFragmentSize(const MCFragment &F) const { + TargetLocation += Val; + } + int64_t Size = TargetLocation - FragmentOffset; ++ if (Size < 0 && OF.getAllowOmission()) ++ return 0; + if (Size < 0 || Size >= 0x40000000) { + recordError(OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) + + "' (at offset '" + Twine(FragmentOffset) + +diff --git a/llvm/lib/MC/MCObjectStreamer.cpp b/llvm/lib/MC/MCObjectStreamer.cpp +index d89e5df706b2..a54a0311aaca 100644 +--- a/llvm/lib/MC/MCObjectStreamer.cpp ++++ b/llvm/lib/MC/MCObjectStreamer.cpp +@@ -704,7 +704,13 @@ void MCObjectStreamer::emitPrefAlign(Align Alignment, const MCSymbol &End, + void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset, + unsigned char Value, + SMLoc Loc) { +- newSpecialFragment(*Offset, Value, Loc); ++ emitValueToOffset(Offset, Value, Loc, /*AllowOmission=*/false); ++} ++ ++void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset, ++ unsigned char Value, SMLoc Loc, ++ bool AllowOmission) { ++ newSpecialFragment(*Offset, Value, Loc, AllowOmission); + } + + void MCObjectStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name, diff --git a/.gitlab/benchmarks/container/llvm-bolt-align/smoke-test.sh b/.gitlab/benchmarks/container/llvm-bolt-align/smoke-test.sh new file mode 100644 index 0000000000..1708529e5b --- /dev/null +++ b/.gitlab/benchmarks/container/llvm-bolt-align/smoke-test.sh @@ -0,0 +1,99 @@ +#!/bin/sh +set -eu + +bolt_align=$1 +test_dir=$(mktemp -d) +trap 'rm -rf "$test_dir"' EXIT +cd "$test_dir" + +cat > input.c <<'EOF' +__attribute__((noinline)) int first(int value) { +#if VARIATION + __asm__ volatile(".rept 32\nnop\n.endr"); +#endif + return value + 1; +} +__attribute__((noinline)) int second(int value) { + return first(value) + 1; +} +int main(void) { + return second(40) != 42; +} +EOF + +cat > load.c <<'EOF' +#include +int main(int argc, char **argv) { + if (argc != 2) return 1; + void *handle = dlopen(argv[1], RTLD_NOW); + if (!handle) return 2; + int (*second)(int) = (int (*)(int))dlsym(handle, "second"); + int result = !second || second(40) != 42; + dlclose(handle); + return result; +} +EOF +cc load.c -o load -ldl + +# Cover both executables and PHP-style dynamically loaded shared libraries. +for kind in executable shared; do + link_flags= + if [ "$kind" = shared ]; then + link_flags='-fPIC -shared' + fi + for variation in 0 1; do + cc -O2 -fno-reorder-blocks-and-partition -fno-toplevel-reorder \ + -DVARIATION="$variation" $link_flags -Wl,--emit-relocs \ + input.c -o "$kind.$variation" + done + "$bolt_align" "$kind.0" "$kind.1" \ + -o-a="$kind.0.aligned" -o-b="$kind.1.aligned" > "$kind.log" 2>&1 \ + || { cat "$kind.log"; exit 1; } + cat "$kind.log" + if grep -q 'missed offset' "$kind.log"; then + exit 1 + fi + for variation in 0 1; do + nm -n --defined-only "$kind.$variation.aligned" \ + | awk '$3 ~ /^(first|second|main)$/ { print $1, $3 }' \ + > "$kind.$variation.symbols" + test "$(wc -l < "$kind.$variation.symbols")" -eq 3 + if [ "$kind" = shared ]; then + ./load "./$kind.$variation.aligned" + else + "./$kind.$variation.aligned" + fi + done + diff -u "$kind.0.symbols" "$kind.1.symbols" +done + +# Exercise the backported PLT fix with mixed JUMP_SLOT/IRELATIVE relocations. +if [ "$(uname -m)" = x86_64 ]; then + cat > plt-library.c <<'EOF' +int long_name(void) { return 0; } +EOF + cat > plt-main.c <<'EOF' +extern int long_name(void); +__attribute__((target_clones("default,avx2"))) int foo(int x) { return x + 1; } +int main(void) { return foo(1) != 2 || long_name() != 0; } +EOF + cc -fPIC -shared plt-library.c -o libexample.so + cc -O2 -fno-pie -no-pie -fuse-ld=bfd -Wl,--emit-relocs \ + '-Wl,-rpath,$ORIGIN' plt-main.c -L. -lexample -o plt-main + "$bolt_align" plt-main plt-main -o-a=plt-main.a -o-b=plt-main.b \ + > plt.log 2>&1 || { cat plt.log; exit 1; } + cat plt.log + for binary in plt-main plt-main.a plt-main.b; do + readelf -Wr "$binary" | awk ' + /^Relocation section/ { in_plt = $3 ~ /[.]rela[.]plt/ } + in_plt && $3 ~ /^R_X86_64_/ { + print $3, ($3 == "R_X86_64_JUMP_SLOT" ? $5 : "") + } + ' > "$binary.plt" + grep -q R_X86_64_JUMP_SLOT "$binary.plt" + grep -q R_X86_64_IRELATIVE "$binary.plt" + "./$binary" + done + diff -u plt-main.plt plt-main.a.plt + diff -u plt-main.plt plt-main.b.plt +fi diff --git a/.gitlab/benchmarks/steps/prepare-bolt.sh b/.gitlab/benchmarks/steps/prepare-bolt.sh new file mode 100755 index 0000000000..89e70455e9 --- /dev/null +++ b/.gitlab/benchmarks/steps/prepare-bolt.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash + +set -euo pipefail + +if [ "$#" -ne 3 ]; then + echo "Usage: $0 " >&2 + exit 1 +fi + +CANDIDATE_SRC=$(realpath "$1") +BASELINE_SRC=$2 +VARIANTS=(candidate) +if [ -n "$BASELINE_SRC" ]; then + BASELINE_SRC=$(realpath "$BASELINE_SRC") + VARIANTS+=(baseline) +fi +BOLT_DIR=$3 +mkdir -p "$BOLT_DIR" +BOLT_DIR=$(realpath "$BOLT_DIR") +BOLT_MODE=${BOLT_MODE:-align} +case "$BOLT_MODE" in + align) BOLT_BIN=llvm-bolt-align ;; + plain) BOLT_BIN=llvm-bolt ;; + *) echo "Preparing BOLT modules requires BOLT_MODE=plain or align." >&2; exit 1 ;; +esac +if [ "$BOLT_MODE" = align ] && [ -z "$BASELINE_SRC" ]; then + echo "BOLT alignment requires a baseline source directory." >&2 + exit 1 +fi +unset DD_TRACE_ASSUME_COMPILED + +# These flags are required by BOLT; use the same flags for both revisions. +export CFLAGS="${CFLAGS:--O2 -falign-functions=64} -fno-reorder-blocks-and-partition" +export LDFLAGS="${LDFLAGS:+$LDFLAGS }-Wl,--emit-relocs" +"$BOLT_BIN" --version + +# Cargo hashes the absolute path of path dependencies that lie outside the +# workspace root (tmp/build_combined depends on ../../libdatadog), and rustc +# derives Rust symbol names from that hash. Building the revisions in their own +# checkouts would give all the Rust functions different names in each binary, +# and llvm-bolt-align matches functions by name: it could align only the C code +# (~60% of the functions). Build both revisions at the same path instead. +BUILD_ROOT="$BOLT_DIR/build" +for VARIANT in "${VARIANTS[@]}"; do + if [ "$VARIANT" = candidate ]; then SRC=$CANDIDATE_SRC; else SRC=$BASELINE_SRC; fi + rm -rf "$BUILD_ROOT" + cp -a "$SRC" "$BUILD_ROOT" + # Never reuse a previous build (or a BOLT output) from a manually used tree. + rm -rf "$BUILD_ROOT/tmp" + (cd "$BUILD_ROOT" && make -j"$(nproc)" compile_combined) + cp "$BUILD_ROOT/tmp/build_combined/modules/ddtrace.so" "$BOLT_DIR/$VARIANT-natural.so" +done +rm -rf "$BUILD_ROOT" + +if [ "$BOLT_MODE" = align ]; then + if ! "$BOLT_BIN" "$BOLT_DIR/baseline-natural.so" "$BOLT_DIR/candidate-natural.so" \ + -o-a="$BOLT_DIR/baseline.so" -o-b="$BOLT_DIR/candidate.so" \ + > "$BOLT_DIR/alignment.log" 2>&1; then + cat "$BOLT_DIR/alignment.log" >&2 + exit 1 + fi + cat "$BOLT_DIR/alignment.log" + # Each of the two rewrites prints a "satisfied N of M layout constraints" + # summary, and a "missed offset" warning for every function that did not land + # at its agreed offset. Require exactly two summaries, each with all (and at + # least one) of the constraints met, and no misses. + if grep -q 'missed offset' "$BOLT_DIR/alignment.log" || ! awk ' + /satisfied [0-9]+ of [0-9]+ layout constraints/ { + for (i = 1; i <= NF; i++) { + if ($i == "satisfied") { + if ($(i + 1) == 0 || $(i + 1) != $(i + 3)) exit 1 + count++ + } + } + } + END { if (count != 2) exit 1 } + ' "$BOLT_DIR/alignment.log"; then + echo "BOLT alignment did not satisfy the common-function layout constraints." >&2 + exit 1 + fi +else + for VARIANT in "${VARIANTS[@]}"; do + if [ "$VARIANT" = candidate ]; then SRC=$CANDIDATE_SRC; else SRC=$BASELINE_SRC; fi + if ! "$BOLT_BIN" "$BOLT_DIR/$VARIANT-natural.so" \ + -o="$BOLT_DIR/$VARIANT.so" > "$BOLT_DIR/$VARIANT.log" 2>&1; then + cat "$BOLT_DIR/$VARIANT.log" >&2 + exit 1 + fi + cat "$BOLT_DIR/$VARIANT.log" + done +fi +for VARIANT in "${VARIANTS[@]}"; do + if [ "$VARIANT" = candidate ]; then SRC=$CANDIDATE_SRC; else SRC=$BASELINE_SRC; fi + # ASSUME_COMPILED makes the tracer Makefile install this module directly, + # rather than using libtool's original copy in .libs/. + mkdir -p "$SRC/tmp/build_combined/modules" + cp "$BOLT_DIR/$VARIANT.so" "$SRC/tmp/build_combined/modules/ddtrace.so" +done diff --git a/.gitlab/benchmarks/steps/run-benchmarks.sh b/.gitlab/benchmarks/steps/run-benchmarks.sh new file mode 100755 index 0000000000..f45966b292 --- /dev/null +++ b/.gitlab/benchmarks/steps/run-benchmarks.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +set -euo pipefail + +STEPS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +BOLT_MODE=${BOLT_MODE:-} +case "$BOLT_MODE" in + ''|off|plain|align) ;; + *) echo "BOLT_MODE must be off, plain, or align." >&2; exit 1 ;; +esac + +WORK_DIR=$(mktemp -d) +export BOLT_DIR="$WORK_DIR/bolt" +cleanup() { + # Retain diagnostics, without archiving copies of the extension binaries. + if [ -d "$BOLT_DIR" ]; then + mkdir -p "$ARTIFACTS_DIR/bolt" + find "$BOLT_DIR" -maxdepth 1 -name '*.log' -exec cp {} "$ARTIFACTS_DIR/bolt/" \; + fi + rm -rf "$WORK_DIR" +} +trap cleanup EXIT + +fetch_release() { + local destination=$1 branch=$2 revision=$3 + git clone --branch "$branch" https://github.com/DataDog/dd-trace-php/ "$destination" + git -C "$destination" checkout "$revision" + git -C "$destination" submodule update --init --recursive +} + +# The shared analyzer reads Git metadata from these fixed checkout locations. +# Keep the checkouts until analysis finishes; only BOLT's scratch files are +# removed by this script's exit trap. +CANDIDATE_SRC=/app/candidate +BASELINE_SRC= +fetch_release "$CANDIDATE_SRC" "$CI_COMMIT_REF_NAME" "$CI_COMMIT_SHA" + +if [ -z "${BASELINE_BRANCH:-}" ]; then + BASELINE_BRANCH=$(github-find-merge-into-branch \ + --for-repo="$CI_PROJECT_NAME" --for-pr="$CI_COMMIT_REF_NAME") +fi +# No trailing newline: check-big-regressions tests whether the file is empty. +printf '%s' "$BASELINE_BRANCH" > "$ARTIFACTS_DIR/baseline_branch.txt" +if [ -n "$BASELINE_BRANCH" ]; then + BASELINE_SHA=$(git -C "$CANDIDATE_SRC" merge-base \ + "origin/$BASELINE_BRANCH" "$CI_COMMIT_SHA") + BASELINE_SRC=/app/baseline + fetch_release "$BASELINE_SRC" "$BASELINE_BRANCH" "$BASELINE_SHA" +fi + +if [ -z "$BOLT_MODE" ]; then + if [ -n "$BASELINE_SRC" ]; then BOLT_MODE=align; else BOLT_MODE=plain; fi +fi +export BOLT_MODE +if [ "$BOLT_MODE" = align ] && [ -z "$BASELINE_SRC" ]; then + echo "BOLT alignment requires a baseline revision; use BOLT_MODE=plain or off for a candidate-only run." >&2 + exit 1 +fi +echo "PHP benchmark binary processing: $BOLT_MODE" +printf '%s\n' "$BOLT_MODE" > "$ARTIFACTS_DIR/bolt-mode.txt" + +# Older harnesses rebuild separate extensions and would silently discard BOLT's +# output. Both revisions must use the combined-extension harness from #4520. +for SOURCE in "$CANDIDATE_SRC" ${BASELINE_SRC:+"$BASELINE_SRC"}; do + if ! grep -q DD_TRACE_ASSUME_COMPILED "$SOURCE/benchmark/runall.sh"; then + echo "The benchmark revisions must include the combined-extension harness from dd-trace-php#4520: $SOURCE" >&2 + exit 1 + fi +done + +# Both endpoints must be built and rewritten before either endpoint is timed. +if [ "$BOLT_MODE" != off ]; then + "$STEPS_DIR/prepare-bolt.sh" "$CANDIDATE_SRC" "$BASELINE_SRC" "$BOLT_DIR" +fi + +CODE_SRC="$CANDIDATE_SRC" BASELINE_OR_CANDIDATE=candidate "$STEPS_DIR/run-revision.sh" +if [ -n "$BASELINE_SRC" ]; then + CODE_SRC="$BASELINE_SRC" BASELINE_OR_CANDIDATE=baseline "$STEPS_DIR/run-revision.sh" +fi diff --git a/.gitlab/benchmarks/steps/run-revision.sh b/.gitlab/benchmarks/steps/run-revision.sh new file mode 100755 index 0000000000..4e43c2d902 --- /dev/null +++ b/.gitlab/benchmarks/steps/run-revision.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash + +set -euo pipefail + +export SCENARIO=$BP_SCENARIO +unset CI DD_TRACE_ASSUME_COMPILED + +if [ "$BOLT_MODE" != off ]; then + EXTENSION_DIR=$(php -n -r 'echo ini_get("extension_dir");') + # A previous worker may still map the installed library; replace it atomically. + TEMP_MODULE=$(mktemp "$EXTENSION_DIR/ddtrace.XXXXXX.so") + cp "$BOLT_DIR/$BASELINE_OR_CANDIDATE.so" "$TEMP_MODULE" + chmod 755 "$TEMP_MODULE" + mv -f "$TEMP_MODULE" "$EXTENSION_DIR/ddtrace.so" + export DD_TRACE_ASSUME_COMPILED=1 +fi + +cd "$CODE_SRC/benchmark/" +rm -rf /tmp/logs/ +mkdir -p /tmp/logs +# A baseline from before TRACER_PART existed would run every part. +if [ -n "${TRACER_PART:-}" ] && ! grep -q TRACER_PART runall.sh; then + cp "$CI_PROJECT_DIR/benchmark/runall.sh" runall.sh +fi +taskset -c 34-47 ./runall.sh + +if [ "$BOLT_MODE" != off ]; then + # Detect future build-script changes that discard the rewritten module. + cmp "$BOLT_DIR/$BASELINE_OR_CANDIDATE.so" "$EXTENSION_DIR/ddtrace.so" + cmp "$BOLT_DIR/$BASELINE_OR_CANDIDATE.so" "$CODE_SRC/tmp/build_combined/modules/ddtrace.so" +fi + +if [ "$SCENARIO" = profiler ]; then + mv "$ARTIFACTS_DIR/sirun_timeline.ndjson" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-sirun_timeline.ndjson" + mv "$ARTIFACTS_DIR/sirun_exceptions.ndjson" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-sirun_exceptions.ndjson" +elif [ "$SCENARIO" = tracer ]; then + if [ -z "${TRACER_PART:-}" ] || [ "$TRACER_PART" = phpbench-opcache ]; then + # The third CSV column is the subject; distinguish OPcache subjects. + awk -F ',' -v OFS=',' 'NR == 1 { print } NR > 1 { $3 = $3 "-opcache"; print }' \ + "$ARTIFACTS_DIR/tracer-bench-results-opcache.csv" > "$ARTIFACTS_DIR/tracer-bench-results-opcache.tmp" + mv "$ARTIFACTS_DIR/tracer-bench-results-opcache.tmp" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-tracer-bench-results-opcache.csv" + rm "$ARTIFACTS_DIR/tracer-bench-results-opcache.csv" + fi + if [ -z "${TRACER_PART:-}" ] || [ "$TRACER_PART" = phpbench ]; then + mv "$ARTIFACTS_DIR/tracer-bench-results.csv" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-tracer-bench-results.csv" + fi + if [ -z "${TRACER_PART:-}" ] || [ "$TRACER_PART" = tea ]; then + mv "$ARTIFACTS_DIR/tracer-tea-bench-results.json" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-tracer-tea-bench-results.json" + fi +elif [ "$SCENARIO" = appsec ]; then + awk -F ',' -v OFS=',' 'NR == 1 { print } NR > 1 { $3 = $3 "-appsec"; print }' \ + "$ARTIFACTS_DIR/appsec-bench-results.csv" > "$ARTIFACTS_DIR/appsec-bench-results.tmp" + mv "$ARTIFACTS_DIR/appsec-bench-results.tmp" "$ARTIFACTS_DIR/$BASELINE_OR_CANDIDATE-appsec-bench-results.csv" + rm "$ARTIFACTS_DIR/appsec-bench-results.csv" +fi + +tar -zcf "$CI_PROJECT_DIR/$BASELINE_OR_CANDIDATE.tar.gz" /tmp/logs +rm -rf /tmp/logs