Skip to content

Commit 689933b

Browse files
committed
upstream rustc_codegen_llvm changes for enzyme/autodiff
1 parent fd19773 commit 689933b

File tree

17 files changed

+610
-28
lines changed

17 files changed

+610
-28
lines changed

compiler/rustc_ast/src/expand/autodiff_attrs.rs

+3-16
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
use std::fmt::{self, Display, Formatter};
77
use std::str::FromStr;
88

9-
use crate::expand::typetree::TypeTree;
109
use crate::expand::{Decodable, Encodable, HashStable_Generic};
1110
use crate::ptr::P;
1211
use crate::{Ty, TyKind};
@@ -79,10 +78,6 @@ pub struct AutoDiffItem {
7978
/// The name of the function being generated
8079
pub target: String,
8180
pub attrs: AutoDiffAttrs,
82-
/// Describe the memory layout of input types
83-
pub inputs: Vec<TypeTree>,
84-
/// Describe the memory layout of the output type
85-
pub output: TypeTree,
8681
}
8782
#[derive(Clone, Eq, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
8883
pub struct AutoDiffAttrs {
@@ -262,22 +257,14 @@ impl AutoDiffAttrs {
262257
!matches!(self.mode, DiffMode::Error | DiffMode::Source)
263258
}
264259

265-
pub fn into_item(
266-
self,
267-
source: String,
268-
target: String,
269-
inputs: Vec<TypeTree>,
270-
output: TypeTree,
271-
) -> AutoDiffItem {
272-
AutoDiffItem { source, target, inputs, output, attrs: self }
260+
pub fn into_item(self, source: String, target: String) -> AutoDiffItem {
261+
AutoDiffItem { source, target, attrs: self }
273262
}
274263
}
275264

276265
impl fmt::Display for AutoDiffItem {
277266
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278267
write!(f, "Differentiating {} -> {}", self.source, self.target)?;
279-
write!(f, " with attributes: {:?}", self.attrs)?;
280-
write!(f, " with inputs: {:?}", self.inputs)?;
281-
write!(f, " with output: {:?}", self.output)
268+
write!(f, " with attributes: {:?}", self.attrs)
282269
}
283270
}

compiler/rustc_codegen_gcc/src/lib.rs

+10
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ use gccjit::{CType, Context, OptimizationLevel};
9393
#[cfg(feature = "master")]
9494
use gccjit::{TargetInfo, Version};
9595
use rustc_ast::expand::allocator::AllocatorKind;
96+
use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
9697
use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
9798
use rustc_codegen_ssa::back::write::{
9899
CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryFn,
@@ -439,6 +440,15 @@ impl WriteBackendMethods for GccCodegenBackend {
439440
) -> Result<ModuleCodegen<Self::Module>, FatalError> {
440441
back::write::link(cgcx, dcx, modules)
441442
}
443+
fn autodiff(
444+
_cgcx: &CodegenContext<Self>,
445+
_tcx: TyCtxt<'_>,
446+
_module: &ModuleCodegen<Self::Module>,
447+
_diff_fncs: Vec<AutoDiffItem>,
448+
_config: &ModuleConfig,
449+
) -> Result<(), FatalError> {
450+
unimplemented!()
451+
}
442452
}
443453

444454
/// This is the entrypoint for a hot plugged rustc_codegen_gccjit

compiler/rustc_codegen_llvm/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
codegen_llvm_autodiff_without_lto = using the autodiff feature requires using fat-lto
2+
13
codegen_llvm_copy_bitcode = failed to copy bitcode to object file: {$err}
24
35
codegen_llvm_dynamic_linking_with_lto =
@@ -47,6 +49,8 @@ codegen_llvm_parse_bitcode_with_llvm_err = failed to parse bitcode for LTO modul
4749
codegen_llvm_parse_target_machine_config =
4850
failed to parse target machine config to target machine: {$error}
4951
52+
codegen_llvm_prepare_autodiff = failed to prepare autodiff: src: {$src}, target: {$target}, {$error}
53+
codegen_llvm_prepare_autodiff_with_llvm_err = failed to prepare autodiff: {$llvm_err}, src: {$src}, target: {$target}, {$error}
5054
codegen_llvm_prepare_thin_lto_context = failed to prepare thin LTO context
5155
codegen_llvm_prepare_thin_lto_context_with_llvm_err = failed to prepare thin LTO context: {$llvm_err}
5256

compiler/rustc_codegen_llvm/src/back/lto.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,14 @@ pub(crate) fn run_pass_manager(
604604
debug!("running the pass manager");
605605
let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
606606
let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
607-
unsafe { write::llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage) }?;
607+
608+
// If this rustc version was build with enzyme/autodiff enabled, and if users applied the
609+
// `#[autodiff]` macro at least once, then we will later call llvm_optimize a second time.
610+
let first_run = true;
611+
debug!("running llvm pm opt pipeline");
612+
unsafe {
613+
write::llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage, first_run)?;
614+
}
608615
debug!("lto done");
609616
Ok(())
610617
}

