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