Skip to content

Commit 8dfb407

Browse files
committed
Auto merge of #94381 - Kobzol:llvm-bolt, r=Mark-Simulacrum
Use BOLT in CI to optimize LLVM This PR adds an optimization step in the Linux `dist` CI pipeline that uses [BOLT](https://github.com/llvm/llvm-project/tree/main/bolt) to optimize the `libLLVM.so` library built by boostrap. Steps: - [x] Use LLVM 15 as a bootstrap compiler and use it to build BOLT - [x] Compile LLVM with support for relocations (`-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-q"`) - [x] Gather profile data using instrumented LLVM - [x] Apply profile to LLVM that has already been PGOfied - [x] Run with BOLT profiling on more benchmarks - [x] Decide on the order of optimization (PGO -> BOLT?) - [x] Decide how we should get `bolt` (currently we use the host `bolt`) - [x] Clean up The latest perf results can be found [here](#94381 (comment)). The current CI build time with BOLT applied is around 1h 55 minutes.
2 parents e495b37 + cc475f5 commit 8dfb407

File tree

8 files changed

+158
-7
lines changed

8 files changed

+158
-7
lines changed

src/bootstrap/bolt.rs

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
use std::path::Path;
2+
use std::process::Command;
3+
4+
/// Uses the `llvm-bolt` binary to instrument the binary/library at the given `path` with BOLT.
5+
/// When the instrumented artifact is executed, it will generate BOLT profiles into
6+
/// `/tmp/prof.fdata.<pid>.fdata`.
7+
pub fn instrument_with_bolt_inplace(path: &Path) {
8+
let dir = std::env::temp_dir();
9+
let instrumented_path = dir.join("instrumented.so");
10+
11+
let status = Command::new("llvm-bolt")
12+
.arg("-instrument")
13+
.arg(&path)
14+
// Make sure that each process will write its profiles into a separate file
15+
.arg("--instrumentation-file-append-pid")
16+
.arg("-o")
17+
.arg(&instrumented_path)
18+
.status()
19+
.expect("Could not instrument artifact using BOLT");
20+
21+
if !status.success() {
22+
panic!("Could not instrument {} with BOLT, exit code {:?}", path.display(), status.code());
23+
}
24+
25+
std::fs::copy(&instrumented_path, path).expect("Cannot copy instrumented artifact");
26+
std::fs::remove_file(instrumented_path).expect("Cannot delete instrumented artifact");
27+
}
28+
29+
/// Uses the `llvm-bolt` binary to optimize the binary/library at the given `path` with BOLT,
30+
/// using merged profiles from `profile_path`.
31+
///
32+
/// The recorded profiles have to be merged using the `merge-fdata` tool from LLVM and the merged
33+
/// profile path should be then passed to this function.
34+
pub fn optimize_library_with_bolt_inplace(path: &Path, profile_path: &Path) {
35+
let dir = std::env::temp_dir();
36+
let optimized_path = dir.join("optimized.so");
37+
38+
let status = Command::new("llvm-bolt")
39+
.arg(&path)
40+
.arg("-data")
41+
.arg(&profile_path)
42+
.arg("-o")
43+
.arg(&optimized_path)
44+
// Reorder basic blocks within functions
45+
.arg("-reorder-blocks=ext-tsp")
46+
// Reorder functions within the binary
47+
.arg("-reorder-functions=hfsort+")
48+
// Split function code into hot and code regions
49+
.arg("-split-functions=2")
50+
// Split as many basic blocks as possible
51+
.arg("-split-all-cold")
52+
// Move jump tables to a separate section
53+
.arg("-jump-tables=move")
54+
// Use GNU_STACK program header for new segment (workaround for issues with strip/objcopy)
55+
.arg("-use-gnu-stack")
56+
// Fold functions with identical code
57+
.arg("-icf=1")
58+
// Update DWARF debug info in the final binary
59+
.arg("-update-debug-sections")
60+
// Print optimization statistics
61+
.arg("-dyno-stats")
62+
.status()
63+
.expect("Could not optimize artifact using BOLT");
64+
65+
if !status.success() {
66+
panic!("Could not optimize {} with BOLT, exit code {:?}", path.display(), status.code());
67+
}
68+
69+
std::fs::copy(&optimized_path, path).expect("Cannot copy optimized artifact");
70+
std::fs::remove_file(optimized_path).expect("Cannot delete optimized artifact");
71+
}

src/bootstrap/config.rs

+11
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ pub struct Config {
161161
pub llvm_profile_use: Option<String>,
162162
pub llvm_profile_generate: bool,
163163
pub llvm_libunwind_default: Option<LlvmLibunwind>,
164+
pub llvm_bolt_profile_generate: bool,
165+
pub llvm_bolt_profile_use: Option<String>,
164166

165167
pub build: TargetSelection,
166168
pub hosts: Vec<TargetSelection>,
@@ -806,6 +808,15 @@ impl Config {
806808
}
807809
config.llvm_profile_use = flags.llvm_profile_use;
808810
config.llvm_profile_generate = flags.llvm_profile_generate;
811+
config.llvm_bolt_profile_generate = flags.llvm_bolt_profile_generate;
812+
config.llvm_bolt_profile_use = flags.llvm_bolt_profile_use;
813+
814+
if config.llvm_bolt_profile_generate && config.llvm_bolt_profile_use.is_some() {
815+
eprintln!(
816+
"Cannot use both `llvm_bolt_profile_generate` and `llvm_bolt_profile_use` at the same time"
817+
);
818+
crate::detail_exit(1);
819+
}
809820

810821
// Infer the rest of the configuration.
811822

src/bootstrap/dist.rs

+4
Original file line numberDiff line numberDiff line change
@@ -2159,6 +2159,10 @@ impl Step for ReproducibleArtifacts {
21592159
tarball.add_file(path, ".", 0o644);
21602160
added_anything = true;
21612161
}
2162+
if let Some(path) = builder.config.llvm_bolt_profile_use.as_ref() {
2163+
tarball.add_file(path, ".", 0o644);
2164+
added_anything = true;
2165+
}
21622166
if added_anything { Some(tarball.generate()) } else { None }
21632167
}
21642168
}

