Debian Codegraph @

util/build-pgo.sh

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env bash
2 # spell-checker:ignore (jargon) profdata profraw sysroot rustlib nullglob aeiou nocheck CGU Cprofile cygpath atexit
3 #
4 # Build uutils coreutils with Profile-Guided Optimization.
5 #
6 # 1. build an instrumented multicall binary (-Cprofile-generate)
7 # 2. run representative workloads to collect raw profiles
8 # 3. merge them with llvm-profdata
9 # 4. build the optimized binary (-Cprofile-use), unless --train-only
10 #
11 # Runs on Linux, macOS and Windows (git-bash).
12 #
13 # Usage:
14 # util/build-pgo.sh [--target TRIPLE] [--target-dir DIR] [--features LIST]
15 # [--train-only] [--llvm-profdata PATH]
16
17 set -euo pipefail
18
19 # On Windows the instrumented binary, rustc and the profiler runtime are all
20 # native programs that do not understand git-bash's `/d/a/...` paths, while bash
21 # itself does not understand `D:\a\...`. `cygpath -m` yields `D:/a/...`, which
22 # both sides accept, so every path the script builds goes through it.
23 norm_path() {
24 if command -v cygpath >/dev/null 2>&1; then cygpath -m "$1"; else printf '%s\n' "$1"; fi
25 }
26
27 REPO_ROOT="$(norm_path "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)")"
28 TARGET_DIR="${REPO_ROOT}/target/coreutils-pgo"
29 FEATURES="unix"
30 TARGET=""
31 TRAIN_ONLY=0
32 LLVM_PROFDATA=""
33
34 while [ $# -gt 0 ]; do
35 case "$1" in
36 --target) TARGET="$2"; shift 2 ;;
37 --target-dir) TARGET_DIR="$2"; shift 2 ;;
38 --features) FEATURES="$2"; shift 2 ;;
39 --llvm-profdata) LLVM_PROFDATA="$2"; shift 2 ;;
40 --train-only) TRAIN_ONLY=1; shift ;;
41 -h|--help) sed -n '3,16p' "${BASH_SOURCE[0]}"; exit 0 ;;
42 *) echo "unknown argument: $1" >&2; exit 2 ;;
43 esac
44 done
45
46 mkdir -p "$TARGET_DIR"
47 TARGET_DIR="$(norm_path "$(cd "$TARGET_DIR" && pwd)")"
48
49 HOST="$(rustc --print host-tuple)"
50 [ -n "$TARGET" ] || TARGET="$HOST"
51 # Cargo puts the artifacts of an explicit --target under a per-target directory,
52 # and Windows binaries carry a suffix.
53 case "$TARGET" in *windows*) EXE=".exe" ;; *) EXE="" ;; esac
54 echo "target: ${TARGET} (host: ${HOST})"
55
56 SCRIPT_START=$SECONDS
57
58 fmt_duration() { printf '%dm%02ds' $(($1 / 60)) $(($1 % 60)); }
59 begin_step() {
60 STEP_NAME="$1"
61 STEP_START=$SECONDS
62 echo
63 echo "=== ${STEP_NAME} ==="
64 }
65 end_step() { echo "--- ${STEP_NAME}: $(fmt_duration $((SECONDS - STEP_START))) ---"; }
66
67 PROFILE_DIR="${TARGET_DIR}/profiles"
68 CORPUS_DIR="${TARGET_DIR}/corpus"
69 MERGED="${TARGET_DIR}/coreutils.profdata"
70
71 # llvm-profdata must come from the *active* toolchain: its version has to match
72 # the rustc that instrumented the binary.
73 if [ -z "$LLVM_PROFDATA" ]; then
74 SYSROOT="$(norm_path "$(rustc --print sysroot)")"
75 # llvm-profdata ships for the host, whatever we are cross-building for.
76 case "$HOST" in *windows*) PROFDATA_EXE=".exe" ;; *) PROFDATA_EXE="" ;; esac
77 LLVM_PROFDATA="${SYSROOT}/lib/rustlib/${HOST}/bin/llvm-profdata${PROFDATA_EXE}"
78 fi
79 if [ ! -x "$LLVM_PROFDATA" ]; then
80 echo "llvm-profdata not found at ${LLVM_PROFDATA}" >&2
81 echo "Run: rustup component add llvm-tools" >&2
82 exit 1
83 fi
84 echo "llvm-profdata: ${LLVM_PROFDATA}"
85
86 cargo_build() {
87 # $1: target dir, $2: extra rustflags
88 local feature_args=()
89 if [ -n "$FEATURES" ]; then feature_args=(--features="$FEATURES"); fi
90 (
91 cd "$REPO_ROOT"
92 export CARGO_TARGET_DIR="$1"
93 export CARGO_INCREMENTAL=0
94 export RUSTFLAGS="${RUSTFLAGS:+${RUSTFLAGS} }$2"
95 # bash 3.2 (macOS) errors on an empty array expansion under `set -u`,
96 # hence the `[@]+` guard on both expansions below.
97 echo "Running: cargo build --release --target=${TARGET} ${feature_args[*]+${feature_args[*]}}"
98 echo " RUSTFLAGS=${RUSTFLAGS}"
99 cargo build --release --target="$TARGET" ${feature_args[@]+"${feature_args[@]}"}
100 )
101 }
102
103 begin_step "Step 1: instrumented build"
104 INSTR_DIR="${TARGET_DIR}/instrumented"
105 rm -rf "$PROFILE_DIR"
106 mkdir -p "$PROFILE_DIR"
107 # The instrumented build must use the same LTO and codegen-unit settings as the
108 # final one. Inlining happens before instrumentation, so building it with LTO
109 # off yields counters for functions that no longer exist once the final build
110 # runs whole-program codegen, and the profile is then largely wasted on it.
111 #
112 # `--cfg pgo_training` makes the binary flush its own counters before exiting:
113 # it always leaves through `std::process::exit`, which on Windows is
114 # `ExitProcess` and skips the `atexit` handler the profiling runtime would
115 # otherwise write the profile from.
116 cargo_build "$INSTR_DIR" "-Cprofile-generate=${PROFILE_DIR} --cfg pgo_training"
117
118 BIN="${INSTR_DIR}/${TARGET}/release/coreutils${EXE}"
119 [ -x "$BIN" ] || { echo "instrumented binary not found: ${BIN}" >&2; exit 1; }
120 # Training runs the binary we just built, so a foreign target only works where
121 # the host can execute it (x86_64 on arm64 macOS needs Rosetta, for instance).
122 if ! "$BIN" true >/dev/null 2>&1; then
123 echo "cannot run the instrumented ${TARGET} binary on this ${HOST} host" >&2
124 exit 1
125 fi
126 end_step
127
128 begin_step "Step 2: corpus"
129 # Everything is generated from scratch: reading whatever /usr/share/dict/words
130 # or /etc/passwd happens to hold would make the profile machine-dependent.
131 export LLVM_PROFILE_FILE="${PROFILE_DIR}/coreutils-%p.profraw"
132 rm -rf "$CORPUS_DIR"
133 mkdir -p "$CORPUS_DIR"
134
135 WORDS="${CORPUS_DIR}/words.txt"
136 NUMBERS="${CORPUS_DIR}/numbers.txt"
137 REPEATED="${CORPUS_DIR}/repeated.txt"
138 PAIRS="${CORPUS_DIR}/pairs.txt"
139 BLOB="${CORPUS_DIR}/blob.bin"
140 COLUMNS="${CORPUS_DIR}/columns.txt"
141
142 # Built with bash's own printf rather than awk: git-bash has no awk, and the
143 # whole corpus is still generated in a couple of seconds.
144 # Shuffled by a stride so sort/uniq get unordered input rather than a no-op.
145 for ((i = 0; i < 200000; i++)); do printf 'w%06d\n' $(((i * 7919) % 200000)); done > "$WORDS"
146 for ((i = 0; i < 100000; i++)); do printf 'line%04d\n' $((i % 1000)); done > "$REPEATED"
147 for ((i = 0; i < 100000; i++)); do printf '%08d value%d\n' "$i" "$i"; done > "$PAIRS"
148 for ((i = 0; i < 2000; i++)); do printf 'user%d:x:%d:%d:User %d:/home/user%d:/bin/sh\n' "$i" $((1000 + i)) $((1000 + i)) "$i" "$i"; done > "$COLUMNS"
149 # seq/dd are part of what we want to profile, so use the instrumented binary.
150 "$BIN" seq 500000 > "$NUMBERS"
151 "$BIN" dd "if=${BIN}" "of=${BLOB}" bs=64K count=64 2>/dev/null
152 end_step
153
154 begin_step "Step 3: training workloads"
155 # Kept inside the target dir rather than under TMPDIR: git-bash may hand back a
156 # Windows-style TMPDIR that neither mktemp nor the workloads would agree on.
157 WORK="${TARGET_DIR}/work"
158 rm -rf "$WORK"
159 mkdir -p "$WORK"
160 trap 'rm -rf "$WORK"' EXIT
161
162 # Individual workloads are allowed to fail (a util may be absent from the
163 # selected feature set); a partial profile is still a usable profile.
164 run() { "$BIN" "$@" >/dev/null 2>&1 || true; }
165
166 # sort: the single hottest util, in its main modes
167 run sort "$WORDS" -o "${WORK}/sorted.txt"
168 run sort -n "$NUMBERS" -o "${WORK}/sorted-n.txt"
169 run sort -u "$REPEATED" -o "${WORK}/sorted-u.txt"
170 run sort -r "$WORDS" -o "${WORK}/sorted-r.txt"
171 run sort -k2,2 -t: "$COLUMNS" -o "${WORK}/sorted-k.txt"
172
173 # wc / cat / head / tail, to a regular file so the write path is not /dev/null
174 run wc -l "$WORDS"
175 run wc -w "$WORDS"
176 run wc -c "$BLOB"
177 run wc "$WORDS" "$NUMBERS"
178 "$BIN" cat "$WORDS" > "${WORK}/cat.txt" 2>/dev/null || true
179 "$BIN" cat -n "$WORDS" > "${WORK}/cat-n.txt" 2>/dev/null || true
180 "$BIN" head -n 50000 "$WORDS" > "${WORK}/head.txt" 2>/dev/null || true
181 "$BIN" tail -n 50000 "$WORDS" > "${WORK}/tail.txt" 2>/dev/null || true
182 run head -c 1M "$BLOB"
183
184 "$BIN" cat "$WORDS" | "$BIN" sort | "$BIN" uniq -c > "${WORK}/pipe1.txt" 2>/dev/null || true
185 "$BIN" seq 200000 | "$BIN" wc -l > /dev/null 2>&1 || true
186 "$BIN" cat "$BLOB" | "$BIN" sha256sum > /dev/null 2>&1 || true
187 "$BIN" sort -n "$NUMBERS" | "$BIN" tail -n 1000 | "$BIN" cut -c1-4 > "${WORK}/pipe2.txt" 2>/dev/null || true
188
189 # text utils
190 run uniq "$REPEATED"
191 run uniq -c "$REPEATED"
192 run uniq -u "$REPEATED"
193 run cut -d: -f1,3 "$COLUMNS"
194 run cut -c1-10 "$WORDS"
195 run nl "$WORDS"
196 run fold -w 40 "$WORDS"
197 run expand "$WORDS"
198 run unexpand "$WORDS"
199 run paste "$WORDS" "$WORDS"
200 run join "$PAIRS" "$PAIRS"
201 run join --nocheck-order "$PAIRS" "$PAIRS"
202 run split -l 20000 "$WORDS" "${WORK}/split-"
203 "$BIN" tr a-z A-Z < "$WORDS" > "${WORK}/tr.txt" 2>/dev/null || true
204 "$BIN" tr -d aeiou < "$WORDS" > "${WORK}/tr-d.txt" 2>/dev/null || true
205 "$BIN" tee "${WORK}/tee.txt" < "$NUMBERS" > /dev/null 2>&1 || true
206
207 # numbers / encoding / hashing
208 run seq 1000000
209 run seq 0 0.1 10000
210 "$BIN" base64 "$BLOB" > "${WORK}/encoded.b64" 2>/dev/null || true
211 run base64 -d "${WORK}/encoded.b64"
212 run cksum "$BLOB"
213 run md5sum "$BLOB"
214 run sha1sum "$BLOB"
215 run sha256sum "$BLOB"
216
217 # file management: cp/mv/rm/ls are as hot in practice as anything above
218 run cp "$WORDS" "${WORK}/copy.txt"
219 run cp -r "${REPO_ROOT}/src/uu/sort" "${WORK}/tree"
220 run mv "${WORK}/copy.txt" "${WORK}/moved.txt"
221 run mv "${WORK}/tree" "${WORK}/tree2"
222 run ls -la "${REPO_ROOT}/src/uu"
223 run ls -lR "${REPO_ROOT}/src/uu"
224 run ls --color=always -la "${REPO_ROOT}/src"
225 run du -sh "${REPO_ROOT}/src"
226 run df -h
227 run rm -rf "${WORK}/tree2"
228
229 echo "Workloads complete."
230 end_step
231
232 begin_step "Step 4: merging profiles"
233 shopt -s nullglob
234 RAW=("${PROFILE_DIR}"/coreutils-*.profraw)
235 shopt -u nullglob
236 if [ ${#RAW[@]} -eq 0 ]; then
237 echo "no .profraw files found in ${PROFILE_DIR}" >&2
238 exit 1
239 fi
240 echo "Merging ${#RAW[@]} profile(s)..."
241 "$LLVM_PROFDATA" merge -sparse "${RAW[@]}" -o "$MERGED"
242 echo "Merged profile: ${MERGED}"
243
244 # A profile that covers almost nothing still builds fine and silently produces a
245 # barely-optimized binary, so fail loudly instead: every workload in step 3 is
246 # allowed to fail individually, and without this a broken corpus would ship.
247 "$LLVM_PROFDATA" show "$MERGED" | head -6
248 COVERED="$("$LLVM_PROFDATA" show "$MERGED" | sed -n 's/^Total functions: *//p')"
249 MIN_FUNCTIONS=500
250 if [ -z "$COVERED" ] || [ "$COVERED" -lt "$MIN_FUNCTIONS" ]; then
251 echo "profile covers only ${COVERED:-0} functions (expected >= ${MIN_FUNCTIONS})" >&2
252 echo "the training workloads probably did not run; refusing to ship this profile" >&2
253 # Distinguish "the workloads never ran" from "they ran but the counters were
254 # never written": the first leaves no/short raw files, the second leaves
255 # plenty of same-sized ones that merge down to zero functions.
256 echo "--- raw profiles in ${PROFILE_DIR}:" >&2
257 ls -l "$PROFILE_DIR" | head -12 >&2
258 echo "--- first raw profile (${RAW[0]}):" >&2
259 "$LLVM_PROFDATA" show "${RAW[0]}" >&2 || true
260 echo "--- instrumented binary: ${BIN}" >&2
261 ls -l "$BIN" >&2
262 exit 1
263 fi
264 echo "Profile covers ${COVERED} functions."
265 end_step
266
267 # CI needs the absolute, natively-spelled path to put in RUSTFLAGS; it cannot
268 # reconstruct it portably because of the Windows path rewriting above.
269 printf '%s\n' "$MERGED" > "${TARGET_DIR}/profdata-path.txt"
270
271 if [ "$TRAIN_ONLY" -eq 1 ]; then
272 echo
273 echo "To use the profile in a release build, add to RUSTFLAGS:"
274 echo " -Cprofile-use=${MERGED}"
275 echo "Total: $(fmt_duration $((SECONDS - SCRIPT_START)))"
276 exit 0
277 fi
278
279 begin_step "Step 5: optimized build"
280 cargo_build "$TARGET_DIR" "-Cprofile-use=${MERGED}"
281 end_step
282 echo
283 echo "Optimized binary: ${TARGET_DIR}/${TARGET}/release/coreutils${EXE}"
284 echo "Total: $(fmt_duration $((SECONDS - SCRIPT_START)))"