compiler/rustc_codegen_llvm/src/back/write.rs

+48-6
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ use rustc_session::config::{
2727
};
2828
use rustc_span::{BytePos, InnerSpan, Pos, SpanData, SyntaxContext, sym};
2929
use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel};
30-
use tracing::debug;
30+
use tracing::{debug, trace};
3131

32+
//use crate::back::autodiff::*;
3233
use crate::back::lto::ThinBuffer;
3334
use crate::back::owned_target_machine::OwnedTargetMachine;
3435
use crate::back::profiling::{
@@ -529,9 +530,35 @@ pub(crate) unsafe fn llvm_optimize(
529530
config: &ModuleConfig,
530531
opt_level: config::OptLevel,
531532
opt_stage: llvm::OptStage,
533+
skip_size_increasing_opts: bool,
532534
) -> Result<(), FatalError> {
533-
let unroll_loops =
534-
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
535+
// Enzyme:
536+
// The whole point of compiler based AD is to differentiate optimized IR instead of unoptimized
537+
// source code. However, benchmarks show that optimizations increasing the code size
538+
// tend to reduce AD performance. Therefore deactivate them before AD, then differentiate the code
539+
// and finally re-optimize the module, now with all optimizations available.
540+
// FIXME(ZuseZ4): In a future update we could figure out how to only optimize individual functions getting
541+
// differentiated.
542+
543+
let unroll_loops;
544+
let vectorize_slp;
545+
let vectorize_loop;
546+
547+
// When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
548+
// optimizations until after differentiation. FIXME(ZuseZ4): Before shipping on nightly,
549+
// we should make this more granular, or at least check that the user has at least one autodiff
550+
// call in their code, to justify altering the compilation pipeline.
551+
if skip_size_increasing_opts && cfg!(llvm_enzyme) {
552+
unroll_loops = false;
553+
vectorize_slp = false;
554+
vectorize_loop = false;
555+
} else {
556+
unroll_loops =
557+
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
558+
vectorize_slp = config.vectorize_slp;
559+
vectorize_loop = config.vectorize_loop;
560+
}
561+
trace!(?unroll_loops, ?vectorize_slp, ?vectorize_loop);
535562
let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
536563
let pgo_gen_path = get_pgo_gen_path(config);
537564
let pgo_use_path = get_pgo_use_path(config);
@@ -595,8 +622,8 @@ pub(crate) unsafe fn llvm_optimize(
595622
using_thin_buffers,
596623
config.merge_functions,
597624
unroll_loops,
598-
config.vectorize_slp,
599-
config.vectorize_loop,
625+
vectorize_slp,
626+
vectorize_loop,
600627
config.no_builtins,
601628
config.emit_lifetime_markers,
602629
sanitizer_options.as_ref(),
@@ -640,14 +667,29 @@ pub(crate) unsafe fn optimize(
640667
unsafe { llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr()) };
641668
}
642669

670+
// FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
671+
643672
if let Some(opt_level) = config.opt_level {
644673
let opt_stage = match cgcx.lto {
645674
Lto::Fat => llvm::OptStage::PreLinkFatLTO,
646675
Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
647676
_ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
648677
_ => llvm::OptStage::PreLinkNoLTO,
649678
};
650-
return unsafe { llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage) };
679+
680+
// If we know that we will later run AD, then we disable vectorization and loop unrolling
681+
let skip_size_increasing_opts = cfg!(llvm_enzyme);
682+
return unsafe {
683+
llvm_optimize(
684+
cgcx,
685+
dcx,
686+
module,
687+
config,
688+
opt_level,
689+
opt_stage,
690+
skip_size_increasing_opts,
691+
)
692+
};
651693
}
652694
Ok(())
653695
}

compiler/rustc_codegen_llvm/src/builder.rs

+22
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ use std::borrow::Cow;
22
use std::ops::Deref;
33
use std::{iter, ptr};
44

5+
pub(crate) mod autodiff;
6+
57
use libc::{c_char, c_uint};
68
use rustc_abi as abi;
79
use rustc_abi::{Align, Size, WrappingRange};
@@ -1490,6 +1492,26 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
14901492
}
14911493
}
14921494

1495+
pub(crate) fn call2(
1496+
&mut self,
1497+
llty: &'ll Type,
1498+
llfn: &'ll Value,
1499+
args: &[&'ll Value],
1500+
fn_name: &core::ffi::CStr,
1501+
) -> &'ll Value {
1502+
let call = unsafe {
1503+
llvm::LLVMBuildCall2(
1504+
self.llbuilder,
1505+
llty,
1506+
llfn,
1507+
args.as_ptr(),
1508+
args.len().try_into().unwrap(),
1509+
fn_name.as_ptr(),
1510+
)
1511+
};
1512+
call
1513+
}
1514+
14931515
pub(crate) fn callbr(
14941516
&mut self,
14951517
llty: &'ll Type,

0 commit comments

Comments
 (0)