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