rust/src/lib.rs

518 lines
17 KiB
Rust
Raw Normal View History

2018-11-07 06:32:02 -06:00
#![feature(
rustc_private,
macro_at_most_once_rep,
never_type,
2018-11-16 12:53:27 -06:00
extern_crate_item_prelude,
decl_macro,
2018-11-07 06:32:02 -06:00
)]
#![allow(intra_doc_link_resolution_failure)]
2018-06-17 11:05:11 -05:00
2018-09-08 11:00:06 -05:00
extern crate byteorder;
2018-06-17 11:05:11 -05:00
extern crate syntax;
2018-06-18 11:39:07 -05:00
#[macro_use]
2018-06-17 11:05:11 -05:00
extern crate rustc;
2018-11-05 11:29:15 -06:00
extern crate rustc_allocator;
2018-06-17 11:05:11 -05:00
extern crate rustc_codegen_utils;
extern crate rustc_incremental;
extern crate rustc_mir;
extern crate rustc_target;
2018-07-24 07:10:53 -05:00
#[macro_use]
2018-06-17 11:05:11 -05:00
extern crate rustc_data_structures;
2018-11-09 11:38:30 -06:00
extern crate rustc_fs_util;
#[macro_use]
extern crate log;
2018-06-17 11:05:11 -05:00
2018-07-24 07:10:53 -05:00
extern crate ar;
2018-08-09 03:46:56 -05:00
#[macro_use]
extern crate bitflags;
2018-07-24 07:10:53 -05:00
extern crate faerie;
//extern crate goblin;
2018-07-14 04:59:42 -05:00
extern crate cranelift;
extern crate cranelift_faerie;
2018-07-14 04:59:42 -05:00
extern crate cranelift_module;
extern crate cranelift_simplejit;
extern crate target_lexicon;
2018-07-23 04:17:39 -05:00
use std::any::Any;
2018-11-10 08:12:00 -06:00
use std::fs::File;
use std::sync::mpsc;
2018-06-17 11:05:11 -05:00
2018-11-10 08:12:00 -06:00
use syntax::symbol::Symbol;
use rustc::dep_graph::DepGraph;
2018-11-09 11:38:30 -06:00
use rustc::middle::cstore::{
self, CrateSource, LibSource, LinkagePreference, MetadataLoader, NativeLibrary,
};
use rustc::middle::lang_items::LangItem;
use rustc::middle::weak_lang_items;
use rustc::session::{
config::{self, OutputFilenames, OutputType},
CompileIncomplete,
};
use rustc::ty::query::Providers;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_codegen_utils::link::out_filename;
2018-11-09 11:38:30 -06:00
use rustc_codegen_utils::linker::LinkerInfo;
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;
mod intrinsics;
2018-11-07 07:04:44 -06:00
mod link;
mod link_copied;
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;
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};
pub use syntax::source_map::DUMMY_SP;
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::{
2018-06-23 11:54:15 -05:00
self, subst::Substs, FnSig, Instance, InstanceDef, ParamEnv, PolyFnSig, Ty, TyCtxt,
TypeAndMut, TypeFoldable,
2018-06-17 11:05:11 -05:00
};
2018-11-09 11:38:30 -06:00
pub use rustc_codegen_utils::{CompiledModule, ModuleKind};
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-07-14 04:59:42 -05:00
pub use cranelift::codegen::ir::{
condcodes::IntCC, function::Function, ExternalName, FuncRef, Inst, 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::*;
2018-09-08 10:24:52 -05:00
pub use cranelift_module::{Backend, DataContext, DataId, FuncId, Linkage, Module};
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::*;
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-11-09 11:38:30 -06:00
pub use crate::{Caches, CodegenResults, CrateInfo};
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>, ty::PolyExistentialTraitRef<'tcx>), DataId>,
2018-06-30 09:37:02 -05:00
}
2018-09-08 11:00:06 -05:00
impl<'tcx> Caches<'tcx> {
2018-08-26 09:58:52 -05:00
fn new() -> Self {
Caches {
context: Context::new(),
2018-09-08 11:00:06 -05:00
vtables: HashMap::new(),
2018-08-26 09:58:52 -05:00
}
}
}
2018-07-23 04:17:39 -05:00
struct CraneliftCodegenBackend;
2018-11-09 11:38:30 -06:00
pub struct CrateInfo {
panic_runtime: Option<CrateNum>,
compiler_builtins: Option<CrateNum>,
profiler_runtime: Option<CrateNum>,
sanitizer_runtime: Option<CrateNum>,
is_no_builtins: FxHashSet<CrateNum>,
native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
crate_name: FxHashMap<CrateNum, String>,
used_libraries: Lrc<Vec<NativeLibrary>>,
link_args: Lrc<Vec<String>>,
used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
used_crates_static: Vec<(CrateNum, LibSource)>,
used_crates_dynamic: Vec<(CrateNum, LibSource)>,
wasm_imports: FxHashMap<String, String>,
lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
}
impl CrateInfo {
pub fn new(tcx: TyCtxt) -> CrateInfo {
let mut info = CrateInfo {
panic_runtime: None,
compiler_builtins: None,
profiler_runtime: None,
sanitizer_runtime: None,
is_no_builtins: Default::default(),
native_libraries: Default::default(),
used_libraries: tcx.native_libraries(LOCAL_CRATE),
link_args: tcx.link_args(LOCAL_CRATE),
crate_name: Default::default(),
used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
used_crate_source: Default::default(),
wasm_imports: Default::default(),
lang_item_to_crate: Default::default(),
missing_lang_items: Default::default(),
};
let lang_items = tcx.lang_items();
let load_wasm_items = tcx
.sess
.crate_types
.borrow()
.iter()
.any(|c| *c != config::CrateType::Rlib)
&& tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
if load_wasm_items {
info.load_wasm_imports(tcx, LOCAL_CRATE);
}
let crates = tcx.crates();
let n_crates = crates.len();
info.native_libraries.reserve(n_crates);
info.crate_name.reserve(n_crates);
info.used_crate_source.reserve(n_crates);
info.missing_lang_items.reserve(n_crates);
for &cnum in crates.iter() {
info.native_libraries
.insert(cnum, tcx.native_libraries(cnum));
info.crate_name
.insert(cnum, tcx.crate_name(cnum).to_string());
info.used_crate_source
.insert(cnum, tcx.used_crate_source(cnum));
if tcx.is_panic_runtime(cnum) {
info.panic_runtime = Some(cnum);
}
if tcx.is_compiler_builtins(cnum) {
info.compiler_builtins = Some(cnum);
}
if tcx.is_profiler_runtime(cnum) {
info.profiler_runtime = Some(cnum);
}
if tcx.is_sanitizer_runtime(cnum) {
info.sanitizer_runtime = Some(cnum);
}
if tcx.is_no_builtins(cnum) {
info.is_no_builtins.insert(cnum);
}
if load_wasm_items {
info.load_wasm_imports(tcx, cnum);
}
let missing = tcx.missing_lang_items(cnum);
for &item in missing.iter() {
if let Ok(id) = lang_items.require(item) {
info.lang_item_to_crate.insert(item, id.krate);
}
}
// No need to look for lang items that are whitelisted and don't
// actually need to exist.
let missing = missing
.iter()
.cloned()
.filter(|&l| !weak_lang_items::whitelisted(tcx, l))
.collect();
info.missing_lang_items.insert(cnum, missing);
}
return info;
}
fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
self.wasm_imports.extend(
tcx.wasm_import_module_map(cnum)
.iter()
.map(|(&id, module)| {
let instance = Instance::mono(tcx, id);
let import_name = tcx.symbol_name(instance);
(import_name.to_string(), module.clone())
}),
);
}
}
2018-11-10 05:49:25 -06:00
pub struct CodegenResults {
2018-11-07 07:04:44 -06:00
artifact: faerie::Artifact,
2018-11-09 11:38:30 -06:00
modules: Vec<CompiledModule>,
allocator_module: Option<CompiledModule>,
2018-07-24 07:10:53 -05:00
metadata: Vec<u8>,
2018-07-23 04:17:39 -05:00
crate_name: Symbol,
2018-11-09 11:38:30 -06:00
crate_info: CrateInfo,
linker_info: LinkerInfo,
2018-07-23 04:17:39 -05:00
}
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.err(&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.is_some() {
sess.err("pgo is not supported");
}
2018-06-17 11:05:11 -05:00
}
fn metadata_loader(&self) -> Box<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_utils::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_utils::symbol_export::provide_extern(providers);
2018-06-17 11:05:11 -05:00
}
fn codegen_crate<'a, 'tcx>(
&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
_rx: mpsc::Receiver<Box<Any + Send>>,
2018-06-17 11:05:11 -05:00
) -> Box<Any> {
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
let mut flags_builder = settings::builder();
flags_builder.enable("is_pic").unwrap();
use rustc::session::config::OptLevel;
match tcx.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 => {
tcx.sess.warn("Optimizing for size is not supported. Just ignoring the request");
}
}
let flags = settings::Flags::new(flags_builder);
2018-11-07 06:32:02 -06:00
let isa =
cranelift::codegen::isa::lookup(tcx.sess.target.target.llvm_target.parse().unwrap())
.unwrap()
.finish(flags);
2018-06-30 09:37:02 -05:00
2018-08-17 05:57:41 -05:00
// TODO: move to the end of this function when compiling libcore doesn't have unimplemented stuff anymore
save_incremental(tcx);
tcx.sess.warn("Saved incremental data");
2018-08-11 06:59:34 -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();
2018-11-10 05:49:25 -06:00
codegen_mono_items(tcx, &mut jit_module, &mut log);
tcx.sess.abort_if_errors();
println!("Compiled everything");
println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
2018-09-09 07:45:23 -05:00
let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
println!("🎉 Finalized everything");
2018-08-17 06:21:03 -05:00
let f: extern "C" fn(isize, *const *const u8) -> isize =
unsafe { ::std::mem::transmute(finalized_main) };
let res = f(0, 0 as *const _);
2018-09-09 07:45:23 -05:00
tcx.sess.warn(&format!("🚀 main returned {}", res));
2018-06-30 09:37:02 -05:00
2018-08-14 11:52:43 -05:00
jit_module.finish();
::std::process::exit(0);
2018-08-17 05:57:41 -05:00
} else {
let mut faerie_module: Module<FaerieBackend> = Module::new(
2018-08-17 06:01:56 -05:00
FaerieBuilder::new(
isa,
"some_file.o".to_string(),
FaerieTrapCollection::Disabled,
FaerieBuilder::default_libcall_names(),
2018-10-10 12:07:13 -05:00
)
.unwrap(),
2018-08-17 06:01:56 -05:00
);
2018-11-07 06:32:02 -06:00
assert_eq!(
pointer_ty(tcx),
faerie_module.target_config().pointer_type()
);
2018-08-17 06:01:56 -05:00
2018-11-10 05:49:25 -06:00
codegen_mono_items(tcx, &mut faerie_module, &mut log);
2018-08-14 05:13:07 -05:00
2018-08-17 05:57:41 -05:00
tcx.sess.abort_if_errors();
2018-11-09 11:38:30 -06:00
let artifact = faerie_module.finish().artifact;
let tmp_file = tcx
.output_filenames(LOCAL_CRATE)
.temp_path(OutputType::Object, None);
let obj = artifact.emit().unwrap();
std::fs::write(&tmp_file, obj).unwrap();
2018-11-10 05:49:25 -06:00
return Box::new(CodegenResults {
2018-11-09 11:38:30 -06:00
artifact,
2018-08-17 05:57:41 -05:00
metadata: metadata.raw_data,
crate_name: tcx.crate_name(LOCAL_CRATE),
2018-11-09 11:38:30 -06:00
crate_info: CrateInfo::new(tcx),
linker_info: LinkerInfo::new(tcx),
modules: vec![CompiledModule {
name: "dummy".to_string(),
kind: ModuleKind::Regular,
object: Some(tmp_file),
bytecode: None,
bytecode_compressed: None,
}],
//modules: vec![],
allocator_module: None,
2018-08-17 05:57:41 -05:00
});
}
2018-06-17 11:05:11 -05:00
}
fn join_codegen_and_link(
&self,
2018-11-07 07:04:44 -06:00
res: Box<Any>,
2018-06-17 11:05:11 -05:00
sess: &Session,
_dep_graph: &DepGraph,
outputs: &OutputFilenames,
) -> Result<(), CompileIncomplete> {
2018-11-07 07:04:44 -06:00
let res = *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
2018-06-17 11:05:11 -05:00
for &crate_type in sess.opts.crate_types.iter() {
let output_name = out_filename(sess, crate_type, &outputs, &res.crate_name.as_str());
2018-08-11 08:05:57 -05:00
match crate_type {
2018-11-07 07:04:44 -06:00
CrateType::Rlib => link::link_rlib(sess, &res, output_name),
2018-11-09 11:38:30 -06:00
CrateType::Executable => link::link_bin(sess, &res, &output_name),
2018-08-11 08:05:57 -05:00
_ => sess.fatal(&format!("Unsupported crate type: {:?}", crate_type)),
2018-06-17 11:05:11 -05:00
}
}
Ok(())
}
}
2018-08-17 06:01:56 -05:00
fn codegen_mono_items<'a, 'tcx: 'a>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
module: &mut Module<impl Backend + 'static>,
2018-11-10 05:49:25 -06:00
log: &mut Option<File>,
2018-08-17 06:01:56 -05:00
) {
2018-08-26 09:58:52 -05:00
let mut caches = Caches::new();
let mut ccx = ConstantCx::default();
2018-08-17 05:57:41 -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()
.map(|cgu| cgu.items().iter())
.flatten()
.collect::<FxHashSet<(_, _)>>();
2018-08-17 05:57:41 -05:00
let before = ::std::time::Instant::now();
2018-08-31 12:50:26 -05:00
println!("[codegen mono items] start");
2018-08-17 05:57:41 -05:00
for (&mono_item, &(_linkage, _vis)) in mono_items {
2018-11-16 12:53:27 -06:00
unimpl::try_unimpl(tcx, log, || {
2018-11-03 09:04:27 -05:00
base::trans_mono_item(tcx, module, &mut caches, &mut ccx, mono_item);
2018-11-16 12:53:27 -06:00
});
2018-08-17 05:57:41 -05:00
}
crate::main_shim::maybe_create_entry_wrapper(tcx, module);
2018-08-17 06:21:03 -05:00
2018-11-07 06:32:02 -06:00
let any_dynamic_crate = tcx
.sess
.dependency_formats
.borrow()
2018-11-05 11:29:15 -06:00
.iter()
.any(|(_, list)| {
use rustc::middle::dependency_format::Linkage;
2018-11-05 11:29:15 -06:00
list.iter().any(|&linkage| linkage == Linkage::Dynamic)
});
if any_dynamic_crate {
} else if let Some(kind) = *tcx.sess.allocator_kind.get() {
2018-11-07 06:31:02 -06:00
allocator::codegen(module, kind);
2018-11-05 11:29:15 -06:00
}
2018-08-26 09:58:52 -05:00
ccx.finalize(tcx, module);
2018-11-10 05:49:25 -06:00
module.finalize_definitions();
2018-08-17 05:57:41 -05:00
let after = ::std::time::Instant::now();
2018-08-31 12:50:26 -05:00
println!("[codegen mono items] end time: {:?}", after - before);
2018-08-17 05:57:41 -05:00
}
fn save_incremental<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
rustc_incremental::assert_dep_graph(tcx);
rustc_incremental::save_dep_graph(tcx);
rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
}
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]
pub fn __rustc_codegen_backend() -> Box<CodegenBackend> {
2018-07-23 04:17:39 -05:00
Box::new(CraneliftCodegenBackend)
2018-06-18 11:39:07 -05:00
}