1 #![feature(rustc_private, decl_macro, never_type, hash_drain_filter, vec_into_raw_parts, once_cell)]
2 #![warn(rust_2018_idioms)]
3 #![warn(unused_lifetimes)]
4 #![warn(unreachable_pub)]
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_mir;
20 extern crate rustc_session;
21 extern crate rustc_span;
22 extern crate rustc_target;
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;
30 use rustc_codegen_ssa::traits::CodegenBackend;
31 use rustc_codegen_ssa::CodegenResults;
32 use rustc_errors::ErrorReported;
33 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
34 use rustc_middle::middle::cstore::EncodedMetadata;
35 use rustc_session::config::OutputFilenames;
36 use rustc_session::Session;
38 use cranelift_codegen::isa::TargetIsa;
39 use cranelift_codegen::settings::{self, Configurable};
41 pub use crate::config::*;
42 use crate::prelude::*;
53 mod compiler_builtins;
75 pub(crate) use std::convert::{TryFrom, TryInto};
77 pub(crate) use rustc_span::Span;
79 pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
80 pub(crate) use rustc_middle::bug;
81 pub(crate) use rustc_middle::mir::{self, *};
82 pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
83 pub(crate) use rustc_middle::ty::{
84 self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
87 pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
89 pub(crate) use rustc_data_structures::fx::FxHashMap;
91 pub(crate) use rustc_index::vec::Idx;
93 pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
94 pub(crate) use cranelift_codegen::ir::function::Function;
95 pub(crate) use cranelift_codegen::ir::types;
96 pub(crate) use cranelift_codegen::ir::{
97 AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
98 StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
100 pub(crate) use cranelift_codegen::isa::{self, CallConv};
101 pub(crate) use cranelift_codegen::Context;
102 pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
103 pub(crate) use cranelift_module::{self, DataContext, FuncId, Linkage, Module};
105 pub(crate) use crate::abi::*;
106 pub(crate) use crate::base::{codegen_operand, codegen_place};
107 pub(crate) use crate::cast::*;
108 pub(crate) use crate::common::*;
109 pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
110 pub(crate) use crate::pointer::Pointer;
111 pub(crate) use crate::trap::*;
112 pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
115 struct PrintOnPanic<F: Fn() -> String>(F);
116 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
118 if ::std::thread::panicking() {
119 println!("{}", (self.0)());
124 /// The codegen context holds any information shared between the codegen of individual functions
125 /// inside a single codegen unit with the exception of the Cranelift [`Module`](cranelift_module::Module).
126 struct CodegenCx<'tcx> {
129 cached_context: Context,
130 debug_context: Option<DebugContext<'tcx>>,
131 unwind_context: UnwindContext,
134 impl<'tcx> CodegenCx<'tcx> {
137 backend_config: BackendConfig,
141 assert_eq!(pointer_ty(tcx), isa.pointer_type());
144 UnwindContext::new(tcx, isa, matches!(backend_config.codegen_mode, CodegenMode::Aot));
145 let debug_context = if debug_info { Some(DebugContext::new(tcx, isa)) } else { None };
148 global_asm: String::new(),
149 cached_context: Context::new(),
156 pub struct CraneliftCodegenBackend {
157 pub config: Option<BackendConfig>,
160 impl CodegenBackend for CraneliftCodegenBackend {
161 fn init(&self, sess: &Session) {
162 use rustc_session::config::Lto;
164 Lto::No | Lto::ThinLocal => {}
165 Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
169 fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
173 fn print_version(&self) {
174 println!("Cranelift version: {}", cranelift_codegen::VERSION);
180 metadata: EncodedMetadata,
181 need_metadata_module: bool,
183 tcx.sess.abort_if_errors();
184 let config = if let Some(config) = self.config.clone() {
187 if !tcx.sess.unstable_options() && !tcx.sess.opts.cg.llvm_args.is_empty() {
188 tcx.sess.fatal("`-Z unstable-options` must be passed to allow configuring cg_clif");
190 BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
191 .unwrap_or_else(|err| tcx.sess.fatal(&err))
193 match config.codegen_mode {
194 CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
195 CodegenMode::Jit | CodegenMode::JitLazy => {
196 #[cfg(feature = "jit")]
197 let _: ! = driver::jit::run_jit(tcx, config);
199 #[cfg(not(feature = "jit"))]
200 tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift");
207 ongoing_codegen: Box<dyn Any>,
209 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
211 .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
218 codegen_results: CodegenResults,
219 outputs: &OutputFilenames,
220 ) -> Result<(), ErrorReported> {
221 use rustc_codegen_ssa::back::link::link_binary;
223 link_binary::<crate::archive::ArArchiveBuilder<'_>>(sess, &codegen_results, outputs)
227 fn target_triple(sess: &Session) -> target_lexicon::Triple {
228 match sess.target.llvm_target.parse() {
229 Ok(triple) => triple,
230 Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
234 fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
235 use target_lexicon::BinaryFormat;
237 let target_triple = crate::target_triple(sess);
239 let mut flags_builder = settings::builder();
240 flags_builder.enable("is_pic").unwrap();
241 flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
242 let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
243 flags_builder.set("enable_verifier", enable_verifier).unwrap();
245 let tls_model = match target_triple.binary_format {
246 BinaryFormat::Elf => "elf_gd",
247 BinaryFormat::Macho => "macho",
248 BinaryFormat::Coff => "coff",
251 flags_builder.set("tls_model", tls_model).unwrap();
253 flags_builder.set("enable_simd", "true").unwrap();
255 flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();
257 flags_builder.set("regalloc", &backend_config.regalloc).unwrap();
259 use rustc_session::config::OptLevel;
260 match sess.opts.optimize {
262 flags_builder.set("opt_level", "none").unwrap();
264 OptLevel::Less | OptLevel::Default => {}
265 OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
266 flags_builder.set("opt_level", "speed_and_size").unwrap();
270 let flags = settings::Flags::new(flags_builder);
272 let variant = cranelift_codegen::isa::BackendVariant::MachInst;
274 let isa_builder = match sess.opts.cg.target_cpu.as_deref() {
276 let builder = cranelift_native::builder_with_options(variant, true).unwrap();
281 cranelift_codegen::isa::lookup_variant(target_triple.clone(), variant)
282 .unwrap_or_else(|err| {
283 sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
285 if let Err(_) = builder.enable(value) {
286 sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
292 cranelift_codegen::isa::lookup_variant(target_triple.clone(), variant)
293 .unwrap_or_else(|err| {
294 sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
296 if target_triple.architecture == target_lexicon::Architecture::X86_64 {
297 // Don't use "haswell" as the default, as it implies `has_lzcnt`.
298 // macOS CI is still at Ivy Bridge EP, so `lzcnt` is interpreted as `bsr`.
299 builder.enable("nehalem").unwrap();
305 isa_builder.finish(flags)
308 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
310 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
311 Box::new(CraneliftCodegenBackend { config: None })