forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwrite.rs
1842 lines (1660 loc) · 71.4 KB
/
write.rs
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(unused_imports)]
#![allow(unused_variables)]
use crate::llvm::LLVMGetFirstBasicBlock;
use crate::llvm::LLVMBuildCondBr;
use crate::llvm::LLVMBuildICmp;
use crate::llvm::LLVMBuildRetVoid;
use crate::llvm::LLVMRustEraseInstBefore;
use crate::llvm::LLVMRustHasDbgMetadata;
use crate::llvm::LLVMRustHasMetadata;
use crate::llvm::LLVMRustRemoveFncAttr;
use crate::llvm::LLVMMetadataAsValue;
use crate::llvm::LLVMRustGetLastInstruction;
use crate::llvm::LLVMRustDIGetInstMetadata;
use crate::llvm::LLVMRustDIGetInstMetadataOfTy;
use crate::llvm::LLVMRustgetFirstNonPHIOrDbgOrLifetime;
use crate::llvm::LLVMRustGetTerminator;
use crate::llvm::LLVMRustEraseInstFromParent;
use crate::llvm::LLVMRustEraseBBFromParent;
//use crate::llvm::LLVMEraseFromParent;
use crate::back::lto::ThinBuffer;
use crate::back::owned_target_machine::OwnedTargetMachine;
use crate::back::profiling::{
selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
};
use crate::base;
use crate::common;
use crate::errors::{
CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression,
WithLlvmError, WriteBytecode,
};
use crate::llvm::{self, DiagnosticInfo, PassManager};
use crate::llvm::{
enzyme_rust_forward_diff, enzyme_rust_reverse_diff, AttributeKind, BasicBlock, FreeTypeAnalysis,
CreateEnzymeLogic, CreateTypeAnalysis, EnzymeLogicRef, EnzymeTypeAnalysisRef, LLVMAddFunction,
LLVMAppendBasicBlockInContext, LLVMBuildCall2, LLVMBuildExtractValue, LLVMBuildRet,
LLVMCountParams, LLVMCountStructElementTypes, LLVMCreateBuilderInContext,
LLVMCreateStringAttribute, LLVMDeleteFunction, LLVMDisposeBuilder, LLVMDumpModule,
LLVMGetBasicBlockTerminator, LLVMGetFirstFunction, LLVMGetModuleContext,
LLVMGetNextFunction, LLVMGetParams, LLVMGetReturnType, LLVMRustGetFunctionType, LLVMGetStringAttributeAtIndex,
LLVMGlobalGetValueType, LLVMIsEnumAttribute, LLVMIsStringAttribute, LLVMPositionBuilderAtEnd,
LLVMRemoveStringAttributeAtIndex, LLVMReplaceAllUsesWith, LLVMRustAddEnumAttributeAtIndex,
LLVMRustAddFunctionAttributes, LLVMRustGetEnumAttributeAtIndex,
LLVMRustRemoveEnumAttributeAtIndex, LLVMSetValueName2, LLVMVerifyFunction,
LLVMVoidTypeInContext, Value,
};
use crate::llvm_util;
use crate::type_::Type;
use crate::typetree::to_enzyme_typetree;
use crate::DiffTypeTree;
use crate::LlvmCodegenBackend;
use crate::ModuleLlvm;
use llvm::IntPredicate;
use llvm::LLVMRustDISetInstMetadata;
use llvm::{
LLVMRustLLVMHasZlibCompressionForDebugSymbols, LLVMRustLLVMHasZstdCompressionForDebugSymbols, LLVMGetNextBasicBlock,
};
use rustc_ast::expand::autodiff_attrs::{AutoDiffItem, DiffActivity, DiffMode};
use rustc_ast::expand::typetree::FncTree;
use rustc_codegen_ssa::back::link::ensure_removed;
use rustc_codegen_ssa::back::write::{
BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
TargetMachineFactoryFn,
};
use rustc_codegen_ssa::traits::*;
use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::profiling::SelfProfilerRef;
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_errors::{DiagCtxt, FatalError, Level};
use rustc_fs_util::{link_or_copy, path_to_c_string};
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
use rustc_session::Session;
use rustc_span::symbol::sym;
use rustc_span::InnerSpan;
use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel};
use crate::llvm::diagnostic::OptimizationDiagnosticKind;
use libc::{c_char, c_int, c_uint, c_void, size_t};
use std::ffi::{CStr, CString};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::slice;
use std::str;
use std::sync::Arc;
pub fn llvm_err<'a>(dcx: &rustc_errors::DiagCtxt, err: LlvmError<'a>) -> FatalError {
match llvm::last_error() {
Some(llvm_err) => dcx.emit_almost_fatal(WithLlvmError(err, llvm_err)),
None => dcx.emit_almost_fatal(err),
}
}
pub fn write_output_file<'ll>(
dcx: &rustc_errors::DiagCtxt,
target: &'ll llvm::TargetMachine,
pm: &llvm::PassManager<'ll>,
m: &'ll llvm::Module,
output: &Path,
dwo_output: Option<&Path>,
file_type: llvm::FileType,
self_profiler_ref: &SelfProfilerRef,
) -> Result<(), FatalError> {
debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
unsafe {
let output_c = path_to_c_string(output);
let dwo_output_c;
let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
dwo_output_c = path_to_c_string(dwo_output);
dwo_output_c.as_ptr()
} else {
std::ptr::null()
};
let result = llvm::LLVMRustWriteOutputFile(
target,
pm,
m,
output_c.as_ptr(),
dwo_output_ptr,
file_type,
);
// Record artifact sizes for self-profiling
if result == llvm::LLVMRustResult::Success {
let artifact_kind = match file_type {
llvm::FileType::ObjectFile => "object_file",
llvm::FileType::AssemblyFile => "assembly_file",
};
record_artifact_size(self_profiler_ref, artifact_kind, output);
if let Some(dwo_file) = dwo_output {
record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
}
}
result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
}
}
pub fn create_informational_target_machine(sess: &Session) -> OwnedTargetMachine {
let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
// Can't use query system here quite yet because this function is invoked before the query
// system/tcx is set up.
let features = llvm_util::global_llvm_features(sess, false);
target_machine_factory(sess, config::OptLevel::No, &features)(config)
.unwrap_or_else(|err| llvm_err(sess.dcx(), err).raise())
}
pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
tcx.output_filenames(()).split_dwarf_path(
tcx.sess.split_debuginfo(),
tcx.sess.opts.unstable_opts.split_dwarf_kind,
Some(mod_name),
)
} else {
None
};
let output_obj_file =
Some(tcx.output_filenames(()).temp_path(OutputType::Object, Some(mod_name)));
let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
target_machine_factory(
tcx.sess,
tcx.backend_optimization_level(()),
tcx.global_backend_features(()),
)(config)
.unwrap_or_else(|err| llvm_err(tcx.sess.dcx(), err).raise())
}
pub fn to_llvm_opt_settings(
cfg: config::OptLevel,
) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
use self::config::OptLevel::*;
match cfg {
No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
}
}
fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
use config::OptLevel::*;
match cfg {
No => llvm::PassBuilderOptLevel::O0,
Less => llvm::PassBuilderOptLevel::O1,
Default => llvm::PassBuilderOptLevel::O2,
Aggressive => llvm::PassBuilderOptLevel::O3,
Size => llvm::PassBuilderOptLevel::Os,
SizeMin => llvm::PassBuilderOptLevel::Oz,
}
}
fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
match relocation_model {
RelocModel::Static => llvm::RelocModel::Static,
// LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
RelocModel::Ropi => llvm::RelocModel::ROPI,
RelocModel::Rwpi => llvm::RelocModel::RWPI,
RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
}
}
pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
match code_model {
Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
Some(CodeModel::Small) => llvm::CodeModel::Small,
Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
Some(CodeModel::Medium) => llvm::CodeModel::Medium,
Some(CodeModel::Large) => llvm::CodeModel::Large,
None => llvm::CodeModel::None,
}
}
pub fn target_machine_factory(
sess: &Session,
optlvl: config::OptLevel,
target_features: &[String],
) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
let reloc_model = to_llvm_relocation_model(sess.relocation_model());
let (opt_level, _) = to_llvm_opt_settings(optlvl);
let use_softfp = sess.opts.cg.soft_float;
let ffunction_sections =
sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
let fdata_sections = ffunction_sections;
let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
let code_model = to_llvm_code_model(sess.code_model());
let mut singlethread = sess.target.singlethread;
// On the wasm target once the `atomics` feature is enabled that means that
// we're no longer single-threaded, or otherwise we don't want LLVM to
// lower atomic operations to single-threaded operations.
if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
singlethread = false;
}
let triple = SmallCStr::new(&sess.target.llvm_target);
let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
let features = CString::new(target_features.join(",")).unwrap();
let abi = SmallCStr::new(&sess.target.llvm_abiname);
let trap_unreachable =
sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
let asm_comments = sess.opts.unstable_opts.asm_comments;
let relax_elf_relocations =
sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
let use_init_array =
!sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
let path_mapping = sess.source_map().path_mapping().clone();
let use_emulated_tls = matches!(sess.tls_model(), TlsModel::Emulated);
// copy the exe path, followed by path all into one buffer
// null terminating them so we can use them as null terminated strings
let args_cstr_buff = {
let mut args_cstr_buff: Vec<u8> = Vec::new();
let exe_path = std::env::current_exe().unwrap_or_default();
let exe_path_str = exe_path.into_os_string().into_string().unwrap_or_default();
args_cstr_buff.extend_from_slice(exe_path_str.as_bytes());
args_cstr_buff.push(0);
for arg in sess.expanded_args.iter() {
args_cstr_buff.extend_from_slice(arg.as_bytes());
args_cstr_buff.push(0);
}
args_cstr_buff
};
let debuginfo_compression = sess.opts.debuginfo_compression.to_string();
match sess.opts.debuginfo_compression {
rustc_session::config::DebugInfoCompression::Zlib => {
if !unsafe { LLVMRustLLVMHasZlibCompressionForDebugSymbols() } {
sess.emit_warning(UnknownCompression { algorithm: "zlib" });
}
}
rustc_session::config::DebugInfoCompression::Zstd => {
if !unsafe { LLVMRustLLVMHasZstdCompressionForDebugSymbols() } {
sess.emit_warning(UnknownCompression { algorithm: "zstd" });
}
}
rustc_session::config::DebugInfoCompression::None => {}
};
let debuginfo_compression = SmallCStr::new(&debuginfo_compression);
let should_prefer_remapped_for_split_debuginfo_paths =
sess.should_prefer_remapped_for_split_debuginfo_paths();
Arc::new(move |config: TargetMachineFactoryConfig| {
let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
let path = path.unwrap_or_default();
let path = if should_prefer_remapped_for_split_debuginfo_paths {
path_mapping.map_prefix(path).0
} else {
path.into()
};
CString::new(path.to_str().unwrap()).unwrap()
};
let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
let output_obj_file = path_to_cstring_helper(config.output_obj_file);
OwnedTargetMachine::new(
&triple,
&cpu,
&features,
&abi,
code_model,
reloc_model,
opt_level,
use_softfp,
ffunction_sections,
fdata_sections,
funique_section_names,
trap_unreachable,
singlethread,
asm_comments,
emit_stack_size_section,
relax_elf_relocations,
use_init_array,
&split_dwarf_file,
&output_obj_file,
&debuginfo_compression,
use_emulated_tls,
&args_cstr_buff,
)
})
}
pub(crate) fn save_temp_bitcode(
cgcx: &CodegenContext<LlvmCodegenBackend>,
module: &ModuleCodegen<ModuleLlvm>,
name: &str,
) {
if !cgcx.save_temps {
return;
}
unsafe {
let ext = format!("{name}.bc");
let cgu = Some(&module.name[..]);
let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
let cstr = path_to_c_string(&path);
let llmod = module.module_llvm.llmod();
llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
}
}
/// In what context is a dignostic handler being attached to a codegen unit?
pub enum CodegenDiagnosticsStage {
/// Prelink optimization stage.
Opt,
/// LTO/ThinLTO postlink optimization stage.
LTO,
/// Code generation.
Codegen,
}
pub struct DiagnosticHandlers<'a> {
data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a DiagCtxt),
llcx: &'a llvm::Context,
old_handler: Option<&'a llvm::DiagnosticHandler>,
}
impl<'a> DiagnosticHandlers<'a> {
pub fn new(
cgcx: &'a CodegenContext<LlvmCodegenBackend>,
dcx: &'a DiagCtxt,
llcx: &'a llvm::Context,
module: &ModuleCodegen<ModuleLlvm>,
stage: CodegenDiagnosticsStage,
) -> Self {
let remark_passes_all: bool;
let remark_passes: Vec<CString>;
match &cgcx.remark {
Passes::All => {
remark_passes_all = true;
remark_passes = Vec::new();
}
Passes::Some(passes) => {
remark_passes_all = false;
remark_passes =
passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
}
};
let remark_passes: Vec<*const c_char> =
remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
let remark_file = cgcx
.remark_dir
.as_ref()
// Use the .opt.yaml file suffix, which is supported by LLVM's opt-viewer.
.map(|dir| {
let stage_suffix = match stage {
CodegenDiagnosticsStage::Codegen => "codegen",
CodegenDiagnosticsStage::Opt => "opt",
CodegenDiagnosticsStage::LTO => "lto",
};
dir.join(format!("{}.{stage_suffix}.opt.yaml", module.name))
})
.and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
let pgo_available = cgcx.opts.cg.profile_use.is_some();
let data = Box::into_raw(Box::new((cgcx, dcx)));
unsafe {
let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
llvm::LLVMRustContextConfigureDiagnosticHandler(
llcx,
diagnostic_handler,
data.cast(),
remark_passes_all,
remark_passes.as_ptr(),
remark_passes.len(),
// The `as_ref()` is important here, otherwise the `CString` will be dropped
// too soon!
remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
pgo_available,
);
DiagnosticHandlers { data, llcx, old_handler }
}
}
}
impl<'a> Drop for DiagnosticHandlers<'a> {
fn drop(&mut self) {
unsafe {
llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
drop(Box::from_raw(self.data));
}
}
}
fn report_inline_asm(
cgcx: &CodegenContext<LlvmCodegenBackend>,
msg: String,
level: llvm::DiagnosticLevel,
mut cookie: c_uint,
source: Option<(String, Vec<InnerSpan>)>,
) {
// In LTO build we may get srcloc values from other crates which are invalid
// since they use a different source map. To be safe we just suppress these
// in LTO builds.
if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
cookie = 0;
}
let level = match level {
llvm::DiagnosticLevel::Error => Level::Error { lint: false },
llvm::DiagnosticLevel::Warning => Level::Warning(None),
llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
};
cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
}
unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
if user.is_null() {
return;
}
let (cgcx, dcx) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &DiagCtxt));
match llvm::diagnostic::Diagnostic::unpack(info) {
llvm::diagnostic::InlineAsm(inline) => {
report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
}
llvm::diagnostic::Optimization(opt) => {
dcx.emit_note(FromLlvmOptimizationDiag {
filename: &opt.filename,
line: opt.line,
column: opt.column,
pass_name: &opt.pass_name,
kind: match opt.kind {
OptimizationDiagnosticKind::OptimizationRemark => "success",
OptimizationDiagnosticKind::OptimizationMissed
| OptimizationDiagnosticKind::OptimizationFailure => "missed",
OptimizationDiagnosticKind::OptimizationAnalysis
| OptimizationDiagnosticKind::OptimizationAnalysisFPCommute
| OptimizationDiagnosticKind::OptimizationAnalysisAliasing => "analysis",
OptimizationDiagnosticKind::OptimizationRemarkOther => "other",
},
message: &opt.message,
});
}
llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
let message = llvm::build_string(|s| {
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
})
.expect("non-UTF8 diagnostic");
dcx.emit_warning(FromLlvmDiag { message });
}
llvm::diagnostic::Unsupported(diagnostic_ref) => {
let message = llvm::build_string(|s| {
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
})
.expect("non-UTF8 diagnostic");
dcx.emit_err(FromLlvmDiag { message });
}
llvm::diagnostic::UnknownDiagnostic(..) => {}
}
}
fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
match config.pgo_gen {
SwitchWithOptPath::Enabled(ref opt_dir_path) => {
let path = if let Some(dir_path) = opt_dir_path {
dir_path.join("default_%m.profraw")
} else {
PathBuf::from("default_%m.profraw")
};
Some(CString::new(format!("{}", path.display())).unwrap())
}
SwitchWithOptPath::Disabled => None,
}
}
fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
config
.pgo_use
.as_ref()
.map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
}
fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
config
.pgo_sample_use
.as_ref()
.map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
}
fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap())
}
pub(crate) unsafe fn llvm_optimize(
cgcx: &CodegenContext<LlvmCodegenBackend>,
dcx: &DiagCtxt,
module: &ModuleCodegen<ModuleLlvm>,
config: &ModuleConfig,
opt_level: config::OptLevel,
opt_stage: llvm::OptStage,
first_run: bool,
noop: bool,
) -> Result<(), FatalError> {
if noop {
return Ok(());
}
// Enzyme:
// We want to simplify / optimize functions before AD.
// However, benchmarks show that optimizations increasing the code size
// tend to reduce AD performance. Therefore activate them first, then differentiate the code
// and finally re-optimize the module, now with all optimizations available.
// RIP compile time.
let unroll_loops;
let vectorize_slp;
let vectorize_loop;
if first_run {
unroll_loops = false;
vectorize_slp = false;
vectorize_loop = false;
} else {
unroll_loops =
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
vectorize_slp = config.vectorize_slp;
vectorize_loop = config.vectorize_loop;
dbg!("Enzyme: Running with unroll_loops: {}, vectorize_slp: {}, vectorize_loop: {}", unroll_loops, vectorize_slp, vectorize_loop);
}
let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
let pgo_gen_path = get_pgo_gen_path(config);
let pgo_use_path = get_pgo_use_path(config);
let pgo_sample_use_path = get_pgo_sample_use_path(config);
let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
let instr_profile_output_path = get_instr_profile_output_path(config);
// Sanitizer instrumentation is only inserted during the pre-link optimization stage.
let sanitizer_options = if !is_lto {
Some(llvm::SanitizerOptions {
sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
sanitize_kernel_address_recover: config
.sanitizer_recover
.contains(SanitizerSet::KERNELADDRESS),
})
} else {
None
};
let mut llvm_profiler = cgcx
.prof
.llvm_recording_enabled()
.then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
let llvm_selfprofiler =
llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
let llvm_plugins = config.llvm_plugins.join(",");
// FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
// We would have to add upstream support for this first, before we can support
// config.inline_threshold and our more aggressive default thresholds.
let result = llvm::LLVMRustOptimize(
module.module_llvm.llmod(),
&*module.module_llvm.tm,
to_pass_builder_opt_level(opt_level),
opt_stage,
cgcx.opts.cg.linker_plugin_lto.enabled(),
config.no_prepopulate_passes,
config.verify_llvm_ir,
using_thin_buffers,
config.merge_functions,
unroll_loops,
vectorize_slp,
vectorize_loop,
config.emit_lifetime_markers,
sanitizer_options.as_ref(),
pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
config.instrument_coverage,
instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
config.instrument_gcov,
pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
config.debug_info_for_profiling,
llvm_selfprofiler,
selfprofile_before_pass_callback,
selfprofile_after_pass_callback,
extra_passes.as_ptr().cast(),
extra_passes.len(),
llvm_plugins.as_ptr().cast(),
llvm_plugins.len(),
);
result.into_result().map_err(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
}
fn get_params(fnc: &Value) -> Vec<&Value> {
unsafe {
let param_num = LLVMCountParams(fnc) as usize;
let mut fnc_args: Vec<&Value> = vec![];
fnc_args.reserve(param_num);
LLVMGetParams(fnc, fnc_args.as_mut_ptr());
fnc_args.set_len(param_num);
fnc_args
}
}
// DESIGN:
// Today we have our placeholder function, and our Enzyme generated one.
// We create a wrapper function and delete the placeholder body.
// We then call the wrapper from the placeholder.
//
// Soon, we won't delete the whole placeholder, but just the loop,
// and the two inline asm sections. For now we can still call the wrapper.
// In the future we call our Enzyme generated function directly and unwrap the return
// struct in our original placeholder.
//
// define internal double @_ZN2ad3bar17ha38374e821680177E(ptr align 8 %0, ptr align 8 %1, double %2) unnamed_addr #17 !dbg !13678 {
// %4 = alloca double, align 8
// %5 = alloca ptr, align 8
// %6 = alloca ptr, align 8
// %7 = alloca { ptr, double }, align 8
// store ptr %0, ptr %6, align 8
// call void @llvm.dbg.declare(metadata ptr %6, metadata !13682, metadata !DIExpression()), !dbg !13685
// store ptr %1, ptr %5, align 8
// call void @llvm.dbg.declare(metadata ptr %5, metadata !13683, metadata !DIExpression()), !dbg !13685
// store double %2, ptr %4, align 8
// call void @llvm.dbg.declare(metadata ptr %4, metadata !13684, metadata !DIExpression()), !dbg !13686
// call void asm sideeffect alignstack inteldialect "NOP", "~{dirflag},~{fpsr},~{flags},~{memory}"(), !dbg !13687, !srcloc !23
// %8 = call double @_ZN2ad3foo17h95b548a9411653b2E(ptr align 8 %0), !dbg !13687
// %9 = call double @_ZN4core4hint9black_box17h7bd67a41b0f12bdfE(double %8), !dbg !13687
// store ptr %1, ptr %7, align 8, !dbg !13687
// %10 = getelementptr inbounds { ptr, double }, ptr %7, i32 0, i32 1, !dbg !13687
// store double %2, ptr %10, align 8, !dbg !13687
// %11 = getelementptr inbounds { ptr, double }, ptr %7, i32 0, i32 0, !dbg !13687
// %12 = load ptr, ptr %11, align 8, !dbg !13687, !nonnull !23, !align !1047, !noundef !23
// %13 = getelementptr inbounds { ptr, double }, ptr %7, i32 0, i32 1, !dbg !13687
// %14 = load double, ptr %13, align 8, !dbg !13687, !noundef !23
// %15 = call { ptr, double } @_ZN4core4hint9black_box17h669f3b22afdcb487E(ptr align 8 %12, double %14), !dbg !13687
// %16 = extractvalue { ptr, double } %15, 0, !dbg !13687
// %17 = extractvalue { ptr, double } %15, 1, !dbg !13687
// br label %18, !dbg !13687
//
//18: ; preds = %18, %3
// br label %18, !dbg !13687
unsafe fn create_call<'a>(tgt: &'a Value, src: &'a Value, rev_mode: bool,
llmod: &'a llvm::Module, llcx: &llvm::Context, size_positions: &[usize]) {
// first, remove all calls from fnc
let bb = LLVMGetFirstBasicBlock(tgt);
let br = LLVMRustGetTerminator(bb);
LLVMRustEraseInstFromParent(br);
// now add a call to inner.
// append call to src at end of bb.
let f_ty = LLVMRustGetFunctionType(src);
let inner_param_num = LLVMCountParams(src);
let outer_param_num = LLVMCountParams(tgt);
let outer_args: Vec<&Value> = get_params(tgt);
let inner_args: Vec<&Value> = get_params(src);
let mut call_args: Vec<&Value> = vec![];
let mut safety_vals = vec![];
let builder = LLVMCreateBuilderInContext(llcx);
let last_inst = LLVMRustGetLastInstruction(bb).unwrap();
LLVMPositionBuilderAtEnd(builder, bb);
let safety_run_checks;
if std::env::var("ENZYME_NO_SAFETY_CHECKS").is_ok() {
safety_run_checks = false;
} else {
safety_run_checks = true;
}
if inner_param_num == outer_param_num {
call_args = outer_args;
} else {
trace!("Different number of args, adjusting");
let mut outer_pos: usize = 0;
let mut inner_pos: usize = 0;
// copy over if they are identical.
// If not, skip the outer arg (and assert it's int).
while outer_pos < outer_param_num as usize {
let inner_arg = inner_args[inner_pos];
let outer_arg = outer_args[outer_pos];
let inner_arg_ty = llvm::LLVMTypeOf(inner_arg);
let outer_arg_ty = llvm::LLVMTypeOf(outer_arg);
if inner_arg_ty == outer_arg_ty {
call_args.push(outer_arg);
inner_pos += 1;
outer_pos += 1;
} else {
// out: (ptr, <>int1, ptr, int2)
// inner: (ptr, <>ptr, int)
// goal: (ptr, ptr, int1), skipping int2
// we are here: <>
assert!(llvm::LLVMRustGetTypeKind(outer_arg_ty) == llvm::TypeKind::Integer);
assert!(llvm::LLVMRustGetTypeKind(inner_arg_ty) == llvm::TypeKind::Pointer);
let next_outer_arg = outer_args[outer_pos + 1];
let next_inner_arg = inner_args[inner_pos + 1];
let next_outer_arg_ty = llvm::LLVMTypeOf(next_outer_arg);
let next_inner_arg_ty = llvm::LLVMTypeOf(next_inner_arg);
assert!(llvm::LLVMRustGetTypeKind(next_outer_arg_ty) == llvm::TypeKind::Pointer);
assert!(llvm::LLVMRustGetTypeKind(next_inner_arg_ty) == llvm::TypeKind::Integer);
let next2_outer_arg = outer_args[outer_pos + 2];
let next2_outer_arg_ty = llvm::LLVMTypeOf(next2_outer_arg);
assert!(llvm::LLVMRustGetTypeKind(next2_outer_arg_ty) == llvm::TypeKind::Integer);
call_args.push(next_outer_arg);
call_args.push(outer_arg);
outer_pos += 3;
inner_pos += 2;
if safety_run_checks {
// Now we assert if int1 <= int2
let res = LLVMBuildICmp(
builder,
IntPredicate::IntULE as u32,
outer_arg,
next2_outer_arg,
"safety_check".as_ptr() as *const c_char);
safety_vals.push(res);
}
}
}
}
if inner_param_num as usize != call_args.len() {
panic!("Args len shouldn't differ. Please report this. {} : {}", inner_param_num, call_args.len());
}
// Now add the safety checks.
if !safety_vals.is_empty() {
dbg!("Adding safety checks");
assert!(safety_run_checks);
// first we create one bb per check and two more for the fail and success case.
let fail_bb = LLVMAppendBasicBlockInContext(llcx, tgt, "ad_safety_fail".as_ptr() as *const c_char);
let success_bb = LLVMAppendBasicBlockInContext(llcx, tgt, "ad_safety_success".as_ptr() as *const c_char);
for i in 1..safety_vals.len() {
// 'or' all safety checks together
// Doing some binary tree style or'ing here would be more efficient,
// but I assume LLVM will opt it anyway
let prev = safety_vals[i - 1];
let curr = safety_vals[i];
let res = llvm::LLVMBuildOr(builder, prev, curr, "safety_check".as_ptr() as *const c_char);
safety_vals[i] = res;
}
LLVMBuildCondBr(builder, safety_vals.last().unwrap(), success_bb, fail_bb);
LLVMPositionBuilderAtEnd(builder, fail_bb);
let panic_name: CString = get_panic_name(llmod);
let mut arg_vec = vec![add_panic_msg_to_global(llmod, llcx)];
let fnc1 = llvm::LLVMGetNamedFunction(llmod, panic_name.as_ptr() as *const c_char);
assert!(fnc1.is_some());
let fnc1 = fnc1.unwrap();
let ty = LLVMRustGetFunctionType(fnc1);
let call = LLVMBuildCall2(builder, ty, fnc1, arg_vec.as_mut_ptr(), arg_vec.len(), panic_name.as_ptr() as *const c_char);
llvm::LLVMSetTailCall(call, 1);
llvm::LLVMBuildUnreachable(builder);
LLVMPositionBuilderAtEnd(builder, success_bb);
}
let inner_fnc_name = llvm::get_value_name(src);
let c_inner_fnc_name = CString::new(inner_fnc_name).unwrap();
let mut struct_ret = LLVMBuildCall2(
builder,
f_ty,
src,
call_args.as_mut_ptr(),
call_args.len(),
c_inner_fnc_name.as_ptr(),
);
// Add dummy dbg info to our newly generated call, if we have any.
let inst = LLVMRustgetFirstNonPHIOrDbgOrLifetime(bb).unwrap();
let md_ty = llvm::LLVMGetMDKindIDInContext(
llcx,
"dbg".as_ptr() as *const c_char,
"dbg".len() as c_uint,
);
if LLVMRustHasMetadata(last_inst, md_ty) {
let md = LLVMRustDIGetInstMetadata(last_inst);
let md_val = LLVMMetadataAsValue(llcx, md);
let md2 = llvm::LLVMSetMetadata(struct_ret, md_ty, md_val);
} else {
trace!("No dbg info");
}
// Now clean up placeholder code.
LLVMRustEraseInstBefore(bb, last_inst);
let f_return_type = LLVMGetReturnType(LLVMGlobalGetValueType(src));
let f_is_struct = llvm::LLVMRustIsStructType(f_return_type);
let void_type = LLVMVoidTypeInContext(llcx);
// Now unwrap the struct_ret if it's actually a struct
if f_is_struct {
let num_elem_in_ret_struct = LLVMCountStructElementTypes(f_return_type);
if num_elem_in_ret_struct == 1 {
let inner_grad_name = "foo".to_string();
let c_inner_grad_name = CString::new(inner_grad_name).unwrap();
struct_ret = LLVMBuildExtractValue(builder, struct_ret, 0, c_inner_grad_name.as_ptr());
}
}
if f_return_type != void_type {
let _ret = LLVMBuildRet(builder, struct_ret);
} else {
let _ret = LLVMBuildRetVoid(builder);
}
LLVMDisposeBuilder(builder);
let _fnc_ok =
LLVMVerifyFunction(tgt, llvm::LLVMVerifierFailureAction::LLVMAbortProcessAction);
}
unsafe fn get_panic_name(llmod: &llvm::Module) -> CString {
// The names are mangled and their ending changes based on a hash, so just take whichever.
let mut f = LLVMGetFirstFunction(llmod);
loop {
if let Some(lf) = f {
f = LLVMGetNextFunction(lf);
let fnc_name = llvm::get_value_name(lf);
let fnc_name: String = String::from_utf8(fnc_name.to_vec()).unwrap();
if fnc_name.starts_with("_ZN4core9panicking14panic_explicit") {
return CString::new(fnc_name).unwrap();
} else if fnc_name.starts_with("_RN4core9panicking14panic_explicit") {
return CString::new(fnc_name).unwrap();
}
} else {
break;
}
}
panic!("Could not find panic function");
}
unsafe fn add_panic_msg_to_global<'a>(llmod: &'a llvm::Module, llcx: &'a llvm::Context) -> &'a llvm::Value {
use llvm::*;
// Convert the message to a CString
let msg = "autodiff safety check failed!";
let cmsg = CString::new(msg).unwrap();
let msg_global_name = "ad_safety_msg".to_string();
let cmsg_global_name = CString::new(msg_global_name).unwrap();
// Get the length of the message
let msg_len = msg.len();
// Create the array type
let i8_array_type = LLVMRustArrayType(LLVMInt8TypeInContext(llcx), msg_len as u64);
// Create the string constant
let string_const_val = LLVMConstStringInContext(llcx, cmsg.as_ptr() as *const i8, msg_len as u32, 0);
// Create the array initializer
let mut array_elems: Vec<_> = Vec::with_capacity(msg_len);
for i in 0..msg_len {
let char_value = LLVMConstInt(LLVMInt8TypeInContext(llcx), cmsg.as_bytes()[i] as u64, 0);
array_elems.push(char_value);
}
let array_initializer = LLVMConstArray(LLVMInt8TypeInContext(llcx), array_elems.as_mut_ptr(), msg_len as u32);
// Create the struct type
let global_type = LLVMStructTypeInContext(llcx, [i8_array_type].as_mut_ptr(), 1, 0);
// Create the struct initializer
let struct_initializer = LLVMConstStructInContext(llcx, [array_initializer].as_mut_ptr(), 1, 0);
// Add the global variable to the module
let global_var = LLVMAddGlobal(llmod, global_type, cmsg_global_name.as_ptr() as *const i8);
LLVMRustSetLinkage(global_var, Linkage::PrivateLinkage);
LLVMSetInitializer(global_var, struct_initializer);
global_var
}
// As unsafe as it can be.
#[allow(unused_variables)]
#[allow(unused)]
pub(crate) unsafe fn enzyme_ad(
llmod: &llvm::Module,
llcx: &llvm::Context,
diag_handler: &DiagCtxt,
item: AutoDiffItem,
logic_ref: EnzymeLogicRef,
) -> Result<(), FatalError> {
let autodiff_mode = item.attrs.mode;
let rust_name = item.source;
let rust_name2 = &item.target;
let args_activity = item.attrs.input_activity.clone();
let ret_activity: DiffActivity = item.attrs.ret_activity;
// get target and source function
let name = CString::new(rust_name.to_owned()).unwrap();
let name2 = CString::new(rust_name2.clone()).unwrap();
let src_fnc_opt = llvm::LLVMGetNamedFunction(llmod, name.as_c_str().as_ptr());
let src_fnc = match src_fnc_opt {
Some(x) => x,
None => {
return Err(llvm_err(
diag_handler,
LlvmError::PrepareAutoDiff {
src: rust_name.to_owned(),
target: rust_name2.to_owned(),
error: "could not find src function".to_owned(),
},
));
}
};
let target_fnc_opt = llvm::LLVMGetNamedFunction(llmod, name2.as_ptr());
let target_fnc = match target_fnc_opt {
Some(x) => x,
None => {
return Err(llvm_err(
diag_handler,
LlvmError::PrepareAutoDiff {
src: rust_name.to_owned(),
target: rust_name2.to_owned(),
error: "could not find target function".to_owned(),
},
));
}
};
let src_num_args = llvm::LLVMCountParams(src_fnc);
let target_num_args = llvm::LLVMCountParams(target_fnc);
// A really simple check
assert!(src_num_args <= target_num_args);
// create enzyme typetrees
let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(&*llmod) };
let llvm_data_layout =