Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ac70882

Browse files
committedNov 4, 2018
Auto merge of #55349 - bjorn3:rustc_mir_collect_and_partition_mono_items, r=oli-obk
Move collect_and_partition_mono_items to rustc_mir Most of the logic of it is inside rustc_mir anyway. Also removes the single function crate rustc_metadata_utils. Based on #55225
2 parents 86b88e6 + 9e479c2 commit ac70882

File tree

20 files changed

+280
-303
lines changed

20 files changed

+280
-303
lines changed
 

‎src/Cargo.lock

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2141,11 +2141,13 @@ dependencies = [
21412141
"flate2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
21422142
"log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
21432143
"rustc 0.0.0",
2144+
"rustc_allocator 0.0.0",
21442145
"rustc_data_structures 0.0.0",
21452146
"rustc_incremental 0.0.0",
2146-
"rustc_metadata_utils 0.0.0",
2147+
"rustc_metadata 0.0.0",
21472148
"rustc_mir 0.0.0",
21482149
"rustc_target 0.0.0",
2150+
"serialize 0.0.0",
21492151
"syntax 0.0.0",
21502152
"syntax_pos 0.0.0",
21512153
]
@@ -2289,23 +2291,13 @@ dependencies = [
22892291
"rustc 0.0.0",
22902292
"rustc_data_structures 0.0.0",
22912293
"rustc_errors 0.0.0",
2292-
"rustc_metadata_utils 0.0.0",
22932294
"rustc_target 0.0.0",
22942295
"serialize 0.0.0",
22952296
"syntax 0.0.0",
22962297
"syntax_ext 0.0.0",
22972298
"syntax_pos 0.0.0",
22982299
]
22992300

2300-
[[package]]
2301-
name = "rustc_metadata_utils"
2302-
version = "0.0.0"
2303-
dependencies = [
2304-
"rustc 0.0.0",
2305-
"syntax 0.0.0",
2306-
"syntax_pos 0.0.0",
2307-
]
2308-
23092301
[[package]]
23102302
name = "rustc_mir"
23112303
version = "0.0.0"

‎src/librustc_codegen_llvm/back/archive.rs

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -52,28 +52,6 @@ enum Addition {
5252
},
5353
}
5454

