]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Pass around BackendConfig
[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 #[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>, backend_config: BackendConfig, module: M, debug_info: bool) -> Self {
146         let unwind_context = UnwindContext::new(
147             tcx,
148             module.isa(),
149             matches!(backend_config.codegen_mode, CodegenMode::Aot),
150         );
151         let debug_context = if debug_info {
152             Some(DebugContext::new(tcx, module.isa()))
153         } else {
154             None
155         };
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(mut self) -> (M, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
169         self.constants_cx.finalize(self.tcx, &mut self.module);
170         (
171             self.module,
172             self.global_asm,
173             self.debug_context,
174             self.unwind_context,
175         )
176     }
177 }
178
179 #[derive(Copy, Clone, Debug)]
180 pub enum CodegenMode {
181     Aot,
182     Jit,
183     JitLazy,
184 }
185
186 impl Default for CodegenMode {
187     fn default() -> Self {
188         CodegenMode::Aot
189     }
190 }
191
192 impl FromStr for CodegenMode {
193     type Err = String;
194
195     fn from_str(s: &str) -> Result<Self, Self::Err> {
196         match s {
197             "aot" => Ok(CodegenMode::Aot),
198             "jit" => Ok(CodegenMode::Jit),
199             "jit-lazy" => Ok(CodegenMode::JitLazy),
200             _ => Err(format!("Unknown codegen mode `{}`", s)),
201         }
202     }
203 }
204
205 #[derive(Copy, Clone, Debug, Default)]
206 pub struct BackendConfig {
207     pub codegen_mode: CodegenMode,
208 }
209
210 impl BackendConfig {
211     fn from_opts(opts: &[String]) -> Result<Self, String> {
212         let mut config = BackendConfig::default();
213         for opt in opts {
214             if let Some((name, value)) = opt.split_once('=') {
215                 match name {
216                     "mode" => config.codegen_mode = value.parse()?,
217                     _ => return Err(format!("Unknown option `{}`", name)),
218                 }
219             } else {
220                 return Err(format!("Invalid option `{}`", opt));
221             }
222         }
223         Ok(config)
224     }
225 }
226
227 pub struct CraneliftCodegenBackend {
228     pub config: Option<BackendConfig>,
229 }
230
231 impl CodegenBackend for CraneliftCodegenBackend {
232     fn init(&self, sess: &Session) {
233         if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
234             sess.warn("LTO is not supported. You may get a linker error.");
235         }
236     }
237
238     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
239         Box::new(crate::metadata::CraneliftMetadataLoader)
240     }
241
242     fn provide(&self, _providers: &mut Providers) {}
243     fn provide_extern(&self, _providers: &mut Providers) {}
244
245     fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
246         vec![]
247     }
248
249     fn codegen_crate<'tcx>(
250         &self,
251         tcx: TyCtxt<'tcx>,
252         metadata: EncodedMetadata,
253         need_metadata_module: bool,
254     ) -> Box<dyn Any> {
255         let config = if let Some(config) = self.config {
256             config
257         } else {
258             BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
259                 .unwrap_or_else(|err| tcx.sess.fatal(&err))
260         };
261         let res = driver::codegen_crate(tcx, metadata, need_metadata_module, config);
262
263         res
264     }
265
266     fn join_codegen(
267         &self,
268         ongoing_codegen: Box<dyn Any>,
269         _sess: &Session,
270     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
271         Ok(*ongoing_codegen
272             .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
273             .unwrap())
274     }
275
276     fn link(
277         &self,
278         sess: &Session,
279         codegen_results: CodegenResults,
280         outputs: &OutputFilenames,
281     ) -> Result<(), ErrorReported> {
282         use rustc_codegen_ssa::back::link::link_binary;
283
284         let target_cpu = crate::target_triple(sess).to_string();
285         link_binary::<crate::archive::ArArchiveBuilder<'_>>(
286             sess,
287             &codegen_results,
288             outputs,
289             &codegen_results.crate_name.as_str(),
290             &target_cpu,
291         );
292
293         Ok(())
294     }
295 }
296
297 fn target_triple(sess: &Session) -> target_lexicon::Triple {
298     sess.target.llvm_target.parse().unwrap()
299 }
300
301 fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
302     use target_lexicon::BinaryFormat;
303
304     let target_triple = crate::target_triple(sess);
305
306     let mut flags_builder = settings::builder();
307     flags_builder.enable("is_pic").unwrap();
308     flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
309     flags_builder
310         .set(
311             "enable_verifier",
312             if cfg!(debug_assertions) {
313                 "true"
314             } else {
315                 "false"
316             },
317         )
318         .unwrap();
319
320     let tls_model = match target_triple.binary_format {
321         BinaryFormat::Elf => "elf_gd",
322         BinaryFormat::Macho => "macho",
323         BinaryFormat::Coff => "coff",
324         _ => "none",
325     };
326     flags_builder.set("tls_model", tls_model).unwrap();
327
328     flags_builder.set("enable_simd", "true").unwrap();
329
330     use rustc_session::config::OptLevel;
331     match sess.opts.optimize {
332         OptLevel::No => {
333             flags_builder.set("opt_level", "none").unwrap();
334         }
335         OptLevel::Less | OptLevel::Default => {}
336         OptLevel::Aggressive => {
337             flags_builder.set("opt_level", "speed_and_size").unwrap();
338         }
339         OptLevel::Size | OptLevel::SizeMin => {
340             sess.warn("Optimizing for size is not supported. Just ignoring the request");
341         }
342     }
343
344     let flags = settings::Flags::new(flags_builder);
345
346     let variant = if cfg!(feature = "oldbe") {
347         cranelift_codegen::isa::BackendVariant::Legacy
348     } else {
349         cranelift_codegen::isa::BackendVariant::MachInst
350     };
351     let mut isa_builder = cranelift_codegen::isa::lookup_variant(target_triple, variant).unwrap();
352     // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
353     // is interpreted as `bsr`.
354     isa_builder.enable("nehalem").unwrap();
355     isa_builder.finish(flags)
356 }
357
358 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
359 #[no_mangle]
360 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
361     Box::new(CraneliftCodegenBackend { config: None })
362 }