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