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