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