src/bootstrap/flags.rs

+6
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ pub struct Flags {
7878
//
7979
// llvm_out/build/profiles/ is the location this writes to.
8080
pub llvm_profile_generate: bool,
81+
pub llvm_bolt_profile_generate: bool,
82+
pub llvm_bolt_profile_use: Option<String>,
8183
}
8284

8385
#[derive(Debug)]
@@ -255,6 +257,8 @@ To learn more about a subcommand, run `./x.py <subcommand> -h`",
255257
opts.optmulti("D", "", "deny certain clippy lints", "OPT");
256258
opts.optmulti("W", "", "warn about certain clippy lints", "OPT");
257259
opts.optmulti("F", "", "forbid certain clippy lints", "OPT");
260+
opts.optflag("", "llvm-bolt-profile-generate", "generate BOLT profile for LLVM build");
261+
opts.optopt("", "llvm-bolt-profile-use", "use BOLT profile for LLVM build", "PROFILE");
258262

259263
// We can't use getopt to parse the options until we have completed specifying which
260264
// options are valid, but under the current implementation, some options are conditional on
@@ -691,6 +695,8 @@ Arguments:
691695
rust_profile_generate: matches.opt_str("rust-profile-generate"),
692696
llvm_profile_use: matches.opt_str("llvm-profile-use"),
693697
llvm_profile_generate: matches.opt_present("llvm-profile-generate"),
698+
llvm_bolt_profile_generate: matches.opt_present("llvm-bolt-profile-generate"),
699+
llvm_bolt_profile_use: matches.opt_str("llvm-bolt-profile-use"),
694700
}
695701
}
696702
}

src/bootstrap/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ use crate::util::{
122122
check_run, exe, libdir, mtime, output, run, run_suppressed, try_run, try_run_suppressed, CiEnv,
123123
};
124124

125+
mod bolt;
125126
mod builder;
126127
mod cache;
127128
mod cc_detect;

src/bootstrap/native.rs

+29
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use std::io;
1616
use std::path::{Path, PathBuf};
1717
use std::process::Command;
1818

19+
use crate::bolt::{instrument_with_bolt_inplace, optimize_library_with_bolt_inplace};
1920
use crate::builder::{Builder, RunConfig, ShouldRun, Step};
2021
use crate::channel;
2122
use crate::config::TargetSelection;
@@ -403,6 +404,12 @@ impl Step for Llvm {
403404
if let Some(path) = builder.config.llvm_profile_use.as_ref() {
404405
cfg.define("LLVM_PROFDATA_FILE", &path);
405406
}
407+
if builder.config.llvm_bolt_profile_generate
408+
|| builder.config.llvm_bolt_profile_use.is_some()
409+
{
410+
// Relocations are required for BOLT to work.
411+
ldflags.push_all("-Wl,-q");
412+
}
406413

407414
// Disable zstd to avoid a dependency on libzstd.so.
408415
cfg.define("LLVM_ENABLE_ZSTD", "OFF");
@@ -571,12 +578,34 @@ impl Step for Llvm {
571578
}
572579
}
573580

