]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Sync from rust 47aeac648ed56095688c1c20972c9b72bd0da7ce
[rust.git] / src / lib.rs
1 #![feature(rustc_private, decl_macro)]
2 #![cfg_attr(feature = "jit", feature(never_type, vec_into_raw_parts, once_cell))]
3 #![warn(rust_2018_idioms)]
4 #![warn(unused_lifetimes)]
5 #![warn(unreachable_pub)]
6
7 extern crate snap;
8 #[macro_use]
9 extern crate rustc_middle;
10 extern crate rustc_ast;
11 extern crate rustc_codegen_ssa;
12 extern crate rustc_data_structures;
13 extern crate rustc_errors;
14 extern crate rustc_fs_util;
15 extern crate rustc_hir;
16 extern crate rustc_incremental;
17 extern crate rustc_index;
18 extern crate rustc_interface;
19 extern crate rustc_metadata;
20 extern crate rustc_session;
21 extern crate rustc_span;
22 extern crate rustc_target;
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_codegen_ssa::traits::CodegenBackend;
31 use rustc_codegen_ssa::CodegenResults;
32 use rustc_errors::ErrorReported;
33 use rustc_metadata::EncodedMetadata;
34 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
35 use rustc_session::config::OutputFilenames;
36 use rustc_session::Session;
37
38 use cranelift_codegen::isa::TargetIsa;
39 use cranelift_codegen::settings::{self, Configurable};
40
41 pub use crate::config::*;
42 use crate::prelude::*;
43
44 mod abi;
45 mod allocator;
46 mod analyze;
47 mod archive;
48 mod base;
49 mod cast;
50 mod codegen_i128;
51 mod common;
52 mod compiler_builtins;
53 mod config;
54 mod constant;
55 mod debuginfo;
56 mod discriminant;
57 mod driver;
58 mod inline_asm;
59 mod intrinsics;
60 mod linkage;
61 mod main_shim;
62 mod metadata;
63 mod num;
64 mod optimize;
65 mod pointer;
66 mod pretty_clif;
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 rustc_span::{FileNameDisplayPreference, Span};
75
76     pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
77     pub(crate) use rustc_middle::bug;
78     pub(crate) use rustc_middle::mir::{self, *};
79     pub(crate) use rustc_middle::ty::layout::{self, LayoutOf, TyAndLayout};
80     pub(crate) use rustc_middle::ty::{
81         self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
82         TypeFoldable, UintTy,
83     };
84     pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx};
85
86     pub(crate) use rustc_data_structures::fx::FxHashMap;
87
88     pub(crate) use rustc_index::vec::Idx;
89
90     pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
91     pub(crate) use cranelift_codegen::ir::function::Function;
92     pub(crate) use cranelift_codegen::ir::types;
93     pub(crate) use cranelift_codegen::ir::{
94         AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
95         StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
96     };
97     pub(crate) use cranelift_codegen::isa::{self, CallConv};
98     pub(crate) use cranelift_codegen::Context;
99     pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
100     pub(crate) use cranelift_module::{self, DataContext, FuncId, Linkage, Module};
101
102     pub(crate) use crate::abi::*;
103     pub(crate) use crate::base::{codegen_operand, codegen_place};
104     pub(crate) use crate::cast::*;
105     pub(crate) use crate::common::*;
106     pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
107     pub(crate) use crate::pointer::Pointer;
108     pub(crate) use crate::trap::*;
109     pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
110 }
111
112 struct PrintOnPanic<F: Fn() -> String>(F);
113 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
114     fn drop(&mut self) {
115         if ::std::thread::panicking() {
116             println!("{}", (self.0)());
117         }
118     }
119 }
120
121 /// The codegen context holds any information shared between the codegen of individual functions
122 /// inside a single codegen unit with the exception of the Cranelift [`Module`](cranelift_module::Module).
123 struct CodegenCx<'tcx> {
124     tcx: TyCtxt<'tcx>,
125     global_asm: String,
126     cached_context: Context,
127     debug_context: Option<DebugContext<'tcx>>,
128     unwind_context: UnwindContext,
129 }
130
131 impl<'tcx> CodegenCx<'tcx> {
132     fn new(
133         tcx: TyCtxt<'tcx>,
134         backend_config: BackendConfig,
135         isa: &dyn TargetIsa,
136         debug_info: bool,
137     ) -> Self {
138         assert_eq!(pointer_ty(tcx), isa.pointer_type());
139
140         let unwind_context =
141             UnwindContext::new(tcx, isa, matches!(backend_config.codegen_mode, CodegenMode::Aot));
142         let debug_context = if debug_info { Some(DebugContext::new(tcx, isa)) } else { None };
143         CodegenCx {
144             tcx,
145             global_asm: String::new(),
146             cached_context: Context::new(),
147             debug_context,
148             unwind_context,
149         }
150     }
151 }
152
153 pub struct CraneliftCodegenBackend {
154     pub config: Option<BackendConfig>,
155 }
156
157 impl CodegenBackend for CraneliftCodegenBackend {
158     fn init(&self, sess: &Session) {
159         use rustc_session::config::Lto;
160         match sess.lto() {
161             Lto::No | Lto::ThinLocal => {}
162             Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
163         }
164     }
165
166     fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
167         vec![]
168     }
169
170     fn print_version(&self) {
171         println!("Cranelift version: {}", cranelift_codegen::VERSION);
172     }
173
174     fn codegen_crate(
175         &self,
176         tcx: TyCtxt<'_>,
177         metadata: EncodedMetadata,
178         need_metadata_module: bool,
179     ) -> Box<dyn Any> {
180         tcx.sess.abort_if_errors();
181         let config = if let Some(config) = self.config.clone() {
182             config
183         } else {
184             if !tcx.sess.unstable_options() && !tcx.sess.opts.cg.llvm_args.is_empty() {
185                 tcx.sess.fatal("`-Z unstable-options` must be passed to allow configuring cg_clif");
186             }
187             BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
188                 .unwrap_or_else(|err| tcx.sess.fatal(&err))
189         };
190         match config.codegen_mode {
191             CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
192             CodegenMode::Jit | CodegenMode::JitLazy => {
193                 #[cfg(feature = "jit")]
194                 let _: ! = driver::jit::run_jit(tcx, config);
195
196                 #[cfg(not(feature = "jit"))]
197                 tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift");
198             }
199         }
200     }
201
202     fn join_codegen(
203         &self,
204         ongoing_codegen: Box<dyn Any>,
205         _sess: &Session,
206     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
207         Ok(*ongoing_codegen
208             .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
209             .unwrap())
210     }
211
212     fn link(
213         &self,
214         sess: &Session,
215         codegen_results: CodegenResults,
216         outputs: &OutputFilenames,
217     ) -> Result<(), ErrorReported> {
218         use rustc_codegen_ssa::back::link::link_binary;
219
220         link_binary::<crate::archive::ArArchiveBuilder<'_>>(sess, &codegen_results, outputs)
221     }
222 }
223
224 fn target_triple(sess: &Session) -> target_lexicon::Triple {
225     match sess.target.llvm_target.parse() {
226         Ok(triple) => triple,
227         Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
228     }
229 }
230
231 fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
232     use target_lexicon::BinaryFormat;
233
234     let target_triple = crate::target_triple(sess);
235
236     let mut flags_builder = settings::builder();
237     flags_builder.enable("is_pic").unwrap();
238     flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
239     let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
240     flags_builder.set("enable_verifier", enable_verifier).unwrap();
241
242     let tls_model = match target_triple.binary_format {
243         BinaryFormat::Elf => "elf_gd",
244         BinaryFormat::Macho => "macho",
245         BinaryFormat::Coff => "coff",
246         _ => "none",
247     };
248     flags_builder.set("tls_model", tls_model).unwrap();
249
250     flags_builder.set("enable_simd", "true").unwrap();
251
252     flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();
253
254     flags_builder.set("regalloc", &backend_config.regalloc).unwrap();
255
256     use rustc_session::config::OptLevel;
257     match sess.opts.optimize {
258         OptLevel::No => {
259             flags_builder.set("opt_level", "none").unwrap();
260         }
261         OptLevel::Less | OptLevel::Default => {}
262         OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
263             flags_builder.set("opt_level", "speed_and_size").unwrap();
264         }
265     }
266
267     let flags = settings::Flags::new(flags_builder);
268
269     let isa_builder = match sess.opts.cg.target_cpu.as_deref() {
270         Some("native") => {
271             let builder = cranelift_native::builder_with_options(true).unwrap();
272             builder
273         }
274         Some(value) => {
275             let mut builder =
276                 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
277                     sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
278                 });
279             if let Err(_) = builder.enable(value) {
280                 sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
281             }
282             builder
283         }
284         None => {
285             let mut builder =
286                 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
287                     sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
288                 });
289             if target_triple.architecture == target_lexicon::Architecture::X86_64 {
290                 // Don't use "haswell" as the default, as it implies `has_lzcnt`.
291                 // macOS CI is still at Ivy Bridge EP, so `lzcnt` is interpreted as `bsr`.
292                 builder.enable("nehalem").unwrap();
293             }
294             builder
295         }
296     };
297
298     isa_builder.finish(flags)
299 }
300
301 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
302 #[no_mangle]
303 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
304     Box::new(CraneliftCodegenBackend { config: None })
305 }