Repository navigation
Expand file tree
/
Copy pathbuild.rs
More file actions
344 lines (311 loc) · 13.7 KB
/
Copy pathbuild.rs
File metadata and controls
344 lines (311 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use std::env;
use std::path::PathBuf;
fn defined(var: &str) -> bool {
println!("cargo::rerun-if-env-changed={}", var);
env::var_os(var).is_some()
}
fn is_pure() -> bool {
defined("CARGO_FEATURE_PURE")
}
fn is_ci() -> bool {
defined("BLAKE3_CI")
}
fn warn(warning: &str) {
assert!(!warning.contains("\n"));
println!("cargo::warning={}", warning);
if is_ci() {
println!("cargo::warning=Warnings in CI are treated as errors. Build failed.");
std::process::exit(1);
}
}
fn target_components() -> Vec<String> {
let target = env::var("TARGET").unwrap();
target.split("-").map(|s| s.to_string()).collect()
}
fn is_x86_64() -> bool {
target_components()[0] == "x86_64"
}
fn is_windows_target() -> bool {
env::var("CARGO_CFG_TARGET_OS").unwrap() == "windows"
}
/// Windows builds take MSVC's assembler: the fork supports Windows with
/// MSVC alone (README); official BLAKE3 serves MinGW and Clang there.
fn assert_msvc_asm() {
assert!(
use_msvc_asm(),
"blake3-servil builds for Windows with MSVC (cl) alone; for MinGW, or Clang in place of cl, use official BLAKE3 (https://github.com/BLAKE3-team/BLAKE3)"
);
}
fn use_msvc_asm() -> bool {
const MSVC_NAMES: &[&str] = &["", "cl", "cl.exe"];
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
let target_windows_msvc = target_os == "windows" && target_env == "msvc";
let host_triple = env::var("HOST").unwrap_or_default();
let target_triple = env::var("TARGET").unwrap_or_default();
let cross_compiling = host_triple != target_triple;
let cc = env::var("CC").unwrap_or_default().to_ascii_lowercase();
if !target_windows_msvc {
// We are not building for Windows with the MSVC toolchain.
false
} else if !cross_compiling && MSVC_NAMES.contains(&&*cc) {
// We are building on Windows with the MSVC toolchain (and not cross-compiling for another architecture or target).
true
} else {
// We are cross-compiling to Windows with the MSVC toolchain.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
let target_vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap_or_default();
let cc = env::var(format!("CC_{target_arch}_{target_vendor}_windows_msvc")).unwrap_or_default().to_ascii_lowercase();
// Check if we are using the MSVC compiler.
MSVC_NAMES.contains(&&*cc)
}
}
fn is_aarch64() -> bool {
target_components()[0] == "aarch64"
}
fn endianness() -> String {
let endianness = env::var("CARGO_CFG_TARGET_ENDIAN").unwrap();
assert!(endianness == "little" || endianness == "big");
endianness
}
fn is_little_endian() -> bool {
endianness() == "little"
}
// Windows targets may be using the MSVC toolchain or the MinGW toolchain. The
// right compiler flags to use depend on the toolchain. (And we don't want to
// use flag_if_supported, because we don't want features to be silently
// disabled by old compilers.)
fn is_windows_msvc() -> bool {
// Some targets are only two components long, so check in steps.
let second_component = &target_components()[1];
(second_component == "pc" || second_component == "win7") && target_components()[2] == "windows" && target_components()[3] == "msvc"
}
fn new_build() -> cc::Build {
let mut build = cc::Build::new();
if !is_windows_msvc() {
build.flag("-std=c11");
}
// Do NOT trigger a rebuild any time the env changes (e.g. $PATH).
// This prevents all downstream crates from being rebuilt when `cargo check`
// or `cargo build` are run in different environments, like Rust Analyzer
// vs. in the terminal vs. in a Git pre-commit hook.
build.emit_rerun_if_env_changed(false);
build
}
#[derive(PartialEq)]
enum CCompilerSupport {
NoCompiler,
NoAVX512,
YesAVX512,
}
use CCompilerSupport::*;
fn c_compiler_support() -> CCompilerSupport {
let build = new_build();
let flags_checked;
let support_result: Result<bool, _> = if is_windows_msvc() {
flags_checked = "/arch:AVX512";
build.is_flag_supported("/arch:AVX512")
} else {
// Check for both of the flags we use. If -mavx512f works, then -mavx512vl
// will probably always work too, but we might as well be thorough.
flags_checked = "-mavx512f and -mavx512vl";
match build.is_flag_supported("-mavx512f") {
Ok(true) => build.is_flag_supported("-mavx512vl"),
false_or_error => false_or_error,
}
};
match support_result {
Ok(true) => YesAVX512,
Ok(false) => {
warn(&format!("The C compiler {:?} does not support {}.", build.get_compiler().path(), flags_checked,));
NoAVX512
}
Err(e) => {
println!("{:?}", e);
warn(&format!("No C compiler {:?} detected.", build.get_compiler().path()));
NoCompiler
}
}
}
fn build_sse41_avx2_rust_intrinsics() {
// No C code to compile here. Set the cfg flags that enable the Rust
// SSE4.1 and AVX2 intrinsics modules. The regular Cargo build will
// compile them.
println!("cargo::rustc-cfg=blake3_sse41_rust");
println!("cargo::rustc-cfg=blake3_avx2_rust");
}
fn build_sse41_avx2_assembly() {
// Build the assembly implementations for SSE4.1 and AVX2.
assert!(is_x86_64());
println!("cargo::rustc-cfg=blake3_sse41_ffi");
println!("cargo::rustc-cfg=blake3_avx2_ffi");
let mut build = new_build();
if is_windows_target() {
assert_msvc_asm();
build.file("c/blake3_sse41_x86-64_windows_msvc.asm");
build.file("c/blake3_avx2_x86-64_windows_msvc.asm");
} else {
// All non-Windows implementations are assumed to support
// Linux-style assembly. These files do contain a small
// explicit workaround for macOS also.
build.file("c/blake3_sse41_x86-64_unix.S");
build.file("c/blake3_avx2_x86-64_unix.S");
}
build.compile("blake3_sse41_avx2_assembly");
}
fn build_avx512_assembly() {
// Build the assembly implementation for AVX-512.
assert!(is_x86_64());
println!("cargo::rustc-cfg=blake3_avx512_ffi");
let mut build = new_build();
let mut is_msvc = false;
if is_windows_target() {
assert_msvc_asm();
build.file("c/blake3_avx512_x86-64_windows_msvc.asm");
is_msvc = true;
} else {
build.file("c/blake3_avx512_x86-64_unix.S");
}
// Older versions of Clang require these flags, even for assembly. See
// https://github.com/BLAKE3-team/BLAKE3/issues/79.
if !is_msvc {
build.flag("-mavx512f");
build.flag("-mavx512vl");
}
build.compile("blake3_avx512_assembly");
}
// Whether this build assembles `source` with `flag`, as it will assemble the
// kernel files: with the caller's CFLAGS, and with the `.arch` directive that
// opens each kernel file, which reaches the assembler whatever -march the
// flags end with. A test of the flag alone passes under CFLAGS=-march=native,
// whose -march overrides the flag, while an assembler that predates the
// extension still rejects the kernel file's `.arch` line.
fn assembles(name: &str, flag: &str, source: &str) -> bool {
let path = PathBuf::from(env::var("OUT_DIR").unwrap()).join(format!("probe_{name}.S"));
std::fs::write(&path, source).unwrap();
let mut build = new_build();
build.file(&path).flag(flag).cargo_metadata(false).cargo_warnings(false);
build.try_compile(&format!("probe_{name}")).is_ok()
}
// The SME2 assembly implementation needs an assembler that understands
// `.arch armv9-a+sme2` (Clang/LLVM 17+, Xcode 15+, or binutils 2.41+ with
// GCC 14+). With an older compiler the crate builds without the SME2 kernel,
// with a warning: only CPUs with SME2 (Apple M4 and later) run it, and the
// NEON and scalar kernels serve every AArch64 CPU. Common Linux systems
// (Debian 12, Raspberry Pi OS) ship such compilers.
fn c_compiler_supports_sme2() -> bool {
let compiler = new_build().get_compiler().path().to_owned();
let supported = assembles("sme2", "-march=armv9-a+sme2", ".arch armv9-a+sme2\nsmstart sm\nsmstop sm\n");
if !supported {
warn(&format!(
"blake3-servil: {compiler:?} cannot assemble SME2 (-march=armv9-a+sme2), so this \
build leaves out the SME2 kernel, which Apple M4 and later CPUs run. Clang/LLVM 17 \
or later (for example CC=clang-19), Xcode 15 or later, or GCC 14 or later builds it."
));
}
supported
}
fn build_sme2_assembly() {
// The SME2 implementation is assembly only. It requires runtime
// detection (see platform.rs), and it requires a 512-bit streaming vector
// length, which the kernel checks for itself.
assert!(is_aarch64());
println!("cargo::rustc-cfg=blake3_sme2");
let mut build = new_build();
build.file("c/blake3_sme2_aarch64.S");
// Generated by tools/gen_sme2_hybrid.py: SME2 groups with an integer lane.
build.file("c/blake3_sme2_hybrid_aarch64.S");
build.flag("-march=armv9-a+sme2");
build.compile("blake3_sme2_assembly");
}
// The integer + NEON kernels need an assembler that knows armv8.2-a+sha3
// (GNU as 2.30+, LLVM 7+). With an older one the crate builds without them,
// with a warning: the NEON intrinsics and the portable code serve instead.
fn assert_assembles_sha3() {
let compiler = new_build().get_compiler().path().to_owned();
assert!(
assembles("sha3", "-march=armv8.2-a+sha3", ".arch armv8.2-a+sha3\nxar v0.2d, v1.2d, v2.2d, #1\n"),
"blake3-servil: {compiler:?} cannot assemble armv8.2-a+sha3, which the AArch64 kernels need \
(GNU as 2.30 or later, or Clang/LLVM 7 or later); the `pure` feature builds without assembly"
);
}
fn build_neon_hybrid_assembly() {
// Integer + NEON kernels for one to fifteen chunks (and parents). The
// pair kernels use `xar` from the SHA-3 extension, detected at runtime;
// the scalar and quad kernels run everywhere. Assembling needs an
// assembler that knows armv8.2-a+sha3 (GNU as 2.30+, LLVM 7+).
assert!(is_aarch64());
let mut build = new_build();
build.file("c/blake3_neon_hybrid_aarch64.S");
build.compile("blake3_neon_hybrid_assembly");
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// If CFLAGS is set, make sure LTO is disabled by appending -fno-lto. (We can't do this with
// .flag() later on, because CFLAGS takes precedence.) Any mismatch between the C compiler and
// the Rust linker can cause linker errors in our C intrinsics implementations if LTO is
// enabled. See https://github.com/BLAKE3-team/BLAKE3/issues/550.
if !is_windows_msvc() {
if let Some(mut flags) = env::var_os("CFLAGS") {
flags.push(" -fno-lto");
// SAFETY: This build script is single-threaded.
unsafe {
env::set_var("CFLAGS", flags);
}
}
}
// As of Rust 1.80, unrecognized config names are warnings. Give Cargo all of our config names.
// `shuttle` gates tests/shuttle_*.rs (RUSTFLAGS="--cfg shuttle"); the
// library compiles the same either way.
let all_cfgs =
["blake3_sse41_ffi", "blake3_sse41_rust", "blake3_avx2_ffi", "blake3_avx2_rust", "blake3_avx512_ffi", "blake3_neon", "blake3_sme2", "shuttle"];
for cfg_name in all_cfgs {
// https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script
println!("cargo::rustc-check-cfg=cfg({cfg_name}, values(none()))");
}
// x86-64 (32-bit x86 is unsupported: official BLAKE3 serves it).
if is_x86_64() {
let support = c_compiler_support();
if is_pure() || support == NoCompiler {
build_sse41_avx2_rust_intrinsics();
} else {
// We assume that all C compilers can assemble SSE4.1 and AVX2. We
// don't explicitly check for support.
build_sse41_avx2_assembly();
}
if !(is_pure() || support == NoCompiler || support == NoAVX512) {
build_avx512_assembly();
}
}
// Little-endian AArch64 (32-bit ARM is unsupported: official BLAKE3
// serves it).
if !is_pure() && is_aarch64() && is_little_endian() {
println!("cargo::rustc-cfg=blake3_neon");
assert_assembles_sha3();
build_neon_hybrid_assembly();
// SME2 sits on top of NEON: the SME2 wrapper falls back to NEON for
// inputs that don't fill a group of sixteen. It is built on every
// AArch64 target with NEON enabled and runtime detection (Apple
// platforms and Linux, the same cfg as platform.rs's sme2_reported
// and Cargo.toml's libc dependency) whose C compiler assembles SME2.
// Platform::detect() selects the SME2 kernels when the CPU reports
// SME2 with 512-bit streaming vectors and the NEON hybrids otherwise.
let target_vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap_or_default();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target_vendor == "apple" || target_os == "linux" {
if c_compiler_supports_sme2() {
build_sme2_assembly();
}
}
}
// The `cc` crate doesn't automatically emit rerun-if directives for the
// environment variables it supports, in particular for $CC. We expect to
// do a lot of benchmarking across different compilers, so we explicitly
// add the variables that we're likely to need.
println!("cargo::rerun-if-env-changed=CC");
println!("cargo::rerun-if-env-changed=CFLAGS");
// Ditto for source files, though these shouldn't change as often.
for file in std::fs::read_dir("c")? {
println!("cargo::rerun-if-changed={}", file?.path().to_str().expect("utf-8"));
}
Ok(())
}