55-
pub fn find_library(name: &str, search_paths: &[PathBuf], sess: &Session)
56-
-> PathBuf {
57-
// On Windows, static libraries sometimes show up as libfoo.a and other
58-
// times show up as foo.lib
59-
let oslibname = format!("{}{}{}",
60-
sess.target.target.options.staticlib_prefix,
61-
name,
62-
sess.target.target.options.staticlib_suffix);
63-
let unixlibname = format!("lib{}.a", name);
64-
65-
for path in search_paths {
66-
debug!("looking for {} inside {:?}", name, path);
67-
let test = path.join(&oslibname);
68-
if test.exists() { return test }
69-
if oslibname != unixlibname {
70-
let test = path.join(&unixlibname);
71-
if test.exists() { return test }
72-
}
73-
}
74-
sess.fatal(&format!("could not find native static library `{}`, \
75-
perhaps an -L flag is missing?", name));
76-
}
7755

7856
fn is_relevant_child(c: &Child) -> bool {
7957
match c.name() {
@@ -128,7 +106,7 @@ impl<'a> ArchiveBuilder<'a> {
128106
/// Adds all of the contents of a native library to this archive. This will
129107
/// search in the relevant locations for a library named `name`.
130108
pub fn add_native_library(&mut self, name: &str) {
131-
let location = find_library(name, &self.config.lib_search_paths,
109+
let location = ::rustc_codegen_utils::find_library(name, &self.config.lib_search_paths,
132110
self.config.sess);
133111
self.add_archive(&location, |_| false).unwrap_or_else(|e| {
134112
self.config.sess.fatal(&format!("failed to add native library {}: {}",

‎src/librustc_codegen_llvm/back/link.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@ use back::wasm;
1212
use cc::windows_registry;
1313
use super::archive::{ArchiveBuilder, ArchiveConfig};
1414
use super::bytecode::RLIB_BYTECODE_EXTENSION;
15-
use super::linker::Linker;
16-
use super::command::Command;
1715
use super::rpath::RPathConfig;
1816
use super::rpath;
1917
use metadata::METADATA_FILENAME;
@@ -31,6 +29,8 @@ use rustc::hir::def_id::CrateNum;
3129
use tempfile::{Builder as TempFileBuilder, TempDir};
3230
use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor};
3331
use rustc_data_structures::fx::FxHashSet;
32+
use rustc_codegen_utils::linker::Linker;
33+
use rustc_codegen_utils::command::Command;
3434
use context::get_reloc_model;
3535
use llvm;
3636

@@ -701,7 +701,8 @@ fn link_natively(sess: &Session,
701701
}
702702

703703
{
704-
let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor);
704+
let target_cpu = ::llvm_util::target_cpu(sess);
705+
let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor, target_cpu);
705706
link_args(&mut *linker, flavor, sess, crate_type, tmpdir,
706707
out_filename, codegen_results);
707708
cmd = linker.finalize();

‎src/librustc_codegen_llvm/back/lto.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
// except according to those terms.
1010

1111
use back::bytecode::{DecodedBytecode, RLIB_BYTECODE_EXTENSION};
12-
use back::symbol_export;
1312
use back::write::{ModuleConfig, with_llvm_pmb, CodegenContext};
1413
use back::write::{self, DiagnosticHandlers, pre_lto_bitcode_filename};
1514
use errors::{FatalError, Handler};
@@ -24,6 +23,7 @@ use rustc::middle::exported_symbols::SymbolExportLevel;
2423
use rustc::session::config::{self, Lto};
2524
use rustc::util::common::time_ext;
2625
use rustc_data_structures::fx::FxHashMap;
26+
use rustc_codegen_utils::symbol_export;
2727
use time_graph::Timeline;
2828
use {ModuleCodegen, ModuleLlvm, ModuleKind};
2929

‎src/librustc_codegen_llvm/back/write.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@ use attributes;
1212
use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
1313
use back::lto::{self, ModuleBuffer, ThinBuffer, SerializedModule};
1414
use back::link::{self, get_linker, remove};
15-
use back::command::Command;
16-
use back::linker::LinkerInfo;
17-
use back::symbol_export::ExportedSymbols;
1815
use base;
1916
use consts;
2017
use memmap;
@@ -38,6 +35,9 @@ use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passe
3835
use rustc_fs_util::{path2cstr, link_or_copy};
3936
use rustc_data_structures::small_c_str::SmallCStr;
4037
use rustc_data_structures::svh::Svh;
38+
use rustc_codegen_utils::command::Command;
39+
use rustc_codegen_utils::linker::LinkerInfo;
40+
use rustc_codegen_utils::symbol_export::ExportedSymbols;
4141
use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
4242
use errors::emitter::{Emitter};
4343
use syntax::attr;

‎src/librustc_codegen_llvm/base.rs

Lines changed: 4 additions & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ use attributes;
5454
use builder::{Builder, MemFlags};
5555
use callee;
5656
use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
57-
use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
5857
use rustc_mir::monomorphize::item::DefPathBasedNames;
5958
use common::{C_struct_in_context, C_array, val_ty};
6059
use consts;
@@ -64,13 +63,13 @@ use declare;
6463
use meth;
6564
use mir;
6665
use monomorphize::Instance;
67-
use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
66+
use monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
6867
use rustc_codegen_utils::symbol_names_test;
6968
use time_graph;
70-
use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt};
69+
use mono_item::{MonoItem, MonoItemExt};
7170
use type_::Type;
7271
use type_of::LayoutLlvmExt;
73-
use rustc::util::nodemap::{FxHashMap, DefIdSet};
72+
use rustc::util::nodemap::FxHashMap;
7473
use CrateInfo;
7574
use rustc_data_structures::small_c_str::SmallCStr;
7675
use rustc_data_structures::sync::Lrc;
@@ -80,7 +79,6 @@ use std::cmp;
8079
use std::ffi::CString;
8180
use std::i32;
8281
use std::ops::{Deref, DerefMut};
83-
use std::sync::Arc;
8482
use std::sync::mpsc;
8583
use std::time::{Instant, Duration};
8684
use syntax_pos::Span;
@@ -1011,128 +1009,6 @@ fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
10111009
|| rustc_incremental::save_dep_graph(tcx));
10121010
}
10131011

1014-
fn collect_and_partition_mono_items<'a, 'tcx>(
1015-
tcx: TyCtxt<'a, 'tcx, 'tcx>,
1016-
cnum: CrateNum,
1017-
) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
1018-
{
1019-
assert_eq!(cnum, LOCAL_CRATE);
1020-
1021-
let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
1022-
Some(ref s) => {
1023-
let mode_string = s.to_lowercase();
1024-
let mode_string = mode_string.trim();
1025-
if mode_string == "eager" {
1026-
MonoItemCollectionMode::Eager
1027-
} else {
1028-
if mode_string != "lazy" {
1029-
let message = format!("Unknown codegen-item collection mode '{}'. \
1030-
Falling back to 'lazy' mode.",
1031-
mode_string);
1032-
tcx.sess.warn(&message);
1033-
}
1034-
1035-
MonoItemCollectionMode::Lazy
1036-
}
1037-
}
1038-
None => {
1039-
if tcx.sess.opts.cg.link_dead_code {
1040-
MonoItemCollectionMode::Eager
1041-
} else {
1042-
MonoItemCollectionMode::Lazy
1043-
}
1044-
}
1045-
};
1046-
1047-
let (items, inlining_map) =
1048-
time(tcx.sess, "monomorphization collection", || {
1049-
collector::collect_crate_mono_items(tcx, collection_mode)
1050-
});
1051-
1052-
tcx.sess.abort_if_errors();
1053-
1054-
::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
1055-
1056-
let strategy = if tcx.sess.opts.incremental.is_some() {
1057-
PartitioningStrategy::PerModule
1058-
} else {
1059-
PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1060-
};
1061-
1062-
let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
1063-
partitioning::partition(tcx,
1064-
items.iter().cloned(),
1065-
strategy,
1066-
&inlining_map)
1067-
.into_iter()
1068-
.map(Arc::new)
1069-
.collect::<Vec<_>>()
1070-
});
1071-
1072-
let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
1073-
match *mono_item {
1074-
MonoItem::Fn(ref instance) => Some(instance.def_id()),
1075-
MonoItem::Static(def_id) => Some(def_id),
1076-
_ => None,
1077-
}
1078-
}).collect();
1079-
1080-
if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
1081-
let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
1082-
1083-
for cgu in &codegen_units {
1084-
for (&mono_item, &linkage) in cgu.items() {
1085-
item_to_cgus.entry(mono_item)
1086-
.or_default()
1087-
.push((cgu.name().clone(), linkage));
1088-
}
1089-
}
1090-
1091-
let mut item_keys: Vec<_> = items
1092-
.iter()
1093-
.map(|i| {
1094-
let mut output = i.to_string(tcx);
1095-
output.push_str(" @@");
1096-
let mut empty = Vec::new();
1097-
let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1098-
cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1099-
cgus.dedup();
1100-
for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1101-
output.push_str(" ");
1102-
output.push_str(&cgu_name.as_str());
1103-
1104-
let linkage_abbrev = match linkage {
1105-
Linkage::External => "External",
1106-
Linkage::AvailableExternally => "Available",
1107-
Linkage::LinkOnceAny => "OnceAny",
1108-
Linkage::LinkOnceODR => "OnceODR",
1109-
Linkage::WeakAny => "WeakAny",
1110-
Linkage::WeakODR => "WeakODR",
1111-
Linkage::Appending => "Appending",
1112-
Linkage::Internal => "Internal",
1113-
Linkage::Private => "Private",
1114-
Linkage::ExternalWeak => "ExternalWeak",
1115-
Linkage::Common => "Common",
1116-
};
1117-
1118-
output.push_str("[");
1119-
output.push_str(linkage_abbrev);
1120-
output.push_str("]");
1121-
}
1122-
output
1123-
})
1124-
.collect();
1125-
1126-
item_keys.sort();
1127-
1128-
for item in item_keys {
1129-
println!("MONO_ITEM {}", item);
1130-
}
1131-
}
1132-
1133-
(Arc::new(mono_items), Arc::new(codegen_units))
1134-
}
1135-
11361012
impl CrateInfo {
11371013
pub fn new(tcx: TyCtxt) -> CrateInfo {
11381014
let mut info = CrateInfo {
@@ -1222,12 +1098,6 @@ impl CrateInfo {
12221098
}
12231099
}
12241100

1225-
fn is_codegened_item(tcx: TyCtxt, id: DefId) -> bool {
1226-
let (all_mono_items, _) =
1227-
tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1228-
all_mono_items.contains(&id)
1229-
}
1230-
12311101
fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
12321102
cgu_name: InternedString)
12331103
-> Stats {
@@ -1318,24 +1188,7 @@ fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
13181188
}
13191189
}
13201190

