Skip to content

Commit cca0699

Browse files
committed
enzyme backend
1 parent 730d5d4 commit cca0699

File tree

12 files changed

+178
-0
lines changed

12 files changed

+178
-0
lines changed

.gitmodules

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,7 @@
4747
path = src/tools/rustc-perf
4848
url = https://github.com/rust-lang/rustc-perf.git
4949
shallow = true
50+
[submodule "src/tools/enzyme"]
51+
path = src/tools/enzyme
52+
url = git@github.com:EnzymeAD/Enzyme.git
53+
shallow = true

src/bootstrap/src/core/build_steps/compile.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,10 @@ pub fn rustc_cargo_env(
11691169
cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
11701170
}
11711171

1172+
if builder.config.llvm_enzyme {
1173+
cargo.rustflag("--cfg=llvm_enzyme");
1174+
}
1175+
11721176
// Note that this is disabled if LLVM itself is disabled or we're in a check
11731177
// build. If we are in a check build we still go ahead here presuming we've
11741178
// detected that LLVM is already built and good to go which helps prevent
@@ -1772,6 +1776,29 @@ impl Step for Assemble {
17721776
// use that to bootstrap this compiler forward.
17731777
let mut build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
17741778

1779+
// Build enzyme
1780+
let enzyme_install = if builder.config.llvm_enzyme {
1781+
Some(builder.ensure(llvm::Enzyme { target: build_compiler.host }))
1782+
} else {
1783+
None
1784+
};
1785+
1786+
if let Some(enzyme_install) = enzyme_install {
1787+
let lib_ext = match env::consts::OS {
1788+
"macos" => "dylib",
1789+
"windows" => "dll",
1790+
_ => "so",
1791+
};
1792+
1793+
let src_lib = enzyme_install.join("build/Enzyme/libEnzyme-19").with_extension(lib_ext);
1794+
let libdir = builder.sysroot_libdir(build_compiler, build_compiler.host);
1795+
let target_libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
1796+
let dst_lib = libdir.join("libEnzyme-19").with_extension(lib_ext);
1797+
let target_dst_lib = target_libdir.join("libEnzyme-19").with_extension(lib_ext);
1798+
builder.copy_link(&src_lib, &dst_lib);
1799+
builder.copy_link(&src_lib, &target_dst_lib);
1800+
}
1801+
17751802
// Build the libraries for this compiler to link to (i.e., the libraries
17761803
// it uses at runtime). NOTE: Crates the target compiler compiles don't
17771804
// link to these. (FIXME: Is that correct? It seems to be correct most

src/bootstrap/src/core/build_steps/dist.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,6 +1522,7 @@ impl Step for Extended {
15221522
add_component!("llvm-components" => LlvmTools { target });
15231523
add_component!("clippy" => Clippy { compiler, target });
15241524
add_component!("miri" => Miri { compiler, target });
1525+
add_component!("enzyme" => Enzyme { compiler, target });
15251526
add_component!("analysis" => Analysis { compiler, target });
15261527
add_component!("rustc-codegen-cranelift" => CodegenBackend {
15271528
compiler: builder.compiler(stage, target),
@@ -2400,6 +2401,45 @@ impl Step for BuildManifest {
24002401
}
24012402
}
24022403

2404+
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2405+
pub struct Enzyme {
2406+
pub compiler: Compiler,
2407+
pub target: TargetSelection,
2408+
}
2409+
2410+
impl Step for Enzyme {
2411+
type Output = Option<GeneratedTarball>;
2412+
const DEFAULT: bool = false;
2413+
const ONLY_HOSTS: bool = true;
2414+
2415+
fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2416+
run.alias("enzyme")
2417+
}
2418+
2419+
fn make_run(run: RunConfig<'_>) {
2420+
run.builder.ensure(Enzyme {
2421+
compiler: run.builder.compiler_for(
2422+
run.builder.top_stage,
2423+
run.builder.config.build,
2424+
run.target,
2425+
),
2426+
target: run.target,
2427+
});
2428+
}
2429+
2430+
fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2431+
let compiler = self.compiler;
2432+
let target = self.target;
2433+
let enzyme = builder.ensure(tool::Enzyme { compiler, target });
2434+
let mut tarball = Tarball::new(builder, "enzyme", &target.triple);
2435+
tarball.set_overlay(OverlayKind::Enzyme);
2436+
tarball.is_preview(true);
2437+
tarball.add_file(enzyme, "bin", 0o755);
2438+
tarball.add_legal_and_readme_to("share/doc/enzyme");
2439+
Some(tarball.generate())
2440+
}
2441+
}
2442+
24032443
/// Tarball containing artifacts necessary to reproduce the build of rustc.
24042444
///
24052445
/// Currently this is the PGO profile data.

src/bootstrap/src/core/build_steps/llvm.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,7 @@ impl Step for Llvm {
529529
}
530530
};
531531

