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