1321-
pub fn provide(providers: &mut Providers) {
1322-
providers.collect_and_partition_mono_items =
1323-
collect_and_partition_mono_items;
1324-
1325-
providers.is_codegened_item = is_codegened_item;
1326-
1327-
providers.codegen_unit = |tcx, name| {
1328-
let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1329-
all.iter()
1330-
.find(|cgu| *cgu.name() == name)
1331-
.cloned()
1332-
.unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
1333-
};
1334-
1335-
provide_extern(providers);
1336-
}
1337-
1338-
pub fn provide_extern(providers: &mut Providers) {
1191+
pub fn provide_both(providers: &mut Providers) {
13391192
providers.dllimport_foreign_items = |tcx, krate| {
13401193
let module_map = tcx.foreign_modules(krate);
13411194
let module_map = module_map.iter()

‎src/librustc_codegen_llvm/lib.rs

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ use back::bytecode::RLIB_BYTECODE_EXTENSION;
7171

7272
pub use llvm_util::target_features;
7373
use std::any::Any;
74-
use std::path::{PathBuf};
7574
use std::sync::mpsc;
7675
use rustc_data_structures::sync::Lrc;
7776

@@ -87,20 +86,17 @@ use rustc::util::time_graph;
8786
use rustc::util::nodemap::{FxHashSet, FxHashMap};
8887
use rustc::util::profiling::ProfileCategory;
8988
use rustc_mir::monomorphize;
89+
use rustc_codegen_utils::{CompiledModule, ModuleKind};
9090
use rustc_codegen_utils::codegen_backend::CodegenBackend;
9191
use rustc_data_structures::svh::Svh;
9292

9393
mod diagnostics;
9494

9595
mod back {
96-
pub use rustc_codegen_utils::symbol_names;
9796
mod archive;
9897
pub mod bytecode;
99-
mod command;
100-
pub mod linker;
10198
pub mod link;
10299
pub mod lto;
103-
pub mod symbol_export;
104100
pub mod write;
105101
mod rpath;
106102
pub mod wasm;
@@ -194,15 +190,15 @@ impl CodegenBackend for LlvmCodegenBackend {
194190
}
195191

196192
fn provide(&self, providers: &mut ty::query::Providers) {
197-
back::symbol_names::provide(providers);
198-
back::symbol_export::provide(providers);
199-
base::provide(providers);
193+
rustc_codegen_utils::symbol_export::provide(providers);
194+
rustc_codegen_utils::symbol_names::provide(providers);
195+
base::provide_both(providers);
200196
attributes::provide(providers);
201197
}
202198

203199
fn provide_extern(&self, providers: &mut ty::query::Providers) {
204-
back::symbol_export::provide_extern(providers);
205-
base::provide_extern(providers);
200+
rustc_codegen_utils::symbol_export::provide_extern(providers);
201+
base::provide_both(providers);
206202
attributes::provide_extern(providers);
207203
}
208204

@@ -281,13 +277,6 @@ struct CachedModuleCodegen {
281277
source: WorkProduct,
282278
}
283279

284-
#[derive(Copy, Clone, Debug, PartialEq)]
285-
enum ModuleKind {
286-
Regular,
287-
Metadata,
288-
Allocator,
289-
}
290-
291280
impl ModuleCodegen {
292281
fn into_compiled_module(self,
293282
emit_obj: bool,
@@ -321,15 +310,6 @@ impl ModuleCodegen {
321310
}
322311
}
323312

324-
#[derive(Debug)]
325-
struct CompiledModule {
326-
name: String,
327-
kind: ModuleKind,
328-
object: Option<PathBuf>,
329-
bytecode: Option<PathBuf>,
330-
bytecode_compressed: Option<PathBuf>,
331-
}
332-
333313
struct ModuleLlvm {
334314
llcx: &'static mut llvm::Context,
335315
llmod_raw: *const llvm::Module,
@@ -377,7 +357,7 @@ struct CodegenResults {
377357
crate_hash: Svh,
378358
metadata: rustc::middle::cstore::EncodedMetadata,
379359
windows_subsystem: Option<String>,
380-
linker_info: back::linker::LinkerInfo,
360+
linker_info: rustc_codegen_utils::linker::LinkerInfo,
381361
crate_info: CrateInfo,
382362
}
383363

‎src/librustc_codegen_utils/Cargo.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ test = false
1313
flate2 = "1.0"
1414
log = "0.4"
1515

16+
serialize = { path = "../libserialize" }
1617
syntax = { path = "../libsyntax" }
1718
syntax_pos = { path = "../libsyntax_pos" }
1819
rustc = { path = "../librustc" }
20+
rustc_allocator = { path = "../librustc_allocator" }
1921
rustc_target = { path = "../librustc_target" }
2022
rustc_data_structures = { path = "../librustc_data_structures" }
23+
rustc_metadata = { path = "../librustc_metadata" }
2124
rustc_mir = { path = "../librustc_mir" }
2225
rustc_incremental = { path = "../librustc_incremental" }
23-
rustc_metadata_utils = { path = "../librustc_metadata_utils" }

‎src/librustc_codegen_utils/lib.rs

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,28 @@ extern crate flate2;
3030
#[macro_use]
3131
extern crate log;
3232

33+
extern crate serialize;
3334
#[macro_use]
3435
extern crate rustc;
36+
extern crate rustc_allocator;
3537
extern crate rustc_target;
38+
extern crate rustc_metadata;
3639
extern crate rustc_mir;
3740
extern crate rustc_incremental;
3841
extern crate syntax;
3942
extern crate syntax_pos;
4043
#[macro_use] extern crate rustc_data_structures;
41-
extern crate rustc_metadata_utils;
4244

45+
use std::path::PathBuf;
46+
47+
use rustc::session::Session;
4348
use rustc::ty::TyCtxt;
4449

50+
pub mod command;
4551
pub mod link;
52+
pub mod linker;
4653
pub mod codegen_backend;
54+
pub mod symbol_export;
4755
pub mod symbol_names;
4856
pub mod symbol_names_test;
4957

@@ -61,4 +69,43 @@ pub fn check_for_rustc_errors_attr(tcx: TyCtxt) {
6169
}
6270
}
6371

72+
#[derive(Copy, Clone, Debug, PartialEq)]
73+
pub enum ModuleKind {
74+
Regular,
75+
Metadata,
76+
Allocator,
77+
}
78+
79+
#[derive(Debug)]
80+
pub struct CompiledModule {
81+
pub name: String,
82+
pub kind: ModuleKind,
83+
pub object: Option<PathBuf>,
84+
pub bytecode: Option<PathBuf>,
85+
pub bytecode_compressed: Option<PathBuf>,
86+
}
87+
88+
pub fn find_library(name: &str, search_paths: &[PathBuf], sess: &Session)
89+
-> PathBuf {
90+
// On Windows, static libraries sometimes show up as libfoo.a and other
91+
// times show up as foo.lib
92+
let oslibname = format!("{}{}{}",
93+
sess.target.target.options.staticlib_prefix,
94+
name,
95+
sess.target.target.options.staticlib_suffix);
96+
let unixlibname = format!("lib{}.a", name);
97+
98+
for path in search_paths {
99+
debug!("looking for {} inside {:?}", name, path);
100+
let test = path.join(&oslibname);
101+
if test.exists() { return test }
102+
if oslibname != unixlibname {
103+
let test = path.join(&unixlibname);
104+
if test.exists() { return test }
105+
}
106+
}
107+
sess.fatal(&format!("could not find native static library `{}`, \
108+
perhaps an -L flag is missing?", name));
109+
}
110+
64111
__build_diagnostic_array! { librustc_codegen_utils, DIAGNOSTICS }

‎src/librustc_codegen_utils/link.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use rustc::session::Session;
1313
use std::path::{Path, PathBuf};
1414
use syntax::{ast, attr};
1515
use syntax_pos::Span;
16-
use rustc_metadata_utils::validate_crate_name;
1716

1817
pub fn out_filename(sess: &Session,
1918
crate_type: config::CrateType,
@@ -52,7 +51,7 @@ pub fn find_crate_name(sess: Option<&Session>,
5251
attrs: &[ast::Attribute],
5352
input: &Input) -> String {
5453
let validate = |s: String, span: Option<Span>| {
55-
validate_crate_name(sess, &s, span);
54+
::rustc_metadata::validate_crate_name(sess, &s, span);
5655
s
5756
};
5857

‎src/librustc_codegen_llvm/back/linker.rs renamed to ‎src/librustc_codegen_utils/linker.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ use std::io::prelude::*;
1515
use std::io::{self, BufWriter};
1616
use std::path::{Path, PathBuf};
1717

18-
use back::archive;
19-
use back::command::Command;
20-
use back::symbol_export;
18+
use command::Command;
2119
use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
2220
use rustc::middle::dependency_format::Linkage;
2321
use rustc::session::Session;
@@ -26,7 +24,6 @@ use rustc::session::config::{self, CrateType, OptLevel, DebugInfo,
2624
use rustc::ty::TyCtxt;
2725
use rustc_target::spec::{LinkerFlavor, LldFlavor};
2826
use serialize::{json, Encoder};
29-
use llvm_util;
3027

3128
/// For all the linkers we support, and information they might
3229
/// need out of the shared crate context before we get rid of it.
@@ -43,10 +40,13 @@ impl LinkerInfo {
4340
}
4441
}
4542

46-
pub fn to_linker<'a>(&'a self,
47-
cmd: Command,
48-
sess: &'a Session,
49-
flavor: LinkerFlavor) -> Box<dyn Linker+'a> {
43+
pub fn to_linker<'a>(
44+
&'a self,
45+
cmd: Command,
46+
sess: &'a Session,
47+
flavor: LinkerFlavor,
48+
target_cpu: &'a str,
49+
) -> Box<dyn Linker+'a> {
5050
match flavor {
5151
LinkerFlavor::Lld(LldFlavor::Link) |
5252
LinkerFlavor::Msvc => {
@@ -70,6 +70,7 @@ impl LinkerInfo {
7070
info: self,
7171
hinted_static: false,
7272
is_ld: false,
73+
target_cpu,
7374
}) as Box<dyn Linker>
7475
}
7576

@@ -82,6 +83,7 @@ impl LinkerInfo {
8283
info: self,
8384
hinted_static: false,
8485
is_ld: true,
86+
target_cpu,
8587
}) as Box<dyn Linker>
8688
}
8789

@@ -144,6 +146,7 @@ pub struct GccLinker<'a> {
144146
hinted_static: bool, // Keeps track of the current hinting mode.
145147
// Link as ld
146148
is_ld: bool,
149+
target_cpu: &'a str,
147150
}
148151

149152
impl<'a> GccLinker<'a> {
@@ -204,7 +207,8 @@ impl<'a> GccLinker<'a> {
204207
};
205208

206209
self.linker_arg(&format!("-plugin-opt={}", opt_level));
207-
self.linker_arg(&format!("-plugin-opt=mcpu={}", llvm_util::target_cpu(self.sess)));
210+
let target_cpu = self.target_cpu;
211+
self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
208212

209213
match self.sess.lto() {
210214
config::Lto::Thin |
@@ -263,7 +267,7 @@ impl<'a> Linker for GccLinker<'a> {
263267
// -force_load is the macOS equivalent of --whole-archive, but it
264268
// involves passing the full path to the library to link.
265269
self.linker_arg("-force_load");
266-
let lib = archive::find_library(lib, search_path, &self.sess);
270+
let lib = ::find_library(lib, search_path, &self.sess);
267271
self.linker_arg(&lib);
268272
}
269273
}
@@ -898,7 +902,8 @@ impl<'a> Linker for EmLinker<'a> {
898902
fn exported_symbols(tcx: TyCtxt, crate_type: CrateType) -> Vec<String> {
899903
let mut symbols = Vec::new();
900904

901-
let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
905+
let export_threshold =
906+
::symbol_export::crates_export_threshold(&[crate_type]);
902907
for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
903908
if level.is_below_threshold(export_threshold) {
904909
symbols.push(symbol.symbol_name(tcx).to_string());

‎src/librustc_codegen_llvm/back/symbol_export.rs renamed to ‎src/librustc_codegen_utils/symbol_export.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
use rustc_data_structures::sync::Lrc;
1212
use std::sync::Arc;
1313

14-
use monomorphize::Instance;
14+
use rustc::ty::Instance;
1515
use rustc::hir;
1616
use rustc::hir::Node;
1717
use rustc::hir::CodegenFnAttrFlags;

‎src/librustc_metadata/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,3 @@ serialize = { path = "../libserialize" }
2020
syntax = { path = "../libsyntax" }
2121
syntax_ext = { path = "../libsyntax_ext" }
2222
syntax_pos = { path = "../libsyntax_pos" }
23-
rustc_metadata_utils = { path = "../librustc_metadata_utils" }

‎src/librustc_metadata/creader.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@ use rustc::util::common::record_time;
3030
use rustc::util::nodemap::FxHashSet;
3131
use rustc::hir::map::Definitions;
3232

33-
use rustc_metadata_utils::validate_crate_name;
34-
3533
use std::ops::Deref;
3634
use std::path::PathBuf;
3735
use std::{cmp, fs};
@@ -1106,7 +1104,7 @@ impl<'a> CrateLoader<'a> {
11061104
item.ident, orig_name);
11071105
let orig_name = match orig_name {
11081106
Some(orig_name) => {
1109-
validate_crate_name(Some(self.sess), &orig_name.as_str(),
1107+
::validate_crate_name(Some(self.sess), &orig_name.as_str(),
11101108
Some(item.span));
11111109
orig_name
11121110
}

‎src/librustc_metadata/lib.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ extern crate serialize as rustc_serialize; // used by deriving
3838
extern crate rustc_errors as errors;
3939
extern crate syntax_ext;
4040
extern crate proc_macro;
41-
extern crate rustc_metadata_utils;
4241

4342
#[macro_use]
4443
extern crate rustc;
@@ -64,4 +63,34 @@ pub mod cstore;
6463
pub mod dynamic_lib;
6564
pub mod locator;
6665

66+
pub fn validate_crate_name(
67+
sess: Option<&rustc::session::Session>,
68+
s: &str,
69+
sp: Option<syntax_pos::Span>
70+
) {
71+
let mut err_count = 0;
72+
{
73+
let mut say = |s: &str| {
74+
match (sp, sess) {
75+
(_, None) => bug!("{}", s),
76+
(Some(sp), Some(sess)) => sess.span_err(sp, s),
77+
(None, Some(sess)) => sess.err(s),
78+
}
79+
err_count += 1;
80+
};
81+
if s.is_empty() {
82+
say("crate name must not be empty");
83+
}
84+
for c in s.chars() {
85+
if c.is_alphanumeric() { continue }
86+
if c == '_' { continue }
87+
say(&format!("invalid character `{}` in crate name: `{}`", c, s));
88+
}
89+
}
90+
91+
if err_count > 0 {
92+
sess.unwrap().abort_if_errors();
93+
}
94+
}
95+
6796
__build_diagnostic_array! { librustc_metadata, DIAGNOSTICS }

‎src/librustc_metadata_utils/Cargo.toml

Lines changed: 0 additions & 14 deletions
This file was deleted.

‎src/librustc_metadata_utils/lib.rs

Lines changed: 0 additions & 42 deletions
This file was deleted.

‎src/librustc_mir/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ pub fn provide(providers: &mut Providers) {
9393
borrow_check::provide(providers);
9494
shim::provide(providers);
9595
transform::provide(providers);
96+
monomorphize::partitioning::provide(providers);
9697
providers.const_eval = const_eval::const_eval_provider;
9798
providers.const_eval_raw = const_eval::const_eval_raw_provider;
9899
providers.check_match = hair::pattern::check_match;

‎src/librustc_mir/monomorphize/partitioning.rs

Lines changed: 156 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,21 +102,27 @@
102102
//! source-level module, functions from the same module will be available for
103103
//! inlining, even when they are not marked #[inline].
104104
105-
use monomorphize::collector::InliningMap;
105+
use std::collections::hash_map::Entry;
106+
use std::cmp;
107+
use std::sync::Arc;
108+
109+
use syntax::ast::NodeId;
110+
use syntax::symbol::InternedString;
106111
use rustc::dep_graph::{WorkProductId, WorkProduct, DepNode, DepConstructor};
107112
use rustc::hir::CodegenFnAttrFlags;
108-
use rustc::hir::def_id::{DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
113+
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
109114
use rustc::hir::map::DefPathData;
110115
use rustc::mir::mono::{Linkage, Visibility, CodegenUnitNameBuilder};
111116
use rustc::middle::exported_symbols::SymbolExportLevel;
112117
use rustc::ty::{self, TyCtxt, InstanceDef};
113118
use rustc::ty::item_path::characteristic_def_id_of_type;
114-
use rustc::util::nodemap::{FxHashMap, FxHashSet};
115-
use std::collections::hash_map::Entry;
116-
use std::cmp;
117-
use syntax::ast::NodeId;
118-
use syntax::symbol::InternedString;
119+
use rustc::ty::query::Providers;
120+
use rustc::util::common::time;
121+
use rustc::util::nodemap::{DefIdSet, FxHashMap, FxHashSet};
119122
use rustc::mir::mono::MonoItem;
123+
124+
use monomorphize::collector::InliningMap;
125+
use monomorphize::collector::{self, MonoItemCollectionMode};
120126
use monomorphize::item::{MonoItemExt, InstantiationMode};
121127

122128
pub use rustc::mir::mono::CodegenUnit;
@@ -892,3 +898,146 @@ fn debug_dump<'a, 'b, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
892898
}
893899
}
894900
}
901+
902+
fn collect_and_partition_mono_items<'a, 'tcx>(
903+
tcx: TyCtxt<'a, 'tcx, 'tcx>,
904+
cnum: CrateNum,
905+
) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
906+
{
907+
assert_eq!(cnum, LOCAL_CRATE);
908+
909+
let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
910+
Some(ref s) => {
911+
let mode_string = s.to_lowercase();
912+
let mode_string = mode_string.trim();
913+
if mode_string == "eager" {
914+
MonoItemCollectionMode::Eager
915+
} else {
916+
if mode_string != "lazy" {
917+
let message = format!("Unknown codegen-item collection mode '{}'. \
918+
Falling back to 'lazy' mode.",
919+
mode_string);
920+
tcx.sess.warn(&message);
921+
}
922+
923+
MonoItemCollectionMode::Lazy
924+
}
925+
}
926+
None => {
927+
if tcx.sess.opts.cg.link_dead_code {
928+
MonoItemCollectionMode::Eager
929+
} else {
930+
MonoItemCollectionMode::Lazy
931+
}
932+
}
933+
};
934+
935+
let (items, inlining_map) =
936+
time(tcx.sess, "monomorphization collection", || {
937+
collector::collect_crate_mono_items(tcx, collection_mode)
938+
});
939+
940+
tcx.sess.abort_if_errors();
941+
942+
::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
943+
944+
let strategy = if tcx.sess.opts.incremental.is_some() {
945+
PartitioningStrategy::PerModule
946+
} else {
947+
PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
948+
};
949+
950+
let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
951+
partition(
952+
tcx,
953+
items.iter().cloned(),
954+
strategy,
955+
&inlining_map
956+
)
957+
.into_iter()
958+
.map(Arc::new)
959+
.collect::<Vec<_>>()
960+
});
961+
962+
let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
963+
match *mono_item {
964+
MonoItem::Fn(ref instance) => Some(instance.def_id()),
965+
MonoItem::Static(def_id) => Some(def_id),
966+
_ => None,
967+
}
968+
}).collect();
969+
970+
if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
971+
let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
972+
973+
for cgu in &codegen_units {
974+
for (&mono_item, &linkage) in cgu.items() {
975+
item_to_cgus.entry(mono_item)
976+
.or_default()
977+
.push((cgu.name().clone(), linkage));
978+
}
979+
}
980+
981+
let mut item_keys: Vec<_> = items
982+
.iter()
983+
.map(|i| {
984+
let mut output = i.to_string(tcx);
985+
output.push_str(" @@");
986+
let mut empty = Vec::new();
987+
let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
988+
cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
989+
cgus.dedup();
990+
for &(ref cgu_name, (linkage, _)) in cgus.iter() {
991+
output.push_str(" ");
992+
output.push_str(&cgu_name.as_str());
993+
994+
let linkage_abbrev = match linkage {
995+
Linkage::External => "External",
996+
Linkage::AvailableExternally => "Available",
997+
Linkage::LinkOnceAny => "OnceAny",
998+
Linkage::LinkOnceODR => "OnceODR",
999+
Linkage::WeakAny => "WeakAny",
1000+
Linkage::WeakODR => "WeakODR",
1001+
Linkage::Appending => "Appending",
1002+
Linkage::Internal => "Internal",
1003+
Linkage::Private => "Private",
1004+
Linkage::ExternalWeak => "ExternalWeak",
1005+
Linkage::Common => "Common",
1006+
};
1007+
1008+
output.push_str("[");
1009+
output.push_str(linkage_abbrev);
1010+
output.push_str("]");
1011+
}
1012+
output
1013+
})
1014+
.collect();
1015+
1016+
item_keys.sort();
1017+
1018+
for item in item_keys {
1019+
println!("MONO_ITEM {}", item);
1020+
}
1021+
}
1022+
1023+
(Arc::new(mono_items), Arc::new(codegen_units))
1024+
}
1025+
1026+
pub fn provide(providers: &mut Providers) {
1027+
providers.collect_and_partition_mono_items =
1028+
collect_and_partition_mono_items;
1029+
1030+
providers.is_codegened_item = |tcx, def_id| {
1031+
let (all_mono_items, _) =
1032+
tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1033+
all_mono_items.contains(&def_id)
1034+
};
1035+
1036+
providers.codegen_unit = |tcx, name| {
1037+
let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1038+
all.iter()
1039+
.find(|cgu| *cgu.name() == name)
1040+
.cloned()
1041+
.unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
1042+
};
1043+
}

0 commit comments

Comments
 (0)
Please sign in to comment.