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