rust/src/lib.rs

469 lines
15 KiB
Rust
Raw Normal View History

#![feature(rustc_private, never_type, decl_macro)]
#![allow(intra_doc_link_resolution_failure)]
2018-06-17 11:05:11 -05:00
2018-11-24 05:47:53 -06:00
extern crate log;
2018-06-17 11:05:11 -05:00
extern crate rustc;
2018-11-05 11:29:15 -06:00
extern crate rustc_allocator;
extern crate rustc_codegen_ssa;
2018-06-17 11:05:11 -05:00
extern crate rustc_codegen_utils;
2018-11-24 05:47:53 -06:00
extern crate rustc_data_structures;
extern crate rustc_fs_util;
2018-06-17 11:05:11 -05:00
extern crate rustc_incremental;
extern crate rustc_mir;
extern crate rustc_target;
2018-11-24 05:47:53 -06:00
extern crate syntax;
2018-06-17 11:05:11 -05:00
2018-07-23 04:17:39 -05:00
use std::any::Any;
2019-02-21 08:06:09 -06:00
use std::ffi::CString;
2018-11-10 08:12:00 -06:00
use std::fs::File;
use std::os::raw::{c_char, c_int};
2019-02-21 08:06:09 -06:00
use std::sync::mpsc;
2018-06-17 11:05:11 -05:00
use rustc::dep_graph::DepGraph;
use rustc::middle::cstore::MetadataLoader;
2019-02-21 08:06:09 -06:00
use rustc::mir::mono::{Linkage as RLinkage, Visibility};
use rustc::session::config::{DebugInfo, OutputFilenames, OutputType};
use rustc::ty::query::Providers;
use rustc::util::common::ErrorReported;
2018-11-24 05:47:53 -06:00
use rustc_codegen_ssa::back::linker::LinkerInfo;
use rustc_codegen_ssa::CrateInfo;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
2019-03-11 14:36:29 -05:00
use rustc_mir::monomorphize::partitioning::CodegenUnitExt;
2018-06-17 11:05:11 -05:00
2018-07-23 04:17:39 -05:00
use cranelift::codegen::settings;
use cranelift_faerie::*;
2018-06-17 11:05:11 -05:00
2018-11-10 08:12:00 -06:00
use crate::constant::ConstantCx;
use crate::prelude::*;
2018-07-19 12:33:42 -05:00
mod abi;
2018-11-05 11:29:15 -06:00
mod allocator;
2018-08-09 03:46:56 -05:00
mod analyze;
2018-11-09 11:38:30 -06:00
mod archive;
2018-06-17 11:05:11 -05:00
mod base;
2018-06-22 12:18:53 -05:00
mod common;
mod constant;
2019-01-17 11:07:27 -06:00
mod debuginfo;
mod intrinsics;
2019-03-11 14:36:29 -05:00
mod linkage;
mod main_shim;
2018-08-15 05:07:08 -05:00
mod metadata;
mod pretty_clif;
2018-11-16 10:35:47 -06:00
mod trap;
2018-11-16 12:53:27 -06:00
mod unimpl;
mod unsize;
2018-09-08 11:00:06 -05:00
mod vtable;
2018-06-17 11:05:11 -05:00
mod prelude {
2018-06-30 09:37:02 -05:00
pub use std::any::Any;
2018-07-16 08:13:37 -05:00
pub use std::collections::{HashMap, HashSet};
2018-06-22 12:18:53 -05:00
2018-11-10 05:49:25 -06:00
pub use syntax::ast::{FloatTy, IntTy, UintTy};
2019-02-21 08:06:09 -06:00
pub use syntax::source_map::{Pos, Span, DUMMY_SP};
2018-11-10 05:49:25 -06:00
2018-11-17 11:23:52 -06:00
pub use rustc::bug;
2018-11-10 05:49:25 -06:00
pub use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
pub use rustc::mir::{self, interpret::AllocId, *};
2018-11-10 08:12:00 -06:00
pub use rustc::session::{
config::{CrateType, Lto},
Session,
};
pub use rustc::ty::layout::{self, Abi, LayoutOf, Scalar, Size, TyLayout, VariantIdx};
pub use rustc::ty::{
self, FnSig, Instance, InstanceDef, ParamEnv, PolyFnSig, Ty, TyCtxt,
TypeAndMut, TypeFoldable,
2018-06-17 11:05:11 -05:00
};
pub use rustc_data_structures::{
2018-08-17 06:01:56 -05:00
fx::{FxHashMap, FxHashSet},
indexed_vec::Idx,
sync::Lrc,
};
pub use rustc_mir::monomorphize::{collector, MonoItem};
2018-06-22 12:18:53 -05:00
2018-11-21 09:01:33 -06:00
pub use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
pub use rustc_codegen_ssa::traits::*;
2019-02-21 08:06:09 -06:00
pub use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleKind};
2018-11-21 09:01:33 -06:00
2018-07-14 04:59:42 -05:00
pub use cranelift::codegen::ir::{
2019-02-21 08:06:09 -06:00
condcodes::IntCC, function::Function, ExternalName, FuncRef, Inst, SourceLoc, StackSlot,
2018-06-22 12:18:53 -05:00
};
2018-11-07 06:32:02 -06:00
pub use cranelift::codegen::isa::CallConv;
2018-07-14 04:59:42 -05:00
pub use cranelift::codegen::Context;
pub use cranelift::prelude::*;
2019-01-17 11:07:27 -06:00
pub use cranelift_module::{
2019-02-21 08:06:09 -06:00
self, Backend, DataContext, DataId, FuncId, FuncOrDataId, Linkage, Module,
2019-01-17 11:07:27 -06:00
};
pub use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
2018-06-22 12:18:53 -05:00
pub use crate::abi::*;
pub use crate::base::{trans_operand, trans_place};
pub use crate::common::*;
2019-01-17 11:07:27 -06:00
pub use crate::debuginfo::{DebugContext, FunctionDebugContext};
2018-11-16 10:35:47 -06:00
pub use crate::trap::*;
2018-11-16 12:53:27 -06:00
pub use crate::unimpl::{unimpl, with_unimpl_span};
2018-12-18 11:28:02 -06:00
pub use crate::{Caches, CodegenCx};
2018-06-17 11:05:11 -05:00
}
2018-09-08 11:00:06 -05:00
pub struct Caches<'tcx> {
2018-08-14 11:52:43 -05:00
pub context: Context,
pub vtables: HashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
2018-06-30 09:37:02 -05:00
}
2018-12-18 11:28:02 -06:00
impl<'tcx> Default for Caches<'tcx> {
fn default() -> Self {
2018-08-26 09:58:52 -05:00
Caches {
context: Context::new(),
2018-09-08 11:00:06 -05:00
vtables: HashMap::new(),
2018-08-26 09:58:52 -05:00
}
}
}
2018-12-18 11:28:02 -06:00
pub struct CodegenCx<'a, 'clif, 'tcx, B: Backend + 'static> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
module: &'clif mut Module<B>,
ccx: ConstantCx,
caches: Caches<'tcx>,
2019-01-17 11:07:27 -06:00
debug_context: Option<&'clif mut DebugContext<'tcx>>,
2018-12-18 11:28:02 -06:00
}
impl<'a, 'clif, 'tcx, B: Backend + 'static> CodegenCx<'a, 'clif, 'tcx, B> {
2019-01-17 11:07:27 -06:00
fn new(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
module: &'clif mut Module<B>,
debug_context: Option<&'clif mut DebugContext<'tcx>>,
) -> Self {
2018-12-18 11:28:02 -06:00
CodegenCx {
tcx,
module,
ccx: ConstantCx::default(),
caches: Caches::default(),
2019-01-17 11:07:27 -06:00
debug_context,
2018-12-18 11:28:02 -06:00
}
}
fn finalize(self) {
self.ccx.finalize(self.tcx, self.module);
}
}
2018-07-23 04:17:39 -05:00
struct CraneliftCodegenBackend;
2018-07-14 04:59:42 -05:00
impl CodegenBackend for CraneliftCodegenBackend {
2018-06-17 11:05:11 -05:00
fn init(&self, sess: &Session) {
for cty in sess.opts.crate_types.iter() {
match *cty {
2018-08-07 09:43:09 -05:00
CrateType::Rlib | CrateType::Dylib | CrateType::Executable => {}
2018-06-17 11:05:11 -05:00
_ => {
sess.warn(&format!(
"Rustc codegen cranelift doesn't support output type {}",
cty
));
}
2018-06-17 11:05:11 -05:00
}
}
match sess.lto() {
Lto::Fat | Lto::Thin | Lto::ThinLocal => {
sess.warn("Rustc codegen cranelift doesn't support lto");
}
2018-11-10 08:12:00 -06:00
Lto::No => {}
}
if sess.opts.cg.rpath {
sess.err("rpath is not yet supported");
}
if sess.opts.debugging_opts.pgo_gen.enabled() {
sess.err("pgo is not supported");
}
2018-06-17 11:05:11 -05:00
}
2018-11-17 11:23:52 -06:00
fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
2018-08-15 05:07:08 -05:00
Box::new(crate::metadata::CraneliftMetadataLoader)
2018-06-17 11:05:11 -05:00
}
fn provide(&self, providers: &mut Providers) {
rustc_codegen_utils::symbol_names::provide(providers);
rustc_codegen_ssa::back::symbol_export::provide(providers);
2018-06-17 11:05:11 -05:00
providers.target_features_whitelist = |_tcx, _cnum| Lrc::new(Default::default());
2018-06-17 11:05:11 -05:00
}
fn provide_extern(&self, providers: &mut Providers) {
rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
2018-06-17 11:05:11 -05:00
}
fn codegen_crate<'a, 'tcx>(
&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
2018-11-17 11:23:52 -06:00
_rx: mpsc::Receiver<Box<dyn Any + Send>>,
) -> Box<dyn Any> {
2018-12-29 05:04:35 -06:00
env_logger::init();
if !tcx.sess.crate_types.get().contains(&CrateType::Executable)
&& std::env::var("SHOULD_RUN").is_ok()
{
tcx.sess
.err("Can't JIT run non executable (SHOULD_RUN env var is set)");
}
2018-06-17 11:05:11 -05:00
tcx.sess.abort_if_errors();
let metadata = tcx.encode_metadata();
2018-06-30 09:37:02 -05:00
2018-11-10 05:49:25 -06:00
let mut log = if cfg!(debug_assertions) {
2018-11-10 08:12:00 -06:00
Some(File::create(concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/log.txt")).unwrap())
2018-11-10 05:49:25 -06:00
} else {
None
};
2018-08-17 05:57:41 -05:00
if std::env::var("SHOULD_RUN").is_ok() {
let mut jit_module: Module<SimpleJITBackend> = Module::new(SimpleJITBuilder::new());
assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type());
2018-06-30 09:37:02 -05:00
2018-08-17 06:21:03 -05:00
let sig = Signature {
params: vec![
AbiParam::new(jit_module.target_config().pointer_type()),
AbiParam::new(jit_module.target_config().pointer_type()),
2018-08-17 06:21:03 -05:00
],
2018-11-07 06:32:02 -06:00
returns: vec![AbiParam::new(
jit_module.target_config().pointer_type(), /*isize*/
)],
2018-08-17 06:21:03 -05:00
call_conv: CallConv::SystemV,
};
let main_func_id = jit_module
.declare_function("main", Linkage::Import, &sig)
.unwrap();
2019-01-17 11:07:27 -06:00
codegen_cgus(tcx, &mut jit_module, &mut None, &mut log);
crate::allocator::codegen(tcx.sess, &mut jit_module);
jit_module.finalize_definitions();
2018-11-10 05:49:25 -06:00
tcx.sess.abort_if_errors();
2018-09-09 07:45:23 -05:00
let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
2018-08-17 06:21:03 -05:00
unsafe { ::std::mem::transmute(finalized_main) };
2019-02-21 08:06:09 -06:00
let args = ::std::env::var("JIT_ARGS").unwrap_or_else(|_| String::new());
let args = args
.split(" ")
.chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
2019-02-21 08:06:09 -06:00
.map(|arg| CString::new(arg).unwrap())
.collect::<Vec<_>>();
let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
// TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
let ret = f(args.len() as c_int, argv.as_ptr());
2018-06-30 09:37:02 -05:00
2018-08-14 11:52:43 -05:00
jit_module.finish();
std::process::exit(ret);
2018-08-17 05:57:41 -05:00
} else {
let new_module = |name: String| {
let module: Module<FaerieBackend> = Module::new(
FaerieBuilder::new(
build_isa(tcx.sess),
name + ".o",
FaerieTrapCollection::Disabled,
FaerieBuilder::default_libcall_names(),
)
.unwrap(),
);
2019-02-21 08:06:09 -06:00
assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
module
};
2019-02-21 08:06:09 -06:00
let emit_module = |name: &str,
kind: ModuleKind,
mut module: Module<FaerieBackend>,
debug: Option<DebugContext>| {
module.finalize_definitions();
2019-01-17 11:07:27 -06:00
let mut artifact = module.finish().artifact;
if let Some(mut debug) = debug {
debug.emit(&mut artifact);
}
let tmp_file = tcx
.output_filenames(LOCAL_CRATE)
.temp_path(OutputType::Object, Some(name));
let obj = artifact.emit().unwrap();
std::fs::write(&tmp_file, obj).unwrap();
CompiledModule {
name: name.to_string(),
kind,
2018-11-09 11:38:30 -06:00
object: Some(tmp_file),
bytecode: None,
bytecode_compressed: None,
}
};
2018-12-13 08:08:11 -06:00
let mut faerie_module = new_module("some_file".to_string());
let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None
2019-02-21 08:06:09 -06:00
// macOS debuginfo doesn't work yet (see #303)
&& !tcx.sess.target.target.options.is_like_osx
{
2019-02-21 08:06:09 -06:00
let debug = DebugContext::new(
tcx,
faerie_module.target_config().pointer_type().bytes() as u8,
);
2019-01-17 11:07:27 -06:00
Some(debug)
} else {
None
};
codegen_cgus(tcx, &mut faerie_module, &mut debug, &mut log);
2018-12-13 08:08:11 -06:00
tcx.sess.abort_if_errors();
let mut allocator_module = new_module("allocator_shim.o".to_string());
2019-02-21 08:06:09 -06:00
let created_alloc_shim = crate::allocator::codegen(tcx.sess, &mut allocator_module);
rustc_incremental::assert_dep_graph(tcx);
rustc_incremental::save_dep_graph(tcx);
rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
return Box::new(CodegenResults {
crate_name: tcx.crate_name(LOCAL_CRATE),
2019-02-21 08:06:09 -06:00
modules: vec![emit_module(
2019-04-21 08:25:39 -05:00
"u",
2019-02-21 08:06:09 -06:00
ModuleKind::Regular,
faerie_module,
debug,
)],
allocator_module: if created_alloc_shim {
2019-02-21 08:06:09 -06:00
Some(emit_module(
2019-04-21 08:25:39 -05:00
"a",
2019-02-21 08:06:09 -06:00
ModuleKind::Allocator,
allocator_module,
None,
))
} else {
None
},
2018-11-19 12:17:25 -06:00
metadata_module: CompiledModule {
2019-04-21 08:25:39 -05:00
name: "m".to_string(),
2018-11-19 12:17:25 -06:00
kind: ModuleKind::Metadata,
object: None,
bytecode: None,
bytecode_compressed: None,
},
crate_hash: tcx.crate_hash(LOCAL_CRATE),
metadata,
windows_subsystem: None, // Windows is not yet supported
linker_info: LinkerInfo::new(tcx),
crate_info: CrateInfo::new(tcx),
2018-08-17 05:57:41 -05:00
});
}
2018-06-17 11:05:11 -05:00
}
fn join_codegen_and_link(
&self,
2018-11-17 11:23:52 -06:00
res: Box<dyn Any>,
2018-06-17 11:05:11 -05:00
sess: &Session,
_dep_graph: &DepGraph,
outputs: &OutputFilenames,
) -> Result<(), ErrorReported> {
use rustc_codegen_ssa::back::link::link_binary;
let codegen_results = *res
2018-11-10 05:49:25 -06:00
.downcast::<CodegenResults>()
2018-11-07 07:04:44 -06:00
.expect("Expected CraneliftCodegenBackend's CodegenResult, found Box<Any>");
2018-07-24 07:10:53 -05:00
let target_cpu = ::target_lexicon::HOST.to_string();
link_binary::<crate::archive::ArArchiveBuilder<'_>>(
sess,
&codegen_results,
outputs,
&codegen_results.crate_name.as_str(),
&target_cpu,
);
2018-06-17 11:05:11 -05:00
Ok(())
}
}
fn build_isa(sess: &Session) -> Box<isa::TargetIsa + 'static> {
use rustc::session::config::OptLevel;
let mut flags_builder = settings::builder();
flags_builder.enable("is_pic").unwrap();
2018-12-15 10:16:56 -06:00
flags_builder.set("probestack_enabled", "false").unwrap(); // ___cranelift_probestack is not provided
2019-02-21 08:06:09 -06:00
flags_builder.set("enable_verifier", if cfg!(debug_assertions) {
"true"
} else {
"false"
}).unwrap();
// FIXME enable again when https://github.com/CraneStation/cranelift/issues/664 is fixed
/*match sess.opts.optimize {
OptLevel::No => {
flags_builder.set("opt_level", "fastest").unwrap();
}
OptLevel::Less | OptLevel::Default => {}
OptLevel::Aggressive => {
flags_builder.set("opt_level", "best").unwrap();
}
OptLevel::Size | OptLevel::SizeMin => {
sess.warn("Optimizing for size is not supported. Just ignoring the request");
}
}*/
let flags = settings::Flags::new(flags_builder);
cranelift::codegen::isa::lookup(sess.target.target.llvm_target.parse().unwrap())
.unwrap()
.finish(flags)
}
fn codegen_cgus<'a, 'tcx: 'a>(
2018-08-17 06:01:56 -05:00
tcx: TyCtxt<'a, 'tcx, 'tcx>,
module: &mut Module<impl Backend + 'static>,
2019-01-17 11:07:27 -06:00
debug: &mut Option<DebugContext<'tcx>>,
2018-11-10 05:49:25 -06:00
log: &mut Option<File>,
2018-08-17 06:01:56 -05:00
) {
let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
2018-11-07 06:32:02 -06:00
let mono_items = cgus
.iter()
2019-03-11 14:36:29 -05:00
.map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
2018-11-07 06:32:02 -06:00
.flatten()
.collect::<FxHashMap<_, (_, _)>>();
2019-01-17 11:07:27 -06:00
codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items);
crate::main_shim::maybe_create_entry_wrapper(tcx, module);
}
fn codegen_mono_items<'a, 'tcx: 'a>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
module: &mut Module<impl Backend + 'static>,
2019-01-17 11:07:27 -06:00
debug_context: Option<&mut DebugContext<'tcx>>,
log: &mut Option<File>,
mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>,
) {
2019-01-17 11:07:27 -06:00
let mut cx = CodegenCx::new(tcx, module, debug_context);
time("codegen mono items", move || {
2019-03-11 14:36:29 -05:00
for (mono_item, (linkage, visibility)) in mono_items {
unimpl::try_unimpl(tcx, log, || {
2019-03-11 14:36:29 -05:00
let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
base::trans_mono_item(&mut cx, mono_item, linkage);
});
}
2018-08-17 06:21:03 -05:00
2018-12-18 11:28:02 -06:00
cx.finalize();
});
}
2018-08-17 05:57:41 -05:00
fn time<R>(name: &str, f: impl FnOnce() -> R) -> R {
println!("[{}] start", name);
let before = ::std::time::Instant::now();
let res = f();
2018-08-17 05:57:41 -05:00
let after = ::std::time::Instant::now();
println!("[{}] end time: {:?}", name, after - before);
res
2018-08-17 05:57:41 -05:00
}
2018-07-14 04:59:42 -05:00
/// This is the entrypoint for a hot plugged rustc_codegen_cranelift
2018-06-17 11:05:11 -05:00
#[no_mangle]
2018-11-17 11:23:52 -06:00
pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
2018-07-23 04:17:39 -05:00
Box::new(CraneliftCodegenBackend)
2018-06-18 11:39:07 -05:00
}