]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/lib.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / compiler / rustc_codegen_cranelift / src / lib.rs
1 #![feature(rustc_private)]
2 // Note: please avoid adding other feature gates where possible
3 #![warn(rust_2018_idioms)]
4 #![warn(unused_lifetimes)]
5 #![warn(unreachable_pub)]
6
7 extern crate jobserver;
8 #[macro_use]
9 extern crate rustc_middle;
10 extern crate rustc_ast;
11 extern crate rustc_codegen_ssa;
12 extern crate rustc_data_structures;
13 extern crate rustc_errors;
14 extern crate rustc_fs_util;
15 extern crate rustc_hir;
16 extern crate rustc_incremental;
17 extern crate rustc_index;
18 extern crate rustc_interface;
19 extern crate rustc_metadata;
20 extern crate rustc_session;
21 extern crate rustc_span;
22 extern crate rustc_target;
23
24 // This prevents duplicating functions and statics that are already part of the host rustc process.
25 #[allow(unused_extern_crates)]
26 extern crate rustc_driver;
27
28 use std::any::Any;
29 use std::cell::{Cell, RefCell};
30 use std::sync::Arc;
31
32 use rustc_codegen_ssa::traits::CodegenBackend;
33 use rustc_codegen_ssa::CodegenResults;
34 use rustc_data_structures::profiling::SelfProfilerRef;
35 use rustc_errors::ErrorGuaranteed;
36 use rustc_metadata::EncodedMetadata;
37 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
38 use rustc_session::config::OutputFilenames;
39 use rustc_session::Session;
40 use rustc_span::Symbol;
41
42 use cranelift_codegen::isa::TargetIsa;
43 use cranelift_codegen::settings::{self, Configurable};
44
45 pub use crate::config::*;
46 use crate::prelude::*;
47
48 mod abi;
49 mod allocator;
50 mod analyze;
51 mod archive;
52 mod base;
53 mod cast;
54 mod codegen_i128;
55 mod common;
56 mod compiler_builtins;
57 mod concurrency_limiter;
58 mod config;
59 mod constant;
60 // FIXME revert back to the external crate with Cranelift 0.93
61 mod cranelift_native;
62 mod debuginfo;
63 mod discriminant;
64 mod driver;
65 mod global_asm;
66 mod inline_asm;
67 mod intrinsics;
68 mod linkage;
69 mod main_shim;
70 mod num;
71 mod optimize;
72 mod pointer;
73 mod pretty_clif;
74 mod toolchain;
75 mod trap;
76 mod unsize;
77 mod value_and_place;
78 mod vtable;
79
80 mod prelude {
81     pub(crate) use rustc_span::{FileNameDisplayPreference, Span};
82
83     pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
84     pub(crate) use rustc_middle::bug;
85     pub(crate) use rustc_middle::mir::{self, *};
86     pub(crate) use rustc_middle::ty::layout::{self, LayoutOf, TyAndLayout};
87     pub(crate) use rustc_middle::ty::{
88         self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
89         TypeFoldable, TypeVisitable, UintTy,
90     };
91     pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx};
92
93     pub(crate) use rustc_data_structures::fx::FxHashMap;
94
95     pub(crate) use rustc_index::vec::Idx;
96
97     pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
98     pub(crate) use cranelift_codegen::ir::function::Function;
99     pub(crate) use cranelift_codegen::ir::types;
100     pub(crate) use cranelift_codegen::ir::{
101         AbiParam, Block, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, StackSlot,
102         StackSlotData, StackSlotKind, TrapCode, Type, Value,
103     };
104     pub(crate) use cranelift_codegen::isa::{self, CallConv};
105     pub(crate) use cranelift_codegen::Context;
106     pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
107     pub(crate) use cranelift_module::{self, DataContext, FuncId, Linkage, Module};
108
109     pub(crate) use crate::abi::*;
110     pub(crate) use crate::base::{codegen_operand, codegen_place};
111     pub(crate) use crate::cast::*;
112     pub(crate) use crate::common::*;
113     pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
114     pub(crate) use crate::pointer::Pointer;
115     pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
116 }
117
118 struct PrintOnPanic<F: Fn() -> String>(F);
119 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
120     fn drop(&mut self) {
121         if ::std::thread::panicking() {
122             println!("{}", (self.0)());
123         }
124     }
125 }
126
127 /// The codegen context holds any information shared between the codegen of individual functions
128 /// inside a single codegen unit with the exception of the Cranelift [`Module`](cranelift_module::Module).
129 struct CodegenCx {
130     profiler: SelfProfilerRef,
131     output_filenames: Arc<OutputFilenames>,
132     should_write_ir: bool,
133     global_asm: String,
134     inline_asm_index: Cell<usize>,
135     debug_context: Option<DebugContext>,
136     unwind_context: UnwindContext,
137     cgu_name: Symbol,
138 }
139
140 impl CodegenCx {
141     fn new(
142         tcx: TyCtxt<'_>,
143         backend_config: BackendConfig,
144         isa: &dyn TargetIsa,
145         debug_info: bool,
146         cgu_name: Symbol,
147     ) -> Self {
148         assert_eq!(pointer_ty(tcx), isa.pointer_type());
149
150         let unwind_context =
151             UnwindContext::new(isa, matches!(backend_config.codegen_mode, CodegenMode::Aot));
152         let debug_context = if debug_info && !tcx.sess.target.options.is_like_windows {
153             Some(DebugContext::new(tcx, isa))
154         } else {
155             None
156         };
157         CodegenCx {
158             profiler: tcx.prof.clone(),
159             output_filenames: tcx.output_filenames(()).clone(),
160             should_write_ir: crate::pretty_clif::should_write_ir(tcx),
161             global_asm: String::new(),
162             inline_asm_index: Cell::new(0),
163             debug_context,
164             unwind_context,
165             cgu_name,
166         }
167     }
168 }
169
170 pub struct CraneliftCodegenBackend {
171     pub config: RefCell<Option<BackendConfig>>,
172 }
173
174 impl CodegenBackend for CraneliftCodegenBackend {
175     fn init(&self, sess: &Session) {
176         use rustc_session::config::Lto;
177         match sess.lto() {
178             Lto::No | Lto::ThinLocal => {}
179             Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
180         }
181
182         let mut config = self.config.borrow_mut();
183         if config.is_none() {
184             let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
185                 .unwrap_or_else(|err| sess.fatal(&err));
186             *config = Some(new_config);
187         }
188     }
189
190     fn target_features(&self, _sess: &Session, _allow_unstable: bool) -> Vec<rustc_span::Symbol> {
191         vec![]
192     }
193
194     fn print_version(&self) {
195         println!("Cranelift version: {}", cranelift_codegen::VERSION);
196     }
197
198     fn codegen_crate(
199         &self,
200         tcx: TyCtxt<'_>,
201         metadata: EncodedMetadata,
202         need_metadata_module: bool,
203     ) -> Box<dyn Any> {
204         tcx.sess.abort_if_errors();
205         let config = self.config.borrow().clone().unwrap();
206         match config.codegen_mode {
207             CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
208             CodegenMode::Jit | CodegenMode::JitLazy => {
209                 #[cfg(feature = "jit")]
210                 driver::jit::run_jit(tcx, config);
211
212                 #[cfg(not(feature = "jit"))]
213                 tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift");
214             }
215         }
216     }
217
218     fn join_codegen(
219         &self,
220         ongoing_codegen: Box<dyn Any>,
221         sess: &Session,
222         _outputs: &OutputFilenames,
223     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
224         Ok(ongoing_codegen
225             .downcast::<driver::aot::OngoingCodegen>()
226             .unwrap()
227             .join(sess, self.config.borrow().as_ref().unwrap()))
228     }
229
230     fn link(
231         &self,
232         sess: &Session,
233         codegen_results: CodegenResults,
234         outputs: &OutputFilenames,
235     ) -> Result<(), ErrorGuaranteed> {
236         use rustc_codegen_ssa::back::link::link_binary;
237
238         link_binary(sess, &crate::archive::ArArchiveBuilderBuilder, &codegen_results, outputs)
239     }
240 }
241
242 fn target_triple(sess: &Session) -> target_lexicon::Triple {
243     match sess.target.llvm_target.parse() {
244         Ok(triple) => triple,
245         Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
246     }
247 }
248
249 fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
250     use target_lexicon::BinaryFormat;
251
252     let target_triple = crate::target_triple(sess);
253
254     let mut flags_builder = settings::builder();
255     flags_builder.enable("is_pic").unwrap();
256     let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
257     flags_builder.set("enable_verifier", enable_verifier).unwrap();
258     flags_builder.set("regalloc_checker", enable_verifier).unwrap();
259
260     let tls_model = match target_triple.binary_format {
261         BinaryFormat::Elf => "elf_gd",
262         BinaryFormat::Macho => "macho",
263         BinaryFormat::Coff => "coff",
264         _ => "none",
265     };
266     flags_builder.set("tls_model", tls_model).unwrap();
267
268     flags_builder.set("enable_simd", "true").unwrap();
269
270     flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();
271
272     use rustc_session::config::OptLevel;
273     match sess.opts.optimize {
274         OptLevel::No => {
275             flags_builder.set("opt_level", "none").unwrap();
276         }
277         OptLevel::Less | OptLevel::Default => {}
278         OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
279             flags_builder.set("opt_level", "speed_and_size").unwrap();
280         }
281     }
282
283     if let target_lexicon::Architecture::Aarch64(_) | target_lexicon::Architecture::X86_64 =
284         target_triple.architecture
285     {
286         // Windows depends on stack probes to grow the committed part of the stack
287         flags_builder.enable("enable_probestack").unwrap();
288         flags_builder.set("probestack_strategy", "inline").unwrap();
289     } else {
290         // __cranelift_probestack is not provided and inline stack probes are only supported on AArch64 and x86_64
291         flags_builder.set("enable_probestack", "false").unwrap();
292     }
293
294     let flags = settings::Flags::new(flags_builder);
295
296     let isa_builder = match sess.opts.cg.target_cpu.as_deref() {
297         Some("native") => {
298             let builder = cranelift_native::builder_with_options(true).unwrap();
299             builder
300         }
301         Some(value) => {
302             let mut builder =
303                 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
304                     sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
305                 });
306             if let Err(_) = builder.enable(value) {
307                 sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
308             }
309             builder
310         }
311         None => {
312             let mut builder =
313                 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
314                     sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
315                 });
316             if target_triple.architecture == target_lexicon::Architecture::X86_64 {
317                 // Don't use "haswell" as the default, as it implies `has_lzcnt`.
318                 // macOS CI is still at Ivy Bridge EP, so `lzcnt` is interpreted as `bsr`.
319                 builder.enable("nehalem").unwrap();
320             }
321             builder
322         }
323     };
324
325     match isa_builder.finish(flags) {
326         Ok(target_isa) => target_isa,
327         Err(err) => sess.fatal(&format!("failed to build TargetIsa: {}", err)),
328     }
329 }
330
331 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
332 #[no_mangle]
333 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
334     Box::new(CraneliftCodegenBackend { config: RefCell::new(None) })
335 }