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