581+
// After LLVM is built, we modify (instrument or optimize) the libLLVM.so library file
582+
// in place. This is fine, because currently we do not support incrementally rebuilding
583+
// LLVM after a configuration change, so to rebuild it the build files have to be removed,
584+
// which will also remove these modified files.
585+
if builder.config.llvm_bolt_profile_generate {
586+
instrument_with_bolt_inplace(&get_built_llvm_lib_path(&build_llvm_config));
587+
}
588+
if let Some(path) = &builder.config.llvm_bolt_profile_use {
589+
optimize_library_with_bolt_inplace(
590+
&get_built_llvm_lib_path(&build_llvm_config),
591+
&Path::new(path),
592+
);
593+
}
594+
574595
t!(stamp.write());
575596

576597
build_llvm_config
577598
}
578599
}
579600

601+
/// Returns path to a built LLVM library (libLLVM.so).
602+
/// Assumes that we have built LLVM into a single library file.
603+
fn get_built_llvm_lib_path(llvm_config_path: &Path) -> PathBuf {
604+
let mut cmd = Command::new(llvm_config_path);
605+
cmd.arg("--libfiles");
606+
PathBuf::from(output(&mut cmd).trim())
607+
}
608+
580609
fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
581610
if !builder.config.llvm_version_check {
582611
return;

src/ci/docker/host-x86_64/dist-x86_64-linux/build-clang.sh

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ INC="/rustroot/include:/usr/include"
2222

2323
# We need compiler-rt for the profile runtime (used later to PGO the LLVM build)
2424
# but sanitizers aren't currently building. Since we don't need those, just
25-
# disable them.
25+
# disable them. BOLT is used for optimizing LLVM.
2626
hide_output \
2727
cmake ../llvm \
2828
-DCMAKE_C_COMPILER=/rustroot/bin/gcc \
@@ -36,7 +36,7 @@ hide_output \
3636
-DLLVM_INCLUDE_BENCHMARKS=OFF \
3737
-DLLVM_INCLUDE_TESTS=OFF \
3838
-DLLVM_INCLUDE_EXAMPLES=OFF \
39-
-DLLVM_ENABLE_PROJECTS="clang;lld;compiler-rt" \
39+
-DLLVM_ENABLE_PROJECTS="clang;lld;compiler-rt;bolt" \
4040
-DC_INCLUDE_DIRS="$INC"
4141

4242
hide_output make -j$(nproc)

src/ci/pgo.sh

+34-5
Original file line numberDiff line numberDiff line change
@@ -190,11 +190,40 @@ rm -r $RUSTC_PROFILE_DIRECTORY_ROOT
190190
# directories ourselves.
191191
rm -r $BUILD_ARTIFACTS/llvm $BUILD_ARTIFACTS/lld
192192

193-
# This produces the actual final set of artifacts, using both the LLVM and rustc
194-
# collected profiling data.
195-
$@ \
196-
--rust-profile-use=${RUSTC_PROFILE_MERGED_FILE} \
197-
--llvm-profile-use=${LLVM_PROFILE_MERGED_FILE}
193+
if isLinux; then
194+
# Gather BOLT profile (BOLT is currently only available on Linux)
195+
python3 ../x.py build --target=$PGO_HOST --host=$PGO_HOST \
196+
--stage 2 library/std \
197+
--llvm-profile-use=${LLVM_PROFILE_MERGED_FILE} \
198+
--llvm-bolt-profile-generate
199+
200+
BOLT_PROFILE_MERGED_FILE=/tmp/bolt.profdata
201+
202+
# Here we're profiling Bolt.
203+
gather_profiles "Check,Debug,Opt" "Full" \
204+
"syn-1.0.89,serde-1.0.136,ripgrep-13.0.0,regex-1.5.5,clap-3.1.6,hyper-0.14.18"
205+
206+
merge-fdata /tmp/prof.fdata* > ${BOLT_PROFILE_MERGED_FILE}
207+
208+
echo "BOLT statistics"
209+
du -sh /tmp/prof.fdata*
210+
du -sh ${BOLT_PROFILE_MERGED_FILE}
211+
echo "Profile file count"
212+
find /tmp/prof.fdata* -type f | wc -l
213+
214+
rm -r $BUILD_ARTIFACTS/llvm $BUILD_ARTIFACTS/lld
215+
216+
# This produces the actual final set of artifacts, using both the LLVM and rustc
217+
# collected profiling data.
218+
$@ \
219+
--rust-profile-use=${RUSTC_PROFILE_MERGED_FILE} \
220+
--llvm-profile-use=${LLVM_PROFILE_MERGED_FILE} \
221+
--llvm-bolt-profile-use=${BOLT_PROFILE_MERGED_FILE}
222+
else
223+
$@ \
224+
--rust-profile-use=${RUSTC_PROFILE_MERGED_FILE} \
225+
--llvm-profile-use=${LLVM_PROFILE_MERGED_FILE}
226+
fi
198227

199228
echo "Rustc binary size"
200229
ls -la ./build/$PGO_HOST/stage2/bin

0 commit comments

Comments
 (0)