532+
// Manuel: TODO: Do we need that for Enzyme too?
532533
// When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
533534
// libLLVM.dylib will be built. However, llvm-config will still look
534535
// for a versioned path like libLLVM-14.dylib. Manually create a symbolic
@@ -849,6 +850,76 @@ fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
849850
.or_else(|| env::var_os(var_base))
850851
}
851852

853+
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
854+
pub struct Enzyme {
855+
pub target: TargetSelection,
856+
}
857+
858+
impl Step for Enzyme {
859+
type Output = PathBuf;
860+
const ONLY_HOSTS: bool = true;
861+
862+
fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
863+
run.path("src/tools/enzyme/enzyme")
864+
}
865+
866+
fn make_run(run: RunConfig<'_>) {
867+
run.builder.ensure(Enzyme { target: run.target });
868+
}
869+
870+
/// Compile Enzyme for `target`.
871+
fn run(self, builder: &Builder<'_>) -> PathBuf {
872+
builder.require_submodule(
873+
"src/tools/enzyme",
874+
Some("The Enzyme sources are required for autodiff."),
875+
);
876+
if builder.config.dry_run() {
877+
let out_dir = builder.enzyme_out(self.target);
878+
return out_dir;
879+
}
880+
let target = self.target;
881+
882+
let LlvmResult { llvm_config, .. } = builder.ensure(Llvm { target: self.target });
883+
884+
let out_dir = builder.enzyme_out(target);
885+
let done_stamp = out_dir.join("enzyme-finished-building");
886+
if done_stamp.exists() {
887+
return out_dir;
888+
}
889+
890+
builder.info(&format!("Building Enzyme for {}", target));
891+
let _time = helpers::timeit(&builder);
892+
t!(fs::create_dir_all(&out_dir));
893+
894+
builder.update_submodule(Path::new("src").join("tools").join("enzyme").to_str().unwrap());
895+
let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
896+
// TODO: Find a nicer way to use Enzyme Debug builds
897+
//cfg.profile("Debug");
898+
//cfg.define("CMAKE_BUILD_TYPE", "Debug");
899+
configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), &[]);
900+
901+
// Re-use the same flags as llvm to control the level of debug information
902+
// generated for lld.
903+
let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
904+
(false, _) => "Debug",
905+
(true, false) => "Release",
906+
(true, true) => "RelWithDebInfo",
907+
};
908+
909+
cfg.out_dir(&out_dir)
910+
.profile(profile)
911+
.env("LLVM_CONFIG_REAL", &llvm_config)
912+
.define("LLVM_ENABLE_ASSERTIONS", "ON")
913+
.define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
914+
.define("LLVM_DIR", builder.llvm_out(target));
915+
916+
cfg.build();
917+
918+
t!(File::create(&done_stamp));
919+
out_dir
920+
}
921+
}
922+
852923
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
853924
pub struct Lld {
854925
pub target: TargetSelection,

src/bootstrap/src/core/build_steps/tool.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ bootstrap_tool!(
325325
Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true, allow_features = "test";
326326
BuildManifest, "src/tools/build-manifest", "build-manifest";
327327
RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
328+
Enzyme, "src/tools/enzyme", "enzyme";
328329
RustInstaller, "src/tools/rust-installer", "rust-installer";
329330
RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
330331
LintDocs, "src/tools/lint-docs", "lint-docs";

src/bootstrap/src/core/builder.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,7 @@ impl<'a> Builder<'a> {
798798
tool::Miri,
799799
tool::CargoMiri,
800800
llvm::Lld,
801+
llvm::Enzyme,
801802
llvm::CrtBeginEnd,
802803
tool::RustdocGUITest,
803804
tool::OptimizedDist,
@@ -1582,6 +1583,12 @@ impl<'a> Builder<'a> {
15821583
rustflags.arg(sysroot_str);
15831584
}
15841585

1586+
// https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/.E2.9C.94.20link.20new.20library.20into.20stage1.2Frustc
1587+
if self.config.llvm_enzyme {
1588+
rustflags.arg("-l");
1589+
rustflags.arg("Enzyme-19");
1590+
}
1591+
15851592
let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
15861593
Some(setting) => {
15871594
// If an explicit setting is given, use that

src/bootstrap/src/core/config/config.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ pub struct Config {
213213
// llvm codegen options
214214
pub llvm_assertions: bool,
215215
pub llvm_tests: bool,
216+
pub llvm_enzyme: bool,
216217
pub llvm_plugins: bool,
217218
pub llvm_optimize: bool,
218219
pub llvm_thin_lto: bool,
@@ -876,6 +877,7 @@ define_config! {
876877
release_debuginfo: Option<bool> = "release-debuginfo",
877878
assertions: Option<bool> = "assertions",
878879
tests: Option<bool> = "tests",
880+
enzyme: Option<bool> = "enzyme",
879881
plugins: Option<bool> = "plugins",
880882
ccache: Option<StringOrBool> = "ccache",
881883
static_libstdcpp: Option<bool> = "static-libstdcpp",
@@ -1561,6 +1563,7 @@ impl Config {
15611563
// we'll infer default values for them later
15621564
let mut llvm_assertions = None;
15631565
let mut llvm_tests = None;
1566+
let mut llvm_enzyme = None;
15641567
let mut llvm_plugins = None;
15651568
let mut debug = None;
15661569
let mut debug_assertions = None;
@@ -1707,6 +1710,8 @@ impl Config {
17071710
config.llvm_tools_enabled = llvm_tools.unwrap_or(true);
17081711
config.rustc_parallel =
17091712
parallel_compiler.unwrap_or(config.channel == "dev" || config.channel == "nightly");
1713+
config.llvm_enzyme =
1714+
llvm_enzyme.unwrap_or(config.channel == "dev" || config.channel == "nightly");
17101715
config.rustc_default_linker = default_linker;
17111716
config.musl_root = musl_root.map(PathBuf::from);
17121717
config.save_toolstates = save_toolstates.map(PathBuf::from);
@@ -1791,6 +1796,7 @@ impl Config {
17911796
release_debuginfo,
17921797
assertions,
17931798
tests,
1799+
enzyme,
17941800
plugins,
17951801
ccache,
17961802
static_libstdcpp,
@@ -1824,6 +1830,7 @@ impl Config {
18241830
set(&mut config.ninja_in_file, ninja);
18251831
llvm_assertions = assertions;
18261832
llvm_tests = tests;
1833+
llvm_enzyme = enzyme;
18271834
llvm_plugins = plugins;
18281835
set(&mut config.llvm_optimize, optimize_toml);
18291836
set(&mut config.llvm_thin_lto, thin_lto);
@@ -2025,6 +2032,7 @@ impl Config {
20252032

20262033
config.llvm_assertions = llvm_assertions.unwrap_or(false);
20272034
config.llvm_tests = llvm_tests.unwrap_or(false);
2035+
config.llvm_enzyme = llvm_enzyme.unwrap_or(false);
20282036
config.llvm_plugins = llvm_plugins.unwrap_or(false);
20292037
config.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true));
20302038

src/bootstrap/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
7575
#[allow(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
7676
const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
7777
(None, "bootstrap", None),
78+
(Some(Mode::Rustc), "llvm_enzyme", None),
79+
(Some(Mode::Codegen), "llvm_enzyme", None),
80+
(Some(Mode::ToolRustc), "llvm_enzyme", None),
7881
(Some(Mode::Rustc), "parallel_compiler", None),
7982
(Some(Mode::ToolRustc), "parallel_compiler", None),
8083
(Some(Mode::ToolRustc), "rust_analyzer", None),
@@ -138,6 +141,7 @@ pub struct Build {
138141
clippy_info: GitInfo,
139142
miri_info: GitInfo,
140143
rustfmt_info: GitInfo,
144+
enzyme_info: GitInfo,
141145
in_tree_llvm_info: GitInfo,
142146
local_rebuild: bool,
143147
fail_fast: bool,
@@ -304,6 +308,7 @@ impl Build {
304308
let clippy_info = GitInfo::new(omit_git_hash, &src.join("src/tools/clippy"));
305309
let miri_info = GitInfo::new(omit_git_hash, &src.join("src/tools/miri"));
306310
let rustfmt_info = GitInfo::new(omit_git_hash, &src.join("src/tools/rustfmt"));
311+
let enzyme_info = GitInfo::new(omit_git_hash, &src.join("src/tools/enzyme"));
307312

308313
// we always try to use git for LLVM builds
309314
let in_tree_llvm_info = GitInfo::new(false, &src.join("src/llvm-project"));
@@ -391,6 +396,7 @@ impl Build {
391396
clippy_info,
392397
miri_info,
393398
rustfmt_info,
399+
enzyme_info,
394400
in_tree_llvm_info,
395401
cc: RefCell::new(HashMap::new()),
396402
cxx: RefCell::new(HashMap::new()),
@@ -849,6 +855,10 @@ impl Build {
849855
}
850856
}
851857

858+
fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
859+
self.out.join(&*target.triple).join("enzyme")
860+
}
861+
852862
fn lld_out(&self, target: TargetSelection) -> PathBuf {
853863
self.out.join(&*target.triple).join("lld")
854864
}

src/bootstrap/src/utils/tarball.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub(crate) enum OverlayKind {
2020
Cargo,
2121
Clippy,
2222
Miri,
23+
Enzyme,
2324
Rustfmt,
2425
Rls,
2526
RustAnalyzer,
@@ -61,6 +62,7 @@ impl OverlayKind {
6162
"src/tools/rust-analyzer/LICENSE-APACHE",
6263
"src/tools/rust-analyzer/LICENSE-MIT",
6364
],
65+
OverlayKind::Enzyme => &["src/tools/enzyme/README.md", "src/tools/enzyme/LICENSE"],
6466
OverlayKind::RustcCodegenCranelift => &[
6567
"compiler/rustc_codegen_cranelift/Readme.md",
6668
"compiler/rustc_codegen_cranelift/LICENSE-APACHE",
@@ -93,6 +95,9 @@ impl OverlayKind {
9395
OverlayKind::RustAnalyzer => builder
9496
.rust_analyzer_info
9597
.version(builder, &builder.release_num("rust-analyzer/crates/rust-analyzer")),
98+
OverlayKind::Enzyme => {
99+
builder.enzyme_info.version(builder, &builder.release_num("enzyme"))
100+
}
96101
OverlayKind::RustcCodegenCranelift => builder.rust_version(),
97102
OverlayKind::LlvmBitcodeLinker => builder.rust_version(),
98103
}

src/tools/build-manifest/src/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,7 @@ impl Builder {
470470
| PkgType::Rls
471471
| PkgType::RustAnalyzer
472472
| PkgType::Rustfmt
473+
| PkgType::Enzyme
473474
| PkgType::LlvmTools
474475
| PkgType::RustAnalysis
475476
| PkgType::JsonDocs

0 commit comments

Comments
 (0)