]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Rustup to rustc 1.48.0-nightly (c59199efc 2020-09-04)
[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 )]
9 #![warn(rust_2018_idioms)]
10 #![warn(unused_lifetimes)]
11
12 #[cfg(feature = "jit")]
13 extern crate libc;
14 #[macro_use]
15 extern crate rustc_middle;
16 extern crate rustc_ast;
17 extern crate rustc_codegen_ssa;
18 extern crate rustc_data_structures;
19 extern crate rustc_errors;
20 extern crate rustc_fs_util;
21 extern crate rustc_hir;
22 extern crate rustc_incremental;
23 extern crate rustc_index;
24 extern crate rustc_mir;
25 extern crate rustc_session;
26 extern crate rustc_span;
27 extern crate rustc_symbol_mangling;
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
36 use rustc_codegen_ssa::traits::CodegenBackend;
37 use rustc_codegen_ssa::CodegenResults;
38 use rustc_errors::ErrorReported;
39 use rustc_middle::dep_graph::{DepGraph, 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 atomic_shim;
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 target_features_whitelist;
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_ast::ast::{FloatTy, IntTy, UintTy};
84     pub(crate) use rustc_span::Span;
85
86     pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
87     pub(crate) use rustc_middle::bug;
88     pub(crate) use rustc_middle::mir::{self, *};
89     pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
90     pub(crate) use rustc_middle::ty::{
91         self, FnSig, Instance, InstanceDef, ParamEnv, Ty, TyCtxt, TypeAndMut, TypeFoldable,
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::{
111         self, Backend, DataContext, DataId, FuncId, Linkage, Module,
112     };
113
114     pub(crate) use crate::abi::*;
115     pub(crate) use crate::base::{trans_operand, trans_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, B: Backend + 'static> {
134     tcx: TyCtxt<'tcx>,
135     module: Module<B>,
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, B: Backend + 'static> CodegenCx<'tcx, B> {
145     fn new(tcx: TyCtxt<'tcx>, module: Module<B>, debug_info: bool) -> Self {
146         let unwind_context = UnwindContext::new(tcx, module.isa());
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(
165         mut self,
166     ) -> (
167         Module<B>,
168         String,
169         Option<DebugContext<'tcx>>,
170         UnwindContext<'tcx>,
171     ) {
172         self.constants_cx.finalize(self.tcx, &mut self.module);
173         (
174             self.module,
175             self.global_asm,
176             self.debug_context,
177             self.unwind_context,
178         )
179     }
180 }
181
182 struct CraneliftCodegenBackend;
183
184 impl CodegenBackend for CraneliftCodegenBackend {
185     fn init(&self, sess: &Session) {
186         if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
187             sess.warn("LTO is not supported. You may get a linker error.");
188         }
189     }
190
191     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
192         Box::new(crate::metadata::CraneliftMetadataLoader)
193     }
194
195     fn provide(&self, providers: &mut Providers) {
196         providers.supported_target_features = |tcx, cnum| {
197             assert_eq!(cnum, LOCAL_CRATE);
198             if tcx.sess.opts.actually_rustdoc {
199                 // rustdoc needs to be able to document functions that use all the features, so
200                 // whitelist them all
201                 target_features_whitelist::all_known_features()
202                     .map(|(a, b)| (a.to_string(), b))
203                     .collect()
204             } else {
205                 target_features_whitelist::supported_target_features(tcx.sess)
206                     .iter()
207                     .map(|&(a, b)| (a.to_string(), b))
208                     .collect()
209             }
210         };
211     }
212     fn provide_extern(&self, _providers: &mut Providers) {}
213
214     fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
215         vec![]
216     }
217
218     fn codegen_crate<'tcx>(
219         &self,
220         tcx: TyCtxt<'tcx>,
221         metadata: EncodedMetadata,
222         need_metadata_module: bool,
223     ) -> Box<dyn Any> {
224         let res = driver::codegen_crate(tcx, metadata, need_metadata_module);
225
226         rustc_symbol_mangling::test::report_symbol_names(tcx);
227
228         res
229     }
230
231     fn join_codegen(
232         &self,
233         ongoing_codegen: Box<dyn Any>,
234         sess: &Session,
235         dep_graph: &DepGraph,
236     ) -> Result<Box<dyn Any>, ErrorReported> {
237         let (codegen_results, work_products) = *ongoing_codegen
238             .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
239             .unwrap();
240
241         sess.time("serialize_work_products", move || {
242             rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
243         });
244
245         Ok(Box::new(codegen_results))
246     }
247
248     fn link(
249         &self,
250         sess: &Session,
251         res: Box<dyn Any>,
252         outputs: &OutputFilenames,
253     ) -> Result<(), ErrorReported> {
254         use rustc_codegen_ssa::back::link::link_binary;
255
256         sess.abort_if_errors();
257
258         let codegen_results = *res
259             .downcast::<CodegenResults>()
260             .expect("Expected CraneliftCodegenBackend's CodegenResult, found Box<Any>");
261
262         let _timer = sess.prof.generic_activity("link_crate");
263
264         sess.time("linking", || {
265             let target_cpu = crate::target_triple(sess).to_string();
266             link_binary::<crate::archive::ArArchiveBuilder<'_>>(
267                 sess,
268                 &codegen_results,
269                 outputs,
270                 &codegen_results.crate_name.as_str(),
271                 &target_cpu,
272             );
273         });
274
275         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
276
277         Ok(())
278     }
279 }
280
281 fn target_triple(sess: &Session) -> target_lexicon::Triple {
282     sess.target.target.llvm_target.parse().unwrap()
283 }
284
285 fn build_isa(sess: &Session, enable_pic: bool) -> Box<dyn isa::TargetIsa + 'static> {
286     use target_lexicon::BinaryFormat;
287
288     let target_triple = crate::target_triple(sess);
289
290     let mut flags_builder = settings::builder();
291     if enable_pic {
292         flags_builder.enable("is_pic").unwrap();
293     } else {
294         flags_builder.set("is_pic", "false").unwrap();
295     }
296     flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
297     flags_builder
298         .set(
299             "enable_verifier",
300             if cfg!(debug_assertions) {
301                 "true"
302             } else {
303                 "false"
304             },
305         )
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     // FIXME(CraneStation/cranelift#732) fix LICM in presence of jump tables
319     /*
320     use rustc_session::config::OptLevel;
321     match sess.opts.optimize {
322         OptLevel::No => {
323             flags_builder.set("opt_level", "none").unwrap();
324         }
325         OptLevel::Less | OptLevel::Default => {}
326         OptLevel::Aggressive => {
327             flags_builder.set("opt_level", "speed_and_size").unwrap();
328         }
329         OptLevel::Size | OptLevel::SizeMin => {
330             sess.warn("Optimizing for size is not supported. Just ignoring the request");
331         }
332     }*/
333
334     let flags = settings::Flags::new(flags_builder);
335
336     let mut isa_builder = cranelift_codegen::isa::lookup(target_triple).unwrap();
337     // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
338     // is interpreted as `bsr`.
339     isa_builder.enable("nehalem").unwrap();
340     isa_builder.finish(flags)
341 }
342
343 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
344 #[no_mangle]
345 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
346     Box::new(CraneliftCodegenBackend)
347 }